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

参考链接:

整理收藏的优质文章

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

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

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

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)

你可能感兴趣的:(图像/音频/视频处理,Image.mode,图像处理)