Python OpenCV 旋转图像并防止裁减的完整实现

林见深
林见深
发布时间:2026-10-13 | 1人浏览过
原创

本文介绍使用 Python 和 OpenCV 库实现图像旋转并保持完整画面的方法。通过计算旋转后的新尺寸并调整仿射变换矩阵的平移参数,有效避免图像边缘被裁减。

本文分享了利用 Python 和 OpenCV 进行图像旋转的具体代码示例,重点在于保持旋转后的图像不被裁减,供读者参考学习。

# -*- coding:gb2312 -*-
import cv2
from math import *
import numpy as np

img = cv2.imread("3-2.jpg")

height,width=img.shape[:2]

degree=45
#旋转后的尺寸
heightNew=int(width*fabs(sin(radians(degree)))+height*fabs(cos(radians(degree))))
widthNew=int(height*fabs(sin(radians(degree)))+width*fabs(cos(radians(degree))))

matRotation=cv2.getRotationMatrix2D((width/2,height/2),degree,1)

matRotation[0,2] +=(widthNew-width)/2 #重点在这步,目前不懂为什么加这步
matRotation[1,2] +=(heightNew-height)/2 #重点在这步

imgRotation=cv2.warpAffine(img,matRotation,(widthNew,heightNew),borderValue=(255,255,255))

cv2.imshow("img",img)
cv2.imshow("imgRotation",imgRotation)
cv2.waitKey(0)

运行效果如下图所示:

以上内容为本文的全部介绍,希望能为读者的学习提供有益帮助,同时也欢迎大家继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表