目录
前言
环境依赖
代码
总结
前言
本文提供对图片旋转,垂直翻转、水平翻转等操作工具方法,可以直接使用。
环境依赖
ffmpeg基础环境,直接参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客
ffmpy安装,命令如下:
pip install ffmpy -i https://pypi.douban.com/simple
代码
不废话,上代码。
#!/user/bin/env python
# coding=utf-8
"""
@author : huyi
@file : image_move_tool.py
@ide : PyCharm
@time : 2021-11-18 14:10:57
"""
import os
import uuid
from ffmpy import FFmpeg
# 垂直翻转
def vflip(image_path: str, output_dir: str):
ext = _check_format(image_path)
result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
ff = FFmpeg(inputs={image_path: None},
outputs={result: '-vf vflip -y'})
print(ff.cmd)
ff.run()
return result
# 水平翻转
def hflip(image_path: str, output_dir: str):
ext = _check_format(image_path)
result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
ff = FFmpeg(inputs={image_path: None},
outputs={result: '-vf hflip -y'})
print(ff.cmd)
ff.run()
return result
# 旋转
def rotate(image_path: str, output_dir: str, angle: int):
ext = _check_format(image_path)
result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
ff = FFmpeg(inputs={image_path: None},
outputs={result: '-vf rotate=PI*{}/180 -y'.format(angle)})
print(ff.cmd)
ff.run()
return result
# 转置
'''
type:0 逆时针旋转90度,对称翻转
type:1 顺时针旋转90度
type:2 逆时针旋转90度
type:3 顺时针旋转90度,对称翻转
'''
def transpose(image_path: str, output_dir: str, type: int):
ext = _check_format(image_path)
result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid4(), ext))
ff = FFmpeg(inputs={image_path: None},
outputs={result: '-vf transpose={} -y'.format(type)})
print(ff.cmd)
ff.run()
return result
def _check_format(image_path: str):
ext = os.path.basename(image_path).strip().split('.')[-1]
if ext not in ['png', 'jpg']:
raise Exception('format error')
return ext
代码说明
1、vflip主要是对图片做垂直翻转,hflip对图片做水平翻转,rotate对图片做顺时针旋转(参数angle为角度,例如:90),transpose对图片有4个类型的转置(type参数为:0,1,2,3,类型如下图)。
2、输出路径避免文件名冲突,使用uuid作为文件名。
3、图片后缀校验目前只做了两种格式校验,如果需要,自行补充。
验证一下
准备的图片如下:
验证代码
if __name__ == '__main__':
print(vflip('C:/Users/huyi/Desktop/1.jpg', 'C:/Users/huyi/Desktop/'))
print(hflip('C:/Users/huyi/Desktop/1.jpg', 'C:/Users/huyi/Desktop/'))
print(rotate('C:/Users/huyi/Desktop/1.jpg', 'C:/Users/huyi/Desktop/', 203))
print(transpose('C:/Users/huyi/Desktop/1.jpg', 'C:/Users/huyi/Desktop/', 2))
vflip效果
hflip效果
rotate效果
transpose效果
OK,完美。
总结
没什么好总结的,抬头看了一眼日历,2021年快过去了,今年你收获了什么呢?
分享
这世上没有奇迹,有的是偶然和必然,还有谁做了什么而已!——《悠久之翼》