Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

Python Image masking and removing Background

I have two images: the temple and the mask (the heart). I want to mask the temple with the shape of the heart and leave out the black background. The result should be a heart shaped cutout from the temple with a white or transparent background.

Background

White Heart


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use pillow and putalpha to add grayscale image (L) to RGB image as alpha channel - so it will have transparent background. But both images have to be the same size.

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


BTW:

You can use other functions in pillow to resize only mask and keep original proportions of heart.

Black color give full transparent, white color keep original color, but you can also gray colors to make pixel half-transparent.


EDIT:

The same with 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,400))

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

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

BTW: cv2 uses BGR instead og RGB


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...