Python批量更改图片颜色,可做证件照底色的更换

红色部分图片更改为白色

Python批量更改图片颜色,可做证件照底色的更换_第1张图片

  • originData:将需要转换的图片放置到这个文件夹中,可自定义文件夹名
  • resData:转换后结果保存的位置,可自定义文件夹名
def img_path(read_path,res_path):
    read_path_list = [read_path+'/'+i for i in os.listdir(read_path)]
    if not os.path.exists(res_path):
        os.mkdir(res_path)
    sava_path_list = [res_path+'/'+i for i in os.listdir(read_path)]
    return read_path_list,sava_path_list

def red_to_white(read_path,save_path):
    print(f"处理路径名称:{read_path}")
    img = Image.open(read_path)
    img_rgb_array = np.array(img.convert("RGB"))
    for x in range(0,img_rgb_array.shape[0]):
        for y in range(0,img_rgb_array.shape[1]):
        		 # 重点就是修改这儿,需要将RGB转为你需要的RGB,更改此处逻辑即可
            if img_rgb_array[x,y][0] == 128:
                img_rgb_array[x, y] = (255, 255, 255)
    print(f"保存路径名称:{save_path}")
    Image.fromarray(img_rgb_array).save(save_path)

def main(read_path_name,res_path_name):
    try:
        read_path_list,sava_path_list = img_path(read_path_name,res_path_name)
        for read_path,save_path in zip(read_path_list,sava_path_list):
            red_to_white(read_path,save_path)
    except Exception as e:
        print(e)

from PIL import Image
import numpy as np
import os
if __name__=='__main__':
    main("originData","resData")

你可能感兴趣的:(python文件处理,python,计算机视觉,图像处理)