-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetectChars.py
421 lines (295 loc) · 15.8 KB
/
DetectChars.py
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# DetectChars.py
import cv2
import numpy as np
import math
import random
import Main
import Preprocess
import PossibleChar
# module level variables ##########################################################################
kNearest = cv2.ml.KNearest_create()
# constants for checkIfPossibleChar, this checks one possible char only (does not compare to another char)
MIN_PIXEL_WIDTH = 2
MIN_PIXEL_HEIGHT = 8
MIN_ASPECT_RATIO = 0.25
MAX_ASPECT_RATIO = 1.0
MIN_PIXEL_AREA = 80
# constants for comparing two chars
MIN_DIAG_SIZE_MULTIPLE_AWAY = 0.3
MAX_DIAG_SIZE_MULTIPLE_AWAY = 5.0
MAX_CHANGE_IN_AREA = 0.5
MAX_CHANGE_IN_WIDTH = 0.8
MAX_CHANGE_IN_HEIGHT = 0.2
MAX_ANGLE_BETWEEN_CHARS = 12.0
# other constants
MIN_NUMBER_OF_MATCHING_CHARS = 3
RESIZED_CHAR_IMAGE_WIDTH = 20
RESIZED_CHAR_IMAGE_HEIGHT = 30
MIN_CONTOUR_AREA = 100
###################################################################################################
def loadKNNDataAndTrainKNN():
allContoursWithData = [] # declare empty lists,
validContoursWithData = [] # we will fill these shortly
try:
npaClassifications = np.loadtxt("classifications.txt", np.float32) # read in training classifications
except:
print "error, unable to open classifications.txt, exiting program\n"
os.system("pause")
return False
# end try
try:
npaFlattenedImages = np.loadtxt("flattened_images.txt", np.float32) # read in training images
except:
print "error, unable to open flattened_images.txt, exiting program\n"
os.system("pause")
return False
# end try
npaClassifications = npaClassifications.reshape((npaClassifications.size, 1)) # reshape numpy array to 1d, necessary to pass to call to train
kNearest.setDefaultK(1)
kNearest.train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
return True
# end function
###################################################################################################
def detectCharsInPlates(listOfPossiblePlates):
intPlateCounter = 0
imgContours = None
contours = []
if len(listOfPossiblePlates) == 0:
return listOfPossiblePlates
# end if
# at this point we can be sure the list of possible plates has at least one plate
for possiblePlate in listOfPossiblePlates:
possiblePlate.imgGrayscale, possiblePlate.imgThresh = Preprocess.preprocess(possiblePlate.imgPlate)
if Main.showSteps == True:
cv2.imshow("5a", possiblePlate.imgPlate)
cv2.imshow("5b", possiblePlate.imgGrayscale)
cv2.imshow("5c", possiblePlate.imgThresh)
# end if
# increase size of plate image for easier viewing and char detection
possiblePlate.imgThresh = cv2.resize(possiblePlate.imgThresh, (0, 0), fx = 1.6, fy = 1.6)
# threshold image to only black or white (eliminate grayscale)
thresholdValue, possiblePlate.imgThresh = cv2.threshold(possiblePlate.imgThresh, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
if Main.showSteps == True:
cv2.imshow("5d", possiblePlate.imgThresh)
# end if
listOfPossibleCharsInPlate = findPossibleCharsInPlate(possiblePlate.imgGrayscale, possiblePlate.imgThresh)
if Main.showSteps == True:
height, width, numChannels = possiblePlate.imgPlate.shape
imgContours = np.zeros((height, width, 3), np.uint8)
del contours[:] # clear the contours list
for possibleChar in listOfPossibleCharsInPlate:
contours.append(possibleChar.contour)
# end for
cv2.drawContours(imgContours, contours, -1, Main.SCALAR_WHITE)
cv2.imshow("6", imgContours)
# end if
listOfListsOfMatchingCharsInPlate = findListOfListsOfMatchingChars(listOfPossibleCharsInPlate)
if Main.showSteps == True:
imgContours = np.zeros((height, width, 3), np.uint8)
del contours[:]
for listOfMatchingChars in listOfListsOfMatchingCharsInPlate:
intRandomBlue = random.randint(0, 255)
intRandomGreen = random.randint(0, 255)
intRandomRed = random.randint(0, 255)
for matchingChar in listOfMatchingChars:
contours.append(matchingChar.contour)
# end for
cv2.drawContours(imgContours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed))
# end for
cv2.imshow("7", imgContours)
# end if
if (len(listOfListsOfMatchingCharsInPlate) == 0): # if no groups of matching chars were found in the plate
if Main.showSteps == True:
print "chars found in plate number " + str(intPlateCounter) + " = (none), click on any image and press a key to continue . . ."
intPlateCounter = intPlateCounter + 1
cv2.destroyWindow("8")
cv2.destroyWindow("9")
cv2.destroyWindow("10")
cv2.waitKey(0)
# end if
possiblePlate.strChars = ""
continue # go back to top of for loop
# end if
for listOfMatchingChars in listOfListsOfMatchingCharsInPlate: # within each list of matching chars
listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX) # sort chars from left to right
listOfMatchingChars = removeInnerOverlappingChars(listOfMatchingChars) # and remove inner overlapping chars
# end for
if Main.showSteps == True:
imgContours = np.zeros((height, width, 3), np.uint8)
for listOfMatchingChars in listOfListsOfMatchingCharsInPlate:
intRandomBlue = random.randint(0, 255)
intRandomGreen = random.randint(0, 255)
intRandomRed = random.randint(0, 255)
del contours[:]
for matchingChar in listOfMatchingChars:
contours.append(matchingChar.contour)
# end for
cv2.drawContours(imgContours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed))
# end for
cv2.imshow("8", imgContours)
# end if
# within each possible plate, suppose the longest list of potential matching chars is the actual list of chars
intLenOfLongestListOfChars = 0
intIndexOfLongestListOfChars = 0
# loop through all the vectors of matching chars, get the index of the one with the most chars
for i in range(0, len(listOfListsOfMatchingCharsInPlate)):
if len(listOfListsOfMatchingCharsInPlate[i]) > intLenOfLongestListOfChars:
intLenOfLongestListOfChars = len(listOfListsOfMatchingCharsInPlate[i])
intIndexOfLongestListOfChars = i
# end if
# end for
longestListOfMatchingCharsInPlate = listOfListsOfMatchingCharsInPlate[intIndexOfLongestListOfChars]
if Main.showSteps == True:
imgContours = np.zeros((height, width, 3), np.uint8)
del contours[:]
for matchingChar in longestListOfMatchingCharsInPlate:
contours.append(matchingChar.contour)
# end for
cv2.drawContours(imgContours, contours, -1, Main.SCALAR_WHITE)
cv2.imshow("9", imgContours)
# end if
possiblePlate.strChars = recognizeCharsInPlate(possiblePlate.imgThresh, longestListOfMatchingCharsInPlate)
if Main.showSteps == True:
print "chars found in plate number " + str(intPlateCounter) + " = " + possiblePlate.strChars + ", click on any image and press a key to continue . . ."
intPlateCounter = intPlateCounter + 1
cv2.waitKey(0)
# end if
# end of big for loop that takes up most of the function
if Main.showSteps == True:
print "\nchar detection complete, click on any image and press a key to continue . . .\n"
cv2.waitKey(0)
# end if
return listOfPossiblePlates
# end function
###################################################################################################
def findPossibleCharsInPlate(imgGrayscale, imgThresh):
listOfPossibleChars = [] # this will be the return value
contours = []
imgThreshCopy = imgThresh.copy()
imgContours, contours, npaHierarchy = cv2.findContours(imgThreshCopy, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
possibleChar = PossibleChar.PossibleChar(contour)
if checkIfPossibleChar(possibleChar):
listOfPossibleChars.append(possibleChar)
# end if
# end if
return listOfPossibleChars
# end function
###################################################################################################
def checkIfPossibleChar(possibleChar):
if (possibleChar.intBoundingRectArea > MIN_PIXEL_AREA and
possibleChar.intBoundingRectWidth > MIN_PIXEL_WIDTH and possibleChar.intBoundingRectHeight > MIN_PIXEL_HEIGHT and
MIN_ASPECT_RATIO < possibleChar.fltAspectRatio and possibleChar.fltAspectRatio < MAX_ASPECT_RATIO):
return True
else:
return False
# end if
# end function
###################################################################################################
def findListOfListsOfMatchingChars(listOfPossibleChars):
listOfListsOfMatchingChars = [] # this will be the return value
for possibleChar in listOfPossibleChars:
listOfMatchingChars = findListOfMatchingChars(possibleChar, listOfPossibleChars)
listOfMatchingChars.append(possibleChar)
if len(listOfMatchingChars) < MIN_NUMBER_OF_MATCHING_CHARS:
continue
# end if
# if we get here, the current list passed test as a "group" or "cluster" of matching chars
listOfListsOfMatchingChars.append(listOfMatchingChars)
listOfPossibleCharsWithCurrentMatchesRemoved = []
listOfPossibleCharsWithCurrentMatchesRemoved = list(set(listOfPossibleChars) - set(listOfMatchingChars))
recursiveListOfListsOfMatchingChars = findListOfListsOfMatchingChars(listOfPossibleCharsWithCurrentMatchesRemoved)
for recursiveListOfMatchingChars in recursiveListOfListsOfMatchingChars:
listOfListsOfMatchingChars.append(recursiveListOfMatchingChars)
# end for
break # exit for
# end for
return listOfListsOfMatchingChars
# end function
###################################################################################################
def findListOfMatchingChars(possibleChar, listOfChars):
listOfMatchingChars = [] # this will be the return value
for possibleMatchingChar in listOfChars:
if possibleMatchingChar == possibleChar:
continue
# end if
fltDistanceBetweenChars = distanceBetweenChars(possibleChar, possibleMatchingChar)
fltAngleBetweenChars = angleBetweenChars(possibleChar, possibleMatchingChar)
fltChangeInArea = float(abs(possibleMatchingChar.intBoundingRectArea - possibleChar.intBoundingRectArea)) / float(possibleChar.intBoundingRectArea)
fltChangeInWidth = float(abs(possibleMatchingChar.intBoundingRectWidth - possibleChar.intBoundingRectWidth)) / float(possibleChar.intBoundingRectWidth)
fltChangeInHeight = float(abs(possibleMatchingChar.intBoundingRectHeight - possibleChar.intBoundingRectHeight)) / float(possibleChar.intBoundingRectHeight)
if (fltDistanceBetweenChars < (possibleChar.fltDiagonalSize * MAX_DIAG_SIZE_MULTIPLE_AWAY) and
fltAngleBetweenChars < MAX_ANGLE_BETWEEN_CHARS and
fltChangeInArea < MAX_CHANGE_IN_AREA and
fltChangeInWidth < MAX_CHANGE_IN_WIDTH and
fltChangeInHeight < MAX_CHANGE_IN_HEIGHT):
listOfMatchingChars.append(possibleMatchingChar)
# end if
# end for
return listOfMatchingChars
# end function
###################################################################################################
def distanceBetweenChars(firstChar, secondChar):
intX = abs(firstChar.intCenterX - secondChar.intCenterX)
intY = abs(firstChar.intCenterY - secondChar.intCenterY)
return math.sqrt((intX ** 2) + (intY ** 2))
# end function
###################################################################################################
def angleBetweenChars(firstChar, secondChar):
fltAdj = float(abs(firstChar.intCenterX - secondChar.intCenterX))
fltOpp = float(abs(firstChar.intCenterY - secondChar.intCenterY))
if fltAdj != 0.0:
fltAngleInRad = math.atan(fltOpp / fltAdj)
else:
fltAngleInRad = 1.5708
# end if
fltAngleInDeg = fltAngleInRad * (180.0 / math.pi)
return fltAngleInDeg
# end function
###################################################################################################
def removeInnerOverlappingChars(listOfMatchingChars):
listOfMatchingCharsWithInnerCharRemoved = [] # this will be the return value
for currentChar in listOfMatchingChars:
for otherChar in listOfMatchingChars:
if currentChar.contour.all() == otherChar.contour.all():
if distanceBetweenChars(currentChar, otherChar) < (currentChar.fltDiagonalSize * MIN_DIAG_SIZE_MULTIPLE_AWAY):
if currentChar.intBoundingRectArea < otherChar.intBoundingRectArea:
if currentChar in listOfMatchingCharsWithInnerCharRemoved:
listOfMatchingCharsWithInnerCharRemoved.remove(currentChar)
# end if
else:
if otherChar in listOfMatchingCharsWithInnerCharRemoved:
listOfMatchingCharsWithInnerCharRemoved.remove(otherChar)
# end if
# end if
# end if
# end if
# end for
# end for
return listOfMatchingCharsWithInnerCharRemoved
# end function
###################################################################################################
def recognizeCharsInPlate(imgThresh, listOfMatchingChars):
strChars = "" # this will be the return value, the chars in the lic plate
height, width = imgThresh.shape
imgThreshColor = np.zeros((height, width, 3), np.uint8)
listOfMatchingChars.sort(key = lambda matchingChar: matchingChar.intCenterX) # sort chars from left to right
cv2.cvtColor(imgThresh, cv2.COLOR_GRAY2BGR, imgThreshColor)
for currentChar in listOfMatchingChars:
pt1 = (currentChar.intBoundingRectX, currentChar.intBoundingRectY)
pt2 = ((currentChar.intBoundingRectX + currentChar.intBoundingRectWidth), (currentChar.intBoundingRectY + currentChar.intBoundingRectHeight))
cv2.rectangle(imgThreshColor, pt1, pt2, Main.SCALAR_GREEN, 2)
imgROI = imgThresh[currentChar.intBoundingRectY : currentChar.intBoundingRectY + currentChar.intBoundingRectHeight,
currentChar.intBoundingRectX : currentChar.intBoundingRectX + currentChar.intBoundingRectWidth]
imgROIResized = cv2.resize(imgROI, (RESIZED_CHAR_IMAGE_WIDTH, RESIZED_CHAR_IMAGE_HEIGHT))
npaROIResized = imgROIResized.reshape((1, RESIZED_CHAR_IMAGE_WIDTH * RESIZED_CHAR_IMAGE_HEIGHT))
npaROIResized = np.float32(npaROIResized)
retval, npaResults, neigh_resp, dists = kNearest.findNearest(npaROIResized, k = 1) # finally we can call findNearest !!!
strCurrentChar = str(chr(int(npaResults[0][0])))
strChars = strChars + strCurrentChar # append current char to full string
# end for
if Main.showSteps == True:
cv2.imshow("10", imgThreshColor)
# end if
return strChars
# end function