atalaydenknalbant commited on
Commit
9c39e47
·
verified ·
1 Parent(s): b0a31e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -61
app.py CHANGED
@@ -2,69 +2,192 @@ import gradio as gr
2
  from PIL import Image, ImageDraw, ImageFont
3
  from ultralytics import YOLO
4
  import spaces
 
 
 
5
 
6
  @spaces.GPU
7
- def yolo_inference(images, model_id, conf_threshold, iou_threshold, max_detection):
8
- if images is None:
9
- # Create a blank image
10
- width, height = 640, 480
11
- blank_image = Image.new("RGB", (width, height), color="white")
12
- draw = ImageDraw.Draw(blank_image)
13
- message = "No image provided"
14
- font = ImageFont.load_default(size=40)
15
- bbox = draw.textbbox((0, 0), message, font=font)
16
- text_width = bbox[2] - bbox[0]
17
- text_height = bbox[3] - bbox[1]
18
- text_x = (width - text_width) / 2
19
- text_y = (height - text_height) / 2
20
- draw.text((text_x, text_y), message, fill="black", font=font)
21
- return blank_image
22
-
23
- model = YOLO(model_id)
24
- results = model.predict(
25
- source=images,
26
- conf=conf_threshold,
27
- iou=iou_threshold,
28
- imgsz=640,
29
- max_det=max_detection,
30
- show_labels=True,
31
- show_conf=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  )
 
33
 
34
- for r in results:
35
- image_array = r.plot()
36
- image = Image.fromarray(image_array[..., ::-1])
37
- return image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- interface = gr.Interface(
40
- fn=yolo_inference,
41
- inputs=[
42
- gr.Image(type="pil", label="Upload Image"),
43
- gr.Dropdown(
44
- choices=['yolo11n.pt', 'yolo11s.pt', 'yolo11m.pt', 'yolo11l.pt', 'yolo11x.pt',
45
- 'yolo11n-seg.pt', 'yolo11s-seg.pt', 'yolo11m-seg.pt', 'yolo11l-seg.pt', 'yolo11x-seg.pt',
46
- 'yolo11n-pose.pt', 'yolo11s-pose.pt', 'yolo11m-pose.pt', 'yolo11l-pose.pt', 'yolo11x-pose.pt',
47
- 'yolo11n-obb.pt', 'yolo11s-obb.pt', 'yolo11m-obb.pt', 'yolo11l-obb.pt', 'yolo11x-obb.pt',
48
- 'yolo11n-cls.pt', 'yolo11s-cls.pt', 'yolo11m-cls.pt', 'yolo11l-cls.pt', 'yolo11x-cls.pt'],
49
- label="Model Name",
50
- value="yolo11n.pt",
51
- ),
52
- gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence Threshold"),
53
- gr.Slider(minimum=0, maximum=1, value=0.45, label="IoU Threshold"),
54
- gr.Slider(minimum=1, maximum=300, step=1, value=300, label="Max Detection"),
55
- ],
56
- outputs=gr.Image(type="pil", label="Annotated Image"),
57
- cache_examples=True,
58
- title="Yolo11: Object Detection, Instance Segmentation, Pose/Keypoints, Oriented Detection, Classification",
59
- description="Upload image(s) for inference using the latest Ultralytics YOLO11 models.",
60
- examples=[
61
- ["zidane.jpg", "yolo11s.pt", 0.25, 0.45, 300],
62
- ["bus.jpg", "yolo11m.pt", 0.25, 0.45, 300],
63
- ["yolo_vision.jpg", "yolo11x.pt", 0.25, 0.45, 300],
64
- ["Tricycle.jpg", "yolo11x-cls.pt", 0.25, 0.45, 300],
65
- ["tcganadolu.jpg", "yolo11m-obb.pt", 0.25, 0.45, 300],
66
- ["San Diego Airport.jpg", "yolo11x-seg.pt", 0.25, 0.45, 300],
67
- ["Theodore_Roosevelt.png", "yolo11l-pose.pt", 0.25, 0.45, 300],
68
- ],
69
- )
70
- interface.launch()
 
2
  from PIL import Image, ImageDraw, ImageFont
3
  from ultralytics import YOLO
4
  import spaces
5
+ import cv2
6
+ import numpy as np
7
+ import tempfile
8
 
9
  @spaces.GPU
