图片旋转 1. cv2.getRotationMatrix2D(获得仿射变化矩阵) 2. cv2.warpAffine(进行仿射变化)

原文:https://www.cnblogs.com/my-love-is-python/p/10959612.html

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])) 获得仿射变化以后的图像

第五步:如果是图片上的一个点,那么经过变化以后的坐标值为

扫描二维码关注公众号,回复: 8284389 查看本文章

(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)

   

                  原始图像                                       旋转以后的图像

猜你喜欢

转载自www.cnblogs.com/Ph-one/p/12082649.html