案例© Fu Xianjun. All Rights Reserved.
几何变换是指将一幅图像映射到另外一幅图像内的操作。OpenCV提供了多个与映射有关的函数,这些函数使用起来方便灵活,能够高效地完成图像的映射。
根据OpenCV函数的不同,本章将映射关系划分为缩放、翻转、仿射变换、透视、重映射等。
import cv2
import numpy as np
img = cv2.imread('lianxi.png')
rows, cols = img.shape[:2]
pts_o = np.float32([[45, 180], [220, 80], [60, 290], [270, 190]])
pts_d = np.float32([[0, 0], [200, 0], [0, 100], [200, 100]])
M = cv2.getPerspectiveTransform(pts_o, pts_d)
dst = cv2.warpPerspective(img, M, (200, 100))
cv2.imshow('img', img)
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img=cv2.imread("lena.jpg")
rows,cols,_ = img.shape
size = (int(rows*1.0),int(cols*0.6))
img_resize = cv2.resize(img,size)
cv2.imshow("SRC",img)
cv2.imshow("RESIZE",img_resize)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img_flip1=cv2.flip(img,0)
cv2.imshow("FLIP1",img_flip1)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
rows,cols,_ = img.shape
x = 100
y = 200
M = np.float32([[1,0,x],[0,1,y]])
img_move=cv2.warpAffine(img,M,(cols,rows))
cv2.imshow("MOVE",img_move)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
height,width,_ = img.shape
M = cv2.getRotationMatrix2D((width/2, height/2), 45, 0.6)
img_rotate=cv2.warpAffine(img,M,(width, height))
cv2.imshow("ROTATE",img_rotate)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread('lena.jpg')
rows, cols,_ = img.shape
pts_o = np.float32([[88, 177], [716, 85], [216, 695], [957, 551]])
pts_d = np.float32([[0, 0], [600, 0], [0, 600], [600, 600]])
M = cv2.getPerspectiveTransform(pts_o, pts_d)
dst = cv2.warpPerspective(img, M, (420, 420))
cv2.imshow('img', img)
cv2.imshow('dst', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()