旋转/翻转/改变尺寸
这篇教学会介绍 OpenCV 里的 transpose()、flip()、rotate() 和 reize() 方法,透过这些方法,可以将图像进行旋转、上下左右翻转以及改变尺寸。
快速导览:
因为程序中的 OpenCV 会需要使用镜头或 GPU,所以请使用本机环境 ( 参考:使用 Python 虚拟环境 ) 或使用 Anaconda Jupyter 进行实作 ( 参考:使用 Anaconda ) ,并安装 OpenCV 函数库 ( 参考:OpenCV 函数库 )。
flip() 翻转图像
使用 flip() 方法,可以将图像上下左右翻转,flip 有一个参数,参数设定如下:
| 数值 | 说明 |
|---|---|
| 0 | 以 x 轴为中心上下翻转。 |
| 1 | 以 y 轴为中心左右翻转。 |
| -1 | 同时进行上下左右翻转。 |
下方的程序码,会产生三张图,一张上下翻转,一张左右翻转,一张上下左右翻转。
import cv2
img = cv2.imread('meme.jpg') # 開啟圖片
output_0 = cv2.flip(img, 0) # 上下翻轉
output_1 = cv2.flip(img, 1) # 左右翻轉
output_2 = cv2.flip(img, -1) # 上下左右翻轉
cv2.imwrite('meme_0.jpg', output_0)
cv2.imwrite('meme_1.jpg', output_1)
cv2.imwrite('meme_2.jpg', output_2)
transpose() 旋转图像
使用 transpose() 方法,可以将图像“左右翻转后逆时针”旋转 90 度,下方的程序码,会产生一张左右翻转后逆时针旋转 90 度的图片。
import cv2
img = cv2.imread('meme.jpg')
output = cv2.transpose(img) # 逆時針旋轉 90 度。
cv2.imwrite('output.jpg', output)
rotate() 旋转图像
有别于 transpose() 方法一次只能逆时针旋转 90 度,rotate() 方法可以设定逆时针旋转 90 度、顺时针旋转 90 度,以及旋转 180 度。
import cv2
img = cv2.imread('meme.jpg')
output_ROTATE_90_CLOCKWISE = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
output_ROTATE_90_COUNTERCLOCKWISE = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
output_ROTATE_180 = cv2.rotate(img, cv2.ROTATE_180)
cv2.imwrite('output_1.jpg', output_ROTATE_90_CLOCKWISE)
cv2.imwrite('output_2.jpg', output_ROTATE_90_COUNTERCLOCKWISE)
cv2.imwrite('output_3.jpg', output_ROTATE_180)
reize() 改变尺寸
使用 reize() 方法,可以将图像输出为指定的尺寸,下方的程序码,会产生两张不同尺寸的图片。
使用 reize() 方法时,可以设定 interpolation 参数,指定改变尺寸的插值方式,默认使用 INTER_LINEAR ( 完整名称参考:InterpolationFlags )
import cv2
img = cv2.imread('meme.jpg')
output_1 = cv2.resize(img, (200, 200)) # 產生 200x200 的圖
output_2 = cv2.resize(img, (100, 300)) # 產生 100x300 的圖
cv2.imwrite('output_1.jpg', output_1)
cv2.imwrite('output_2.jpg', output_2)
翻转影片、改变影片尺寸
延伸“写入并储存影片”文章的范例,将读取到的图像缩小为 640x360,并进行上下翻转的效果。
import cv2
cap = cv2.VideoCapture(0) # 讀取電腦攝影機鏡頭影像。
fourcc = cv2.VideoWriter_fourcc(*'MJPG') # 設定影片的格式為 MJPG
out = cv2.VideoWriter('output_1.mp4', fourcc, 20.0, (640, 360)) # 產生空的影片,尺寸為 640x360
if not cap.isOpened():
print("Cannot open camera")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Cannot receive frame")
break
img_1 = cv2.resize(frame,(640, 360)) # 改變圖片尺寸
img_2 = cv2.flip(img_1, 0) # 上下翻轉
out.write(img_2) # 將取得的每一幀圖像寫入空的影片
cv2.imshow('oxxostudio', frame)
if cv2.waitKey(1) == ord('q'):
break # 按下 q 鍵停止
cap.release()
out.release() # 釋放資源
cv2.destroyAllWindows()
微信扫码关注
抖音扫码关注