本文執行個體為大家分享了python批量轉換圖檔為黑白的具體代碼,供大家參考,具體内容如下
用到的庫:OpenCV、os
import cv2
import os
def re_name(path):
files = os.listdir(path)
for i, file in enumerate(files):
try:
new_file_name = os.path.join(path, str(i) + '.jpg')
old_file_name = os.path.join(path, file)
os.rename(old_file_name, new_file_name)
except:
continue
def gray_pic(path):
files = os.listdir(path)
for file in enumerate(files):
try:
pic = path + "\" + str(file[1])
original_img = cv2.imread(pic)
gray = cv2.cvtColor(original_img, cv2.COLOR_BGR2GRAY)
cv2.imwrite(path + "\" + str(file[1]), gray)
except:
continue
path = r'C:\Users090\Desktop\gray'
#re_name(path)
gray_pic(path)
複制
注意:
- 中文檔案名的圖檔需要先改名
- 這裡筆者用數字序号先進行了編号
小編再為大家分享一段很實用的代碼:python批量處理圖檔顔色反轉
#coding:utf-8
import os
from PIL import Image
import numpy as np
def resize(imgPath,savePath):
files = os.listdir(imgPath)
files.sort()
print('****************')
print('input :',imgPath)
print('start...')
for file in files:
fileType = os.path.splitext(file)
if fileType[1] == '.jpg':
new_png = Image.open(imgPath+'/'+file) #打開圖檔
#new_png = new_png.resize((20, 20),Image.ANTIALIAS) #改變圖檔大小
matrix = 255-np.asarray(new_png) #圖像轉矩陣 并反色
new_png = Image.fromarray(matrix) #矩陣轉圖像
new_png.save(savePath+'/'+file) #儲存圖檔
print('down!')
print('****************')
if __name__ == '__main__':
# 待處理圖檔位址
dataPath = 'F:\clean_images\profiles\'
#儲存圖檔的位址
savePath = 'F:\clean_images\new_mask\'
resize(dataPath,savePath)
複制
以上就是本文的全部内容,希望對大家的學習有所幫助。