png格式图像转成jpg图像时出现异常颜色值

问题描述

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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值