最近在训练图片方向分类器,需要对原始图片进行批量旋转操作,那如何用python脚本实现批量旋转图片为任意角度呢?
此处,以将我的头像旋转90度为例进行演示。
实现图片批量旋转的python源代码如下:
#-*- coding: UTF-8 -*-
import os
import shutil
from PIL import Image
import fire
imgFormats = ['jpg', 'png', 'jpeg', 'bmp', 'gif']
# 递归获得文件夹下所有文件
def get_fileList(inputDir):
fileList = []
for home, dirs, files in os.walk(inputDir):
for file in files:
# 文件名列表,包含完整路径
fileList.append(os.path.join(home, file))
# # 文件名列表,只包含文件名
# Filelist.append( filename)
return fileList
# 判断是否是图片
def isImage(imgPath):
extension = imgPath.rsplit('.',1)[-1]
if extension in imgFormats:
return True
else:
return False
# 根据输入的图片文件完整路径和旋转角度,生成旋转后的图片并保存
# 旋转角度是一个标签值,如输入为n,则实际逆时针旋转90*n度
def rotate_img(imgPath, degree):
img_rotate = Image.open(imgPath)
if degree == 1:
img_rotate = img_rotate.transpose(Image.ROTATE_90)
elif degree == 2:
img_rotate = img_rotate.transpose(Image.ROTATE_180)
elif degree == 3:
img_rotate = img_rotate.transpose(Image.ROTATE_270)
else:
img_rotate = img_rotate.rotate(degree*90)
img_rotate.save(imgPath)
def rotate_imgs(inputDir, degree):
copyDir = ''.join([inputDir, '_rotated_', str(degree)])
# ps: 若copyDir已存在,则会报错
shutil.copytree(inputDir, copyDir)
fileList = get_fileList(copyDir)
imgCount = 0
for file in fileList:
print(file)
fileNoExtension = file.rsplit('.', 1)[0]
fileExtension = file.rsplit('.', 1)[1]
if fileExtension == 'txt':
with open(file, 'w') as f:
f.write(str(degree))
if isImage(file):
imgCount += 1
rotate_img(file, degree)
os.rename(file, ''.join([fileNoExtension, '_', str(int(degree*90)), '.', fileExtension]))
print(' '.join(['total', str(imgCount), 'pictures rotated']))
if __name__ == '__main__':
fire.Fire(rotate_imgs)
源代码运行结果如下:
需要说明的是,源代码运行时需要输入两个参数:一是指定图片文件夹的路径,二是要旋转的角度,本文中是以90度的倍数为例,若要实现旋转为任意角度,可以将90改为对应数值即可,你get到了么?
【总结】因编辑水平有限,文中难免存在个别错误或疏漏,欢迎大家留言区批评指正~~