< python PIL - 批量图像处理 - RGB图像生成灰度图像 >

< python PIL - 批量图像处理 - RGB图像生成灰度图像 >

  • 直接用python自带的PIL图像库,将一个文件夹下所有jpg/png的RGB图像转换成灰度/黑白图像
from PIL import Image 
import os.path
import glob

def convertjpg(jpgfile,outdir):
    try:
        image_file = Image.open(jpgfile) # open colour image
        image_file = image_file.convert('L') # convert image to black and white
        image_file.save(os.path.join(outdir, os.path.basename(jpgfile)))
    except Exception as e:
        print(e)

for jpgfile in glob.glob("C:/Users/62473/Desktop/RGB/*.png"):    ## 所有图片存放路径 png可以改成jpg
    # print(jpgfile)
    convertjpg(jpgfile,"C:/Users/62473/Desktop/gray")        ## 转换完后的保存路径
posted @ 2019-11-21 20:10  黄龙士  阅读(770)  评论(0编辑  收藏  举报