python 透明化掩膜图片的黑色背景

import cv2
import  numpy as np
import PIL
from PIL import Image


def trans2non(a):
    b = a.convert('RGBA')
    L, H = b.size
    color_0 = b.getpixel((0,0))
    for h in range(H):
        for l in range(L):
            dot = (l,h)
            color_1 = b.getpixel(dot)
            if color_1 == color_0:
                color_1 = color_1[:-1] + (0,)
                b.putpixel(dot,color_1)
    return b 

 
img=cv2.imread("D:/18.png")  #原始图片
rows,cols,channels = img.shape
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
for i in range(rows):
    for j in range(cols):
        # if img
        img[i,j,1]=0#此处替换颜色,为BGR通道
        img[i,j,2]=0

cv2.imwrite('blue_mask.png',img) #生成的新图片
new_mask = Image.open("blue_mask.png")
new_mask = trans2non(new_mask)
new_mask.save('new_mask.png')
    原文作者:HunterLiXiaoLong
    原文地址: https://blog.csdn.net/HunterLiXiaoLong/article/details/109586304
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