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

  • getRotationMatrix2D()
    这个函数给定一个旋转中心点的坐标、旋转角度和缩放因子,返回一个仿射变换矩阵 M,不考虑缩放因子的话其形式大概如下:
    M = [ c o s θ s i n θ d x − s i n θ c o s θ d y ] M = \begin{bmatrix} cos\theta&sin\theta&dx \\ -sin\theta&cos\theta&dy\end{bmatrix} M=[cosθsinθsinθcosθdxdy]
    逆时针旋转 θ \theta θ 取正值,反之为负值。如果绕坐标原点旋转,那么 d x , d y = 0 dx,dy=0 dx,dy=0,如果旋转中心点不在原点,那么则要通过 d x , d y dx,dy dx,dy 的值对旋转后的坐标进行调整。

红色框是旋转前的图像 src_img,宽和高分别为 h 和 w,黑色框是逆时针旋转 θ \theta θ 后的图像 dst_img。可以看到,如果旋转后图像的宽和高保持不变,那么肯定会有一部分图片会被裁掉。而如果想要保证旋转后图片的所有像素都保留下来,那么新图像就必须至少为浅蓝色框这么大。易知,新图像的宽和高至少为:
w 1 = w ∗ c o s θ + h ∗ s i n θ w_1=w*cos\theta+h*sin\theta w1=wcosθ+hsinθ
h 1 = w ∗ s i n θ + h ∗ c o s θ h_1=w*sin\theta+h*cos\theta h1=wsinθ+hcosθ

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

d x = d x + w 1 / 2 − w / 2 dx=dx+w_1/2-w/2 dx=dx+w1/2w/2
d y = d y + h 1 / 2 − h / 2 dy=dy+h_1/2-h/2 dy=dy+h1/2h/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)

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值