对 OpenCV 中 getRotationMatrix2D 函数和仿射变换的一点理解 您所在的位置:网站首页 如何求旋转后的函数值 对 OpenCV 中 getRotationMatrix2D 函数和仿射变换的一点理解

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

2024-07-11 12:13| 来源: 网络整理| 查看: 265

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​=w∗cosθ+h∗sinθ h 1 = w ∗ s i n θ + h ∗ c o s θ h_1=w*sin\theta+h*cos\theta h1​=w∗sinθ+h∗cosθ

同时,由于我们是绕着原来图像的中心点进行旋转的,而旋转后图像的中心点 ( 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​/2−w/2 d y = d y + h 1 / 2 − h / 2 dy=dy+h_1/2-h/2 dy=dy+h1​/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)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有