圖片旋轉 1. cv2.getRotationMatrix2D(獲得仿射變化矩陣) 2. cv2.warpAffine(進行仿射變化)


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)

   

                  原始圖像                                       旋轉以后的圖像

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM