from PIL import Image
import numpy as np
import cv2
pillow
# PIL库给影像添加alpha通道
img = Image.open("cut\\gf2_934_Clip.png")
img = img.convert('RGBA')
r, g, b, alpha = img.split()
alpha = alpha.point(lambda i: i>0 and 178)
img.putalpha(alpha)
img.save("cut\\1.png")
OpenCV
# opencv给影像添加alpha通道
img = cv2.imread("cut\\gf2_934_Clip.png")
b_channel, g_channel, r_channel = cv2.split(img)
# 以下两行给影像添加一个左半边透明,右半边不透明的alpha通道
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
alpha_channel[:, :int(b_channel.shape[0] / 2)] = 100
# 添加一个整体透明度为50的alpha通道
# alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 50 # creating a dummy alpha channel image.
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
cv2.imwrite("cut\\3.png", img_BGRA)