import cv2
import numpy as np
def opencv_rotate(img, angle):
"""
图片旋转,默认应该是逆时针转动
:param img:
:param angle:
:return:
"""
h, w = img.shape[:2] # 图像的(行数,列数,色彩通道数)
borderValue = (0, 0, 0, 0)
# 颜色空间转换?
if img.shape[-1] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
elif img.shape[-1] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
center = (w / 2, h / 2)
scale = 1.0
# 2.1获取M矩阵
"""
M矩阵
[
cosA -sinA (1-cosA)*centerX+sinA*centerY
sinA cosA -sinA*centerX+(1-cosA)*centerY
]
"""
# cv2.getRotationMatrix2D(获得仿射变化矩阵)
M = cv2.getRotationMatrix2D(center, angle, scale)
# 2.2 新的宽高,radians(angle) 把角度转为弧度 sin(弧度)
new_H = int(
w * np.fabs(np.sin(np.radians(angle))) + h * np.fabs(np.cos(np.radians(angle)))
)
new_W = int(
h * np.fabs(np.sin(np.radians(angle))) + w * np.fabs(np.cos(np.radians(angle)))
)
# 2.3 平移
M[0, 2] += (new_W - w) / 2
M[1, 2] += (new_H - h) / 2
# cv2.warpAffine(进行仿射变化)
rotate = cv2.warpAffine(img, M, (new_W, new_H), borderValue=borderValue)
return rotate
if __name__ == "__main__":
img = cv2.imread('./xiaowei.png')
# 显示图片查看
# cv2.imshow('imshow', img)
# cv2.waitKey(1)
# cv2.destroyAllWindows()
# 显示图片查看
angle = -45
res = opencv_rotate(img, angle)
cv2.imwrite('./after.png', res)
# print(f"res = {res}")
04-11
10-27
338
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)