1.圖像縮放
result = cv2.resize(src, dsize[, result[. fx[, fy[, interpolation]]]])
- src表示原始圖像
- dsize表示縮放大小,fx和fy表示縮放倍數(shù),dsize或fx\fy設(shè)置一個即可實現(xiàn)圖像縮放
import cv2
import numpy as np
#讀取圖片
src = cv2.imread('data/test1.jpg')
#圖像縮放
result = cv2.resize(src, (200,300))
print(result.shape)
result1 = cv2.resize(src, None, fx=0.5, fy=0.5)
print(result1.shape)
#顯示圖像
cv2.imshow("src", src)
cv2.imshow("result", result)
cv2.imshow("result1", result1)
#等待顯示
cv2.waitKey(0)
cv2.destroyAllWindows()
2.圖像旋轉(zhuǎn)
圖像旋轉(zhuǎn)主要調(diào)用getRotationMatrix2D()函數(shù)和warpAffine()函數(shù)實現(xiàn)
M = cv2.getRotationMatrix2D(旋轉(zhuǎn)中心, 旋轉(zhuǎn)度數(shù), scale)
rotated = cv2.warpAffine(原始圖像, 旋轉(zhuǎn)參數(shù), 原始圖像寬高)
import cv2
import numpy as np
#讀取圖片
src = cv2.imread('data/test1.jpg')
#原圖的高、寬 以及通道數(shù)
rows, cols, channel = src.shape
#繞圖像的中心旋轉(zhuǎn)
#參數(shù):旋轉(zhuǎn)中心 旋轉(zhuǎn)度數(shù) scale
M = cv2.getRotationMatrix2D((cols/2, rows/2), 30, 1)
#參數(shù):原始圖像 旋轉(zhuǎn)參數(shù) 元素圖像寬高
rotated = cv2.warpAffine(src, M, (cols, rows))
#顯示圖像
cv2.imshow("src", src)
cv2.imshow("rotated", rotated)
#等待顯示
cv2.waitKey(0)
cv2.destroyAllWindows()
3.圖像翻轉(zhuǎn)
dst = cv2.flip(src, flipCode)
- src表示原始圖像
- flipCode表示翻轉(zhuǎn)方向,如果flipCode為0,則以X軸為對稱軸翻轉(zhuǎn),如果fliipCode>0則以Y軸為對稱軸翻轉(zhuǎn),如果flipCode<0則在X軸、Y軸方向同時翻轉(zhuǎn)
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
#讀取圖片
img = cv2.imread('data/test3.jpg')
src = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#圖像翻轉(zhuǎn)
#0以X軸為對稱軸翻轉(zhuǎn) >0以Y軸為對稱軸翻轉(zhuǎn) <0X軸Y軸翻轉(zhuǎn)
img1 = cv2.flip(src, 0)
img2 = cv2.flip(src, 1)
img3 = cv2.flip(src, -1)
#顯示圖形
titles = ['Source', 'Image1', 'Image2', 'Image3']
images = [src, img1, img2, img3]
for i in range(4):
plt.subplot(1, 4, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()

image.png
4.圖像平移
圖像平移首先定義平移矩陣M,再調(diào)用warpAffine()函數(shù)實現(xiàn)平移
M = np.float32([[1, 0, x], [0, 1, y]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
#讀取圖片
img = cv2.imread('data/test3.jpg')
image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#圖像平移 下、上、右、左平移
M = np.float32([[1, 0, 0], [0, 1, 100]])
img1 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, 0], [0, 1, -100]])
img2 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, 100], [0, 1, 0]])
img3 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
M = np.float32([[1, 0, -100], [0, 1, 0]])
img4 = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
#顯示圖形
titles = ['Image1', 'Image2', 'Image3', 'Image4']
images = [img1, img2, img3, img4]
for i in range(4):
plt.subplot(1, 4, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()

image.png