At first create a new folder and save it by .py extension.
Click on the terminal -> New terminal option.
Now enter the following two commands in the terminal section.
# pip install opencv-python
# pip install numpy
After that start typing the following code :
##importing opencv library
import cv2
##imorting numpy library as np
import numpy as np
##capturing frames from webcam
cap = cv2.VideoCapture(0)
for i in range(60):
##capture the background of range 60
##dedicated to bachground frame so that it could easily save the background image
ret, background = cap.read()
if ret == False:
continue
while True:
ret,frame=cap.read()
##convert the color space from BGR to HSV
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
##Generate mask to detect blue color
##It works for blue color
## range of HSV value of colour (If something of that colour comes it becomes invisible)
lb = np.array([110,50,50])
mask = cv2.inRange(hsv, lb, ub)
#Dilate Filter
##basic image processing operator for accuracy
mask = cv2.dilate(mask, np.ones((3, 3), np.uint8), iterations = 1)
#Closing Filter
kernal = np.ones((3, 3), np.uint8)
##basic image processing operator for accuracy
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernal)
mask1 = cv2.bitwise_not(mask)
##generating the final output
res1 = cv2.bitwise_and(background, background, mask = mask)
res2 = cv2.bitwise_and(frame, frame, mask = mask1)
final_output = cv2.addWeighted(res1, 1, res2, 1, 0)
##0 means saved video and if from webcam then 1
cv2.imshow('result',final_output)
## waitkey means setting the frame rate and q is the escapeor exit key
if cv2.waitKey(25) & 0xFF == ord('q'):
break