pushpinder06 commited on
Commit
dba657d
·
verified ·
1 Parent(s): b3d0572

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -250
app.py CHANGED
@@ -1,251 +1,71 @@
1
- import io
2
  import gradio as gr
3
- import matplotlib.pyplot as plt
4
- import requests, validators
5
- import torch
6
- import pathlib
7
- from PIL import Image
8
- from transformers import AutoFeatureExtractor, DetrForObjectDetection, YolosForObjectDetection
9
- from ultralyticsplus import YOLO, render_result
10
-
11
- import os
12
-
13
- # colors for visualization
14
- COLORS = [
15
- [0.000, 0.447, 0.741],
16
- [0.850, 0.325, 0.098],
17
- [0.929, 0.694, 0.125],
18
- [0.494, 0.184, 0.556],
19
- [0.466, 0.674, 0.188],
20
- [0.301, 0.745, 0.933]
21
- ]
22
-
23
- YOLOV8_LABELS = ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor']
24
-
25
- def make_prediction(img, feature_extractor, model):
26
- inputs = feature_extractor(img, return_tensors="pt")
27
- outputs = model(**inputs)
28
- img_size = torch.tensor([tuple(reversed(img.size))])
29
- processed_outputs = feature_extractor.post_process(outputs, img_size)
30
- return processed_outputs
31
-
32
- def fig2img(fig):
33
- buf = io.BytesIO()
34
- fig.savefig(buf, bbox_inches="tight")
35
- buf.seek(0)
36
- img = Image.open(buf)
37
- return img
38
-
39
-
40
- def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):
41
- keep = output_dict["scores"] > threshold
42
- boxes = output_dict["boxes"][keep].tolist()
43
- scores = output_dict["scores"][keep].tolist()
44
- labels = output_dict["labels"][keep].tolist()
45
- if id2label is not None:
46
- labels = [id2label[x] for x in labels]
47
-
48
- # print("Labels " + str(labels))
49
-
50
- plt.figure(figsize=(16, 10))
51
- plt.imshow(pil_img)
52
- ax = plt.gca()
53
- colors = COLORS * 100
54
- for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
55
- ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
56
- ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
57
- plt.axis("off")
58
- return fig2img(plt.gcf())
59
-
60
- def detect_objects(model_name,url_input,image_input,threshold):
61
-
62
-
63
- if 'yolov8' in model_name:
64
- # Working on getting this to work, another approach
65
- # https://docs.ultralytics.com/modes/predict/#key-features-of-predict-mode
66
-
67
- model = YOLO(model_name)
68
- # set model parameters
69
- model.overrides['conf'] = 0.15 # NMS confidence threshold
70
- model.overrides['iou'] = 0.05 # NMS IoU threshold https://www.google.com/search?client=firefox-b-1-d&q=intersection+over+union+meaning
71
- model.overrides['agnostic_nms'] = False # NMS class-agnostic
72
- model.overrides['max_det'] = 1000 # maximum number of detections per image
73
-
74
- results = model.predict(image_input)
75
-
76
- render = render_result(model=model, image=image_input, result=results[0])
77
-
78
- final_str = ""
79
- final_str_abv = ""
80
- final_str_else = ""
81
-
82
- for result in results:
83
- boxes = result.boxes.cpu().numpy()
84
- for i, box in enumerate(boxes):
85
- # r = box.xyxy[0].astype(int)
86
- coordinates = box.xyxy[0].astype(int)
87
- try:
88
- label = YOLOV8_LABELS[int(box.cls)]
89
- except:
90
- label = "ERROR"
91
- try:
92
- confi = float(box.conf)
93
- except:
94
- confi = 0.0
95
- # final_str_abv += str() + "__" + str(box.cls) + "__" + str(box.conf) + "__" + str(box) + "\n"
96
- if confi >= threshold:
97
- final_str_abv += f"Detected `{label}` with confidence `{confi}` at location `{coordinates}`\n"
98
- else:
99
- final_str_else += f"Detected `{label}` with confidence `{confi}` at location `{coordinates}`\n"
100
-
101
- final_str = "{:*^50}\n".format("ABOVE THRESHOLD OR EQUAL") + final_str_abv + "\n{:*^50}\n".format("BELOW THRESHOLD")+final_str_else
102
-
103
- return render, final_str
104
- else:
105
-
106
- #Extract model and feature extractor
107
- feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
108
- if 'detr' in model_name:
109
-
110
- model = DetrForObjectDetection.from_pretrained(model_name)
111
-
112
- elif 'yolos' in model_name:
113
-
114
- model = YolosForObjectDetection.from_pretrained(model_name)
115
-
116
- tb_label = ""
117
- if validators.url(url_input):
118
- image = Image.open(requests.get(url_input, stream=True).raw)
119
- tb_label = "Confidence Values URL"
120
-
121
- elif image_input:
122
- image = image_input
123
- tb_label = "Confidence Values Upload"
124
-
125
- #Make prediction
126
- processed_output_list = make_prediction(image, feature_extractor, model)
127
- # print("After make_prediction" + str(processed_output_list))
128
- processed_outputs = processed_output_list[0]
129
-
130
- #Visualize prediction
131
- viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
132
-
133
- # return [viz_img, processed_outputs]
134
- # print(type(viz_img))
135
-
136
- final_str_abv = ""
137
- final_str_else = ""
138
- for score, label, box in sorted(zip(processed_outputs["scores"], processed_outputs["labels"], processed_outputs["boxes"]), key = lambda x: x[0].item(), reverse=True):
139
- box = [round(i, 2) for i in box.tolist()]
140
- if score.item() >= threshold:
141
- final_str_abv += f"Detected `{model.config.id2label[label.item()]}` with confidence `{round(score.item(), 3)}` at location `{box}`\n"
142
- else:
143
- final_str_else += f"Detected `{model.config.id2label[label.item()]}` with confidence `{round(score.item(), 3)}` at location `{box}`\n"
144
-
145
- # https://docs.python.org/3/library/string.html#format-examples
146
- final_str = "{:*^50}\n".format("ABOVE THRESHOLD OR EQUAL") + final_str_abv + "\n{:*^50}\n".format("BELOW THRESHOLD")+final_str_else
147
-
148
- return viz_img, final_str
149
-
150
- def set_example_image(example: list) -> dict:
151
- return gr.Image(value=example[0]["path"])
152
-
153
- def set_example_url(example: list) -> dict:
154
- return gr.Textbox(value=example[0]["path"])
155
-
156
-
157
- title = """<h1 id="title">Object Detection App with DETR and YOLOS</h1>"""
158
-
159
- description = """
160
- Links to HuggingFace Models:
161
-
162
- - [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50)
163
- - [facebook/detr-resnet-101](https://huggingface.co/facebook/detr-resnet-101)
164
- - [hustvl/yolos-small](https://huggingface.co/hustvl/yolos-small)
165
- - [hustvl/yolos-tiny](https://huggingface.co/hustvl/yolos-tiny)
166
- - [facebook/detr-resnet-101-dc5](https://huggingface.co/facebook/detr-resnet-101-dc5)
167
- - [hustvl/yolos-small-300](https://huggingface.co/hustvl/yolos-small-300)
168
- - [mshamrai/yolov8x-visdrone](https://huggingface.co/mshamrai/yolov8x-visdrone)
169
-
170
- """
171
-
172
- models = ["facebook/detr-resnet-50","facebook/detr-resnet-101",'hustvl/yolos-small','hustvl/yolos-tiny','facebook/detr-resnet-101-dc5', 'hustvl/yolos-small-300', 'mshamrai/yolov8x-visdrone']
173
- urls = ["https://c8.alamy.com/comp/J2AB4K/the-new-york-stock-exchange-on-the-wall-street-in-new-york-J2AB4K.jpg"]
174
-
175
- # twitter_link = """
176
- # [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
177
- # """
178
-
179
- css = '''
180
- h1#title {
181
- text-align: center;
182
- }
183
- '''
184
- demo = gr.Blocks(css=css)
185
-
186
-
187
- def changing():
188
- # https://discuss.huggingface.co/t/how-to-programmatically-enable-or-disable-components/52350/4
189
- return gr.Button('Detect', interactive=True), gr.Button('Detect', interactive=True)
190
-
191
-
192
-
193
- with demo:
194
- gr.Markdown(title)
195
- gr.Markdown(description)
196
- # gr.Markdown(twitter_link)
197
- options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)
198
-
199
- slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.7,label='Prediction Threshold')
200
-
201
-
202
-
203
- with gr.Tabs():
204
- with gr.TabItem('Image URL'):
205
- with gr.Row():
206
- url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
207
- img_output_from_url = gr.Image(height=650,width=650)
208
-
209
- with gr.Row():
210
- example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
211
-
212
- url_but = gr.Button('Detect', interactive=False)
213
-
214
- with gr.TabItem('Image Upload'):
215
- with gr.Row():
216
- img_input = gr.Image(type='pil')
217
- img_output_from_upload= gr.Image(height=650,width=650)
218
-
219
- with gr.Row():
220
- example_images = gr.Dataset(components=[img_input],
221
- samples=[[path.as_posix()]
222
- for path in sorted(pathlib.Path('images').rglob('*.JPG'))]) # Can't get case_sensitive to work
223
-
224
- img_but = gr.Button('Detect', interactive=False)
225
-
226
-
227
- # output_text1 = gr.outputs.Textbox(label="Confidence Values")
228
- output_text1 = gr.components.Textbox(label="Confidence Values")
229
- # https://huggingface.co/spaces/vishnun/CLIPnCROP/blob/main/app.py -- Got .outputs. from this
230
-
231
- options.change(fn=changing, inputs=[], outputs=[img_but, url_but])
232
-
233
-
234
- url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_url, output_text1],queue=True)
235
- img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_upload, output_text1],queue=True)
236
- # url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_url, _],queue=True)
237
- # img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=[img_output_from_upload, _],queue=True)
238
-
239
- # url_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_url,queue=True)
240
- # img_but.click(detect_objects,inputs=[options,url_input,img_input,slider_input],outputs=img_output_from_upload,queue=True)
241
-
242
-
243
- example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
244
- example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input])
245
-
246
-
247
- # gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-object-detection-with-detr-and-yolos)")
248
-
249
-
250
- # demo.launch(enable_queue=True)
251
- demo.launch() #removed (share=True)
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ import tempfile
5
+
6
+ # Load the YOLOS object detection model
7
+ detector = pipeline("object-detection", model="hustvl/yolos-small")
8
+
9
+ # Define some colors to differentiate classes
10
+ COLORS = ["red", "blue", "green", "orange", "purple", "yellow", "cyan", "magenta"]
11
+
12
+ # Helper function to assign color per label
13
+ def get_color_for_label(label):
14
+ return COLORS[hash(label) % len(COLORS)]
15
+
16
+ # Main function: detect, draw, and return outputs
17
+ def detect_and_draw(image, threshold):
18
+ results = detector(image)
19
+ image = image.convert("RGB")
20
+ draw = ImageDraw.Draw(image)
21
+
22
+ try:
23
+ font = ImageFont.truetype("arial.ttf", 16)
24
+ except:
25
+ font = ImageFont.load_default()
26
+
27
+ annotations = []
28
+
29
+ for obj in results:
30
+ score = obj["score"]
31
+ if score < threshold:
32
+ continue
33
+
34
+ label = f"{obj['label']} ({score:.2f})"
35
+ box = obj["box"]
36
+ color = get_color_for_label(obj["label"])
37
+
38
+ draw.rectangle(
39
+ [(box["xmin"], box["ymin"]), (box["xmax"], box["ymax"])],
40
+ outline=color,
41
+ width=3,
42
+ )
43
+
44
+ draw.text((box["xmin"] + 5, box["ymin"] + 5), label, fill=color, font=font)
45
+
46
+ box_coords = (box["xmin"], box["ymin"], box["xmax"], box["ymax"])
47
+ annotations.append((box_coords, label))
48
+
49
+ # Save image for download
50
+ temp_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
51
+ image.save(temp_file.name)
52
+
53
+ # Return the (image, annotations) tuple and the path to the saved image
54
+ return (image, annotations), temp_file.name
55
+
56
+ # Gradio UI setup
57
+ demo = gr.Interface(
58
+ fn=detect_and_draw,
59
+ inputs=[
60
+ gr.Image(type="pil", label="Upload Image"),
61
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Confidence Threshold"),
62
+ ],
63
+ outputs=[
64
+ gr.AnnotatedImage(label="Detected Image"),
65
+ gr.File(label="Download Processed Image"),
66
+ ],
67
+ title="YOLOS Object Detection",
68
+ description="Upload an image to detect objects using the YOLOS-small model. Adjust the confidence threshold using the slider.",
69
+ )
70
+
71
+ demo.launch()