OpenCV基础之几何变换
图像几个变换一般包括:旋转、平移、缩放、仿射变换和透视变换。
旋转
围绕图像的某个点进行给定角度的旋转变换,旋转矩阵的表现形式:
OpenCV提供了根据旋转中心和角度生成旋转矩阵的方法:cv2.getRotationMatrix2D
但是该方法获得旋转矩阵与上述略有不同形式:
rows,cols,channels= img.shape
degree = 45 #逆时针旋转90度
R = cv2.getRotationMatrix2D((cols//2,rows//2),degree,1) #1 为缩放尺度
dst = cv2.warpAffine(img, R, (cols, rows)) #进行变换
平移
平移就是图像中的像素沿着x方向和y方向移动,平移矩阵的形式:
img = cv2.imread("images/2.jpg")
T = np.float32([[1, 0, 1000],[0, 1, 500]])
dst = cv2.warpAffine(img, T, (img.shape[1], img.shape[0]))
缩放
图像的缩放就是图像的尺寸的宽和高发生放大或者缩小,OpenCV常用的方法是 cv2.resize()
img = cv2.imread("images/2.jpg")
rows, cols, channels=img.shape
dst = cv2.resize(img, (0.5 * cols, 0.5 * rows), interpolation=cv2.INTER_CUBIC)
仿射变换
就是表示两幅图之间的关系,放射变换是线性的,所以表现的特点就是直线 变换后还是直线,矩形变换后还是矩形。
也就是旋转、平移、缩放的组合。它的变换矩阵是2 X 3,所以给定3对点就可以计算出该矩阵。
img = cv2.imread('drawing.png')
rows,cols,ch = img.shape
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
M = cv2.getAffineTransform(pts1,pts2)
dst = cv2.warpAffine(img,M,(cols,rows))
透视变换
在放射变换的基础上,图像变形还包括z方向,相机成像模型就是属于透视投影,特点:平行线可能不再平行,矩形变换后可能梯形等,它的变换矩阵是3 X 3 ,至少需要4对点。
img = cv2.imread('sudokusmall.png')
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 = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(img,M,(300,300))
实例(图像任意角度旋转)
通过输入图片显示任意角度
思路:
1. 获得旋转矩阵
2. 计算转换后的图像尺寸
代码:
@img 图像
@degree 角度
def rotateImage(img,degree):
rows,cols,channels= img.shape
R = cv2.getRotationMatrix2D((cols//2,rows//2),degree,1)
# 计算图像的尺寸
corners = [[0, 0, 1], [rows, cols, 1], [0, cols, 1], [rows, 0, 1]]
tmp = np.array(corners).transpose()
ret=np.dot(R, tmp)
width = max(math.ceil(abs(ret[1][0]-ret[1][1])),math.ceil(abs(ret[1][2]-ret[1][3])))
height = max(math.ceil(abs(ret[0][0]-ret[0][1])),math.ceil(abs(ret[0][2]-ret[0][3])))
# 平移
T = np.zeros((2,3))
T[0][2] =width//2 - cols//2
T[1][2] =height//2 - rows//2
print("Height:{},Width:{}".format(height,width))
#for corner in corner:
dst = cv2.warpAffine(img, R+T, (width, height))
return dst