Python批量将图片灰度化的实现代码

2020-09-27 0 592

技术关键

os 模块的使用

  • 使用 os.getcwd 获取当前路径
  • 使用 os.listdir()获取文件列表
  • 使用 os.path.splitext() 分割文件名和扩展名
  • 使用 PLI 的 convert(\'L\') 方法将图片转为灰度

代码实现

from PIL import Image
import os
path = os.getcwd() # 获取当前路径
file_list = os.listdir()
for file in file_list:
 filename = os.path.splitext(file)[0]
 filexten = os.path.splitext(file)[1]
 if filexten == \'.png\' or \'.jpg\':
  I = Image.open(file)
  L = I.convert(\'L\')
  L.save(\'灰度 - \'+file)

效果展示

处理前

Python批量将图片灰度化的实现代码

处理后

Python批量将图片灰度化的实现代码

以上内容参考如下:

1.将RGB图像转换为灰度图像:

from PIL import Image
I = Image.open(\'F:\\\\pycharm\\\\picture_format\\\\data\\\\lena.jpg\')
I.show()
L = I.convert(\'L\')
L.show()

输出图像结果图为:

Python批量将图片灰度化的实现代码

2.将RGB图像转换为1模式图像:

from PIL import Image
I = Image.open(\'F:\\\\pycharm\\\\picture_format\\\\data\\\\lena.jpg\')
I.show()
L = I.convert(\'1\')
L.show()

输出结果图为:

Python批量将图片灰度化的实现代码

补充代码:

使用Python将图像批量转换为灰度图像并保存

from PIL import Image
import os
 
input_dir = \'输入文件夹/\'
out_dir = \'输出文件夹/\'
a = os.listdir(file_dir)
 
for i in a:
 print(i)
 I = Image.open(file_dir+i)
 L = I.convert(\'L\')
 L.save(out_dir+i)

总结

到此这篇关于Python批量将图片灰度化的实现代码的文章就介绍到这了,更多相关python 图片灰度化内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

遇见资源网 Linux Python批量将图片灰度化的实现代码 http://www.ox520.com/29519.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务