nickmuchi commited on
Commit
69f28bd
1 Parent(s): b5808c9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import gradio as gr
3
+ import matplotlib.pyplot as plt
4
+ import requests, validators
5
+ import torch
6
+ from PIL import Image
7
+ from transformers import AutoFeatureExtractor, DetrForObjectDetection, YolosForObjectDetection
8
+
9
+ import os
10
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
11
+
12
+ # colors for visualization
13
+ COLORS = [
14
+ [0.000, 0.447, 0.741],
15
+ [0.850, 0.325, 0.098],
16
+ [0.929, 0.694, 0.125],
17
+ [0.494, 0.184, 0.556],
18
+ [0.466, 0.674, 0.188],
19
+ [0.301, 0.745, 0.933]
20
+ ]
21
+
22
+ title = 'Object Detection App with DETR and YOLOS'
23
+
24
+ description = """
25
+ Links to HuggingFace Models:
26
+
27
+ - [facebook/detr-resnet-50](https://huggingface.co/facebook/detr-resnet-50)
28
+ - [facebook/detr-resnet-101](https://huggingface.co/facebook/detr-resnet-101)
29
+ - [hustvl/yolos-small](https://huggingface.co/hustvl/yolos-small)
30
+
31
+ """
32
+
33
+ models = ["facebook/detr-resnet-50","facebook/detr-resnet-101",'hustvl/yolos-small']
34
+
35
+ options = gr.Dropdown(choices=models,label='Select Object Detection Model',show_label=True)
36
+
37
+ def make_prediction(img, feature_extractor, model):
38
+ inputs = feature_extractor(img, return_tensors="pt")
39
+ outputs = model(**inputs)
40
+ img_size = torch.tensor([tuple(reversed(img.size))])
41
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
42
+ return processed_outputs[0]
43
+
44
+ def fig2img(fig):
45
+ buf = io.BytesIO()
46
+ fig.savefig(buf)
47
+ buf.seek(0)
48
+ img = Image.open(buf)
49
+ return img
50
+
51
+
52
+ def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):
53
+ keep = output_dict["scores"] > threshold
54
+ boxes = output_dict["boxes"][keep].tolist()
55
+ scores = output_dict["scores"][keep].tolist()
56
+ labels = output_dict["labels"][keep].tolist()
57
+ if id2label is not None:
58
+ labels = [id2label[x] for x in labels]
59
+
60
+ plt.figure(figsize=(16, 10))
61
+ plt.imshow(pil_img)
62
+ ax = plt.gca()
63
+ colors = COLORS * 100
64
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
65
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
66
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
67
+ plt.axis("off")
68
+ return fig2img(plt.gcf())
69
+
70
+ def detect_objects(model_name,url,image_upload,threshold):
71
+
72
+ #Extract model and feature extractor
73
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
74
+
75
+ if 'detr' in model_name:
76
+
77
+ model = DetrForObjectDetection.from_pretrained(model_name)
78
+
79
+ elif 'yolos' in model_name:
80
+
81
+ model = YolosForObjectDetection.from_pretrained(model_name)
82
+
83
+ if validators.url(url):
84
+ image = Image.open(requests.get(url, stream=True).raw)
85
+ elif image_upload:
86
+ image = image_upload
87
+
88
+ #Make prediction
89
+ processed_outputs = make_prediction(image, feature_extractor, model)
90
+
91
+ #Visualize prediction
92
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
93
+
94
+ return viz_img
95
+
96
+ gr.Interface(
97
+ fn = detect_objects,
98
+ inputs = [options,
99
+ gr.Textbox(lines=1,label='Enter valid image URL here..'),
100
+ gr.Image(type='pil'),
101
+ gr.Slider(minimum=0.2,maximum=1,value=0.7,label='Prediction Threshold')],
102
+ outputs=gr.Image(shape=(400,400)),
103
+ title = title,
104
+ description=description
105
+
106
+ ).launch()