python图片旋转

这篇博客主要介绍了如何使用Python进行图片旋转操作,通过简洁的代码示例展示了具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python图片旋转

  • 少废话,直接上代码
#!/usr/bin/env python

import os
from optparse import OptionParser
from sys import stdout

# 导入损坏图片
from PIL import ImageFile, Image
ImageFile.LOAD_TRUNCATED_IMAGES = True

# 计数器
def out_hint(total=[0]):
    total[0] += 1
    stdout.write('generating %6dimgs...\r' % total[0])
    stdout.flush()

# 新建文件夹
def make_folder(folder_name):
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)

# 命令行获取
### 实现图片旋转 #### 使用PIL库进行图像旋转 通过`PIL.Image`模块中的`rotate()`方法能够轻松实现图像旋转变换。此函数接受角度作为输入参数,正数代表逆时针方向旋转。 ```python from PIL import Image def rotate_image_pil(image_path, angle): with Image.open(image_path) as img: rotated_img = img.rotate(angle, expand=True) return rotated_img ``` 该代码片段定义了一个名为`rotate_image_pil`的函数,用于接收图像路径和旋转角度两个参数,并返回经过旋转后的图像对象[^3]。 为了展示旋转效果并保存结果: ```python rotated_image = rotate_image_pil('example.jpg', 45) rotated_image.show() rotated_image.save('rotated_example.png') ``` 这段脚本调用了之前定义好的函数,传入具体的角度值(这里设为45度),接着利用`.show()`命令预览旋转后的图像,并最终将其另存为PNG格式文件。 #### 使用OpenCV库进行图像旋转 对于OpenCV而言,则需借助于仿射变换矩阵来完成这一操作。下面是一个完整的例子,不仅实现了图像本身的旋转,还考虑到了边界填充等问题。 ```python import cv2 import numpy as np def rotate_image_opencv(image_path, angle): image = cv2.imread(image_path) (h, w) = image.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, scale=1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) new_w = int((h * sin) + (w * cos)) new_h = int((h * cos) + (w * sin)) M[0, 2] += (new_w / 2) - center[0] M[1, 2] += (new_h / 2) - center[1] rotated = cv2.warpAffine( image, M, (new_w, new_h), borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255) ) return rotated ``` 上述代码首先计算出原始图像的高度宽度及其中心位置,之后构建了围绕着这个中心点按指定角度旋转所需的转换矩阵M。考虑到旋转过程中可能出现的部分区域被裁剪掉的情况,程序动态调整了输出画布大小以适应新的尺寸需求。最后一步则是应用`cv2.warpAffine()`来进行实际的空间映射工作[^5]。 同样地,如果想要查看或存储处理过的图像,只需简单添加几行额外的语句即可: ```python rotated_image_cv = rotate_image_opencv('example.jpg', 45) cv2.imshow("Rotated", rotated_image_cv) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite('rotated_example_cv.png', rotated_image_cv) ``` 这组指令先是在屏幕上弹出了一个小窗显示已旋转图像,等待按键事件触发关闭窗口的动作;随后又把修改过的内容写回到磁盘上形成一个新的JPEG文件[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值