Sarvamangalak commited on
Commit
a26a707
·
verified ·
1 Parent(s): ec9d5f9

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +5 -5
  2. app.py +203 -0
  3. gitattributes +31 -0
  4. requirements.txt +7 -0
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
- title: Smart Vehicle Classification
3
- emoji: 🌍
4
- colorFrom: indigo
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 6.3.0
8
  app_file: app.py
9
  pinned: false
10
  ---
 
1
  ---
2
+ title: License Plate Detection with YOLOS
3
+ emoji: 🚗
4
+ colorFrom: green
5
+ colorTo: gray
6
  sdk: gradio
7
+ sdk_version: 3.1.4
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, DetrForObjectDetection
9
+ import os
10
+
11
+
12
+ os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
13
+
14
+ # colors for visualization
15
+ COLORS = [
16
+ [0.000, 0.447, 0.741],
17
+ [0.850, 0.325, 0.098],
18
+ [0.929, 0.694, 0.125],
19
+ [0.494, 0.184, 0.556],
20
+ [0.466, 0.674, 0.188],
21
+ [0.301, 0.745, 0.933]
22
+ ]
23
+
24
+ def make_prediction(img, feature_extractor, model):
25
+ inputs = feature_extractor(img, return_tensors="pt")
26
+ outputs = model(**inputs)
27
+ img_size = torch.tensor([tuple(reversed(img.size))])
28
+ processed_outputs = feature_extractor.post_process(outputs, img_size)
29
+ return processed_outputs[0]
30
+
31
+ def fig2img(fig):
32
+ buf = io.BytesIO()
33
+ fig.savefig(buf)
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()
46
+ scores = output_dict["scores"][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)
56
+ ax = plt.gca()
57
+ colors = COLORS * 100
58
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
59
+ if label == 'license-plates':
60
+
61
+ # Crop plate
62
+ plate_crop = img.crop((xmin, ymin, xmax, ymax))
63
+
64
+ # Check EV
65
+ ev = is_green_plate(plate_crop)
66
+
67
+ if ev:
68
+ plate_type = "EV (Green Plate)"
69
+ box_color = "green"
70
+ else:
71
+ plate_type = "Non-EV Plate"
72
+ box_color = "red"
73
+
74
+ ax.add_patch(
75
+ plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
76
+ fill=False, color=box_color, linewidth=10)
77
+ )
78
+
79
+ ax.text(
80
+ xmin, ymin - 20,
81
+ f"{plate_type} | {score:0.2f}",
82
+ fontsize=50,
83
+ bbox=dict(facecolor=box_color, alpha=0.7),
84
+ color="white"
85
+ )
86
+ plt.axis("off")
87
+ return fig2img(plt.gcf())
88
+
89
+ def get_original_image(url_input):
90
+ if validators.url(url_input):
91
+ image = Image.open(requests.get(url_input, stream=True).raw)
92
+
93
+ return image
94
+
95
+ def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
96
+
97
+ #Extract model and feature extractor
98
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
99
+
100
+ if "yolos" in model_name:
101
+ model = YolosForObjectDetection.from_pretrained(model_name)
102
+ elif "detr" in model_name:
103
+ model = DetrForObjectDetection.from_pretrained(model_name)
104
+
105
+ if validators.url(url_input):
106
+ image = get_original_image(url_input)
107
+
108
+ elif image_input:
109
+ image = image_input
110
+
111
+ elif webcam_input:
112
+ image = webcam_input
113
+
114
+ #Make prediction
115
+ processed_outputs = make_prediction(image, feature_extractor, model)
116
+
117
+ #Visualize prediction
118
+ viz_img = visualize_prediction(image, processed_outputs, threshold, model.config.id2label)
119
+
120
+ return viz_img
121
+
122
+ def set_example_image(example: list) -> dict:
123
+ return gr.Image.update(value=example[0])
124
+
125
+ def set_example_url(example: list) -> dict:
126
+ return gr.Textbox.update(value=example[0]), gr.Image.update(value=get_original_image(example[0]))
127
+
128
+
129
+ title = """<h1 id="title">License Plate Detection with YOLOS</h1>"""
130
+
131
+ description = """
132
+ 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).
133
+ 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).
134
+ 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.
135
+ Links to HuggingFace Models:
136
+ - [nickmuchi/yolos-small-rego-plates-detection](https://huggingface.co/nickmuchi/yolos-small-rego-plates-detection)
137
+ - [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
138
+ """
139
+
140
+ models = ["nickmuchi/yolos-small-finetuned-license-plate-detection","nickmuchi/detr-resnet50-license-plate-detection"]
141
+ urls = ["https://drive.google.com/uc?id=1j9VZQ4NDS4gsubFf3m2qQoTMWLk552bQ","https://drive.google.com/uc?id=1p9wJIqRz3W50e2f_A0D8ftla8hoXz4T5"]
142
+ images = [[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))]
143
+
144
+ twitter_link = """
145
+ [![](https://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
146
+ """
147
+
148
+ css = '''
149
+ h1#title {
150
+ text-align: center;
151
+ }
152
+ '''
153
+ demo = gr.Blocks(css=css)
154
+
155
+ with demo:
156
+ gr.Markdown(title)
157
+ gr.Markdown(description)
158
+ gr.Markdown(twitter_link)
159
+ options = gr.Dropdown(choices=models,label='Object Detection Model',value=models[0],show_label=True)
160
+ slider_input = gr.Slider(minimum=0.2,maximum=1,value=0.5,step=0.1,label='Prediction Threshold')
161
+
162
+ with gr.Tabs():
163
+ with gr.TabItem('Image URL'):
164
+ with gr.Row():
165
+ with gr.Column():
166
+ url_input = gr.Textbox(lines=2,label='Enter valid image URL here..')
167
+ original_image = gr.Image(shape=(750,750))
168
+ url_input.change(get_original_image, url_input, original_image)
169
+ with gr.Column():
170
+ img_output_from_url = gr.Image(shape=(750,750))
171
+
172
+ with gr.Row():
173
+ example_url = gr.Examples(examples=urls,inputs=[url_input])
174
+
175
+
176
+ url_but = gr.Button('Detect')
177
+
178
+ with gr.TabItem('Image Upload'):
179
+ with gr.Row():
180
+ img_input = gr.Image(type='pil',shape=(750,750))
181
+ img_output_from_upload= gr.Image(shape=(750,750))
182
+
183
+ with gr.Row():
184
+ example_images = gr.Examples(examples=images,inputs=[img_input])
185
+
186
+
187
+ img_but = gr.Button('Detect')
188
+
189
+ with gr.TabItem('WebCam'):
190
+ with gr.Row():
191
+ web_input = gr.Image(source='webcam',type='pil',shape=(750,750),streaming=True)
192
+ img_output_from_webcam= gr.Image(shape=(750,750))
193
+
194
+ cam_but = gr.Button('Detect')
195
+
196
+ url_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_url],queue=True)
197
+ img_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_upload],queue=True)
198
+ cam_but.click(detect_objects,inputs=[options,url_input,img_input,web_input,slider_input],outputs=[img_output_from_webcam],queue=True)
199
+
200
+ gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-license-plate-detection-with-yolos)")
201
+
202
+
203
+ demo.launch(debug=True,enable_queue=True)
gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ beautifulsoup4
2
+ bs4
3
+ requests-file
4
+ torch
5
+ transformers
6
+ validators
7
+ timm