问题描述
png图像有的可能包含透明通道,包含透明通道的png格式图像转换成jpg格式图像时,会出现异常的颜色值。非通过直接修改扩展名的方法,读取后又保存的。直接通过修改扩展名的方法读取保存后没有异常,但是本质没改变。
对应图像属性
解决方法
img_path = '/special_data'
out_path = '/special_data_jpg'
for img_name in os.listdir(img_path):
img = Image.open(os.path.join(img_path, img_name))
print(img_name, img.mode)
img_name_base, img_name_ext = os.path.splitext(img_name)
if img_name_ext in ['.png', '.PNG']:
if img.mode == 'RGBA':
img_arr = np.array(img)
img_white = np.ones((img_arr.shape[0], img_arr.shape[1], 3), np.uint8) * 255
alpha = img_arr[:, :, 3]
alpha = alpha[:, :, np.newaxis] / 255.
img_out = img_arr[:, :, :3] * alpha + img_white * (1 - alpha)
img_out = np.clip(img_out, 0, 255)
img_out = img_out.astype(np.uint8)
save_img = Image.fromarray(img_out)
elif img.mode == 'P':
img = img.convert('RGBA')
img_arr = np.array(img)
img_white = np.ones((img_arr.shape[0], img_arr.shape[1], 3), np.uint8) * 255
alpha = img_arr[:, :, 3]
alpha = alpha[:, :, np.newaxis] / 255.
img_out = img_arr[:, :, :3] * alpha + img_white * (1 - alpha)
img_out = np.clip(img_out, 0, 255)
img_out = img_out.astype(np.uint8)
save_img = Image.fromarray(img_out)
else:
if img.mode in ['1', 'L']:
save_img = img.convert('RGB')
elif img.mode == 'CMYK':
img = ImageCms.profileToProfile(img, 'USWebCoatedSWOP.icc', 'sRGB Color Space Profile.icm',
renderingIntent=0, outputMode='RGB')
save_img = img
else:
save_img = img
output_img_name = os.path.splitext(img_name)[0] + '.jpg'
print(save_img.mode)
save_img.save(os.path.join(out_path, output_img_name))