Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -8,7 +8,8 @@ from PIL import Image
|
|
8 |
from transformers import AutoFeatureExtractor, YolosForObjectDetection, DetrForObjectDetection
|
9 |
import os
|
10 |
|
11 |
-
|
|
|
12 |
|
13 |
# colors for visualization
|
14 |
COLORS = [
|
@@ -33,11 +34,12 @@ def fig2img(fig):
|
|
33 |
buf.seek(0)
|
34 |
pil_img = Image.open(buf)
|
35 |
basewidth = 750
|
36 |
-
wpercent = (basewidth
|
37 |
-
hsize = int((float(pil_img.size[1])
|
38 |
-
img = pil_img.resize((basewidth,
|
39 |
return img
|
40 |
|
|
|
41 |
def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
42 |
keep = output_dict["scores"] > threshold
|
43 |
boxes = output_dict["boxes"][keep].tolist()
|
@@ -45,7 +47,9 @@ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
|
45 |
labels = output_dict["labels"][keep].tolist()
|
46 |
|
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)
|
@@ -57,45 +61,66 @@ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
|
57 |
ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=60, bbox=dict(facecolor="yellow", alpha=0.8))
|
58 |
plt.axis("off")
|
59 |
return fig2img(plt.gcf())
|
60 |
-
|
61 |
def get_original_image(url_input):
|
62 |
if validators.url(url_input):
|
63 |
image = Image.open(requests.get(url_input, stream=True).raw)
|
|
|
64 |
return image
|
65 |
|
66 |
-
def detect_objects(model_name,
|
67 |
-
|
|
|
68 |
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
|
|
69 |
if "yolos" in model_name:
|
70 |
model = YolosForObjectDetection.from_pretrained(model_name)
|
71 |
elif "detr" in model_name:
|
72 |
model = DetrForObjectDetection.from_pretrained(model_name)
|
|
|
73 |
if validators.url(url_input):
|
74 |
image = get_original_image(url_input)
|
75 |
-
|
|
|
76 |
image = image_input
|
77 |
-
|
|
|
78 |
image = webcam_input
|
79 |
-
|
80 |
-
|
81 |
-
# Make prediction
|
82 |
processed_outputs = make_prediction(image, feature_extractor, model)
|
83 |
-
|
|
|
84 |
viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
|
|
|
85 |
return viz_img
|
86 |
-
|
87 |
def set_example_image(example: list) -> dict:
|
88 |
return gr.Image.update(value=example[0])
|
89 |
|
90 |
def set_example_url(example: list) -> dict:
|
91 |
return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
|
92 |
|
93 |
-
title = """<h1 id="title">License Plate Detection with YOLOS</h1>"""
|
94 |
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
images = [[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))]
|
98 |
|
|
|
|
|
|
|
|
|
99 |
css = '''
|
100 |
h1#title {
|
101 |
text-align: center;
|
@@ -104,41 +129,51 @@ h1#title {
|
|
104 |
demo = gr.Blocks(css=css)
|
105 |
|
106 |
with demo:
|
107 |
-
gr.Markdown(title)
|
108 |
-
|
109 |
-
|
|
|
|
|
110 |
|
111 |
with gr.Tabs():
|
112 |
with gr.TabItem('Image URL'):
|
113 |
with gr.Row():
|
114 |
with gr.Column():
|
115 |
-
url_input = gr.Textbox(lines=2,
|
116 |
-
original_image = gr.Image()
|
117 |
url_input.change(get_original_image, url_input, original_image)
|
118 |
with gr.Column():
|
119 |
-
img_output_from_url = gr.Image()
|
|
|
120 |
with gr.Row():
|
121 |
-
example_url = gr.Examples(examples=urls,
|
|
|
|
|
122 |
url_but = gr.Button('Detect')
|
123 |
|
124 |
with gr.TabItem('Image Upload'):
|
125 |
with gr.Row():
|
126 |
-
img_input = gr.Image(type='pil')
|
127 |
-
img_output_from_upload
|
128 |
-
|
129 |
-
|
|
|
|
|
|
|
130 |
img_but = gr.Button('Detect')
|
131 |
|
132 |
with gr.TabItem('WebCam'):
|
133 |
with gr.Row():
|
134 |
-
web_input = gr.
|
135 |
-
img_output_from_webcam
|
|
|
136 |
cam_but = gr.Button('Detect')
|
137 |
|
138 |
-
url_but.click(detect_objects,
|
139 |
-
img_but.click(detect_objects,
|
140 |
-
cam_but.click(detect_objects,
|
141 |
|
142 |
gr.Markdown("")
|
143 |
|
144 |
-
|
|
|
|
8 |
from transformers import AutoFeatureExtractor, YolosForObjectDetection, DetrForObjectDetection
|
9 |
import os
|
10 |
|
11 |
+
|
12 |
+
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
|
13 |
|
14 |
# colors for visualization
|
15 |
COLORS = [
|
|
|
34 |
buf.seek(0)
|
35 |
pil_img = Image.open(buf)
|
36 |
basewidth = 750
|
37 |
+
wpercent = (basewidth/float(pil_img.size[0]))
|
38 |
+
hsize = int((float(pil_img.size[1])*float(wpercent)))
|
39 |
+
img = pil_img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
|
40 |
return img
|
41 |
|
42 |
+
|
43 |
def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
|
44 |
keep = output_dict["scores"] > threshold
|
45 |
boxes = output_dict["boxes"][keep].tolist()
|
|
|
47 |
labels = output_dict["labels"][keep].tolist()
|
48 |
|
49 |
if id2label is not None:
|
50 |
+
|
51 |
labels = [id2label[x] for x in labels]
|
52 |
+
|
53 |
|
54 |
plt.figure(figsize=(50, 50))
|
55 |
plt.imshow(img)
|
|
|
61 |
ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=60, bbox=dict(facecolor="yellow", alpha=0.8))
|
62 |
plt.axis("off")
|
63 |
return fig2img(plt.gcf())
|
64 |
+
|
65 |
def get_original_image(url_input):
|
66 |
if validators.url(url_input):
|
67 |
image = Image.open(requests.get(url_input, stream=True).raw)
|
68 |
+
|
69 |
return image
|
70 |
|
71 |
+
def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
|
72 |
+
|
73 |
+
#Extract model and feature extractor
|
74 |
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
75 |
+
|
76 |
if "yolos" in model_name:
|
77 |
model = YolosForObjectDetection.from_pretrained(model_name)
|
78 |
elif "detr" in model_name:
|
79 |
model = DetrForObjectDetection.from_pretrained(model_name)
|
80 |
+
|
81 |
if validators.url(url_input):
|
82 |
image = get_original_image(url_input)
|
83 |
+
|
84 |
+
elif image_input:
|
85 |
image = image_input
|
86 |
+
|
87 |
+
elif webcam_input:
|
88 |
image = webcam_input
|
89 |
+
|
90 |
+
#Make prediction
|
|
|
91 |
processed_outputs = make_prediction(image, feature_extractor, model)
|
92 |
+
|
93 |
+
#Visualize prediction
|
94 |
viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
|
95 |
+
|
96 |
return viz_img
|
97 |
+
|
98 |
def set_example_image(example: list) -> dict:
|
99 |
return gr.Image.update(value=example[0])
|
100 |
|
101 |
def set_example_url(example: list) -> dict:
|
102 |
return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
|
103 |
|
|
|
104 |
|
105 |
+
title = """<h1 id="title">License Plate Detection with YOLOS</h1>"""
|
106 |
+
|
107 |
+
description = """
|
108 |
+
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).
|
109 |
+
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).
|
110 |
+
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.
|
111 |
+
Links to HuggingFace Models:
|
112 |
+
- [nickmuchi/yolos-small-rego-plates-detection](https://huggingface.co/nickmuchi/yolos-small-rego-plates-detection)
|
113 |
+
- [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
|
114 |
+
"""
|
115 |
+
|
116 |
+
models = ["nickmuchi/yolos-small-finetuned-license-plate-detection","nickmuchi/detr-resnet50-license-plate-detection"]
|
117 |
+
urls = ["https://drive.google.com/uc?id=1j9VZQ4NDS4gsubFf3m2qQoTMWLk552bQ","https://drive.google.com/uc?id=1p9wJIqRz3W50e2f_A0D8ftla8hoXz4T5"]
|
118 |
images = [[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))]
|
119 |
|
120 |
+
twitter_link = """
|
121 |
+
[](https://twitter.com/nickmuchi)
|
122 |
+
"""
|
123 |
+
|
124 |
css = '''
|
125 |
h1#title {
|
126 |
text-align: center;
|
|
|
129 |
demo = gr.Blocks(css=css)
|
130 |
|
131 |
with demo:
|
132 |
+
gr.Markdown(title)
|
133 |
+
gr.Markdown(description)
|
134 |
+
gr.Markdown(twitter_link)
|
135 |
+
options = gr.Dropdown(choices=models,label='Object Detection Model',value=models[0],show_label=True)
|
136 |
+
slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
|
137 |
|
138 |
with gr.Tabs():
|
139 |
with gr.TabItem('Image URL'):
|
140 |
with gr.Row():
|
141 |
with gr.Column():
|
142 |
+
url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
|
143 |
+
original_image = gr.Image(shape=(750,750))
|
144 |
url_input.change(get_original_image, url_input, original_image)
|
145 |
with gr.Column():
|
146 |
+
img_output_from_url = gr.Image(shape=(750,750))
|
147 |
+
|
148 |
with gr.Row():
|
149 |
+
example_url = gr.Examples(examples=urls,inputs=[url_input])
|
150 |
+
|
151 |
+
|
152 |
url_but = gr.Button('Detect')
|
153 |
|
154 |
with gr.TabItem('Image Upload'):
|
155 |
with gr.Row():
|
156 |
+
img_input = gr.Image(type='pil',shape=(750,750))
|
157 |
+
img_output_from_upload= gr.Image(shape=(750,750))
|
158 |
+
|
159 |
+
with gr.Row():
|
160 |
+
example_images = gr.Examples(examples=images,inputs=[img_input])
|
161 |
+
|
162 |
+
|
163 |
img_but = gr.Button('Detect')
|
164 |
|
165 |
with gr.TabItem('WebCam'):
|
166 |
with gr.Row():
|
167 |
+
web_input = gr.Image(source='webcam',type='pil',shape=(750,750),streaming=True)
|
168 |
+
img_output_from_webcam= gr.Image(shape=(750,750))
|
169 |
+
|
170 |
cam_but = gr.Button('Detect')
|
171 |
|
172 |
+
url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
|
173 |
+
img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
|
174 |
+
cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
|
175 |
|
176 |
gr.Markdown("")
|
177 |
|
178 |
+
|
179 |
+
demo.launch(debug=True,enable_queue=True)
|