python图片旋转45度(使用Python批量旋转,镜像图片)
前言
当我们进行大量图像处理时 ,经常需要旋转或镜像图像 。但一张张处理图片费神又费力 ,有什么好的办法可以帮助我们快速搞定这个问题呢?这时候我们可以写个简单的python程序来搞定它!~
在Python中,我们可以使用Pillow库(Python Imaging Library)进行图像处理 。Pillow库提供了很多函数和类 ,使得图像旋转和镜像变得容易。
本文将会以一下三张图片为例 ,在每一部分将会简单介绍函数后附上批量处理图片的代码 ,零基础的小伙伴也可以轻松使用嗷~
〇 、准备工作 ,PIL库安装
一 、图像旋转
二、图片镜像
〇 、准备工作 ,PIL库安装
可以通过以下命令在Python中安装Pillow库(它是Python Imaging Library的分支版本):
pip install Pillow此外 ,还可以通过Anaconda或Miniconda等科学计算发行版进行安装 。如果你使用Anaconda ,可以使用以下命令来安装Pillow库:
conda install pillow一 、图像旋转
对于图像旋转 ,可以使用Pillow库中的rotate()函数 ,可以通过指定旋转角度来实现 。具体来说,我们可以使用Image.rotate(angle)函数(其中angle为旋转角度 ,单位为度) 。例如 ,我们想将图像旋转90度,可以这样做:
from PIL import Image image = Image.open("path/to/image.jpg") # 读取图片 ,这里要注意图片的格式 rotated_image = image.rotate(90, expand=True) #确定旋转角度在这个例子中 ,我们打开了一张图片,然后使用rotate()函数将其旋转了90度 。我们可以使用show()函数来查看或是用.save(path)直接保存旋转后的图像:
rotated_image.show() #查看图片 rotated_image.save(rotated_image.jpg) #保存图片当我们希望可以批量旋转一个文件夹里的图片90°180°270°时 ,我们可以这么做:
from PIL import Image import os # 设置输入和输出目录 input_dir = /path/to/input/directory/ output_dir = /path/to/output/directory/ # 循环输入目录中的所有JPEG图像 for filename in os.listdir(input_dir): #只可以处理jpg和jpeg后缀下的程序 ,如果你的图片是别的后缀 ,请直接更改点后的文件格式 if filename.endswith(.jpg) or filename.endswith(.jpeg): # 打开图像 img = Image.open(os.path.join(input_dir, filename)) # 旋转图像并保存 这里可以直接添加或删除以选取你需要的旋转角度 for angle in [90, 180, 270]: rotated_img = img.rotate(angle, expand=True) rotated_img.save(os.path.join(output_dir, f{angle}_{filename}))成品如下~!
二 、图片镜像
对于图像镜像 ,可以使用Pillow库中的transpose()函数 ,可以通过指定翻转模式来实现 。具体来说 ,我们可以使用Image.transpose(mode)函数 ,其中mode为翻转模式 ,可以为Image.FLIP_LEFT_RIGHT(水平翻转)或Image.FLIP_TOP_BOTTOM(垂直翻转) 。例如 ,如果我们想将图像水平翻转,可以这样做:
from PIL import Image image = Image.open("path/to/image.jpg") mirrored_image = image.transpose(Image.FLIP_LEFT_RIGHT)在这个例子中 ,我们打开了一张图像 ,然后使用transpose()函数将其水平翻转 。我们可以使用show()或是用.save(path)函数来查看或保存翻转后的图像:
mirrored_image.show() mirrored_image.save(mirrored_image.jpg)当我们希望可以批量水平和垂直镜像一个文件夹里的图片时,我们可以这么做:
from PIL import Image import os # 设置输入和输出目录 input_dir = /path/to/input/directory/ output_dir = /path/to/output/directory/ # 循环输入目录中的所有JPEG图像 , 这里如果你是别的类型格式图片 ,直接更改点后图片类型即可 for filename in os.listdir(input_dir): if filename.endswith(.jpg) or filename.endswith(.jpeg): # 打开图像 img = Image.open(os.path.join(input_dir, filename)) # 水平镜像并保存 mirrored_img = img.transpose(Image.FLIP_LEFT_RIGHT) mirrored_img.save(os.path.join(output_dir, fhoriz_{filename})) # 垂直镜像并保存 mirrored_img = img.transpose(Image.FLIP_TOP_BOTTOM) mirrored_img.save(os.path.join(output_dir, fvert_{filename}))成品如下~!
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!