Abhishek Gola commited on
Commit
fc4a671
·
1 Parent(s): 44c131e

Added license plate detection to opencv spaces

Browse files
Files changed (4) hide show
  1. README.md +6 -0
  2. app.py +57 -0
  3. lpd_yunet.py +136 -0
  4. requirements.txt +4 -0
README.md CHANGED
@@ -7,6 +7,12 @@ sdk: gradio
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
 
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
10
+ short_description: License plate detection with yunet using OpenCV
11
+ tags:
12
+ - opencv
13
+ - license-plate-detection
14
+ - yunet
15
+ - LPD-yunet
16
  ---
17
 
18
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2 as cv
2
+ import numpy as np
3
+ import gradio as gr
4
+ from lpd_yunet import LPD_YuNet
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ # Download ONNX model from Hugging Face
8
+ model_path = hf_hub_download(
9
+ repo_id="opencv/license_plate_detection_yunet",
10
+ filename="license_plate_detection_lpd_yunet_2023mar.onnx"
11
+ )
12
+
13
+ # Initialize LPD-YuNet model
14
+ model = LPD_YuNet(
15
+ modelPath=model_path,
16
+ confThreshold=0.9,
17
+ nmsThreshold=0.3,
18
+ topK=5000,
19
+ keepTopK=750,
20
+ backendId=cv.dnn.DNN_BACKEND_OPENCV,
21
+ targetId=cv.dnn.DNN_TARGET_CPU
22
+ )
23
+
24
+ def visualize(image, dets, line_color=(0, 255, 0), text_color=(0, 0, 255)):
25
+ output = image.copy()
26
+ for det in dets:
27
+ bbox = det[:-1].astype(np.int32)
28
+ x1, y1, x2, y2, x3, y3, x4, y4 = bbox
29
+ cv.line(output, (x1, y1), (x2, y2), line_color, 2)
30
+ cv.line(output, (x2, y2), (x3, y3), line_color, 2)
31
+ cv.line(output, (x3, y3), (x4, y4), line_color, 2)
32
+ cv.line(output, (x4, y4), (x1, y1), line_color, 2)
33
+ return output
34
+
35
+ def detect_license_plates(input_image):
36
+ input_image = cv.cvtColor(input_image, cv.COLOR_RGB2BGR)
37
+ h, w, _ = input_image.shape
38
+ model.setInputSize([w, h])
39
+ results = model.infer(input_image)
40
+ if results is None or len(results) == 0:
41
+ return cv.cvtColor(input_image, cv.COLOR_BGR2RGB)
42
+ output = visualize(input_image, results)
43
+ output = cv.cvtColor(output, cv.COLOR_BGR2RGB)
44
+ return output
45
+
46
+ # Gradio Interface
47
+ demo = gr.Interface(
48
+ fn=detect_license_plates,
49
+ inputs=gr.Image(type="numpy", label="Upload Vehicle Image"),
50
+ outputs=gr.Image(type="numpy", label="Detected License Plates"),
51
+ title="License Plate Detection (LPD-YuNet)",
52
+ allow_flagging="never",
53
+ description="Upload a vehicle image to detect license plates using OpenCV's ONNX-based LPD-YuNet model."
54
+ )
55
+
56
+ if __name__ == "__main__":
57
+ demo.launch()
lpd_yunet.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+
3
+ import numpy as np
4
+ import cv2 as cv
5
+
6
+ class LPD_YuNet:
7
+ def __init__(self, modelPath, inputSize=[320, 240], confThreshold=0.8, nmsThreshold=0.3, topK=5000, keepTopK=750, backendId=0, targetId=0):
8
+ self.model_path = modelPath
9
+ self.input_size = np.array(inputSize)
10
+ self.confidence_threshold=confThreshold
11
+ self.nms_threshold = nmsThreshold
12
+ self.top_k = topK
13
+ self.keep_top_k = keepTopK
14
+ self.backend_id = backendId
15
+ self.target_id = targetId
16
+
17
+ self.output_names = ['loc', 'conf', 'iou']
18
+ self.min_sizes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
19
+ self.steps = [8, 16, 32, 64]
20
+ self.variance = [0.1, 0.2]
21
+
22
+ # load model
23
+ self.model = cv.dnn.readNet(self.model_path)
24
+ # set backend and target
25
+ self.model.setPreferableBackend(self.backend_id)
26
+ self.model.setPreferableTarget(self.target_id)
27
+ # generate anchors/priorboxes
28
+ self._priorGen()
29
+
30
+ @property
31
+ def name(self):
32
+ return self.__class__.__name__
33
+
34
+ def setBackendAndTarget(self, backendId, targetId):
35
+ self.backend_id = backendId
36
+ self.target_id = targetId
37
+ self.model.setPreferableBackend(self.backend_id)
38
+ self.model.setPreferableTarget(self.target_id)
39
+
40
+ def setInputSize(self, inputSize):
41
+ self.input_size = inputSize
42
+ # re-generate anchors/priorboxes
43
+ self._priorGen()
44
+
45
+ def _preprocess(self, image):
46
+ return cv.dnn.blobFromImage(image)
47
+
48
+ def infer(self, image):
49
+ assert image.shape[0] == self.input_size[1], '{} (height of input image) != {} (preset height)'.format(image.shape[0], self.input_size[1])
50
+ assert image.shape[1] == self.input_size[0], '{} (width of input image) != {} (preset width)'.format(image.shape[1], self.input_size[0])
51
+
52
+ # Preprocess
53
+ inputBlob = self._preprocess(image)
54
+
55
+ # Forward
56
+ self.model.setInput(inputBlob)
57
+ outputBlob = self.model.forward(self.output_names)
58
+
59
+ # Postprocess
60
+ results = self._postprocess(outputBlob)
61
+
62
+ return results
63
+
64
+ def _postprocess(self, blob):
65
+ # Decode
66
+ dets = self._decode(blob)
67
+
68
+ # NMS
69
+ keepIdx = cv.dnn.NMSBoxes(
70
+ bboxes=dets[:, 0:4].tolist(),
71
+ scores=dets[:, -1].tolist(),
72
+ score_threshold=self.confidence_threshold,
73
+ nms_threshold=self.nms_threshold,
74
+ top_k=self.top_k
75
+ ) # box_num x class_num
76
+ if len(keepIdx) > 0:
77
+ dets = dets[keepIdx]
78
+ return dets[:self.keep_top_k]
79
+ else:
80
+ return np.empty(shape=(0, 9))
81
+
82
+ def _priorGen(self):
83
+ w, h = self.input_size
84
+ feature_map_2th = [int(int((h + 1) / 2) / 2),
85
+ int(int((w + 1) / 2) / 2)]
86
+ feature_map_3th = [int(feature_map_2th[0] / 2),
87
+ int(feature_map_2th[1] / 2)]
88
+ feature_map_4th = [int(feature_map_3th[0] / 2),
89
+ int(feature_map_3th[1] / 2)]
90
+ feature_map_5th = [int(feature_map_4th[0] / 2),
91
+ int(feature_map_4th[1] / 2)]
92
+ feature_map_6th = [int(feature_map_5th[0] / 2),
93
+ int(feature_map_5th[1] / 2)]
94
+
95
+ feature_maps = [feature_map_3th, feature_map_4th,
96
+ feature_map_5th, feature_map_6th]
97
+
98
+ priors = []
99
+ for k, f in enumerate(feature_maps):
100
+ min_sizes = self.min_sizes[k]
101
+ for i, j in product(range(f[0]), range(f[1])): # i->h, j->w
102
+ for min_size in min_sizes:
103
+ s_kx = min_size / w
104
+ s_ky = min_size / h
105
+
106
+ cx = (j + 0.5) * self.steps[k] / w
107
+ cy = (i + 0.5) * self.steps[k] / h
108
+
109
+ priors.append([cx, cy, s_kx, s_ky])
110
+ self.priors = np.array(priors, dtype=np.float32)
111
+
112
+ def _decode(self, blob):
113
+ loc, conf, iou = blob
114
+ # get score
115
+ cls_scores = conf[:, 1]
116
+ iou_scores = iou[:, 0]
117
+ # clamp
118
+ _idx = np.where(iou_scores < 0.)
119
+ iou_scores[_idx] = 0.
120
+ _idx = np.where(iou_scores > 1.)
121
+ iou_scores[_idx] = 1.
122
+ scores = np.sqrt(cls_scores * iou_scores)
123
+ scores = scores[:, np.newaxis]
124
+
125
+ scale = self.input_size
126
+
127
+ # get four corner points for bounding box
128
+ bboxes = np.hstack((
129
+ (self.priors[:, 0:2] + loc[:, 4: 6] * self.variance[0] * self.priors[:, 2:4]) * scale,
130
+ (self.priors[:, 0:2] + loc[:, 6: 8] * self.variance[0] * self.priors[:, 2:4]) * scale,
131
+ (self.priors[:, 0:2] + loc[:, 10:12] * self.variance[0] * self.priors[:, 2:4]) * scale,
132
+ (self.priors[:, 0:2] + loc[:, 12:14] * self.variance[0] * self.priors[:, 2:4]) * scale
133
+ ))
134
+
135
+ dets = np.hstack((bboxes, scores))
136
+ return dets
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ opencv-python
2
+ gradio
3
+ numpy
4
+ huggingface_hub