10
+ def yolo_inference(input_type, image, video, model_id, conf_threshold, iou_threshold, max_detection):
11
+ if input_type == "Image":
12
+ if image is None:
13
+ width, height = 640, 480
14
+ blank_image = Image.new("RGB", (width, height), color="white")
15
+ draw = ImageDraw.Draw(blank_image)
16
+ message = "No image provided"
17
+ font = ImageFont.load_default(size=40)
18
+ bbox = draw.textbbox((0, 0), message, font=font)
19
+ text_width = bbox[2] - bbox[0]
20
+ text_height = bbox[3] - bbox[1]
21
+ text_x = (width - text_width) / 2
22
+ text_y = (height - text_height) / 2
23
+ draw.text((text_x, text_y), message, fill="black", font=font)
24
+ return blank_image, None
25
+
26
+ model = YOLO(model_id)
27
+ results = model.predict(
28
+ source=image,
29
+ conf=conf_threshold,
30
+ iou=iou_threshold,
31
+ imgsz=640,
32
+ max_det=max_detection,
33
+ show_labels=True,
34
+ show_conf=True,
35
+ )
36
+ for r in results:
37
+ image_array = r.plot()
38
+ annotated_image = Image.fromarray(image_array[..., ::-1])
39
+ return annotated_image, None
40
+
41
+ elif input_type == "Video":
42
+ if video is None:
43
+ width, height = 640, 480
44
+ blank_image = Image.new("RGB", (width, height), color="white")
45
+ draw = ImageDraw.Draw(blank_image)
46
+ message = "No video provided"
47
+ font = ImageFont.load_default(size=40)
48
+ bbox = draw.textbbox((0, 0), message, font=font)
49
+ text_width = bbox[2] - bbox[0]
50
+ text_height = bbox[3] - bbox[1]
51
+ text_x = (width - text_width) / 2
52
+ text_y = (height - text_height) / 2
53
+ draw.text((text_x, text_y), message, fill="black", font=font)
54
+ temp_video_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
55
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
56
+ out = cv2.VideoWriter(temp_video_file, fourcc, 1, (width, height))
57
+ frame = cv2.cvtColor(np.array(blank_image), cv2.COLOR_RGB2BGR)
58
+ out.write(frame)
59
+ out.release()
60
+ return None, temp_video_file
61
+
62
+ model = YOLO(model_id)
63
+ cap = cv2.VideoCapture(video)
64
+ fps = cap.get(cv2.CAP_PROP_FPS) if cap.get(cv2.CAP_PROP_FPS) > 0 else 25
65
+ frames = []
66
+ while True:
67
+ ret, frame = cap.read()
68
+ if not ret:
69
+ break
70
+ pil_frame = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
71
+ results = model.predict(
72
+ source=pil_frame,
73
+ conf=conf_threshold,
74
+ iou=iou_threshold,
75
+ imgsz=640,
76
+ max_det=max_detection,
77
+ show_labels=True,
78
+ show_conf=True,
79
+ )
80
+ for r in results:
81
+ annotated_frame_array = r.plot()
82
+ annotated_frame = cv2.cvtColor(annotated_frame_array, cv2.COLOR_BGR2RGB)
83
+ frames.append(annotated_frame)
84
+ cap.release()
85
+ if len(frames) == 0:
86
+ return None, None
87
+
88
+ height_out, width_out, _ = frames[0].shape
89
+ temp_video_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
90
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
91
+ out = cv2.VideoWriter(temp_video_file, fourcc, fps, (width_out, height_out))
92
+ for f in frames:
93
+ f_bgr = cv2.cvtColor(f, cv2.COLOR_RGB2BGR)
94
+ out.write(f_bgr)
95
+ out.release()
96
+ return None, temp_video_file
97
+
98
+ else:
99
+ return None, None
100
+
101
+ def update_visibility(input_type):
102
+ """
103
+ Show/hide image/video input and output depending on input_type.
104
+ """
105
+ if input_type == "Image":
106
+ # image, video, output_image, output_video
107
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
108
+ else:
109
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)
110
+
111
+ def yolo_inference_for_examples(image, model_id, conf_threshold, iou_threshold, max_detection):
112
+ """
113
+ This is called by gr.Examples. We force the radio to 'Image'
114
+ and then do a standard image inference, returning both updated radio
115
+ value and the annotated image.
116
+ """
117
+ annotated_image, _ = yolo_inference(
118
+ input_type="Image",
119
+ image=image,
120
+ video=None,
121
+ model_id=model_id,
122
+ conf_threshold=conf_threshold,
123
+ iou_threshold=iou_threshold,
124
+ max_detection=max_detection
125
  )
