1.rot_mat = cv2.getRotationMatrix2D(center, -5, 1)
參數說明:center表示中間點的位置,-5表示逆時針旋轉5度,1表示進行等比列的縮放
2. cv2.warpAffine(img, rot_mat, (img.shape[1], img.shape[0]))
參數說明: img表示輸入的圖片,rot_mat表示仿射變化矩陣,(image.shape[1], image.shape[0])表示變換后的圖片大小
代碼說明:
第一步:讀入圖片,進行圖片展示
第二步:獲取圖片的寬,長,通道數,構造[0, 0, w, h], 即構造[x1, y1, x2, y2] 矩陣,實列化一個矩陣
第三步:計算其center值,將其代入到cv2.getRotationMatrix2D生成變化矩陣
第四步:使用cv2.warpAffine(img, rot_mat, (img.shape[1], img.shape[0])) 獲得仿射變化以后的圖像
第五步:如果是圖片上的一個點,那么經過變化以后的坐標值為
(rot_mat[0][0] * x + rot_mat[0][1] * y + rot_mat[0][2], rot_mat[1][0] * x + rot_mat[1][1] * y + rot_mat[1][2]
第六步:進行旋轉圖片的圖片展示,為了保證,這里也可以進行截圖操作
import cv2 import numpy as np class BBox(object): def __init__(self, bbox): self.left = bbox[0] self.top = bbox[1] self.right = bbox[2] self.bottom = bbox[3] img = cv2.imread('0001.jpg') cv2.imshow('img', img) cv2.waitKey(0) h, w, c = img.shape box = [0, 0, w, h] bbox = BBox(box) center = ((bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2) rot_mat = cv2.getRotationMatrix2D(center, -5, 1) img_rotated_by_alpha = cv2.warpAffine(img, rot_mat, (img.shape[1], img.shape[0])) # 獲得圖片旋轉以后的關鍵點的位置 # lanmark_ = np.asarray([(rot_mat[0][0] * x + rot_mat[0][1] * y + rot_mat[0][2], # rot_mat[1][0] * x + rot_mat[1][1] + rot_mat[1][2]) for (x, y) in landmark]) cv2.imshow('img_rotated', img_rotated_by_alpha) cv2.waitKey(0) # face = img_rotated_by_alpha[bbox.top:bbox.bottom + 1, bbox.left:bbox.right + 1] # # cv2.imshow('face', face) # cv2.waitKey(0)
原始圖像 旋轉以后的圖像