旋转图片两种方法

这两种方法在旋转图像时,可能会产生一些不同的效果:

rotate_image_new()旋转后的图像完全包含旋转前的内容,并且填充边界尽可能小

rotate_image() 保持原始图像的大小,并根据填充选项决定是否填充边界为白色。如果 if_fill_white 参数为 True,则填充边界为白色;否则,边界将保持原始图像的值。这种方法可以更快速地旋转图像,但可能会导致旋转后的图像包含额外的空白区域或丢失部分图像信息。

python 复制代码
def rotate_image_new(image, degree):
    '''
    旋转图片角度
    '''
    from math import *
    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]

    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(image, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))

    return imgRotation

def rotate_image( image, angle,if_fill_white = False):
    '''
    顺时针旋转
    '''
    # dividing height and width by 2 to get the center of the image
    height, width = image.shape[:2]
    # get the center coordinates of the image to create the 2D rotation matrix
    center = (width / 2, height / 2)

    # using cv2.getRotationMatrix2D() to get the rotation matrix
    rotate_matrix = cv2.getRotationMatrix2D(center=center, angle=angle, scale=1)

    # rotate the image using cv2.warpAffine
    if not if_fill_white:
        rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height) )
    else:
        color = (255, 255) if len(image.shape)==2 else (255, 255,255)
        rotated_image = cv2.warpAffine(src=image, M=rotate_matrix, dsize=(width, height), borderValue=color)
    return rotated_image
相关推荐
周杰伦_Jay几秒前
【Python开发面试题及答案】核心考点+原理解析+实战场景
开发语言·python
HyperAI超神经8 分钟前
【vLLM 学习】vLLM TPU 分析
开发语言·人工智能·python·学习·大语言模型·vllm·gpu编程
爱笑的眼睛1111 分钟前
FastAPI 请求验证:超越 Pydantic 基础,构建企业级验证体系
java·人工智能·python·ai
拉姆哥的小屋12 分钟前
基于深度学习的瞬变电磁法裂缝参数智能反演研究
人工智能·python·深度学习
码界奇点41 分钟前
Python与OpenCV集成海康威视工业相机从基础配置到高级应用的全方位指南
python·数码相机·opencv·相机·python3.11
来两个炸鸡腿43 分钟前
DW动手学大模型应用全栈开发 - (1)大模型应用开发应知必会
python·深度学习·学习·nlp
qq_418247881 小时前
恒源云/autodl与pycharm远程连接
ide·人工智能·python·神经网络·机器学习·pycharm·图论
我命由我123451 小时前
Python Flask 开发 - Flask 快速上手(Flask 最简单的案例、Flask 处理跨域、Flask 基础接口)
服务器·开发语言·后端·python·学习·flask·学习方法
大飞记Python1 小时前
从零配置Python测试环境:详解路径、依赖与虚拟环境最佳实践
开发语言·python·环境配置·安装目录
资深设备全生命周期管理1 小时前
SOP实时侦测系统
python