-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.py
237 lines (180 loc) · 9.75 KB
/
Main.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
# Main.py
import os
from _curses import flash
from builtins import int, round, tuple, len, float
import cv2
import pymysql
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename, redirect
from flask_sqlalchemy import SQLAlchemy
import DetectCharactersHelper
import DetectPlatesHelper
app = Flask(__name__)
global numberplateintotext
numberplateintotext = ""
ALLOWED_EXTENSION = ['.jpg, .png, .jpeg, .gif']
APP_ROOT = os.path.dirname(os.path.dirname(__file__))
UPLOAD_FOLDER = '/home/sarin/PycharmProjects/AI_PROJECTS/UPLOAD_FOLDER/'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
black = (0.0, 0.0, 0.0)
white = (255.0, 255.0, 255.0)
yellow = (0.0, 255.0, 255.0)
green = (0.0, 255.0, 0.0)
red = (0.0, 0.0, 255.0)
@app.route("/", methods=['GET'])
def index():
return render_template("upload.html")
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSION
@app.route("/uploads", methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
print("No fileee")
return redirect(request.url)
else:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print("file uploaded ")
main(UPLOAD_FOLDER + str(filename))
return render_template("completed.html", numberplate=numberplateintotext)
# print("Skippeddddd")
@app.route("/uploads/data", methods=['GET', 'POST'])
def data():
db = pymysql.connect("localhost", "testuser", "test123", "number_plate_recognition")
cursor = db.cursor()
sql = "SELECT * FROM information WHERE ID='"+numberplateintotext+"'"
print(sql)
#ya hera
try:
# Execute the SQL command
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
ID = row[0]
CompanyName = row[1]
ModelNumber = row[2]
ManufactureDate = row[3]
HorsePower = row[4]
CC = row[5]
EngineNumber = row[6]
ChassisNo = row[7]
EngineType = row[8]
SeaterCapacity = row[9]
BorderEntrance = row [10]
VechileType = row[11]
VechileColor = row[12]
print("=======================================DATABASE QUERY=============================================")
print("====================================================================================")
print("")
print("ID=%s,CompanyName=%s,ModelNumber=%s,ManufactureDate=%s,HorsePower=%d, CC=%d, EngineNumber=%s, ChassisNo=%s, EngineType=%s, SeaterCapacity=%d, BorderEntrance=%s, VechileType=%s, VechileColor=%s " %
(ID, CompanyName, ModelNumber, ManufactureDate, HorsePower,CC,EngineNumber,ChassisNo,EngineType,SeaterCapacity, BorderEntrance ,VechileType, VechileColor ))
print("")
print("====================================================================================")
print("====================================================================================")
except:
print("Error: unable to fetch data")
finally:
# disconnect from server
db.close()
return render_template("data.html", query=results, id=ID, companyname = CompanyName, modelnumber= ModelNumber, manufacturedate=ManufactureDate, horsepower= HorsePower, cc= CC, enginenumber= EngineNumber, chassisno = ChassisNo, enginetype=EngineType, seatercapacity= SeaterCapacity, border=BorderEntrance, vechiletype= VechileType, color= VechileColor)
def main(path):
dataTraining = DetectCharactersHelper.loadDataAndTrain() # attempt KNN training
if dataTraining == False: # if KNN training was not successful
print("\n error: KNN-traning was not successful\n") # show error message
return # and exit program
# end if
originalImage = cv2.imread(path) # open image
print(path)
if originalImage is None: # if image was not read successfully
print("\n ERROR:: image not read from the picture \n\n")
os.system("pause") # pauses the code so error can be checked
return # and exit program
# end if
listOfPossiblePlates = DetectPlatesHelper.detectPlatesInScene(originalImage) # detect plates
listOfPossiblePlates = DetectCharactersHelper.detectCharsInPlates(listOfPossiblePlates) # detect chars in plates
# cv2.imshow("Original_Image", originalImage) # show scene image
if len(listOfPossiblePlates) == 0: # if no plates were found
print("\n ERROR:: no license plates were detected\n") # print user no plates were found
else:
# sort the list of possible plates in DESCENDING order (most number of chars to least number of chars)
listOfPossiblePlates.sort(key=lambda possiblePlate: len(possiblePlate.strChars), reverse=True)
# suppose the plate with the most recognized chars (the first plate in sorted by string length descending order) is the actual plate
licPlate = listOfPossiblePlates[0]
# cv2.imshow("Plate_image", licPlate.imgPlate) # show crop of plate and threshold of plate
# cv2.imshow("Threshold_image", licPlate.imgThresh)
if len(licPlate.strChars) == 0: # if no chars were found in the plate
print("\n ERROR :: no characters were detected\n\n") # show message
return # and exit program
# end if
# draw red rectangle around plate
drawRedRectangleAroundPlate(originalImage, licPlate)
print("------------------DETECTED-NUMBER PLATE FROM IMAGE----------------------")
print("\n " + licPlate.strChars + "\n")
print("----------------------------------------")
writeLicensePlateCharsOnImage(originalImage, licPlate) # write license plate text on the image
# cv2.imshow("final_image", originalImage) # showing image again from image comparision
cv2.imwrite("original_Image.png", originalImage) # write image out to file
cv2.waitKey(0) # hold windows open until user presses a key
# end if else
global numberplateintotext
numberplateintotext = licPlate.strChars
return
# end main
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):
p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # four sides of rotated rectangle plate
cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), red, 2) # draw 4 red lines
cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), red, 2)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), red, 2)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), red, 2)
# end function
###################################################################################################
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written to
ptCenterOfTextAreaY = 0
BottomLowerLeftTextFromNumberPlateX = 0 # this will be the bottom left of the area that the text will be written to
BottomLowerLeftTextFromNumberPlateY = 0
sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape
plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape
intFontFace = cv2.FONT_HERSHEY_SIMPLEX # choose a plain jane font
fltFontScale = float(plateHeight) / 30.0 # base font scale on height of plate area
intFontThickness = int(round(fltFontScale * 1)) # base font thickness on font scale
textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale,
intFontThickness) # call getTextSize
# unpack roatated rect into center point, width and height, and angle
((intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight),
fltCorrectionAngleInDeg) = licPlate.rrLocationOfPlateInScene
intPlateCenterX = int(intPlateCenterX) # make sure center is an integer
intPlateCenterY = int(intPlateCenterY)
ptCenterOfTextAreaX = int(intPlateCenterX) # the horizontal location of the text area is the same as the plate
if intPlateCenterY < (sceneHeight * 0.75): # if the license plate is in the upper 3/4 of the image
ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(
round(plateHeight * 1.6)) # write the chars in below the plate
else: # else if the license plate is in the lower 1/4 of the image
ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(
round(plateHeight * 1.6)) # write the chars in above the plate
# end if
textSizeWidth, textSizeHeight = textSize # unpack text size width and height
BottomLowerLeftTextFromNumberPlateX = int(
ptCenterOfTextAreaX - (textSizeWidth / 2)) # calculate the lower left origin of the text area
BottomLowerLeftTextFromNumberPlateY = int(
ptCenterOfTextAreaY + (textSizeHeight / 2)) # based on the text area center, width, and height
# write the text on the image
cv2.putText(imgOriginalScene, licPlate.strChars,
(BottomLowerLeftTextFromNumberPlateX, BottomLowerLeftTextFromNumberPlateY), intFontFace, fltFontScale,
yellow, intFontThickness)
# end function
showSteps = False
# main()
# database()
if __name__ == '__main__':
app.run(debug=True)