OpenCV removing the background with a mask image

Viewed 5122

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?

3 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

Here is another way in Python OpenCV. Convert the image to BGRA and then insert the alpha channel.

result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask

Add alpha channel to your input image and copy mask into it.

Mat img;
cvtColor(imread("img.jpg", CV_LOAD_IMAGE_COLOR), img , cv::COLOR_RGB2RGBA);
Mat mask = imread("mask.jpg", CV_LOAD_IMAGE_GRAYSCALE);
for(int r = 0; r < img.rows; r++){
    for(int c = 0; c < img.cols; c++){
        uchar alpha = 0;
        if(r < mask.rows && c < mask.cols)
            alpha = mask.at<uchar>(r, c);
        img.at<Vec4b>(r, c)[3] = alpha;
    }
}
imwrite("result.png", img);

Btw your image doesn't have the same resolution as your mask, but still the result looks ok.

(I know it's not Python but there is c++ tag so... :D)

Related