opencv-python透明图和纯白背景图互转

import numpy as np
import cv2

'''
    opencv-python:透明背景图和纯白背景图互转
'''


# 修改透明背景为白色背景图
def transparent2white(img):
    height, width, channel = img.shape
    for 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.shape
    for 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 img


if __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)

你可能感兴趣的:(opencv,python,计算机视觉)