1import cv2
2import time
3import numpy as np
4
5
6# Get the webcam
7cap = cv2.VideoCapture(0)
8
9# Time is just used to get the Frames Per Second (FPS)
10last_time = time.time()
11while True:
12 # Step 1: Capture the frame
13 _, frame = cap.read()
14
15 # Step 2: Convert to the HSV color space
16 hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
17 # Step 3: Create a mask based on medium to high Saturation and Value
18 # - These values can be changed (the lower ones) to fit your environment
19 mask = cv2.inRange(hsv, (0, 75, 40), (180, 255, 255))
20 # We need a to copy the mask 3 times to fit the frames
21 mask_3d = np.repeat(mask[:, :, np.newaxis], 3, axis=2)
22 # Step 4: Create a blurred frame using Gaussian blur
23 blurred_frame = cv2.GaussianBlur(frame, (25, 25), 0)
24 # Step 5: Combine the original with the blurred frame based on mask
25 frame = np.where(mask_3d == (255, 255, 255), frame, blurred_frame)
26
27 # Add a FPS label to image
28 text = f"FPS: {int(1 / (time.time() - last_time))}"
29 last_time = time.time()
30 cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)
31
32 # Step 6: Show the frame with blurred background
33 cv2.imshow("Webcam", frame)
34 # If q is pressed terminate
35 if cv2.waitKey(1) == ord('q'):
36 break
37
38# Release and destroy all windows
39cap.release()
40cv2.destroyAllWindows()
41