Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, YolosForObjectDetection
|
9 |
+
import os
|
10 |
+
|
11 |
+
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
|
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 |
+
def make_prediction(img, feature_extractor, model):
|
24 |
+
inputs = feature_extractor(img, return_tensors="pt")
|
25 |
+
outputs = model(**inputs)
|
26 |
+
img_size = torch.tensor([tuple(reversed(img.size))])
|
27 |
+
processed_outputs = feature_extractor.post_process(outputs, img_size)
|
28 |
+
return processed_outputs[0]
|
29 |
+
|
30 |
+
def fig2img(fig):
|
31 |
+
buf = io.BytesIO()
|
32 |
+
fig.savefig(buf)
|
33 |
+
buf.seek(0)
|
34 |
+
pil_img = Image.open(buf)
|
35 |
+
basewidth = 750
|
36 |
+
wpercent = (basewidth/float(pil_img.size[0]))
|
37 |
+
hsize = int((float(pil_img.size[1])*float(wpercent)))
|
38 |
+
img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
|
39 |
+
return img
|
40 |
+
|
41 |
+
|
42 |
+
def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
43 |
+
keep = output_dict["scores"] > threshold
|
44 |
+
boxes = output_dict["boxes"][keep].tolist()
|
45 |
+
scores = output_dict["scores"][keep].tolist()
|
46 |
+
labels = output_dict["labels"][keep].tolist()
|
47 |
+
if id2label is not None:
|
48 |
+
labels = [id2label[x] for x in labels]
|
49 |
+
|
50 |
+
plt.figure(figsize=(50, 50))
|
51 |
+
plt.imshow(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 get_original_image(url_input):
|
61 |
+
if validators.url(url_input):
|
62 |
+
image = Image.open(requests.get(url_input, stream=True).raw)
|
63 |
+
|
64 |
+
return image
|
65 |
+
|
66 |
+
def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
|
67 |
+
|
68 |
+
#Extract model and feature extractor
|
69 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
70 |
+
|
71 |
+
model = YolosForObjectDetection.from_pretrained(model_name)
|
72 |
+
|
73 |
+
|
74 |
+
if validators.url(url_input):
|
75 |
+
image = get_original_image(url_input)
|
76 |
+
|
77 |
+
elif image_input:
|
78 |
+
image = image_input
|
79 |
+
|
80 |
+
elif webcam_input:
|
81 |
+
image = webcam_input
|
82 |
+
|
83 |
+
#Make prediction
|
84 |
+
processed_outputs = make_prediction(image, feature_extractor, model)
|
85 |
+
|
86 |
+
#Visualize prediction
|
87 |
+
viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
|
88 |
+
|
89 |
+
return viz_img
|
90 |
+
|
91 |
+
def set_example_image(example: list) -> dict:
|
92 |
+
return gr.Image.update(value=example[0])
|
93 |
+
|
94 |
+
def set_example_url(example: list) -> dict:
|
95 |
+
return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
|
96 |
+
|
97 |
+
|
98 |
+
title = """<h1 id="title">Face Mask Detection with YOLOS</h1>"""
|
99 |
+
|
100 |
+
description = """
|
101 |
+
YOLOS is a Vision Transformer (ViT) trained using the DETR loss. Despite its simplicity, a base-sized YOLOS model is able to achieve 42 AP on COCO validation 2017 (similar to DETR and more complex frameworks such as Faster R-CNN).
|
102 |
+
The YOLOS model was fine-tuned on COCO 2017 object detection (118k annotated images). It was introduced in the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Fang et al. and first released in [this repository](https://github.com/hustvl/YOLOS).
|
103 |
+
This model was further fine-tuned on the [Car license plate dataset]("https://www.kaggle.com/datasets/andrewmvd/car-plate-detection") from Kaggle. The dataset consists of 443 images of vehicle with annotations categorised as "Vehicle" and "Rego Plates". The model was trained for 200 epochs on a single GPU.
|
104 |
+
Links to HuggingFace Models:
|
105 |
+
- [nickmuchi/yolos-small-rego-plates-detection](https://huggingface.co/nickmuchi/yolos-small-rego-plates-detection)
|
106 |
+
- [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
|
107 |
+
"""
|
108 |
+
|
109 |
+
models = ["nickmuchi/yolos-small-rego-plates-detection"]
|
110 |
+
urls = ["https://drive.google.com/uc?id=1j9VZQ4NDS4gsubFf3m2qQoTMWLk552bQ","https://drive.google.com/uc?id=1p9wJIqRz3W50e2f_A0D8ftla8hoXz4T5"]
|
111 |
+
|
112 |
+
twitter_link = """
|
113 |
+
[![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
|
114 |
+
"""
|
115 |
+
|
116 |
+
css = '''
|
117 |
+
h1#title {
|
118 |
+
text-align: center;
|
119 |
+
}
|
120 |
+
'''
|
121 |
+
demo = gr.Blocks(css=css)
|
122 |
+
|
123 |
+
with demo:
|
124 |
+
gr.Markdown(title)
|
125 |
+
gr.Markdown(description)
|
126 |
+
gr.Markdown(twitter_link)
|
127 |
+
options = gr.Dropdown(choices=models,label='Object Detection Model',show_label=True,value=models[0])
|
128 |
+
slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.3,step=0.1,label='Prediction Threshold')
|
129 |
+
|
130 |
+
with gr.Tabs():
|
131 |
+
with gr.TabItem('Image URL'):
|
132 |
+
with gr.Row():
|
133 |
+
with gr.Column():
|
134 |
+
url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
|
135 |
+
original_image = gr.Image(shape=(750,750))
|
136 |
+
with gr.Column():
|
137 |
+
img_output_from_url = gr.Image(shape=(750,750))
|
138 |
+
|
139 |
+
with gr.Row():
|
140 |
+
example_url = gr.Dataset(components=[url_input],samples=[[str(url)] for url in urls])
|
141 |
+
|
142 |
+
url_but = gr.Button('Detect')
|
143 |
+
|
144 |
+
with gr.TabItem('Image Upload'):
|
145 |
+
with gr.Row():
|
146 |
+
img_input = gr.Image(type='pil',shape=(750,750))
|
147 |
+
img_output_from_upload= gr.Image(shape=(750,750))
|
148 |
+
|
149 |
+
with gr.Row():
|
150 |
+
example_images = gr.Dataset(components=[img_input],
|
151 |
+
samples=[[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))])
|
152 |
+
|
153 |
+
|
154 |
+
img_but = gr.Button('Detect')
|
155 |
+
|
156 |
+
with gr.TabItem('WebCam'):
|
157 |
+
with gr.Row():
|
158 |
+
web_input = gr.Image(source='webcam',type='pil',shape=(750,750),streaming=True)
|
159 |
+
img_output_from_webcam= gr.Image(shape=(750,750))
|
160 |
+
#gr.Image(source="webcam",type='pil',shape=(750,750)).stream(detect_objects, inputs=[options,url_input,img_input,slider_input], outputs =[img_output_from_webcam])
|
161 |
+
|
162 |
+
cam_but = gr.Button('Detect')
|
163 |
+
|
164 |
+
url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
|
165 |
+
img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
|
166 |
+
cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
|
167 |
+
example_images.click(fn=set_example_image,inputs=[example_images],outputs=[img_input])
|
168 |
+
example_url.click(fn=set_example_url,inputs=[example_url],outputs=[url_input,original_image])
|
169 |
+
|
170 |
+
|
171 |
+
gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-face-mask-detections-with-yolos)")
|
172 |
+
|
173 |
+
|
174 |
+
demo.launch(debug=True,enable_queue=True)
|