保留掩膜白色部分,将黑色部分变为透明:
import PIL.Image as Image
import os
imgfolder= './img-ds/'
maskfolder = './mask-ds'
output_file = './mergeimg-transparent/'
for imgf in os.listdir(imgfolder):
imgfile = os.path.join(imgfolder, imgf)
maskfile = os.path.join(maskfolder, imgf)
mask = Image.open(maskfile)
mask = mask.convert('RGBA')
img = Image.open(imgfile)
img = img.convert('RGBA')
W, H = img.size
white_pixel = (255,255,255,255)
for h in range(H):
for w in range(W):
if mask.getpixel((w,h)) != white_pixel:
img.putpixel((w,h),(255,255,255,0))
savepath = os.path.join(output_file, imgf)
img.save(savepath)
运行代码结果如下图: