How to create mask from alpha channel in OpenCV?

I need to make a black and white mask for seamless clone, I have a png image, I need to convert it like these photos.

I didn’t find the cut photo, just imagine that there is a transparent background behind, it needs to be filled in black, and the girl in white

enter image description here enter image description here

1 answer

  • answered 2019-09-12 05:26 James

    Assuming your background is 100% transparent, the following example gives you a single channel mask with the dimensions of the image. Replaced 'girl.png' with the filename of your image.

    import cv2
    im = cv2.imread("girl.png", cv2.IMREAD_UNCHANGED)
    ret, mask = cv2.threshold(im[:, :, 3], 0, 255, cv2.THRESH_BINARY)