Python Image.mode 属性,解决丢失透明通道的问题

这篇博客探讨了图像数据预处理中的不同模式,包括'P','RGBA','RGB'等,重点介绍了如何处理带有透明通道的图像。通过使用OpenCV和PIL库,作者展示了如何读取、处理并保存带有ICC配置文件的图像,同时保留Alpha通道信息。此外,还提供了处理透明通道的实用函数示例。

参考链接:

整理收藏的优质文章

图像数据的预处理,从'P','RGBA','RGB'多种mode的图像说起_qiusuoxiaozi的博客-优快云博客

图像数据的预处理,从'P','RGBA','RGB'多种mode的图像说起_qiusuoxiaozi的博客-优快云博客

【笔记】Python Image.mode 属性:L 灰度图像;RGB 真彩色图像;CMYK 出版图像_程序猿的探索之路的博客-优快云博客

opencv: 

def reinsert_alpha(raw_path, new_path, save_path):
    raw_img = cv2.imread(raw_path, cv2.IMREAD_UNCHANGED)
    new_img = cv2.imread(new_path, cv2.IMREAD_UNCHANGED)
    assert raw_img.shape[-1] == 4
    assert new_img.shape[-1] == 3

    alpha = raw_img[..., -1]
    new_img = np.concatenate([new_img, alpha], -1)
    cv2.imwrite(save_path, new_img)
    return new_img

 

Image:

# 代码片段
def get_img_and_icc_host_use(self, image_buffer):
        # img = self.open_img_by_bytes(image_buffer)
        # img = Image.open(BytesIO(image_buffer))
        img = Image.open(image_buffer)
        img = img.convert("RGBA")
        from visionline.utils.logger import logger
        logger.info(f"img.mode = {img.mode}")
        if img.mode == "RGBA":
            alpha_channel = np.array(img)[..., 3]
        else:
            alpha_channel = None
        img = img.convert('RGB')
        icc = img.info.get('icc_profile')
        logger.info(f" icc = {icc} | alpha_channel = {alpha_channel}")
        return img, icc, alpha_channel


    def img_to_bytes(img, icc, alpha_channel=None):
        f = BytesIO()
        if alpha_channel is not None:
            Image.fromarray(
                npy.concatenate((cv2.cvtColor(npy.array(img), cv2.IMREAD_COLOR), alpha_channel[..., npy.newaxis]),
                                axis=2)).save(f, 'PNG', icc_profile=icc)
        else:
            # img.save(f, format='PNG', icc_profile=icc)
            Image.fromarray(cv2.cvtColor(npy.array(img), cv2.IMREAD_COLOR)).save(f, 'PNG', icc_profile=icc)
        img_byte_arr = f.getvalue()
        try:
            f.close()
        except:
            pass
        return img_byte_arr



if __name__ == "__main__":
with open(temp_file_path, 'wb') as f:
    f.write(image_content)

#读取透明通道
img, icc, alpha_channel = self.pic_operate.get_img_and_icc_host_use(temp_file_path)

# 重写的时候,传入透明通道
img_byte_arr = self.faceswap_lib.img_to_bytes(img, icc, alpha_channel=alpha_channel)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值