< 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") ## 轉換完后的保存路徑