Opencv4 官方文檔 : https://docs.opencv.org/4.2.0/
Opencv4 for Python中文文檔點擊下載:OpenCV4 for Python 中文文檔
1 幾何變換爲何
其實就是圖像的變換 ,包括平移 ,旋轉,縮放,仿射,透視等。
2 圖像的縮放
def resize_demo(image):
print("Origin size:", image.shape)
# 第一種方法:通過fx,fy縮放因子
res = cv.resize(image, None, fx=2, fy=2, interpolation=cv.INTER_CUBIC)
print("After resize 1 size:", res.shape)
# 第二種方法:直接設置輸出圖像的尺寸,所以不用設置縮放因子
height,width = image.shape[:2]
res=cv.resize(image,(2*width,2*height),interpolation=cv.INTER_CUBIC)
print("After resize 2 size:", res.shape)
while(1):
cv.imshow('res',res)
cv.imshow('img',image)
if cv.waitKey(0) & 0xFF == ord("q"):
break
效果:原圖放大至兩倍,改爲小數的話就是縮小至相應倍數。
3 圖像的平移
def move_demo(image):
rows, cols = image.shape[:2]
M = np.float32([[1, 0, 100], [0, 1, 50]])
dst = cv.warpAffine(image, M, (cols, rows))
cv.imshow('image', dst)
4 圖像的旋轉
def rotation_demo(img):
rows, cols = img.shape[:2]
# 將圖像相對於中心旋轉90度,而不進行任何縮放。旋轉中心,角度,縮放比率
M = cv.getRotationMatrix2D((cols / 2, rows / 2), 90, 1)
dst = cv.warpAffine(img, M, (cols, rows))
cv.imshow('original', img)
cv.imshow('result', dst)
cv.waitKey(0)
cv.destroyAllWindows()
效果:
5 圖像的仿射變換
在仿射變換中,原始圖像中的所有平行線在輸出圖像中仍將平行。爲了找到變換矩陣,我們需要輸入圖像中的三個點及其在輸出圖像中的對應位置。然後cv.getAffineTransform將創建一個2x3
矩陣,該矩陣將傳遞給cv.warpAffine。
def perspective_demo(img):
rows, cols, ch = img.shape
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
M = cv.getPerspectiveTransform(pts1, pts2)
dst = cv.warpPerspective(img, M, (300, 300))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()
效果:
6 圖像的透視變換
對於透視變換,需要3x3變換矩陣。即使在轉換後,直線也將保持直線。要找到此變換矩陣,需要在輸入圖像上有4個點,在輸出圖像上需要相應的點。在這四個點中,其中三個不應共線。然後可以通過函數cv.getPerspectiveTransform找到變換矩陣。然後將cv.warpPerspective應用於此3x3轉換矩陣。
def perspective_demo(img):
rows, cols, ch = img.shape
pts1 = np.float32([[56, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [300, 0], [0, 300], [300, 300]])
M = cv.getPerspectiveTransform(pts1, pts2)
dst = cv.warpPerspective(img, M, (300, 300))
plt.subplot(121), plt.imshow(img), plt.title('Input')
plt.subplot(122), plt.imshow(dst), plt.title('Output')
plt.show()
轉載請註明轉自:https://leejason.blog.csdn.net/article/details/106442313