JBJ
JBJ

Reputation: 288

OpenCV remove background preserving the foreground

I'm new to openCv and I'm trying to extract myself from the background in a video that I got from my webcam. So far I'm able to remove background while the foreground(video of me) is still appearing in white. I want it to be exactly like it was in the original video. Below is my current code:

fgbg = cv2.createBackgroundSubtractorMOG2()

while(1):
ret, frame = cap.read()

fgmask = fgbg.apply(frame)

cv2.imshow('fgmask',frame)
cv2.imshow('frame',fgmask)

Any hint or some sense of direction will be much appreciated.

Upvotes: 0

Views: 2321

Answers (1)

Petr Blahos
Petr Blahos

Reputation: 2433

fgmask is a white mask of the foreground. You must mask your original frame with this mask. Now, the frame is an RGB or possibly a BGR image, while the mask is a single channel (you can check by printing frame.shape and fgmask.shape). Therefore you must convert the mask to RGB and then apply the mask:

mask_rgb = cv2.cvtColor(fgmask, cv2.COLOR_GRAY2RGB)
out_frame = cv2.bitwise_and(frame, mask_rgb)
cv2.imshow("FG", out_frame)

Upvotes: 3

Related Questions