前言
????????僅供個人學習用,如果對各位朋友有參考價值,給個贊或者收藏吧 ^_^
一. cv2.getRotationMatrix2D(center, angle, scale)
1.1 參數說明?
parameters | center:旋轉中心坐標,是一個元組參數(col, row) angle:旋轉角度,旋轉方向,負號為逆時針,正號為順時針 scale:旋轉后圖像相比原來的縮放比例,1為等比例縮放 |
returns | 返回一個2*3的旋轉(變換)矩陣,因為變換矩陣第三行形式固定,所以忽略。 |
returns:返回下面的2*3行列式,注:α=cosθ,β=sinθ
還是不太懂的話參考:cv2.getRotationMatrix2D的旋轉矩陣的正確形式-CSDN博客
二、cv2.warpAffine(src, M, dsize, dst, flags, borderMode, borderValue)?
2.1 參數說明?
parameters | src:原始圖像。 |
returns | 返回旋轉后的圖像 |
2.2 flags 值說明?
三、舉例
?3.1 demo
import cv2 as cv
import numpy as np
import matplotlib.pyplot as pltimg = cv.imread('E:/Desktop/jianli/lenna.png')
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
(h, w) = img.shape[:2]
print('原圖像的高和寬', h, w)
(cX, cY) = (w // 2, h // 2)
M = cv.getRotationMatrix2D((cX, cY), -45, 1.0)
print('旋轉矩陣:\n', M)
rotate0 = cv.warpAffine(src=img, M=M, dsize=(h, w))
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nH = int((h*cos) + (w*sin))
nW = int((h*sin) + (w*cos))
print('新圖像的高和寬', nH, nW)
rotate1 = cv.warpAffine(img, M, (nW, nH))
# 調整旋轉矩陣的中心以平移到中心顯示全圖
M[0, 2] += (nW/2) - cX
M[1, 2] += (nH/2) - cY
rotate2 = cv.warpAffine(img, M, (nW, nH))
print('中心點平移后的旋轉矩陣:\n', M)
# 顯示圖像
plt.subplot(1, 3, 1), plt.imshow(rotate0, 'gray'), plt.title('rotate0')
plt.subplot(1, 3, 2), plt.imshow(rotate1, 'gray'), plt.title('rotate1')
plt.subplot(1, 3, 3), plt.imshow(rotate2, 'gray'), plt.title('rotate2')
plt.show()
3.1.1? 新圖像的高和寬計算
計算經過仿射變換或旋轉后新圖像的寬度和高度,尤其是在旋轉圖像時保持圖像的完整性而不裁剪任何部分,需要一些幾何計算。
看了以下圖就能知道為啥子這么計算啦
nH = int((h*cos) + (w*sin))
nW = int((h*sin) + (w*cos))