import cv2
import os
import numpy as np
from PIL import Image
import skimage.io as io
def colorful(img):
'''
img:需要上色的图片
'''
img = Image.fromarray(img) # 将图像从numpy的数据格式转为PIL中的图像格式
palette = []
for i in range(256):
palette.extend((i, i, i))
palette[:3 * 21] = np.array([[0, 0, 0],
[128, 0, 0],
[0, 128, 0],
[128, 128, 0],
[0, 0, 128],
[128, 0, 128],
[0, 128, 128],
[128, 128, 128],
[64, 0, 0],
[192, 0, 0],
[64, 128, 0],
[192, 128, 0],
[64, 0, 128],
[192, 0, 128],
[64, 128, 128],
[192, 128, 128],
[0, 64, 0],
[128, 64, 0],
[0, 192, 0],
[128, 192, 0],
[0, 64, 128]
], dtype='uint8').flatten()
img.putpalette(palette)
return img
data_dir = "使用你自己的要处理的文件夹绝对路径"
for filename in os.listdir(data_dir):
print(filename)
img = cv2.imread(data_dir+'/'+filename,cv2.IMREAD_GRAYSCALE)
img = colorful(img)
img.save('存储路径'+"/"+filename)