要将图片转换成黑白,可以使用Python的图像处理库PIL(Python Imaging Library)和其分支库Pillow,以下是详细的技术教学:
![python如何将图片转换成黑白](https://www.kdun.com/ask/wp-content/themes/justnews/themer/assets/images/lazy.png)
(图片来源网络,侵删)
1、安装Pillow库
确保已经安装了Python,使用以下命令安装Pillow库:
pip install pillow
2、导入所需库
在Python代码中,导入所需的库:
from PIL import Image
3、打开图片
使用Image.open()
方法打开要转换的图片文件:
image = Image.open("example.jpg")
4、转换为灰度图
使用convert()
方法将图片转换为灰度图:
gray_image = image.convert("L")
5、保存黑白图片
使用save()
方法将黑白图片保存到文件:
gray_image.save("example_bw.jpg")
6、显示图片
使用show()
方法显示原始图片和黑白图片:
image.show() gray_image.show()
7、完整代码示例
将以上步骤整合到一个完整的Python代码示例中:
from PIL import Image 打开图片文件 image = Image.open("example.jpg") 转换为灰度图并保存为黑白图片 gray_image = image.convert("L") gray_image.save("example_bw.jpg") 显示原始图片和黑白图片 image.show() gray_image.show()
将上述代码保存为一个Python文件(convert_to_bw.py),然后在命令行中运行该文件:
python convert_to_bw.py
运行完成后,会在当前目录下生成一个名为“example_bw.jpg”的黑白图片文件,原始图片和黑白图片也会在屏幕上显示出来。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/443533.html