import numpy as npimport cv2'''opencv-python:透明背景图和纯白背景图互转'''# 修改透明背景为白色背景图def transparent2white(img):height, width, channel = img.shapefor h in range(height):for w in range(width):color = img[h, w]if (color == np.array([0, 0, 0, 0])).all():img[h, w] = [255, 255, 255, 255]return img# 修改纯白背景图为透明背景图def white2transparent(img):height, width, channel = img.shapefor h in range(height):for w in range(width):color = img[h, w]if (color == np.array([255, 255, 255, 255])).all():img[h, w] = [0, 0, 0, 0]return imgif __name__ == '__main__':transparent_path = r'transparent.png'# 一:透明背景图转白背景图transparent_img = cv2.imread(transparent_path, -1)# print(transparent_img.shape) #(796, 796, 4)white_img = transparent2white(transparent_img)cv2.imwrite('white.jpg', white_img)# 二:白背景图转透明背景图white_img = cv2.imread('white.jpg')# print(white_img.shape) # (796, 796, 3)white_img = cv2.cvtColor(white_img, cv2.COLOR_BGR2BGRA) # 转为4通道# print(white_img.shape) # (796, 796, 4)new_transparent = white2transparent(white_img)cv2.imwrite('new_transparent.png', new_transparent)
1500字范文,内容丰富有趣,写作好帮手!