1+
2+ import cv2
3+ import time
4+ import numpy as np
5+
6+ ## Preparation for writing the ouput video
7+ fourcc = cv2 .VideoWriter_fourcc (* 'XVID' )
8+ out = cv2 .VideoWriter ('output.avi' , fourcc , 20.0 , (640 , 480 ))
9+
10+ ##reading from the webcam
11+ cap = cv2 .VideoCapture (0 )
12+
13+ ## Allow the system to sleep for 3 seconds before the webcam starts
14+ time .sleep (3 )
15+ count = 0
16+ background = 0
17+
18+ ## Capture the background in range of 60
19+ for i in range (60 ):
20+ ret , background = cap .read ()
21+ background = np .flip (background , axis = 1 )
22+
23+ ## Read every frame from the webcam, until the camera is open
24+ while (cap .isOpened ()):
25+ ret , img = cap .read ()
26+ if not ret :
27+ break
28+ count += 1
29+ img = np .flip (img , axis = 1 )
30+
31+ ## Convert the color space from BGR to HSV
32+ hsv = cv2 .cvtColor (img , cv2 .COLOR_BGR2HSV )
33+
34+ ## Generat masks to detect red color
35+ lower_red = np .array ([0 , 120 , 50 ])
36+ upper_red = np .array ([10 , 255 ,255 ])
37+ mask1 = cv2 .inRange (hsv , lower_red , upper_red )
38+
39+ lower_red = np .array ([170 , 120 , 70 ])
40+ upper_red = np .array ([180 , 255 , 255 ])
41+ mask2 = cv2 .inRange (hsv , lower_red , upper_red )
42+
43+ mask1 = mask1 + mask2
44+
45+ ## Open and Dilate the mask image
46+ mask1 = cv2 .morphologyEx (mask1 , cv2 .MORPH_OPEN , np .ones ((3 , 3 ), np .uint8 ))
47+ mask1 = cv2 .morphologyEx (mask1 , cv2 .MORPH_DILATE , np .ones ((3 , 3 ), np .uint8 ))
48+
49+ ## Create an inverted mask to segment out the red color from the frame
50+ mask2 = cv2 .bitwise_not (mask1 )
51+
52+ ## Segment the red color part out of the frame using bitwise and with the inverted mask
53+ res1 = cv2 .bitwise_and (img , img , mask = mask2 )
54+
55+ ## Create image showing static background frame pixels only for the masked region
56+ res2 = cv2 .bitwise_and (background , background , mask = mask1 )
57+
58+ ## Generating the final output and writing
59+ finalOutput = cv2 .addWeighted (res1 , 1 , res2 , 1 , 0 )
60+ out .write (finalOutput )
61+ cv2 .imshow ("magic" , finalOutput )
62+ cv2 .waitKey (1 )
63+
64+
65+ cap .release ()
66+ out .release ()
67+ cv2 .destroyAllWindows ()
68+
69+ #------------------------
70+ #colors code
71+
72+ #skin color
73+ #lower_red = np.array([0, 0, 70])
74+ #upper_red = np.array([100, 255,255])
75+ # mask1 = cv2.inRange(hsv, lower_red, upper_red)
76+
77+ # lower_red = np.array([170, 120, 70])
78+ # upper_red = np.array([180, 255, 255])
79+
80+ #-----------------------
0 commit comments