网络中有很多关于cv2旋转图片的代码,但是在旋转图片的同时选择相应的坐标代码却很少或者不符合要求,因此在此整理相关代码并展示。
import cv2
import numpy as np
def rotate_img_and_points(image, angle, points):
"""
旋转图片
:param image:输入图像
:param angle: 旋转角度
:return: 旋转后的图片
"""
def rotate_points(ps, m):
pts = np.float32(ps).reshape([-1, 2]) # 要映射的点
pts = np.hstack([pts, np.ones([len(pts), 1])]).T
target_point = np.dot(m, pts).T
return target_point
h, w = image.shape[:2]
c_x, c_y = w / 2, h / 2
M = cv2.getRotationMatrix2D((c_x, c_y), angle, 1.0)
cos, sin = np.abs(M[0, :2])
# compute the new bounding dimensions of the image
n_w = int(h * sin + w * cos)
n_h = int(h * cos + w * sin)
# adjust the rotation matrix to take into account translation
M[0, 2] += n_w / 2 - c_x
M[1, 2] += n_h / 2 - c_y
# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (n_w, n_h), borderValue=(255, 255, 255)), rotate_points(points, M)
| 留言与评论(共有 0 条评论) “” |