How to add background in webcam using python and opencv
I am trying to add video as background when (like this video https://www.youtube.com/watch?v=G_AVZ... am connecting to webcam. For this i did Background extraction first in this code i folow these steps
- First it will read the data from videos by using "VideoCapture"
- Next create and update the background model by using "createBackgroundSubtractorMOG2()" class because i am using opencv3
- Finally it will get and show the foreground mask by using "imshow"
- Then i added the background to the webcam
- It is not capturing frames in color In this the video is added as background but the webcam captures the frames in gray.
How to capture the frames in color and i am attaching my code and i tried using convert from grayscale to RGB but it is not working.
I am getting error like
\color.cpp:10655: error: (-215) scn == 1 && (dcn == 3 || dcn == 4) in function cv::cvtColor And here is my code
import cv2
import numpy as np
cap=cv2.VideoCapture(0)
fgbg=cv2.createBackgroundSubtractorMOG2()
history = 100
background_capture =
cv2.VideoCapture('/house.mp4')
while True:
frame = get_frame(cap, 0.5)
ret, background = background_capture.read()
background=cv2.resize(background, (640,480), interpolation =
cv2.INTER_AREA)
ret, frame = cap.read()
# gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
mask=fgbg.apply(frame,learningRate=1.0//history)
#convert from grayscale to RGB
gray=cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
bitwise= cv2.bitwise_and(background,background, mask = mask)
gaussian = cv2.GaussianBlur(bitwise, (5, 5), 10)
add=cv2.add(background,gaussian)
add=cv2.resize(add, (1366,768), interpolation = cv2.INTER_AREA)
cv2.imshow('add',add)
k=cv2.waitKey(30) & 0xff
if k==27:
break
cap.release()
cv2.destroyAllWindows()
i have no idea, why your webcam is showing grayscale (like) images only, but the error hints at it giving you 3channel (all identical) images, not single channel ones, thus your cvtColor conversion fails.
could you check this ?
Hi, thank you for your valuable reply, i am not getting RGB images using webcam i dont know why i am getting like this. any changes in code ??
can you check
frame.shape
?Yaa i checked using mask = np.zeros(frame.shape[:2], np.uint8) still i am not getting RGB image