对 OpenCV 中 getRotationMatrix2D 函数和仿射变换的一点理解

  • getRotationMatrix2D()
    这个函数给定一个旋转中心点的坐标、旋转角度和缩放因子,返回一个仿射变换矩阵 M,不考虑缩放因子的话其形式大概如下:

\[M = \begin{bmatrix} cos\theta&sin\theta&dx \\ -sin\theta&cos\theta&dy\end{bmatrix} \]

逆时针旋转 \(\theta\) 取正值,反之为负值。如果绕坐标原点旋转,那么 \(dx,dy=0\),如果旋转中心点不在原点,那么则要通过 \(dx,dy\) 的值对旋转后的坐标进行调整。

红色框是旋转前的图像 src_img,宽和高分别为 h 和 w,黑色框是逆时针旋转 \(\theta\) 后的图像 dst_img。可以看到,如果旋转后图像的宽和高保持不变,那么肯定会有一部分图片会被裁掉。而如果想要保证旋转后图片的所有像素都保留下来,那么新图像就必须至少为浅蓝色框这么大。易知,新图像的宽和高至少为:

\[w_1=w*cos\theta+h*sin\theta \]

\[h_1=w*sin\theta+h*cos\theta \]

同时,由于我们是绕着原来图像的中心点进行旋转的,而旋转后图像的中心点\((w_1/2,h_1/2)\)离原图像中心点\((w/2,h/2)\)有偏移,所以我们需要将旋转后的坐标调整到以旋转后图像的中心点为基准。

\[dx=dx+w_1/2-w/2 \]

\[dy=dy+h_1/2-h/2 \]

import numpy as np
import cv2

img = cv2.imread(r'C:\Users\21058\Downloads\a.jpg')
img = cv2.resize(img, (512, 512))
h, w = img.shape[:2]
angle = 30
M = cv2.getRotationMatrix2D((w//2, h//2), angle, 1.0)
angle = angle / 180 * np.pi # 转化为弧度制
h1 = int(w * np.sin(angle) + h * np.cos(angle))
w1 = int(w * np.cos(angle) + h * np.sin(angle))
M[0, 2] += (w1 - w) / 2
M[1, 2] += (h1 - h) / 2
rotate_img = cv2.warpAffine(img, M, (w1, h1))
cv2.imshow('img', img)
cv2.imshow('rotate_img', rotate_img)
cv2.waitKey(0)

posted @ 2021-01-31 20:31  seniusen  阅读(541)  评论(0编辑  收藏  举报