MUHAMMEDHAFEEZ commited on
Commit
2190bb1
·
1 Parent(s): ec27adb

Add application file

Browse files
Files changed (1) hide show
  1. app.py +176 -58
app.py CHANGED
@@ -1,61 +1,179 @@
1
- import cv2
2
- import imghdr
3
- import pytesseract
4
-
5
- def extract_number_plate(image_path):
6
- # Load the image
7
- image = cv2.imread(image_path)
8
-
9
- # Check if the image is valid
10
- if image is None:
11
- print("Invalid image file!")
12
- return
13
-
14
- # Convert the image to grayscale
15
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
16
-
17
- # Apply Gaussian blur to reduce noise
18
- blurred = cv2.GaussianBlur(gray, (7, 7), 0)
19
-
20
- # Perform edge detection using Canny algorithm
21
- edges = cv2.Canny(blurred, 30, 150)
22
-
23
- # Find contours in the edge-detected image
24
- contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
25
-
26
- # Filter contours based on area to select potential number plates
27
- number_plate_contours = []
28
- for contour in contours:
29
- x, y, w, h = cv2.boundingRect(contour)
30
- area = cv2.contourArea(contour)
31
- if area > 1000 and w > h:
32
- number_plate_contours.append(contour)
33
-
34
- # Draw bounding rectangles around the number plates
35
- for contour in number_plate_contours:
36
- x, y, w, h = cv2.boundingRect(contour)
37
- cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Extract the region of interest (number plate)
40
- plate = gray[y:y+h, x:x+w]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # Apply OCR to the number plate region
43
- plate_text = pytesseract.image_to_string(plate, config='--psm 7')
 
 
 
 
 
 
 
 
44
 
45
- # Print the extracted text
46
- print("Number Plate Text:", plate_text)
47
-
48
- # Display the image with bounding rectangles
49
- cv2.imshow("Number Plates", image)
50
- cv2.waitKey(0)
51
- cv2.destroyAllWindows()
52
-
53
- # Path to the input image
54
- image_path = "cars/car2.jpg"
55
-
56
- # Check if the file is an image
57
- if imghdr.what(image_path) is not None:
58
- # Extract the number plates and print the text
59
- extract_number_plate(image_path)
60
- else:
61
- print("Invalid image file format!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=10))
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://img.shields.io/twitter/follow/nickmuchi?label=@nickmuchi&style=social)](https://twitter.com/nickmuchi)
122
+ """
123
+
124
+ css = '''
125
+ 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)