Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

vt_lpr_code.py 14 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
  1. # import streamlit as st
  2. # dependencies
  3. from IPython.display import Image
  4. from matplotlib import pyplot as plt
  5. import cv2
  6. import argparse
  7. import sys
  8. import numpy as np
  9. import os
  10. import os.path
  11. from random import randint
  12. from os import rename
  13. from PIL import Image
  14. import pandas as pd
  15. import time
  16. confThreshold = 0.5 #Confidence threshold
  17. nmsThreshold = 0.4 #Non-maximum suppression threshold
  18. inpWidth = 416 #Width of network's input image
  19. inpHeight = 416 #Height of network's input image
  20. #===================== SPLIT CLASSES ============================
  21. def split_classes(classesFile):
  22. classes = None
  23. with open(classesFile, 'rt') as f:
  24. classes = f.read().rstrip('\n').split('\n')
  25. return classes
  26. #===================================================================
  27. # ================= Get the names of the output layers =============
  28. def getOutputsNames(net):
  29. # Get the names of all the layers in the network
  30. layersNames = net.getLayerNames()
  31. # Get the names of the output layers, i.e. the layers with unconnected outputs
  32. return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
  33. #=======================================================================
  34. #===================== DEFINING NETWORK ============================
  35. def network (modelConfiguration, modelWeights):
  36. net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
  37. net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
  38. net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
  39. return net
  40. #======================================================================
  41. def drawPred(classId, conf, left, top, right, bottom, frame,classes):
  42. # Draw a bounding box.
  43. cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, ), 3)
  44. label = '%.2f' % conf
  45. # Get the label for the class name and its confidence
  46. if classes:
  47. assert(classId < len(classes))
  48. label = '%s:%s' % (classes[classId], label)
  49. #Display the label at the top of the bounding box
  50. labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
  51. top = max(top, labelSize[1])
  52. # cv2.rectangle(frame, (left, top - round(2*labelSize[1])), (left + round(2*labelSize[0]), top + baseLine), (255, 0, 0), cv2.FILLED)
  53. cv2.rectangle(frame, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine-10), (255, 255, 255), cv2.FILLED)
  54. cv2.putText(frame, label, (left, top-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)
  55. #====================================================================
  56. def postprocess(frame, outs,classes):
  57. frameHeight = frame.shape[0]
  58. frameWidth = frame.shape[1]
  59. classIds = []
  60. confidences = []
  61. boxes = []
  62. for out in outs:
  63. for detection in out:
  64. #if detection[4]>0.001:
  65. scores = detection[5:]
  66. classId = np.argmax(scores)
  67. confidence = scores[classId]
  68. if confidence > confThreshold:
  69. center_x = int(detection[0] * frameWidth)
  70. center_y = int(detection[1] * frameHeight)
  71. width = int(detection[2] * frameWidth)
  72. height = int(detection[3] * frameHeight)
  73. left = int(center_x - width / 2)
  74. top = int(center_y - height / 2)
  75. classIds.append(classId)
  76. confidences.append(float(confidence))
  77. boxes.append([left, top, width, height])
  78. # Perform non maximum suppression to eliminate redundant overlapping boxes with
  79. # lower confidences.
  80. labeled = []
  81. indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
  82. print(indices)
  83. if(len (indices)<=0):
  84. cropped = np.zeros(3)
  85. left=0
  86. top=0
  87. right=0
  88. bottom=0
  89. labeled="Nothing"
  90. else:
  91. for i in indices:
  92. i = i[0]
  93. box = boxes[i]
  94. left = box[0]
  95. top = box[1]
  96. width = box[2]
  97. height = box[3]
  98. label = str.upper((classes[classIds[i]]))
  99. labeled.append( classes[classIds[i]])
  100. # calculate bottom and right
  101. bottom = top + height
  102. right = left + width
  103. print("top:",top)
  104. print("b:",bottom)
  105. print("l:",left)
  106. print("r:",right)
  107. if top<0:
  108. top=0
  109. if left<0:
  110. left=0
  111. if right>frameWidth:
  112. right=frameWidth
  113. if bottom>frameHeight:
  114. bottom=frameHeight
  115. cropped = frame[top:bottom, left:right].copy()
  116. print("cr:",cropped)
  117. # drawPred
  118. drawPred(classIds[i], confidences[i], left, top, right, bottom, frame,classes)
  119. return cropped,left, top, right, bottom,labeled
  120. # #
  121. # @pyqt.cache()
  122. def load_net():
  123. modelConfiguration_1 = "Weights/type/yolov4_custom.cfg"
  124. modelWeights_1 = "Weights/type/yolov4_custom_last.weights"
  125. classesFile_1 = "Weights/type/obj.names"
  126. # modelConfiguration_2 = "New_weights/lp/yolov3_custom.cfg"
  127. # modelWeights_2 = "New_weights/lp/yolov3_custom_last.weights"
  128. # classesFile_2 = "New_weights/lp/obj.names"
  129. modelConfiguration_2 = "Weights/lp/yolov4_custom.cfg"
  130. modelWeights_2 = "Weights/lp/yolov4_custom_last.weights"
  131. classesFile_2 = "Weights/lp/obj.names"
  132. modelConfiguration_3 = "Weights/char/yolov4_custom.cfg"
  133. modelWeights_3 = "Weights/char/yolov4_custom_last.weights"
  134. classesFile_3 = "Weights/char/obj.names"
  135. ################ TINY WEIGHTS
  136. # modelConfiguration_1 = "New_weights_tiny/type/yolov3-tiny_custom.cfg"
  137. # modelWeights_1 = "New_weights_tiny/type/yolov3-tiny_custom_last.weights"
  138. # classesFile_1 = "New_weights_tiny/type/obj.names"
  139. # modelConfiguration_2 = "New_weights_tiny/lp/yolov3-tiny_custom.cfg"
  140. # modelWeights_2 = "New_weights_tiny/lp/yolov3-tiny_custom_last.weights"
  141. # classesFile_2 = "New_weights_tiny/lp/obj.names"
  142. # modelConfiguration_3 = "New_weights_tiny/char/yolov3-tiny_custom.cfg"
  143. # modelWeights_3 = "New_weights_tiny/char/yolov3-tiny_custom_last.weights"
  144. # classesFile_3 = "New_weights_tiny/char/obj.names"
  145. print ("------------- DEFINING YOLO PATHS -----------------")
  146. #====================== split classes ===========================
  147. classes_1 = split_classes(classesFile_1)
  148. classes_2 = split_classes(classesFile_2)
  149. classes_3 = split_classes(classesFile_3)
  150. print ("------------- SPLIT ALL CLASSES -----------------")
  151. #===================== LOADING YOLO ===========================
  152. net_1 = network(modelConfiguration_1, modelWeights_1)
  153. net_2 = network(modelConfiguration_2, modelWeights_2)
  154. net_3 = network(modelConfiguration_3, modelWeights_3)
  155. print ("------------- LOADING ALL YOLO's -----------------")
  156. return classes_1,classes_2,classes_3,net_1,net_2,net_3
  157. def yolo3(new_name,log_file):
  158. while cv2.waitKey(1) < 0:
  159. frame1 = cv2.cvtColor(new_name,1)
  160. blob = cv2.dnn.blobFromImage(frame1, 1/255, (inpWidth, inpHeight), [0,0,0], True, crop=False)
  161. net_1.setInput(blob)
  162. t1 = time.time()
  163. outs_1 = net_1.forward(getOutputsNames(net_1))
  164. t2 = time.time()
  165. tx1=t2-t1
  166. print("time 1: ",tx1)
  167. cropped1,left1, top1, right1, bottom1,label1 = postprocess(frame1, outs_1,classes_1)
  168. cv2.imwrite('sample1.jpg', frame1)
  169. print("cropped1 ",cropped1)
  170. f1 = cropped1.flatten()
  171. if (f1.any()<=0):
  172. frame1=frame1
  173. cropped1=frame1
  174. characters=frame1
  175. label1="No Detection"
  176. label2="No Detection"
  177. lp_num="No Detection"
  178. return frame1,cropped1,characters,label1,label2,lp_num
  179. break
  180. blob = cv2.dnn.blobFromImage(cropped1, 1/255, (inpWidth, inpHeight), [0,0,0], 1, crop=False)
  181. # Sets the input to the network
  182. net_2.setInput(blob)
  183. # Runs the forward pass to get output of the output layers
  184. t3 = time.time()
  185. outs_2 = net_2.forward(getOutputsNames(net_2))
  186. t4 = time.time()
  187. tx2=t4-t3
  188. print("time 2: ",tx2)
  189. cropped2,left2, top2, right2, bottom2,label2 = postprocess(cropped1, outs_2,classes_2)
  190. print("cropped 2: ",cropped2)
  191. cv2.imwrite('sample2.jpg', cropped1)
  192. f2 = cropped2.flatten()
  193. if (f2.any()<=0):
  194. frame1=frame1
  195. cropped1=frame1
  196. characters=frame1
  197. label1="No Detection"
  198. label2="No Detection"
  199. lp_num="No Detection"
  200. return frame1,cropped1,characters,label1[0],label2[0],lp_num
  201. break
  202. blob = cv2.dnn.blobFromImage(cropped2, 1/255, (inpWidth, inpHeight), [0,0,0], 1, crop=False)
  203. # Sets the input to the network
  204. net_3.setInput(blob)
  205. # Runs the forward pass to get output of the output layers
  206. t5 = time.time()
  207. outs_3 = net_3.forward(getOutputsNames(net_3))
  208. t6 = time.time()
  209. tx3=t6-t5
  210. print("time 3: ",tx3)
  211. boxes, confidences, class_IDs = [], [], []
  212. H, W = cropped2.shape[:2]
  213. for output in outs_3:
  214. for detection in output:
  215. scores = detection[5:]
  216. classID = np.argmax(scores)
  217. confidence = scores[classID]
  218. if confidence > confThreshold:
  219. box = detection[0:4] * np.array([W, H, W, H])
  220. centerX, centerY, width, height = box.astype("int")
  221. x, y = int(centerX - (width / 2)), int(centerY - (height / 2))
  222. boxes.append([x, y, int(width), int(height)])
  223. confidences.append(float(confidence))
  224. class_IDs.append(classID)
  225. # Apply non-max suppression to identify best bounding box
  226. indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
  227. xmin, xmax, ymin, ymax, labels = [], [], [], [], []
  228. xmi,xma,ymi,yma,lc=[],[],[],[],[]
  229. xc,xcm,yc,ycm,ln=[],[],[],[],[]
  230. if len(indices) > 0:
  231. for i in indices.flatten():
  232. x, y, w, h = boxes[i][0], boxes[i][1], boxes[i][2], boxes[i][3]
  233. xmin.append(x)
  234. ymin.append(y)
  235. xmax.append(x+w)
  236. ymax.append(y+h)
  237. label = str.upper((classes_3[class_IDs[i]]))
  238. # print("-------------")
  239. # print('label ',label)
  240. if (label == str('A') or label == str('B')or label == str('C')
  241. or label == str('D')or label == str('E')or label == str('F')
  242. or label == str('G')or label == str('H')or label == str('I')
  243. or label == str('J')or label == str('K')or label == str('L')
  244. or label == str('M')or label == str('N')or label == str('O')
  245. or label == str('P')or label == str('Q')or label == str('R')
  246. or label == str('S')or label == str('T')or label == str('U')or label == str('V')
  247. or label == str('W')or label == str('X')or label == str('Y')or label == str('Z')):
  248. xmi.append(x)
  249. ymi.append(y)
  250. xma.append(x+w)
  251. yma.append(y+h)
  252. lc.append(label)
  253. # print("xmi ",xmi,ymi,xma,yma)
  254. if (label == str('0') or label == str('1')or label == str('2')or label == str('3')
  255. or label == str('4')or label == str('5')or label == str('6')or label == str('7')
  256. or label == str('8')or label == str('9')):
  257. xc.append(x)
  258. yc.append(y)
  259. xcm.append(x+w)
  260. ycm.append(y+h)
  261. ln.append(label)
  262. # print("xc ",xc,yc,xcm,ycm)
  263. boxes = pd.DataFrame({"xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax})
  264. char = pd.DataFrame({"xmi": xmi, "ymi": ymi, "xma": xma, "yma": yma, "Label": lc})
  265. num = pd.DataFrame({"xmi": xc, "yc": yc, "xca": xcm, "yca": ycm, "Label": ln})
  266. char.sort_values(by=['xmi'], inplace=True)
  267. num.sort_values(by=['xmi'], inplace=True)
  268. a=char[char.columns[4]]
  269. b=num[num.columns[4]]
  270. res = a.append(b)
  271. # Add a layer on top on a detected object
  272. LABEL_COLORS = [0, 255, 0]
  273. image_with_boxes = cropped2.astype(np.float64)
  274. for _, (xmin, ymin, xmax, ymax) in boxes.iterrows():
  275. image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] += (np.random.randint(0, 255, size=(3),dtype="uint8"))
  276. cv2.rectangle(image_with_boxes,(xmin,ymin),(xmax,ymax),(0,0,0),1)
  277. # cv2.rectangle(frame, (left, top - round(1.5*labelSize[1])), (left + round(1.5*labelSize[0]), top + baseLine-10), (255, 255, 255), cv2.FILLED)
  278. image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] /= 2
  279. tx=tx1+tx2+tx3
  280. print("OVERALL TIME: ",tx)
  281. characters = image_with_boxes.astype(np.uint8)
  282. d1 = pd.DataFrame({"label":res})
  283. d2 = d1.transpose()
  284. d3 = d2.values.tolist()
  285. flatten_mat=[]
  286. for sublist in d3:
  287. for val in sublist:
  288. flatten_mat.append(val)
  289. lp_num = ''.join(map(str,flatten_mat))
  290. print("LP NUM: ",lp_num)
  291. print("LABEL100",label1[0])
  292. cv2.imwrite('sample3.jpg', image_with_boxes.astype(np.uint8))
  293. # ,channels='BGR'
  294. with open(log_file, 'r') as f:
  295. dataf= pd.DataFrame({"Vehicle Type":label1,"LP Number":lp_num,"Inference Time":tx})
  296. dataf.to_csv(log_file,index=False,mode='a',header=False)
  297. return frame1,cropped1,characters,label1[0],label2[0],lp_num
  298. break
  299. classes_1,classes_2,classes_3,net_1,net_2,net_3 = load_net()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...