#annotated_image = img2.copy()
BG_COLOR = (192, 192, 192) # gray
MASK_COLOR = (255, 255, 255) # white
annotated_image = np.zeros(img2.shape, dtype=np.uint8)
annotated_image[:] = MASK_COLOR
白色背景的图片替换成 透明背景
import cv2
import numpy as np
path = "./test.png"
src = cv2.imread(path)
# Point 1: 生成与白色部分对应的mask图像
mask = np.all(src[:,:,:] == [255, 255, 255], axis=-1)
# Point 2: 将图片从三通道转为四通道
dst = cv2.cvtColor(src, cv2.COLOR_BGR2BGRA)
# Point3: 以mask图像为基础,使白色部分透明化
dst[mask,3] = 0
# 保存图片
cv2.imwrite("dst.png", dst)
如果需要将图的透明底转为不透明,则是改动如下:
import cv2
import numpy as np
path = "./test.png" # 透明底的图
src = cv2.imread(path)
# Point 1: 生成获得所有颜色通道对应的mask图像
mask = np.all(src[:,:,:], axis=-1)
# Point 2: 将图片从四通道转为三通道
# dst = cv2.cvtColor(src, cv2.COLOR_BGRA2BGR) # 不要这一句,不然有透明通道会报错
# Point3: 以mask图像为基础,使不透明化
src[mask,3] = 255 # 主要是修改alpha通道为不透明
# 保存图片
cv2.imwrite("dst.png", src)