EVad commited on
Commit
2ffd98b
·
1 Parent(s): 18f6281

Added app file.

Browse files
Files changed (1) hide show
  1. app.py +101 -0
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
9
+
10
+ import os
11
+ # Defining functions for the code
12
+
13
+ def make_prediction(img, feature_extractor, model):
14
+ inputs = feature_extractor(img, return_tensors="pt")
15
+ outputs = model(**inputs)
16
+ img_size = torch.tensor([tuple(reversed(img.size))])
17
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
18
+ return processed_outputs[0]
19
+
20
+ def detect_objects(url_input):
21
+
22
+ #Extract model and feature extractor
23
+ feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/detr-resnet-50")
24
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
25
+
26
+ # if image comes from URL
27
+ if validators.url(url_input):
28
+ image = Image.open(requests.get(url_input, stream=True).raw)
29
+
30
+ #Make prediction
31
+ processed_outputs = make_prediction(image, feature_extractor, model)
32
+
33
+ #Visualize prediction
34
+ viz_img = visualize_prediction(image, processed_outputs, 0.7, model.config.id2label)
35
+
36
+ return viz_img
37
+
38
+ # visualization
39
+ COLORS = [
40
+ [0.000, 0.447, 0.741],
41
+ [0.850, 0.325, 0.098],
42
+ [0.929, 0.694, 0.125],
43
+ [0.494, 0.184, 0.556],
44
+ [0.466, 0.674, 0.188],
45
+ [0.301, 0.745, 0.933]
46
+ ]
47
+
48
+ # Draw the bounding boxes on image.
49
+ def fig2img(fig):
50
+ buf = io.BytesIO()
51
+ fig.savefig(buf)
52
+ buf.seek(0)
53
+ img = Image.open(buf)
54
+ return img
55
+
56
+ # Draw the bounding boxes.
57
+ def visualize_prediction(pil_img, output_dict, threshold=0.7, id2label=None):
58
+ keep = output_dict["scores"] > threshold
59
+ boxes = output_dict["boxes"][keep].tolist()
60
+ scores = output_dict["scores"][keep].tolist()
61
+ labels = output_dict["labels"][keep].tolist()
62
+ if id2label is not None:
63
+ labels = [id2label[x] for x in labels]
64
+
65
+ plt.figure(figsize=(16, 10))
66
+ plt.imshow(pil_img)
67
+ ax = plt.gca()
68
+ colors = COLORS * 100
69
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
70
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
71
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
72
+ plt.axis("off")
73
+ return fig2img(plt.gcf())
74
+
75
+
76
+ # Gradio interface
77
+ title = """<h1 id="title">Object Detection App with DETR</h1>"""
78
+
79
+ css = '''
80
+ h1#title {
81
+ text-align: center;
82
+ }
83
+ '''
84
+ demo = gr.Blocks(css=css)
85
+
86
+ with demo:
87
+ gr.Markdown(title)
88
+
89
+ with gr.Tabs():
90
+ with gr.TabItem('Image URL'):
91
+ with gr.Row():
92
+ url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
93
+ img_output_from_url = gr.Image(shape=(650,650))
94
+
95
+
96
+ url_but = gr.Button('Detect')
97
+
98
+
99
+ url_but.click(detect_objects,inputs=[url_input],outputs=img_output_from_url,queue=True)
100
+
101
+ demo.launch(enable_queue=True)