python img2pdf 模块不能上传含alpha通道透明度的图片

官网说明

pypi-img2pdf

Input images with alpha channels are not allowed. PDF doesn’t support alpha channels in images and thus, the alpha channel of the input would have to be discarded. But img2pdf will always be lossless and thus, input images must not carry transparency information.

不允许使用带有Alpha通道的输入图像。PDF不支持图像中的Alpha通道,因此必须丢弃输入的Alpha通道。但是img2pdf将始终是无损的,因此,输入图像不得包含透明度信息。

    if ics in ["LA", "PA", "RGBA"] or "transparency" in imgdata.info:
        logging.warning(
            "Image contains transparency which cannot be retained " "in PDF."
        )
        logging.warning("img2pdf will not perform a lossy operation.")
        logging.warning("You can remove the alpha channel using imagemagick:")
        logging.warning(
            "  $ convert input.png -background white -alpha "
            "remove -alpha off output.png"
        )
        raise Exception("Refusing to work on images with alpha channel")

读取图片

cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道
cv2.IMREAD_GRAYSCALE:读入灰度图片
cv2.IMREAD_UNCHANGED:顾名思义,读入完整图片,包括alpha通道

import numpy as np
import cv2
img = cv2.imread(1.jpg’,cv2.IMREAD_GRAYSCALE)
print(img.shape)  # 查看alpha通道
# (120, 125, 3)输出为3表示没有alpha通道,如果是4表示有alpha通道

添加alpha通道

opencv 读取图片后通道为BGR的格式,这里做个示范将图片的左半边设置为透明效果。

import cv2
import numpy as np
 
img = cv2.imread("/home/shuai/Desktop/lena.jpg") 
b_channel, g_channel, r_channel = cv2.split(img) 
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
# 最小值为0
alpha_channel[:, :int(b_channel.shape[1] / 2)] = 100 
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel)) 
cv2.imwrite("lena.png", img_BGRA) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值