DevBM commited on
Commit
0c1f3a6
·
verified ·
1 Parent(s): 60072d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -52
app.py CHANGED
@@ -1,17 +1,17 @@
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],
@@ -30,16 +30,15 @@ def make_prediction(img, feature_extractor, model):
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()
@@ -47,9 +46,7 @@ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
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,16 +58,14 @@ def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
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:
@@ -80,41 +75,32 @@ def detect_objects(model_name,url_input,image_input,webcam_input,threshold):
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 = """
@@ -126,54 +112,52 @@ h1#title {
126
  text-align: center;
127
  }
128
  '''
 
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("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-license-plate-detection-with-yolos)")
177
 
178
-
179
- demo.launch(debug=True,enable_queue=True)
 
1
  import io
2
  import gradio as gr
3
  import matplotlib.pyplot as plt
4
+ import requests
5
+ import validators
6
  import torch
7
  import pathlib
8
  from PIL import Image
9
  from transformers import AutoFeatureExtractor, YolosForObjectDetection, DetrForObjectDetection
10
  import os
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],
 
30
 
31
  def fig2img(fig):
32
  buf = io.BytesIO()
33
+ fig.savefig(buf, format='png')
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
  def visualize_prediction(img, output_dict, threshold=0.5, id2label=None):
43
  keep = output_dict["scores"] > threshold
44
  boxes = output_dict["boxes"][keep].tolist()
 
46
  labels = output_dict["labels"][keep].tolist()
47
 
48
  if id2label is not None:
 
49
  labels = [id2label[x] for x in labels]
 
50
 
51
  plt.figure(figsize=(50, 50))
52
  plt.imshow(img)
 
58
  ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=60, bbox=dict(facecolor="yellow", alpha=0.8))
59
  plt.axis("off")
60
  return fig2img(plt.gcf())
61
+
62
  def get_original_image(url_input):
63
  if validators.url(url_input):
64
  image = Image.open(requests.get(url_input, stream=True).raw)
 
65
  return image
66
 
67
+ def detect_objects(model_name, url_input, image_input, webcam_input, threshold):
68
+ # Extract model and feature extractor
 
69
  feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
70
 
71
  if "yolos" in model_name:
 
75
 
76
  if validators.url(url_input):
77
  image = get_original_image(url_input)
78
+ elif image_input is not None:
 
79
  image = image_input
80
+ elif webcam_input is not None:
 
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
  title = """<h1 id="title">License Plate Detection with YOLOS</h1>"""
92
 
93
  description = """
94
  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).
95
+ 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).
96
+ 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 vehicles with annotations categorized as "Vehicle" and "Rego Plates". The model was trained for 200 epochs on a single GPU.
97
  Links to HuggingFace Models:
98
  - [nickmuchi/yolos-small-rego-plates-detection](https://huggingface.co/nickmuchi/yolos-small-rego-plates-detection)
99
  - [hustlv/yolos-small](https://huggingface.co/hustlv/yolos-small)
100
  """
101
 
102
+ models = ["nickmuchi/yolos-small-finetuned-license-plate-detection", "nickmuchi/detr-resnet50-license-plate-detection"]
103
+ urls = ["https://drive.google.com/uc?id=1j9VZQ4NDS4gsubFf3m2qQoTMWLk552bQ", "https://drive.google.com/uc?id=1p9wJIqRz3W50e2f_A0D8ftla8hoXz4T5"]
104
  images = [[path.as_posix()] for path in sorted(pathlib.Path('images').rglob('*.j*g'))]
105
 
106
  twitter_link = """
 
112
  text-align: center;
113
  }
114
  '''
115
+
116
  demo = gr.Blocks(css=css)
117
 
118
  with demo:
119
  gr.Markdown(title)
120
  gr.Markdown(description)
121
  gr.Markdown(twitter_link)
122
+ options = gr.Dropdown(choices=models, label='Object Detection Model', value=models[0], show_label=True)
123
+ slider_input = gr.Slider(minimum=0.2, maximum=1, value=0.5, step=0.1, label='Prediction Threshold')
124
 
125
  with gr.Tabs():
126
  with gr.TabItem('Image URL'):
127
  with gr.Row():
128
  with gr.Column():
129
+ url_input = gr.Textbox(lines=2, label='Enter valid image URL here..')
130
+ original_image = gr.Image()
131
+ url_input.change(fn=get_original_image, inputs=url_input, outputs=original_image)
132
  with gr.Column():
133
+ img_output_from_url = gr.Image()
134
 
135
  with gr.Row():
136
+ example_url = gr.Examples(examples=urls, inputs=[url_input])
137
 
 
138
  url_but = gr.Button('Detect')
139
 
140
  with gr.TabItem('Image Upload'):
141
  with gr.Row():
142
+ img_input = gr.Image(type='pil')
143
+ img_output_from_upload = gr.Image()
144
 
145
  with gr.Row():
146
+ example_images = gr.Examples(examples=images, inputs=[img_input])
147
 
 
148
  img_but = gr.Button('Detect')
149
 
150
  with gr.TabItem('WebCam'):
151
  with gr.Row():
152
+ web_input = gr.Image(source='webcam', type='pil')
153
+ img_output_from_webcam = gr.Image()
154
 
155
  cam_but = gr.Button('Detect')
156
 
157
+ url_but.click(fn=detect_objects, inputs=[options, url_input, img_input, web_input, slider_input], outputs=[img_output_from_url], queue=True)
158
+ img_but.click(fn=detect_objects, inputs=[options, url_input, img_input, web_input, slider_input], outputs=[img_output_from_upload], queue=True)
159
+ cam_but.click(fn=detect_objects, inputs=[options, url_input, img_input, web_input, slider_input], outputs=[img_output_from_webcam], queue=True)
160
 
161
  gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=nickmuchi-license-plate-detection-with-yolos)")
162
 
163
+ demo.launch(debug=True, enable_queue=True)