周末闲来无事,总结下opencv几何变换操作。
import cv2
def translation(img, M, dsize):
"""
平移
:param img: cv.imread('messi5.jpg',0)
:param M: np.float32([[1,0,100],[0,1,50]])
:param dsize: (cols,rows)
:return:
"""
return cv2.warpAffine(img, M, (dsize[0], dsize[1])) # 2x3
def rotate(img, angle, center_xy_tuple, dsize_xy_tuple):
"""
旋转
:param img:
:param angle:
:param dsize_xy_tuple:
:return:
"""
M = cv2.getRotationMatrix2D(center_xy_tuple, 90, 1) # 2x3
return cv2.warpAffine(img, M, dsize_xy_tuple)
def affine_transformation(img, old_pts_list, new_pts_list, dsize_xy_tuple):
"""
仿射变换
:param img: img = cv.imread('drawing.png')
:param old_pts_list: 三个点,np.float32([[50,50],[200,50],[50,200]])
:param new_pts_list: np.float32([[10,100],[200,50],[100,250]])
:param dsize_xy_tuple:
:return:
"""
M = cv2.getAffineTransform(old_pts_list, new_pts_list) # 2x3
return cv2.warpAffine(img, M, dsize_xy_tuple) # (cols, rows)
def perspective_transformation(img, old_pts_list, new_pts_list, dsize_xy_tuple):
"""
透视变换
:param img:
:param old_pts_list: 四个点,np.float32([[56,65],[368,52],[28,387],[389,390]])
:param new_pts_list: np.float32([[0,0],[300,0],[0,300],[300,300]])
:param dsize_xy_tuple:
:return:
"""
M = cv2.getPerspectiveTransform(old_pts_list, new_pts_list) # 3x3
return cv2.warpPerspective(img, M, dsize_xy_tuple)