1、代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : roteTest.py
# @Author: DianaZhang
# @Date : 2018/11/27
import cv2
import math
def rotate_bound(image, angle):
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
# 计算变换矩阵,参数一次表示(旋转中心,旋转角度,缩放因子),其中旋转角度正为逆时针
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
# 为了使旋转后的图片完全显示,所以需要调整输出图片的大小
nH=int(abs(h*math.cos(math.radians(angle)))+abs(w*math.sin(math.radians(angle))))
nW=int(abs(h*math.sin(math.radians(angle)))+abs(w*math.cos(math.radians(angle))))
# 调整旋转矩阵以考虑旋转
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
# 计算旋转后的图片并输出
return cv2.warpAffine(image, M, (nW, nH))
if __name__ == '__main__':
# 读取并显示原图
img=cv2.imread('Lenna.jpg')
print(img.shape)
cv2.imshow('origin', img)
cv2.waitKey()
#计算并输出旋转后的图片
img=rotate_bound(img, 45)
print(img.shape)
cv2.imshow('rote',img)
cv2.waitKey()
2、结果
参考:
https://blog.youkuaiyun.com/hui3909/article/details/78854387
https://blog.youkuaiyun.com/jnulzl/article/details/47057673