Python批量將圖片灰度化的實(shí)現(xiàn)代碼
技術(shù)關(guān)鍵
os 模塊的使用
使用 os.getcwd 獲取當(dāng)前路徑 使用 os.listdir()獲取文件列表 使用 os.path.splitext() 分割文件名和擴(kuò)展名 使用 PLI 的 convert(’L’) 方法將圖片轉(zhuǎn)為灰度代碼實(shí)現(xiàn)
from PIL import Imageimport ospath = os.getcwd() # 獲取當(dāng)前路徑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)
效果展示
處理前
處理后
以上內(nèi)容參考如下:
1.將RGB圖像轉(zhuǎn)換為灰度圖像:
from PIL import ImageI = Image.open(’F:pycharmpicture_formatdatalena.jpg’)I.show()L = I.convert(’L’)L.show()
輸出圖像結(jié)果圖為:
2.將RGB圖像轉(zhuǎn)換為1模式圖像:
from PIL import ImageI = Image.open(’F:pycharmpicture_formatdatalena.jpg’)I.show()L = I.convert(’1’)L.show()
輸出結(jié)果圖為:
補(bǔ)充代碼:
使用Python將圖像批量轉(zhuǎn)換為灰度圖像并保存
from PIL import Imageimport 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)
總結(jié)
到此這篇關(guān)于Python批量將圖片灰度化的實(shí)現(xiàn)代碼的文章就介紹到這了,更多相關(guān)python 圖片灰度化內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ajax請(qǐng)求添加自定義header參數(shù)代碼2. ASP基礎(chǔ)知識(shí)VBScript基本元素講解3. 使用python 計(jì)算百分位數(shù)實(shí)現(xiàn)數(shù)據(jù)分箱代碼4. Kotlin + Flow 實(shí)現(xiàn)Android 應(yīng)用初始化任務(wù)啟動(dòng)庫(kù)5. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟6. 基于javascript處理二進(jìn)制圖片流過程詳解7. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)8. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)9. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……10. 教你如何寫出可維護(hù)的JS代碼
