nehulagrawal commited on
Commit
c72f916
1 Parent(s): 099822b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -0
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+
4
+ from transformers import AutoImageProcessor, AutoModelForObjectDetection
5
+ #from transformers import pipeline
6
+
7
+ from PIL import Image
8
+ import matplotlib.pyplot as plt
9
+ import matplotlib.patches as patches
10
+
11
+ import io
12
+ from random import choice
13
+
14
+
15
+ image_processor_tiny = AutoImageProcessor.from_pretrained("/home/pc-1/Documents/Object detection/weights")
16
+ model_tiny = AutoModelForObjectDetection.from_pretrained("/home/pc-1/Documents/Object detection/weights")
17
+
18
+ import gradio as gr
19
+
20
+
21
+ COLORS = ["#ff7f7f", "#ff7fbf", "#ff7fff", "#bf7fff",
22
+ "#7f7fff", "#7fbfff", "#7fffff", "#7fffbf",
23
+ "#7fff7f", "#bfff7f", "#ffff7f", "#ffbf7f"]
24
+
25
+ fdic = {
26
+ "family" : "DejaVu Serif",
27
+ "style" : "normal",
28
+ "size" : 18,
29
+ "color" : "yellow",
30
+ "weight" : "bold"
31
+ }
32
+
33
+
34
+ def get_figure(in_pil_img, in_results):
35
+ plt.figure(figsize=(16, 10))
36
+ plt.imshow(in_pil_img)
37
+ ax = plt.gca()
38
+
39
+ for score, label, box in zip(in_results["scores"], in_results["labels"], in_results["boxes"]):
40
+ selected_color = choice(COLORS)
41
+
42
+ box_int = [i.item() for i in torch.round(box).to(torch.int32)]
43
+ x, y, w, h = box_int[0], box_int[1], box_int[2]-box_int[0], box_int[3]-box_int[1]
44
+ #x, y, w, h = torch.round(box[0]).item(), torch.round(box[1]).item(), torch.round(box[2]-box[0]).item(), torch.round(box[3]-box[1]).item()
45
+
46
+ ax.add_patch(plt.Rectangle((x, y), w, h, fill=False, color=selected_color, linewidth=3, alpha=0.8))
47
+ ax.text(x, y, f"{model_tiny.config.id2label[label.item()]}: {round(score.item()*100, 2)}%", fontdict=fdic, alpha=0.8)
48
+
49
+ plt.axis("off")
50
+
51
+ return plt.gcf()
52
+
53
+
54
+ def infer(in_pil_img, in_model="yolos-tiny", in_threshold=0.9):
55
+ target_sizes = torch.tensor([in_pil_img.size[::-1]])
56
+ inputs = image_processor_tiny(images=in_pil_img, return_tensors="pt")
57
+ outputs = model_tiny(**inputs)
58
+
59
+ # convert outputs (bounding boxes and class logits) to COCO API
60
+ results = image_processor_tiny.post_process_object_detection(outputs, threshold=in_threshold, target_sizes=target_sizes)[0]
61
+
62
+ figure = get_figure(in_pil_img, results)
63
+
64
+ buf = io.BytesIO()
65
+ figure.savefig(buf, bbox_inches='tight')
66
+ buf.seek(0)
67
+ output_pil_img = Image.open(buf)
68
+
69
+ return output_pil_img
70
+
71
+
72
+ with gr.Blocks(title="YOLOS Object Detection - ClassCat",
73
+ css=".gradio-container {background:lightyellow;}"
74
+ ) as demo:
75
+ #sample_index = gr.State([])
76
+
77
+ gr.HTML("""<div style="font-family:'Times New Roman', 'Serif'; font-size:16pt; font-weight:bold; text-align:center; color:royalblue;">YOLOS Object Detection</div>""")
78
+
79
+ gr.HTML("""<h4 style="color:navy;">1. Select a model.</h4>""")
80
+
81
+ model = gr.Radio(["yolos-tiny", "yolos-small"], value="yolos-tiny", label="Model name")
82
+
83
+ gr.HTML("""<br/>""")
84
+ gr.HTML("""<h4 style="color:navy;">2-a. Select an example by clicking a thumbnail below.</h4>""")
85
+ gr.HTML("""<h4 style="color:navy;">2-b. Or upload an image by clicking on the canvas.</h4>""")
86
+
87
+ with gr.Row():
88
+ input_image = gr.Image(label="Input image", type="pil")
89
+ output_image = gr.Image(label="Output image with predicted instances", type="pil")
90
+
91
+ gr.Examples(['samples/cats.jpg', 'samples/detectron2.png', 'samples/cat.jpg', 'samples/hotdog.jpg'], inputs=input_image)
92
+
93
+ gr.HTML("""<br/>""")
94
+ gr.HTML("""<h4 style="color:navy;">3. Set a threshold value (default to 0.9)</h4>""")
95
+
96
+ threshold = gr.Slider(0, 1.0, value=0.9, label='threshold')
97
+
98
+ gr.HTML("""<br/>""")
99
+ gr.HTML("""<h4 style="color:navy;">4. Then, click "Infer" button to predict object instances. It will take about 10 seconds (yolos-tiny) or 20 seconds (yolos-small).</h4>""")
100
+
101
+ send_btn = gr.Button("Infer")
102
+ send_btn.click(fn=infer, inputs=[input_image, model, threshold], outputs=[output_image])
103
+
104
+ gr.HTML("""<br/>""")
105
+ gr.HTML("""<h4 style="color:navy;">Reference</h4>""")
106
+ gr.HTML("""<ul>""")
107
+ gr.HTML("""<li><a href="https://huggingface.co/docs/transformers/model_doc/yolos" target="_blank">Hugging Face Transformers - YOLOS</a>""")
108
+ gr.HTML("""</ul>""")
109
+
110
+
111
+ #demo.queue()
112
+ demo.launch(debug=True)
113
+
114
+
115
+
116
+
117
+ ### EOF ###