官網說明
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)