技术关键
- 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)
效果展示
处理前
处理后
参考资料
https://blog.youkuaiyun.com/littlle_yan/article/details/79204544