Python 旋转、翻转图片(附代码)

562次阅读
没有评论

目录

前言

环境依赖

代码

总结


前言

本文提供对图片旋转,垂直翻转、水平翻转等操作工具方法,可以直接使用。

环境依赖

ffmpeg基础环境,直接参考我的另一篇文章:windows ffmpeg安装部署_阿良的博客-CSDN博客

ffmpy安装,命令如下:

pip install ffmpy -i https://pypi.douban.com/simple

代码

不废话,上代码。

#!/user/bin/env python
# coding=utf-8
"""
@project : csdn
@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,类型如下图)。

Python

2、输出路径避免文件名冲突,使用uuid作为文件名。

3、图片后缀校验目前只做了两种格式校验,如果需要,自行补充。

验证一下

准备的图片如下:

Python

 

 验证代码

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效果

Python

hflip效果

Python

rotate效果

Python 

transpose效果 

Python

OK,完美。

总结

没什么好总结的,抬头看了一眼日历,2021年快过去了,今年你收获了什么呢?

分享

        这世上没有奇迹,有的是偶然和必然,还有谁做了什么而已!——《悠久之翼》 

如果本文对你有帮助的话,请不要吝啬你的赞,谢谢!

Python

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-19发表,共计2455字。
新手QQ群:570568346,欢迎进群讨论 Python51学习