merve HF staff commited on
Commit
0ae17b9
1 Parent(s): d33769e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -0
app.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import os
3
+ import numpy as np
4
+ import supervision as sv
5
+ import uuid
6
+ import torch
7
+ from tqdm import tqdm
8
+ import gradio as gr
9
+ import torch
10
+ import numpy as np
11
+ from PIL import Image
12
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
13
+
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+
16
+ processor = AutoImageProcessor.from_pretrained("PekingU/rtdetr_r50vd_coco_o365")
17
+ model = AutoModelForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd_coco_o365").to(device)
18
+
19
+
20
+ BOUNDING_BOX_ANNOTATOR = sv.BoundingBoxAnnotator()
21
+ MASK_ANNOTATOR = sv.MaskAnnotator()
22
+ LABEL_ANNOTATOR = sv.LabelAnnotator()
23
+
24
+
25
+ def calculate_end_frame_index(source_video_path):
26
+ video_info = sv.VideoInfo.from_video_path(source_video_path)
27
+ return min(
28
+ video_info.total_frames,
29
+ video_info.fps * 2
30
+ )
31
+
32
+
33
+ def annotate_image(
34
+ input_image,
35
+ detections,
36
+ labels
37
+ ) -> np.ndarray:
38
+ output_image = MASK_ANNOTATOR.annotate(input_image, detections)
39
+ output_image = BOUNDING_BOX_ANNOTATOR.annotate(output_image, detections)
40
+ output_image = LABEL_ANNOTATOR.annotate(output_image, detections, labels=labels)
41
+ return output_image
42
+
43
+ def process_video(
44
+ input_video,
45
+ progress=gr.Progress(track_tqdm=True)
46
+ ):
47
+ video_info = sv.VideoInfo.from_video_path(input_video)
48
+ total = calculate_end_frame_index(input_video)
49
+ frame_generator = sv.get_video_frames_generator(
50
+ source_path=input_video,
51
+ end=total
52
+ )
53
+
54
+ result_file_name = f"{uuid.uuid4()}.mp4"
55
+ result_file_path = os.path.join("./", result_file_name)
56
+ with sv.VideoSink(result_file_path, video_info=video_info) as sink:
57
+ for _ in tqdm(range(total), desc="Processing video.."):
58
+ frame = next(frame_generator)
59
+ results = query(Image.fromarray(frame))
60
+ final_labels = []
61
+ detections = []
62
+
63
+ detections = sv.Detections.from_transformers(results[0])
64
+
65
+ for label in results[0]["labels"]:
66
+ final_labels.append(model.config.id2label[label.item()])
67
+ frame = annotate_image(
68
+ input_image=frame,
69
+ detections=detections,
70
+ labels=final_labels,
71
+ )
72
+ sink.write_frame(frame)
73
+ return result_file_path
74
+
75
+ def query(image):
76
+ inputs = processor(images=image, return_tensors="pt").to(device)
77
+ with torch.no_grad():
78
+ outputs = model(**inputs)
79
+ target_sizes = torch.Tensor([image.size])
80
+
81
+ results = processor.post_process_object_detection(outputs=outputs, threshold=0.6, target_sizes=target_sizes)
82
+ return results
83
+
84
+ with gr.Blocks() as demo:
85
+ gr.Markdown("## Real Time Object Tracking with RT-DETR")
86
+ gr.Markdown("This is a demo for object tracking using RT-DETR.")
87
+ gr.Markdown("Simply upload a video and enter the candidate labels, or try the example below. 👇")
88
+ with gr.Row():
89
+ with gr.Column():
90
+ input_video = gr.Video(
91
+ label='Input Video'
92
+ )
93
+ submit = gr.Button()
94
+ with gr.Column():
95
+ output_video = gr.Video(
96
+ label='Output Video'
97
+ )
98
+ gr.Examples(
99
+ fn=process_video,
100
+ examples=[["./cats.mp4"]],
101
+ inputs=[
102
+ input_video
103
+ ],
104
+ outputs=output_video
105
+ )
106
+
107
+ submit.click(
108
+ fn=process_video,
109
+ inputs=input_video,
110
+ outputs=output_video
111
+ )
112
+
113
+ demo.launch(debug=True, show_error=True)