对 OpenCV 中 getRotationMatrix2D 函

2021-02-11  本文已影响0人  seniusen

红色框是旋转前的图像 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)
上一篇 下一篇

猜你喜欢

热点阅读