Miroslav Purkrabek commited on
Commit
73e5f29
·
1 Parent(s): 057cfaa

add webcam demo app

Browse files
Files changed (1) hide show
  1. webcam_remote_demo.py +294 -0
webcam_remote_demo.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ from fastrtc import WebRTC
4
+ import time
5
+ import threading
6
+ import numpy as np
7
+ import mmcv
8
+ from time import sleep
9
+
10
+ from mmpose.apis import inference_topdown
11
+ from mmpose.apis import init_model as init_pose_estimator
12
+ from mmpose.evaluation.functional import nms
13
+ from mmpose.registry import VISUALIZERS
14
+ from mmpose.structures import merge_data_samples
15
+ from mmpose.utils import adapt_mmdet_pipeline
16
+ import hashlib
17
+
18
+ try:
19
+ from mmdet.apis import inference_detector, init_detector
20
+ has_mmdet = True
21
+ except (ImportError, ModuleNotFoundError):
22
+ has_mmdet = False
23
+
24
+ DET_CFG = "demo/mmdetection_cfg/rtmdet_m_640-8xb32_coco-person.py"
25
+ DET_WEIGHTS = "https://download.openmmlab.com/mmpose/v1/projects/rtmpose/rtmdet_m_8xb32-100e_coco-obj365-person-235e8209.pth"
26
+
27
+ POSE_CFG = "configs/body_2d_keypoint/topdown_probmap/coco/td-pm_ProbPose-small_8xb64-210e_coco-256x192.py"
28
+ POSE_WEIGHTS = "models/ProbPose-s.pth"
29
+
30
+ DEVICE = 'cuda:0'
31
+
32
+ # WebRTC configuration for webcam streaming
33
+ rtc_configuration = None
34
+ webcam_constraints = {
35
+ "video": {
36
+ "width": {"exact": 320},
37
+ "height": {"exact": 240},
38
+ "sampleRate": {"ideal": 2, "max": 5}
39
+ }
40
+ }
41
+
42
+
43
+ class AsyncFrameProcessor:
44
+ """
45
+ Asynchronous frame processor that handles real-time video stream processing.
46
+
47
+ Maintains single-slot input and output queues to process only the latest frame,
48
+ preventing queue buildup and ensuring real-time performance.
49
+ """
50
+
51
+ def __init__(self, processing_delay=0.5, startup_delay=0.0):
52
+ """
53
+ Initialize the async frame processor.
54
+
55
+ Args:
56
+ processing_delay (float): Simulated processing time in seconds
57
+ startup_delay (float): Delay before processing starts
58
+ """
59
+ self.processing_delay = processing_delay
60
+ self.startup_delay = startup_delay
61
+ self.first_call_time = None
62
+ self.frame_counter = 0
63
+
64
+ # Thread-safe single-slot queues
65
+ self.input_lock = threading.Lock()
66
+ self.output_lock = threading.Lock()
67
+ self.latest_input_frame = None
68
+ self.latest_output_frame = None
69
+
70
+ # Threading components
71
+ self.processing_thread = None
72
+ self.stop_event = threading.Event()
73
+ self.new_frame_signal = threading.Event()
74
+
75
+ # Detector and pose estimator models
76
+ self.pose_model = None
77
+ self.det_model = None
78
+ self.visualizer = None
79
+ self.init_models()
80
+
81
+ # Start background processing
82
+ self._start_processing_thread()
83
+
84
+ def _start_processing_thread(self):
85
+ """Start the background processing thread"""
86
+ if self.processing_thread is None or not self.processing_thread.is_alive():
87
+ self.stop_event.clear()
88
+ self.processing_thread = threading.Thread(target=self._processing_worker, daemon=True)
89
+ self.processing_thread.start()
90
+
91
+ def _processing_worker(self):
92
+ """Background thread that processes the latest frame"""
93
+ while not self.stop_event.is_set():
94
+ # Wait for a new frame to be available
95
+ if self.new_frame_signal.wait(timeout=1.0):
96
+ self.new_frame_signal.clear()
97
+
98
+ # Get the latest input frame
99
+ with self.input_lock:
100
+ if self.latest_input_frame is not None:
101
+ frame_to_process = self.latest_input_frame.copy()
102
+ frame_number = self.frame_counter
103
+ process_unique_hash = hashlib.md5(frame_to_process.tobytes()).hexdigest()
104
+ # print(f"Processing unique hash: {process_unique_hash}")
105
+
106
+ else:
107
+ continue
108
+
109
+ # Process the frame
110
+ processed_frame = self._process_frame(frame_to_process)
111
+
112
+ # Write frame number in the top left corner
113
+ processed_frame = cv2.putText(
114
+ processed_frame,
115
+ "{:d}".format(frame_number),
116
+ [50, 50],
117
+ fontFace=cv2.FONT_HERSHEY_SIMPLEX,
118
+ fontScale=1,
119
+ color=(0, 0, 255),
120
+ thickness=2,
121
+ )
122
+
123
+ # Store the processed result
124
+ with self.output_lock:
125
+ self.latest_output_frame = processed_frame
126
+
127
+ def _process_frame(self, frame, bbox_thr=0.3, nms_thr=0.8, kpt_thr=0.3):
128
+ # predict bbox
129
+ processing_start = time.time()
130
+
131
+ # Mirror the frame
132
+ frame = frame[:, ::-1, :] # Flip horizontally for webcam mirroring
133
+
134
+ det_result = inference_detector(self.det_model, frame)
135
+ pred_instance = det_result.pred_instances.cpu().numpy( )
136
+ bboxes = np.concatenate(
137
+ (pred_instance.bboxes, pred_instance.scores[:, None]), axis=1)
138
+ bboxes = bboxes[np.logical_and(pred_instance.labels == 0,
139
+ pred_instance.scores > bbox_thr)]
140
+ # Sort bboxes by confidence score (column 4) in descending order
141
+ order = np.argsort(bboxes[:, 4])[::-1]
142
+ bboxes = bboxes[order[0], :4].reshape((1, -1))
143
+
144
+ self.visualizer.set_image(frame)
145
+
146
+ # predict keypoints
147
+ pose_start = time.time()
148
+ pose_results = inference_topdown(self.pose_model, frame, bboxes)
149
+ data_samples = merge_data_samples(pose_results)
150
+
151
+ # Visualize results
152
+ visualization_start = time.time()
153
+ self.visualizer.add_datasample(
154
+ 'result',
155
+ frame,
156
+ data_sample=data_samples,
157
+ draw_gt=False,
158
+ draw_heatmap=False,
159
+ draw_bbox=True,
160
+ show_kpt_idx=False,
161
+ show=False,
162
+ kpt_thr=kpt_thr)
163
+
164
+ stop_time = time.time()
165
+ # print("Processing time: {:.3f}\tDetection time {:.3f}\tPose time: {:.3f}\tVisualization time: {:.3f}".format(
166
+ # stop_time - processing_start,
167
+ # pose_start - processing_start,
168
+ # visualization_start - pose_start,
169
+ # stop_time - visualization_start,
170
+ # ))
171
+ return self.visualizer.get_image()
172
+
173
+
174
+
175
+ def process(self, frame):
176
+ """
177
+ Main processing function called by Gradio stream.
178
+ Stores incoming frame and returns latest processed result.
179
+ """
180
+ current_time = time.time()
181
+ if self.first_call_time is None:
182
+ self.first_call_time = current_time
183
+
184
+ # Store the new frame in the input slot (replacing any existing frame)
185
+ with self.input_lock:
186
+ self.latest_input_frame = frame.copy()
187
+ self.frame_counter += 1
188
+ input_unique_hash = hashlib.md5(frame.tobytes()).hexdigest()
189
+ # print(f"Input unique hash: {input_unique_hash}")
190
+
191
+ # Signal that a new frame is available for processing
192
+ self.new_frame_signal.set()
193
+
194
+ # Return the latest processed output, or original frame if no processing done yet
195
+ with self.output_lock:
196
+ if self.latest_output_frame is not None:
197
+ output_unique_hash = hashlib.md5(self.latest_output_frame.tobytes()).hexdigest()
198
+ # print(f"Output unique hash: {output_unique_hash}")
199
+ return self.latest_output_frame
200
+ else:
201
+ # Add indicator that this is unprocessed
202
+ temp_frame = frame.copy()
203
+ cv2.putText(
204
+ temp_frame,
205
+ f"Waiting... {self.frame_counter}",
206
+ (50, 50),
207
+ cv2.FONT_HERSHEY_SIMPLEX,
208
+ 1,
209
+ (255, 0, 0), # Red for unprocessed frames
210
+ 2,
211
+ )
212
+ return temp_frame
213
+
214
+ def stop(self):
215
+ """Stop the processing thread"""
216
+ self.stop_event.set()
217
+ if self.processing_thread and self.processing_thread.is_alive():
218
+ self.processing_thread.join(timeout=2.0)
219
+
220
+ def init_models(self):
221
+ # Init detector
222
+ if self.det_model is None:
223
+ print("Initializing MMDetection detector...")
224
+ self.det_model = init_detector(DET_CFG, DET_WEIGHTS, device=DEVICE)
225
+ self.det_model.cfg = adapt_mmdet_pipeline(self.det_model.cfg)
226
+ print("Detector initialized successfully!")
227
+
228
+ # Init pose estimator
229
+ if self.pose_model is None:
230
+ print("Initializing MMPose estimator...")
231
+ self.pose_model = init_pose_estimator(
232
+ POSE_CFG,
233
+ POSE_WEIGHTS,
234
+ device=DEVICE,
235
+ cfg_options=dict(model=dict(test_cfg=dict(output_heatmaps=True)))
236
+ )
237
+
238
+ # Build visualizer
239
+ self.pose_model.cfg.visualizer.radius = 4
240
+ self.pose_model.cfg.visualizer.alpha = 0.8
241
+ self.pose_model.cfg.visualizer.line_width = 2
242
+ self.visualizer = VISUALIZERS.build(self.pose_model.cfg.visualizer)
243
+ self.visualizer.set_dataset_meta(
244
+ self.pose_model.dataset_meta, skeleton_style='mmpose'
245
+ )
246
+ print("Pose estimator initialized successfully!")
247
+
248
+
249
+ # CSS for styling the Gradio interface
250
+ css = """.my-group {max-width: 600px !important; max-height: 600 !important;}
251
+ .my-column {display: flex !important; justify-content: center !important; align-items: center !important};"""
252
+
253
+ # Initialize the asynchronous frame processor
254
+ frame_processor = AsyncFrameProcessor(processing_delay=0.5)
255
+
256
+ # Create Gradio interface
257
+ with gr.Blocks(css=css) as demo:
258
+ gr.HTML(
259
+ """
260
+ <h1 style='text-align: center'>
261
+ Async Frame Processing Demo (Powered by WebRTC ⚡️)
262
+ </h1>
263
+ """
264
+ )
265
+ gr.HTML(
266
+ """
267
+ <h3 style='text-align: center'>
268
+ Real-time frame processing with single-slot queues
269
+ </h3>
270
+ """
271
+ )
272
+ with gr.Column(elem_classes=["my-column"]):
273
+ with gr.Group(elem_classes=["my-group"]):
274
+ webcam_stream = WebRTC(
275
+ label="Webcam Stream",
276
+ rtc_configuration=rtc_configuration,
277
+ track_constraints=webcam_constraints,
278
+ mirror_webcam=True,
279
+ )
280
+
281
+ # Stream processing: connects webcam input to frame processor
282
+ webcam_stream.stream(
283
+ fn=frame_processor.process,
284
+ inputs=[webcam_stream],
285
+ outputs=[webcam_stream],
286
+ time_limit=None
287
+ )
288
+
289
+ if __name__ == "__main__":
290
+ demo.launch(
291
+ # server_name="0.0.0.0",
292
+ # server_port=17860,
293
+ share=True
294
+ )