Python 图像屏蔽和去除背景

问题描述

我有两个图像:寺庙和面具(心脏)。我想用心的形状遮住寺庙,去掉黑色背景。结果应该是带有白色或透明背景的太阳穴心形切口。

Background

White Heart

解决方法

您可以使用 pillowputalpha 将灰度图像 (​​L) 添加到 RGB 图像作为 alpha 通道 - 因此它将具有透明背景。但两张图片的大小必须相同。

from PIL import Image

# load images
img_org  = Image.open('temple.jpg')
img_mask = Image.open('heart.jpg')

# convert images
#img_org  = img_org.convert('RGB') # or 'RGBA'
img_mask = img_mask.convert('L')    # grayscale

# the same size
img_org  = img_org.resize((400,400))
img_mask = img_mask.resize((400,400))

# add alpha channel    
img_org.putalpha(img_mask)

# save as png which keeps alpha channel 
img_org.save('output-pillow.png')

enter image description here


顺便说一句:

您可以使用 pillow 中的其他功能仅调整蒙版大小并保持心脏的原始比例。

黑色使全透明,白色保持原始颜色,但您也可以使用灰色使像素半透明。


编辑:

cv2相同

import cv2

# load images
img_org  = cv2.imread('temple.jpg')
img_mask = cv2.imread('heart.jpg')

# convert colors
#img_org  = cv2.cvtColor(img_org,???)
img_mask = cv2.cvtColor(img_mask,cv2.COLOR_BGR2GRAY)

# the same size
img_org  = cv2.resize(img_org,(400,400))
img_mask = cv2.resize(img_mask,400))

# add alpha channel 
b,g,r = cv2.split(img_org)
img_output = cv2.merge([b,r,img_mask],4)

# write as png which keeps alpha channel 
cv2.imwrite('output-cv2.png',img_output)

顺便说一句: cv2 使用 BGR 代替 og RGB

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...