Opencv / python: mask in cv2 module when streaming video in webcams

Hi everyone, I'm trying to make a game using my webcam, where I need some objects to fall on the screen while I broadcast the video using my webcam (this stream was my background).

I am using python and the opencv cv2 module

The question arises: how to apply a mask to these objects? I already have an image that is the mask of the original image, but I don’t know how to apply it to subtract the background of the original image.

ive already tried using cv2.bitwise_and, but nothing happened, the image was displayed on a black background:

#targets original_ball = cv2.imread("Aqua-Ball-Red-icon.png") ball = cv2.resize(bola_original, (64,64), fx=1, fy=1) #mask mask_original = cv2.imread("input-mask.png",0) mask = cv2.resize(mask_original, (64,64), fx=1, fy=1) res = cv2.bitwise_and(ball, ball, mask = mask) 

Thanks in advance!

+4
source share
2 answers

If you use cv2 , you are working with numpy arrays, and there is no need to access opencv for something as simple as a mask.

First, manipulate (possibly multiply) your array of masks so that the values ​​you want (that is, those that are not masked) have a value of 1. Then multiply the original image by your mask. This will make the resulting image have the original pixels, where masks == 1 and 0 (i.e.: black), where mask == 0.

Here is its essence:

 import numpy original_ball = cv2.imread("Aqua-Ball-Red-icon.png") ball = cv2.resize(bola_original, (64,64), fx=1, fy=1) mask_original = cv2.imread("input-mask.png",0) mask = cv2.resize(mask_original, (64,64), fx=1, fy=1) max_value= numpy.max(mask) mask/=max_value res= ball*mask 

Depending on the color depth of your input-mask.png, you may need to first reduce it in shades of gray

+1
source

The mask did not appear due to argument 0 next to the mask image name).

+1
source

All Articles