TDN-M commited on
Commit
24ab450
·
verified ·
1 Parent(s): 637c13d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -5
app.py CHANGED
@@ -1,7 +1,127 @@
1
- import gradio as gr
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import mediapipe as mp
3
+ import numpy as np
4
 
 
 
5
 
6
+ def list_connected_cameras():
7
+ """
8
+ Lists all connected cameras by attempting to open camera indexes sequentially.
9
+
10
+ Returns:
11
+ list[int]: A list of valid camera indexes.
12
+ """
13
+ index = 0
14
+ valid_cameras = []
15
+ while True:
16
+ cap = cv2.VideoCapture(index)
17
+ if cap.isOpened():
18
+ ret, _ = cap.read()
19
+ if ret:
20
+ valid_cameras.append(index)
21
+ cap.release()
22
+ else:
23
+ break
24
+ index += 1
25
+ return valid_cameras
26
+
27
+
28
+ def main():
29
+ """
30
+ Main function for real-time background removal. It allows the user to:
31
+ - Select a camera index.
32
+ - Perform segmentation on the video feed.
33
+ - Replace the background with a solid green screen.
34
+ - View the processed output in real-time.
35
+ """
36
+ # Step 1: Detect available cameras
37
+ cameras = list_connected_cameras()
38
+ if not cameras:
39
+ print("No cameras found!")
40
+ return
41
+
42
+ print("Available camera indexes:", cameras)
43
+
44
+ # Step 2: Prompt the user to select a camera
45
+ cam_index = None
46
+ while cam_index not in cameras:
47
+ try:
48
+ cam_index = int(input(f"Select a camera index from the above list: "))
49
+ except ValueError:
50
+ print("Invalid input. Please enter a valid camera index.")
51
+
52
+ # Step 3: Open the selected camera
53
+ cap = cv2.VideoCapture(cam_index)
54
+ if not cap.isOpened():
55
+ print(f"Failed to open camera with index {cam_index}")
56
+ return
57
+
58
+ # Step 4: Initialize MediaPipe Selfie Segmentation
59
+ mp_selfie_segmentation = mp.solutions.selfie_segmentation
60
+ selfie_segmentation = mp_selfie_segmentation.SelfieSegmentation(model_selection=1)
61
+
62
+ # Background color (green screen)
63
+ bg_color = (0, 255, 0)
64
+
65
+ # Temporal smoothing setup
66
+ prev_blurred_mask = None # Store the previous mask for smoothing
67
+ alpha = 0.6 # Blending factor for smoothing
68
+
69
+ # Morphological erosion parameters
70
+ erosion_kernel_size = 5 # Kernel size for erosion
71
+ erosion_iterations = 1 # Number of erosion iterations
72
+ erosion_kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (erosion_kernel_size, erosion_kernel_size))
73
+
74
+ print("Press 'q' to exit.")
75
+
76
+ while True:
77
+ # Step 5: Capture a frame from the camera
78
+ ret, frame = cap.read()
79
+ if not ret:
80
+ print("Failed to read from camera. Exiting...")
81
+ break
82
+
83
+ # Step 6: Convert BGR to RGB for MediaPipe processing
84
+ rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
85
+
86
+ # Step 7: Perform segmentation to obtain the mask
87
+ results = selfie_segmentation.process(rgb_frame)
88
+ mask = results.segmentation_mask # Values range from 0.0 to 1.0
89
+
90
+ # Step 8: Smooth the mask with Gaussian blur
91
+ blurred_mask = cv2.GaussianBlur(mask, (15, 15), 0)
92
+
93
+ # Step 9: Apply temporal smoothing
94
+ if prev_blurred_mask is not None:
95
+ blurred_mask = alpha * prev_blurred_mask + (1 - alpha) * blurred_mask
96
+ prev_blurred_mask = blurred_mask
97
+
98
+ # Step 10: Threshold the mask to create a binary condition
99
+ threshold_value = 0.5
100
+ condition = blurred_mask > threshold_value
101
+
102
+ # Step 11: Refine the mask using morphological erosion
103
+ mask_uint8 = (condition.astype(np.uint8)) * 255 # Convert to 0-255
104
+ eroded_mask = cv2.erode(mask_uint8, erosion_kernel, iterations=erosion_iterations)
105
+ final_condition = eroded_mask > 128 # Convert back to a boolean condition
106
+
107
+ # Step 12: Create a green background
108
+ bg_frame = np.zeros(frame.shape, dtype=np.uint8)
109
+ bg_frame[:] = bg_color
110
+
111
+ # Step 13: Blend the original frame and the green background
112
+ output_frame = np.where(final_condition[..., None], frame, bg_frame)
113
+
114
+ # Step 14: Display the output frame
115
+ cv2.imshow("Green Background - Eroded Mask", output_frame)
116
+
117
+ # Exit the loop when 'q' is pressed
118
+ if cv2.waitKey(1) & 0xFF == ord('q'):
119
+ break
120
+
121
+ # Cleanup resources
122
+ cap.release()
123
+ cv2.destroyAllWindows()
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()