Spaces:
Running
on
Zero
Running
on
Zero
Add tracking
Browse files- app.py +114 -16
- requirements.txt +2 -1
app.py
CHANGED
@@ -6,6 +6,7 @@ import logging
|
|
6 |
|
7 |
import torch
|
8 |
import spaces
|
|
|
9 |
import numpy as np
|
10 |
import gradio as gr
|
11 |
import imageio.v3 as iio
|
@@ -61,13 +62,29 @@ BATCH_SIZE = 4
|
|
61 |
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov"}
|
62 |
VIDEO_OUTPUT_DIR = Path("static/videos")
|
63 |
VIDEO_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
VIDEO_EXAMPLES = [
|
65 |
-
{"path": "./examples/videos/dogs_running.mp4", "label": "Local Video"},
|
66 |
-
{"path": "./examples/videos/traffic.mp4", "label": "Local Video"},
|
67 |
-
{"path": "./examples/videos/fast_and_furious.mp4", "label": "Local Video"},
|
68 |
-
{"path": "./examples/videos/break_dance.mp4", "label": "Local Video"},
|
69 |
]
|
70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
logging.basicConfig(
|
72 |
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
73 |
)
|
@@ -88,12 +105,21 @@ def detect_objects(
|
|
88 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
89 |
target_size: Optional[Tuple[int, int]] = None,
|
90 |
batch_size: int = BATCH_SIZE,
|
|
|
91 |
):
|
92 |
|
93 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
94 |
model, image_processor = get_model_and_processor(checkpoint)
|
95 |
model = model.to(device)
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
if isinstance(images, np.ndarray) and images.ndim == 4:
|
98 |
images = [x for x in images] # split video array into list of images
|
99 |
|
@@ -125,6 +151,9 @@ def detect_objects(
|
|
125 |
# move results to cpu
|
126 |
for i, result in enumerate(results):
|
127 |
results[i] = {k: v.cpu() for k, v in result.items()}
|
|
|
|
|
|
|
128 |
|
129 |
return results, model.config.id2label
|
130 |
|
@@ -201,9 +230,34 @@ def read_video_k_frames(video_path: str, k: int, read_every_i_frame: int = 1):
|
|
201 |
return frames
|
202 |
|
203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
def process_video(
|
205 |
video_path: str,
|
206 |
checkpoint: str,
|
|
|
|
|
207 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
208 |
progress: gr.Progress = gr.Progress(track_tqdm=True),
|
209 |
) -> str:
|
@@ -224,23 +278,51 @@ def process_video(
|
|
224 |
frames = read_video_k_frames(video_path, n_frames_to_read, read_each_i_frame)
|
225 |
frames = [cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_CUBIC) for frame in frames]
|
226 |
|
227 |
-
|
228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
|
230 |
results, id2label = detect_objects(
|
231 |
images=np.array(frames),
|
232 |
checkpoint=checkpoint,
|
233 |
confidence_threshold=confidence_threshold,
|
234 |
target_size=(target_height, target_width),
|
|
|
235 |
)
|
236 |
|
|
|
237 |
annotated_frames = []
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
244 |
|
245 |
output_filename = os.path.join(VIDEO_OUTPUT_DIR, f"output_{uuid.uuid4()}.mp4")
|
246 |
iio.imwrite(output_filename, annotated_frames, fps=target_fps, codec="h264")
|
@@ -296,6 +378,18 @@ def create_video_inputs() -> List[gr.components.Component]:
|
|
296 |
value=DEFAULT_CHECKPOINT,
|
297 |
elem_classes="input-component",
|
298 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
299 |
gr.Slider(
|
300 |
minimum=0.1,
|
301 |
maximum=1.0,
|
@@ -380,7 +474,7 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
|
|
380 |
with gr.Row():
|
381 |
with gr.Column(scale=1, min_width=300):
|
382 |
with gr.Group():
|
383 |
-
video_input, video_checkpoint, video_confidence_threshold = create_video_inputs()
|
384 |
video_detect_button, video_clear_button = create_button_row()
|
385 |
with gr.Column(scale=2):
|
386 |
video_output = gr.Video(
|
@@ -391,10 +485,10 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
|
|
391 |
|
392 |
gr.Examples(
|
393 |
examples=[
|
394 |
-
[example["path"], DEFAULT_CHECKPOINT, DEFAULT_CONFIDENCE_THRESHOLD]
|
395 |
for example in VIDEO_EXAMPLES
|
396 |
],
|
397 |
-
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
398 |
outputs=[video_output],
|
399 |
fn=process_video,
|
400 |
cache_examples=False,
|
@@ -433,12 +527,16 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
|
|
433 |
fn=lambda: (
|
434 |
None,
|
435 |
DEFAULT_CHECKPOINT,
|
|
|
|
|
436 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
437 |
None,
|
438 |
),
|
439 |
outputs=[
|
440 |
video_input,
|
441 |
video_checkpoint,
|
|
|
|
|
442 |
video_confidence_threshold,
|
443 |
video_output,
|
444 |
],
|
@@ -460,7 +558,7 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
|
|
460 |
# Video detect button
|
461 |
video_detect_button.click(
|
462 |
fn=process_video,
|
463 |
-
inputs=[video_input, video_checkpoint, video_confidence_threshold],
|
464 |
outputs=[video_output],
|
465 |
)
|
466 |
|
|
|
6 |
|
7 |
import torch
|
8 |
import spaces
|
9 |
+
import trackers
|
10 |
import numpy as np
|
11 |
import gradio as gr
|
12 |
import imageio.v3 as iio
|
|
|
62 |
ALLOWED_VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov"}
|
63 |
VIDEO_OUTPUT_DIR = Path("static/videos")
|
64 |
VIDEO_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
65 |
+
|
66 |
+
class TrackingAlgorithm:
|
67 |
+
BYTETRACK = "ByteTrack (2021)"
|
68 |
+
DEEPSORT = "DeepSORT (2017)"
|
69 |
+
SORT = "SORT (2016)"
|
70 |
+
|
71 |
+
TRACKERS = [None, TrackingAlgorithm.BYTETRACK, TrackingAlgorithm.DEEPSORT, TrackingAlgorithm.SORT]
|
72 |
VIDEO_EXAMPLES = [
|
73 |
+
{"path": "./examples/videos/dogs_running.mp4", "label": "Local Video", "tracker": None, "classes": "all"},
|
74 |
+
{"path": "./examples/videos/traffic.mp4", "label": "Local Video", "tracker": TrackingAlgorithm.BYTETRACK, "classes": "car, truck, bus"},
|
75 |
+
{"path": "./examples/videos/fast_and_furious.mp4", "label": "Local Video", "tracker": None, "classes": "all"},
|
76 |
+
{"path": "./examples/videos/break_dance.mp4", "label": "Local Video", "tracker": None, "classes": "all"},
|
77 |
]
|
78 |
|
79 |
+
|
80 |
+
# Create a color palette for visualization
|
81 |
+
# These hex color codes define different colors for tracking different objects
|
82 |
+
color = sv.ColorPalette.from_hex([
|
83 |
+
"#ffff00", "#ff9b00", "#ff8080", "#ff66b2", "#ff66ff", "#b266ff",
|
84 |
+
"#9999ff", "#3399ff", "#66ffff", "#33ff99", "#66ff66", "#99ff00"
|
85 |
+
])
|
86 |
+
|
87 |
+
|
88 |
logging.basicConfig(
|
89 |
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
90 |
)
|
|
|
105 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
106 |
target_size: Optional[Tuple[int, int]] = None,
|
107 |
batch_size: int = BATCH_SIZE,
|
108 |
+
classes: Optional[List[str]] = None,
|
109 |
):
|
110 |
|
111 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
112 |
model, image_processor = get_model_and_processor(checkpoint)
|
113 |
model = model.to(device)
|
114 |
|
115 |
+
if classes is not None:
|
116 |
+
wrong_classes = [cls for cls in classes if cls not in model.config.label2id]
|
117 |
+
if wrong_classes:
|
118 |
+
gr.Warning(f"Classes not found in model config: {wrong_classes}")
|
119 |
+
keep_ids = [model.config.label2id[cls] for cls in classes if cls in model.config.label2id]
|
120 |
+
else:
|
121 |
+
keep_ids = None
|
122 |
+
|
123 |
if isinstance(images, np.ndarray) and images.ndim == 4:
|
124 |
images = [x for x in images] # split video array into list of images
|
125 |
|
|
|
151 |
# move results to cpu
|
152 |
for i, result in enumerate(results):
|
153 |
results[i] = {k: v.cpu() for k, v in result.items()}
|
154 |
+
if keep_ids is not None:
|
155 |
+
keep = torch.isin(results[i]["labels"], torch.tensor(keep_ids))
|
156 |
+
results[i] = {k: v[keep] for k, v in results[i].items()}
|
157 |
|
158 |
return results, model.config.id2label
|
159 |
|
|
|
230 |
return frames
|
231 |
|
232 |
|
233 |
+
def get_tracker(tracker: str, fps: float):
|
234 |
+
if tracker == TrackingAlgorithm.SORT:
|
235 |
+
return trackers.SORTTracker(frame_rate=fps)
|
236 |
+
elif tracker == TrackingAlgorithm.DEEPSORT:
|
237 |
+
feature_extractor = trackers.DeepSORTFeatureExtractor.from_timm("mobilenetv4_conv_small.e1200_r224_in1k", device="cpu")
|
238 |
+
return trackers.DeepSORTTracker(feature_extractor, frame_rate=fps)
|
239 |
+
elif tracker == TrackingAlgorithm.BYTETRACK:
|
240 |
+
return sv.ByteTrack(frame_rate=int(fps))
|
241 |
+
else:
|
242 |
+
raise ValueError(f"Invalid tracker: {tracker}")
|
243 |
+
|
244 |
+
|
245 |
+
def update_tracker(tracker, detections, frame):
|
246 |
+
if isinstance(tracker, trackers.SORTTracker):
|
247 |
+
return tracker.update(detections)
|
248 |
+
elif isinstance(tracker, trackers.DeepSORTTracker):
|
249 |
+
return tracker.update(detections, frame)
|
250 |
+
elif isinstance(tracker, sv.ByteTrack):
|
251 |
+
return tracker.update_with_detections(detections)
|
252 |
+
else:
|
253 |
+
raise ValueError(f"Invalid tracker: {tracker}")
|
254 |
+
|
255 |
+
|
256 |
def process_video(
|
257 |
video_path: str,
|
258 |
checkpoint: str,
|
259 |
+
tracker_algorithm: Optional[str] = None,
|
260 |
+
classes: str = "all",
|
261 |
confidence_threshold: float = DEFAULT_CONFIDENCE_THRESHOLD,
|
262 |
progress: gr.Progress = gr.Progress(track_tqdm=True),
|
263 |
) -> str:
|
|
|
278 |
frames = read_video_k_frames(video_path, n_frames_to_read, read_each_i_frame)
|
279 |
frames = [cv2.resize(frame, (target_width, target_height), interpolation=cv2.INTER_CUBIC) for frame in frames]
|
280 |
|
281 |
+
# Set the color lookup mode to assign colors by track ID
|
282 |
+
# This mean objects with the same track ID will be annotated by the same color
|
283 |
+
color_lookup = sv.ColorLookup.TRACK if tracker_algorithm else sv.ColorLookup.CLASS
|
284 |
+
|
285 |
+
box_annotator = sv.BoxAnnotator(color, color_lookup=color_lookup, thickness=1)
|
286 |
+
label_annotator = sv.LabelAnnotator(color, color_lookup=color_lookup, text_scale=0.5)
|
287 |
+
trace_annotator = sv.TraceAnnotator(color, color_lookup=color_lookup, thickness=1, trace_length=100)
|
288 |
+
|
289 |
+
# preprocess classes
|
290 |
+
if classes != "all":
|
291 |
+
classes_list = [cls.strip().lower() for cls in classes.split(",")]
|
292 |
+
else:
|
293 |
+
classes_list = None
|
294 |
|
295 |
results, id2label = detect_objects(
|
296 |
images=np.array(frames),
|
297 |
checkpoint=checkpoint,
|
298 |
confidence_threshold=confidence_threshold,
|
299 |
target_size=(target_height, target_width),
|
300 |
+
classes=classes_list,
|
301 |
)
|
302 |
|
303 |
+
|
304 |
annotated_frames = []
|
305 |
+
|
306 |
+
# detections
|
307 |
+
if tracker_algorithm:
|
308 |
+
tracker = get_tracker(tracker_algorithm, target_fps)
|
309 |
+
for frame, result in progress.tqdm(zip(frames, results), desc="Tracking objects", total=len(frames)):
|
310 |
+
detections = sv.Detections.from_transformers(result, id2label=id2label)
|
311 |
+
detections = detections.with_nms(threshold=0.95, class_agnostic=True)
|
312 |
+
detections = update_tracker(tracker, detections, frame)
|
313 |
+
labels = [f"#{tracker_id} {id2label[class_id]}" for class_id, tracker_id in zip(detections.class_id, detections.tracker_id)]
|
314 |
+
annotated_frame = box_annotator.annotate(scene=frame, detections=detections)
|
315 |
+
annotated_frame = label_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels)
|
316 |
+
annotated_frame = trace_annotator.annotate(scene=annotated_frame, detections=detections)
|
317 |
+
annotated_frames.append(annotated_frame)
|
318 |
+
|
319 |
+
else:
|
320 |
+
for frame, result in tqdm.tqdm(zip(frames, results), desc="Annotating frames", total=len(frames)):
|
321 |
+
detections = sv.Detections.from_transformers(result, id2label=id2label)
|
322 |
+
detections = detections.with_nms(threshold=0.95, class_agnostic=True)
|
323 |
+
annotated_frame = box_annotator.annotate(scene=frame, detections=detections)
|
324 |
+
annotated_frame = label_annotator.annotate(scene=annotated_frame, detections=detections)
|
325 |
+
annotated_frames.append(annotated_frame)
|
326 |
|
327 |
output_filename = os.path.join(VIDEO_OUTPUT_DIR, f"output_{uuid.uuid4()}.mp4")
|
328 |
iio.imwrite(output_filename, annotated_frames, fps=target_fps, codec="h264")
|
|
|
378 |
value=DEFAULT_CHECKPOINT,
|
379 |
elem_classes="input-component",
|
380 |
),
|
381 |
+
gr.Dropdown(
|
382 |
+
choices=TRACKERS,
|
383 |
+
label="Select Tracker (Optional)",
|
384 |
+
value=None,
|
385 |
+
elem_classes="input-component",
|
386 |
+
),
|
387 |
+
gr.TextArea(
|
388 |
+
label="Specify Class Names to Detect (comma separated)",
|
389 |
+
value="all",
|
390 |
+
lines=1,
|
391 |
+
elem_classes="input-component",
|
392 |
+
),
|
393 |
gr.Slider(
|
394 |
minimum=0.1,
|
395 |
maximum=1.0,
|
|
|
474 |
with gr.Row():
|
475 |
with gr.Column(scale=1, min_width=300):
|
476 |
with gr.Group():
|
477 |
+
video_input, video_checkpoint, video_tracker, video_classes, video_confidence_threshold = create_video_inputs()
|
478 |
video_detect_button, video_clear_button = create_button_row()
|
479 |
with gr.Column(scale=2):
|
480 |
video_output = gr.Video(
|
|
|
485 |
|
486 |
gr.Examples(
|
487 |
examples=[
|
488 |
+
[example["path"], DEFAULT_CHECKPOINT, example["tracker"], example["classes"], DEFAULT_CONFIDENCE_THRESHOLD]
|
489 |
for example in VIDEO_EXAMPLES
|
490 |
],
|
491 |
+
inputs=[video_input, video_checkpoint, video_tracker, video_classes, video_confidence_threshold],
|
492 |
outputs=[video_output],
|
493 |
fn=process_video,
|
494 |
cache_examples=False,
|
|
|
527 |
fn=lambda: (
|
528 |
None,
|
529 |
DEFAULT_CHECKPOINT,
|
530 |
+
None,
|
531 |
+
"all",
|
532 |
DEFAULT_CONFIDENCE_THRESHOLD,
|
533 |
None,
|
534 |
),
|
535 |
outputs=[
|
536 |
video_input,
|
537 |
video_checkpoint,
|
538 |
+
video_tracker,
|
539 |
+
video_classes,
|
540 |
video_confidence_threshold,
|
541 |
video_output,
|
542 |
],
|
|
|
558 |
# Video detect button
|
559 |
video_detect_button.click(
|
560 |
fn=process_video,
|
561 |
+
inputs=[video_input, video_checkpoint, video_tracker, video_classes, video_confidence_threshold],
|
562 |
outputs=[video_output],
|
563 |
)
|
564 |
|
requirements.txt
CHANGED
@@ -8,4 +8,5 @@ tqdm
|
|
8 |
pillow
|
9 |
supervision
|
10 |
spaces
|
11 |
-
imageio[pyav]
|
|
|
|
8 |
pillow
|
9 |
supervision
|
10 |
spaces
|
11 |
+
imageio[pyav]
|
12 |
+
trackers @ git+https://github.com/roboflow/trackers
|