Python PIL库图片灰化处理
作者:rainbird 时间:2022-08-18 20:57:30
2020年4月4日,是个特殊的日子,我们看到朋友圈很多灰化的图片.今天我们就聊聊图片灰度处理这事儿.
PIL的基本概念:
PIL中所涉及的基本概念有如下几个:通道(bands)、模式(mode)、尺寸(size)、坐标系统(coordinate system)、调色板(palette)、信息(info)和滤波器(filters)。
PIL(Python Image Library)是python的第三方图像处理库,但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了。其官方主页为:[PIL](http://pythonware.com/products/pil/)。 PIL历史悠久,原来是只支持python2.x的版本的,后来出现了移植到python3的库[pillow](http://python-pillow.org/),pillow号称是`friendly fork for PIL`,其功能和PIL差不多,但是支持python3。
Python可以处理图片的库很多:Matplotlib,OpenCV,TensorFlow,PIL等.我们今天的主角是:PIL(Python Imaging Library).我们的环境是Python3.8.2
安装
pip install Pillow
编码
import os
try:
from PIL import Image
except ImportError as e:
print(e)
print('pip install Pillow')
os._exit(0)
img_url = '/Users/rainbird/Desktop/a.jpg'
img_out = img_url.replace('.jpg','_gray.jpg')
if not os.path.exists(img_url):
print(f'file not found: {img_url}')
os._exit(0)
print(f'''
image in:{img_url}
image out:{img_out}
'''.strip())
img_org = Image.open(img_url)
img_gray= img_org.convert('L')
img_gray.save(img_out)
print('done')
代码不长,主要是:
导入库并判断了异常;
指定处理的文件,个人运行的时候要修改一下;
转换完会产生同名_gray的文件
目前只处理了.jpg
运行
image in:/Users/rainbird/Desktop/a.jpg
image out:/Users/rainbird/Desktop/a_gray.jpg
done
效果
来源:https://blog.cnrainbird.com/index.php/2020/04/05/python_tu_pian_hui_hua_chu_li_pil/
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3.9.1中使用match方法详解
![](https://img.aspxhome.com/file/2023/9/60729_0s.png)
6款jQuery图表插件[译]
![](https://img.aspxhome.com/file/UploadPic/20096/1/08200312t-81s.png)
PHP获取特殊时间戳的方法整理
XML的语法、结构以及相关的一些技术
ASP生成静态模版技术(带参数的标签)
JSQL SQLProxy 的 php 版本代码
现代Python编程的四个关键点你知道几个
![](https://img.aspxhome.com/file/2023/1/64601_0s.jpg)
清除SQL被注入恶意病毒代码的语句
Mysql 数据库双机热备的配置方法
firefox通过XUL实现text-overflow:ellipsis的效果
为你的网页添加背景音乐
![](https://img.aspxhome.com/file/UploadPic/20072/200723113925440s.gif)
如何优化JavaScript脚本的性能
bat和python批量重命名文件的实现代码
SQL Server 中导入导出数据三方法比较
asp如何让我的网页自动适应客户端的屏幕分辨率?
简单获取键盘的KeyCode
谈PHP生成静态页面分析 模板+缓存+写文件
在SQL Server中处理空值时涉及的三个问题
![](https://img.aspxhome.com/file/UploadPic/20092/2009210182215203.jpg)
与 Function 和 Object 相关的有趣代码
![](https://img.aspxhome.com/file/UploadPic/20105/7/javascript_object_layout-52s.jpg)