Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV removing the background with a mask image

Given two input i. original image & ii. mask image, what's the best way to remove to the background from the original image.

Original Image

enter image description here

Mask Image

enter image description here

The final output would contain just the dog without the background and look transparent. I have seen the mask images are also created with OpenCV. Is there a way to just the existing mask image and generate the output image?

Update I tried this

import cv2

# opencv loads the image in BGR, convert it to RGB
img = cv2.imread("originalImage.png")
mask = cv2.imread("maskImage.png")
final = cv2.bitwise_and(img, mask)
cv2.imwrite("final.png", final)

Final Image

enter image description here

Is there a way to set the background to be transparent?

like image 827
DesperateLearner Avatar asked Jan 26 '23 04:01

DesperateLearner


1 Answers

You can create a transparent image by creating a 4-channel BGRA image and copying the first 3 channels from the original image and setting the alpha channel using the mask image.

transparent = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8)
transparent[:,:,0:3] = img
transparent[:, :, 3] = mask
like image 132
Baraa Avatar answered Jan 31 '23 16:01

Baraa