Python使用PIL库实现图片灰度转换与二值化处理
本文介绍如何在Python环境中利用PIL库对图片进行灰度转换和二值化处理。通过示例代码展示如何读取彩色图像,转换为灰度图,并设定阈值生成黑白二值图像,适用于Windows及PyCharm开发环境。
Python图片灰度与二值化处理示例
以下直接提供核心实现代码。
开发环境配置为Windows 10系统,集成PyCharm编辑器。
#!/usr/bin/env python3.5.2
# -*- coding: utf-8 -*-
'''4图片灰度调整及二值化:
集成环境:win10 python3 Pycharm
'''
from PIL import Image
# load a color image
im = Image.open('picture\\haha.png' )#当前目录创建picture文件夹
# convert to grey level image
Lim = im.convert('L' )
Lim.save('pice.jpg' )
# setup a converting table with constant threshold
threshold = 185
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
# convert to binary image by the table
bim = Lim.point(table, '1' )
bim.save('picf.png' )
上述内容即为Python实现图片灰度调整及二值化的完整方案,供参考使用。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









