sidiqadi commited on
Commit
e5cfbd4
·
1 Parent(s): f571285

initial commit

Browse files
Files changed (1) hide show
  1. app.py +162 -0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import gradio as gr
3
+ import cv2
4
+ from ultralytics import ASSETS, YOLO
5
+ import tempfile
6
+ import numpy as np
7
+ import time
8
+
9
+ def load_model(model_name):
10
+ """Loads the specified YOLO model for either segmentation or detection."""
11
+ if model_name == "yolov9c-seg":
12
+ model_path = "yolov9c-seg.pt"
13
+ elif model_name == "yolov9e-seg":
14
+ model_path = "yolov9e-seg.pt"
15
+ elif model_name == "yolov9c":
16
+ model_path = "yolov9c.pt"
17
+ elif model_name == "yolov9e":
18
+ model_path = "yolov9e.pt"
19
+ else:
20
+ raise ValueError(f"Invalid model name: {model_name}")
21
+
22
+ return YOLO(model_path)
23
+
24
+ def predict_image(img, conf_threshold, iou_threshold, task="detection", model_name=None):
25
+ """Predicts and plots results in an image using YOLO model with adjustable confidence and IOU thresholds."""
26
+ if task == "segmentation":
27
+ if not model_name:
28
+ model_name = "yolov9c-seg"
29
+ elif model_name not in ["yolov9c-seg", "yolov9e-seg"]:
30
+ raise ValueError(f"Invalid model name for segmentation: {model_name}")
31
+ elif task == "detection":
32
+ if not model_name:
33
+ model_name = "yolov9c"
34
+ elif model_name not in ["yolov9c", "yolov9e"]:
35
+ raise ValueError(f"Invalid model name for detection: {model_name}")
36
+ else:
37
+ raise ValueError(f"Invalid task: {task}. Choose either 'segmentation' or 'detection'.")
38
+
39
+ model = load_model(model_name)
40
+ results = model.predict(
41
+ source=img,
42
+ conf=conf_threshold,
43
+ iou=iou_threshold,
44
+ show_labels=True,
45
+ show_conf=True,
46
+ imgsz=640,
47
+ )
48
+
49
+ for r in results:
50
+ im_array = r.plot()
51
+ im = Image.fromarray(im_array[..., ::-1])
52
+
53
+ return im
54
+
55
+ def predict_image_with_task(img, conf_threshold, iou_threshold, task, model_name):
56
+
57
+ return predict_image(img, conf_threshold, iou_threshold, task, model_name)
58
+
59
+ image_iface = gr.Interface(
60
+ fn=predict_image_with_task,
61
+ inputs=[
62
+ gr.Image(type="pil", label="Upload Image"),
63
+ gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence threshold"),
64
+ gr.Slider(minimum=0, maximum=1, value=0.45, label="IoU threshold"),
65
+ gr.Dropdown(choices=["detection", "segmentation"], value="detection", label="Task"),
66
+ gr.Dropdown(choices=["yolov9c", "yolov9e", "yolov9c-seg", "yolov9e-seg"], value="yolov9c", label="Model"),
67
+ ],
68
+ outputs=gr.Image(type="pil", label="Result"),
69
+ title="X509",
70
+ description="Upload images for inference. Choose task and corresponding model.",
71
+ examples=[
72
+ ["cars.jpg", 0.25, 0.45, "detection", "yolov9c"],
73
+ ],
74
+ )
75
+
76
+ def predict_video(video_path, conf_threshold, iou_threshold, task="detection", model_name=None):
77
+ """Predicts and processes video frames using YOLO model with adjustable confidence and IOU thresholds."""
78
+ if task == "segmentation":
79
+ if not model_name:
80
+ model_name = "yolov9c-seg"
81
+ elif model_name not in ["yolov9c-seg", "yolov9e-seg"]:
82
+ raise ValueError(f"Invalid model name for segmentation: {model_name}")
83
+ elif task == "detection":
84
+ if not model_name:
85
+ model_name = "yolov9c"
86
+ elif model_name not in ["yolov9c", "yolov9e"]:
87
+ raise ValueError(f"Invalid model name for detection: {model_name}")
88
+ else:
89
+ raise ValueError(f"Invalid task: {task}. Choose either 'segmentation' or 'detection'.")
90
+
91
+ model = load_model(model_name)
92
+ cap = cv2.VideoCapture(video_path)
93
+
94
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
95
+ fps = cap.get(cv2.CAP_PROP_FPS)
96
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
97
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
98
+
99
+ temp_video_path = tempfile.mktemp(suffix=".mp4")
100
+ out = cv2.VideoWriter(temp_video_path, fourcc, fps, (width, height))
101
+
102
+ frame_count = 0
103
+ start_time = time.time()
104
+
105
+ while cap.isOpened():
106
+ ret, frame = cap.read()
107
+ if not ret:
108
+ break
109
+ frame_count += 1
110
+
111
+ elapsed_time = time.time() - start_time
112
+ current_fps = frame_count / elapsed_time
113
+
114
+ pil_img = Image.fromarray(frame[..., ::-1])
115
+ results = model.predict(
116
+ source=pil_img,
117
+ conf=conf_threshold,
118
+ iou=iou_threshold,
119
+ show_labels=True,
120
+ show_conf=True,
121
+ imgsz=640,
122
+ )
123
+
124
+ for r in results:
125
+ im_array = r.plot()
126
+ processed_frame = Image.fromarray(im_array[..., ::-1])
127
+ frame = cv2.cvtColor(np.array(processed_frame), cv2.COLOR_RGB2BGR)
128
+
129
+ cv2.putText(frame, f"FPS: {current_fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
130
+
131
+ out.write(frame)
132
+
133
+ cap.release()
134
+ out.release()
135
+
136
+ return temp_video_path
137
+
138
+ def predict_video_with_task(video_path, conf_threshold, iou_threshold, task, model_name):
139
+
140
+ return predict_video(video_path, conf_threshold, iou_threshold, task, model_name)
141
+
142
+ video_iface = gr.Interface(
143
+ fn=predict_video_with_task,
144
+ inputs=[
145
+ gr.Video(label="Upload Video", interactive=True),
146
+ gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence threshold"),
147
+ gr.Slider(minimum=0, maximum=1, value=0.45, label="IoU threshold"),
148
+ gr.Dropdown(choices=["detection", "segmentation"], value="detection", label="Task"),
149
+ gr.Dropdown(choices=["yolov9c", "yolov9e", "yolov9c-seg", "yolov9e-seg"], value="yolov9c", label="Model"),
150
+ ],
151
+ outputs=gr.File(label="Result"),
152
+ title="X509",
153
+ description="Upload video for inference. Choose task and corresponding model.",
154
+ examples=[
155
+ ["VID_20240517112011.mp4", 0.25, 0.45, "detection", "yolov9c"],
156
+ ]
157
+ )
158
+
159
+ production = gr.TabbedInterface([image_iface, video_iface], ["Image Inference", "Video Inference"])
160
+
161
+ if __name__ == '__main__':
162
+ production.launch()