126
+ return gr.update(value="Image"), annotated_image
127
 
128
+ with gr.Blocks() as app:
129
+ gr.Markdown("# Yolo11: Object Detection, Instance Segmentation, Pose/Keypoints, Oriented Detection, Classification")
130
+ gr.Markdown("Upload image(s) or video(s) for inference using the latest Ultralytics YOLO11 models.")
131
+
132
+ with gr.Row():
133
+ with gr.Column():
134
+ image = gr.Image(type="pil", label="Image", visible=True)
135
+ video = gr.Video(label="Video", visible=False)
136
+ input_type = gr.Radio(
137
+ choices=["Image", "Video"],
138
+ value="Image",
139
+ label="Input Type",
140
+ )
141
+ model_id = gr.Dropdown(
142
+ label="Model Name",
143
+ choices=[
144
+ 'yolo11n.pt', 'yolo11s.pt', 'yolo11m.pt', 'yolo11l.pt', 'yolo11x.pt',
145
+ 'yolo11n-seg.pt', 'yolo11s-seg.pt', 'yolo11m-seg.pt', 'yolo11l-seg.pt', 'yolo11x-seg.pt',
146
+ 'yolo11n-pose.pt', 'yolo11s-pose.pt', 'yolo11m-pose.pt', 'yolo11l-pose.pt', 'yolo11x-pose.pt',
147
+ 'yolo11n-obb.pt', 'yolo11s-obb.pt', 'yolo11m-obb.pt', 'yolo11l-obb.pt', 'yolo11x-obb.pt',
148
+ 'yolo11n-cls.pt', 'yolo11s-cls.pt', 'yolo11m-cls.pt', 'yolo11l-cls.pt', 'yolo11x-cls.pt'
149
+ ],
150
+ value="yolo11n.pt",
151
+ )
152
+ conf_threshold = gr.Slider(minimum=0, maximum=1, value=0.25, label="Confidence Threshold")
153
+ iou_threshold = gr.Slider(minimum=0, maximum=1, value=0.45, label="IoU Threshold")
154
+ max_detection = gr.Slider(minimum=1, maximum=300, step=1, value=300, label="Max Detection")
155
+ infer_button = gr.Button("Detect Objects")
156
+ with gr.Column():
157
+ output_image = gr.Image(type="pil", label="Annotated Image", visible=True)
158
+ output_video = gr.Video(label="Annotated Video", visible=False)
159
+
160
+ # Toggle input/output visibility
161
+ input_type.change(
162
+ fn=update_visibility,
163
+ inputs=input_type,
164
+ outputs=[image, video, output_image, output_video],
165
+ )
166
+
167
+ # Main inference for button click
168
+ infer_button.click(
169
+ fn=yolo_inference,
170
+ inputs=[input_type, image, video, model_id, conf_threshold, iou_threshold, max_detection],
171
+ outputs=[output_image, output_video],
172
+ )
173
+
174
+ # Examples for images only
175
+ gr.Examples(
176
+ examples=[
177
+ ["zidane.jpg", "yolo11s.pt", 0.25, 0.45, 300],
178
+ ["bus.jpg", "yolo11m.pt", 0.25, 0.45, 300],
179
+ ["yolo_vision.jpg", "yolo11x.pt", 0.25, 0.45, 300],
180
+ ["Tricycle.jpg", "yolo11x-cls.pt", 0.25, 0.45, 300],
181
+ ["tcganadolu.jpg", "yolo11m-obb.pt", 0.25, 0.45, 300],
182
+ ["San Diego Airport.jpg", "yolo11x-seg.pt", 0.25, 0.45, 300],
183
+ ["Theodore_Roosevelt.png", "yolo11l-pose.pt", 0.25, 0.45, 300],
184
+ ],
185
+ fn=yolo_inference_for_examples,
186
+ inputs=[image, model_id, conf_threshold, iou_threshold, max_detection],
187
+ outputs=[input_type, output_image],
188
+ label="Examples (Images)",
189
+ cache_examples=True,
190
+ )
191
 
192
+ if __name__ == '__main__':
193
+ app.launch()