0% found this document useful (0 votes)
43 views

Code Explain

This Python code implements a license plate recognition system using OpenCV. It takes an image as input, performs preprocessing like filtering and contour detection, extracts characters by detecting contours, recognizes characters using a trained SVM model, and displays the recognized license plate number. Key steps include preprocessing the image, finding the license plate region, extracting individual characters, recognizing characters with SVM, and displaying the results.

Uploaded by

Thinh Hoang
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Code Explain

This Python code implements a license plate recognition system using OpenCV. It takes an image as input, performs preprocessing like filtering and contour detection, extracts characters by detecting contours, recognizes characters using a trained SVM model, and displays the recognized license plate number. Key steps include preprocessing the image, finding the license plate region, extracting individual characters, recognizing characters with SVM, and displaying the results.

Uploaded by

Thinh Hoang
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

#pip install -r setup.

txt
import cv2 #thu vien cv2
import tkinter as tk #thu vien GUI
from tkinter import *
from tkinter.ttk import *
import numpy as np # thu vien mang array de xu ly anh
import tkinter.font as font
import PIL.Image,PIL.ImageTk # thu vien chuyen doi anh de hien thi
from tkinter import filedialog
import imutils
from tkinter import messagebox
window_=Tk()
window_.title("License Plate Recognize")
frame_camera=tk.Frame(window_, height=400, background="bisque")
frame_button=tk.Frame(window_, width=100, height=100,background="bisque")
canv= Canvas(frame_camera,width=500,height=400,bg='black')
canv_2=Canvas(frame_camera,width=500,height=400,bg='black')
dir_file=""
select_now= 0
img=np.zeros((504,304,3),np.uint8)
#new_image=np.zeros((504,304,3),np.uint8)
char_list = '0123456789ABCDEFGHKLMNPRSTUVXYZ'

dim=(0,0)

def sort_contours(cnts):
reverse = False
i = 0
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b: b[1][i], reverse=reverse))
return cnts
def start():
global img
global dim
print(dim)
#global new_image
#print("start")
try:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("gray-1", gray)
gray = cv2.bilateralFilter(gray, 13, 15, 15)
cv2.imshow("bilafilter-2", gray)
edged = cv2.Canny(gray, 30, 200)

contours = cv2.findContours(edged.copy(), cv2.RETR_TREE,


cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours) #
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]
cv2.drawContours(edged, contours, -1, (255, 0, 0), 3) #draw contour
screenCnt = None
for c in contours:

peri = cv2.arcLength(c, True)


approx = cv2.approxPolyDP(c, 0.018 * peri, True)
if len(approx) == 4:
screenCnt = approx
break
cv2.imshow("canny+contour-3", edged)
if screenCnt is None:
detected = 0
print("No contour detected")
else:
detected = 1
first=0
if detected == 1:
cv2.drawContours(img, [screenCnt], -1, (255, 0, 0), 3)

mask = np.zeros(gray.shape, np.uint8) # tao hinh anh ma tran shape


mask = gray

new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, ) # doi


cho contour thanh 255
cv2.imshow("detect-4", new_image)
new_image = cv2.bitwise_and(img, img, mask=mask) # chuyen ma tran anh
thanh chi la mask
new_image = cv2.convertScaleAbs(new_image, alpha=(255.0))
cv2.imshow("mask-5",new_image)
(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
Cropped = gray[topx:bottomx + 1, topy:bottomy + 1]
cv2.imshow("cropped-6",Cropped)
roi=Cropped
digit_w = 30
digit_h = 60
model_svm = cv2.ml.SVM_load('D:/file_D/File_/svm.xml')
binary = cv2.threshold(Cropped,110, 255,
cv2.THRESH_BINARY_INV)[1] # (110-180) para1

kernel_ = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2)) ## (2,2)


(3,3) #para2
thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel_) #....!!
cont, _ = cv2.findContours(thre_mor, cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(binary, cont, -1, (255, 0, 0), 3) # draw contour
cv2.imshow("thresh_cont-7", binary)
plate_info = ""
max_y=0
min_x=100
y_list=[]
x_list=[]
x_des =0
max_height = 0.4 #0.4->0.7 #para3
crop_2=Cropped.copy()
for c in sort_contours(cont):
(x, y, w, h) = cv2.boundingRect(c)
ratio = h / w
#print(ratio)
cv2.rectangle(crop_2, (x, y), (x + w, y + h), (100, 100, 0), 2)
if 1 <= ratio <= 4.5: # chieu cao va chieu dai nam torng khoang cho
phep

if h / roi.shape[0] >= max_height: # Chon cac contour cao tu


max_heigh% bien so tro len
max_y=max(y,max_y)
#print(max_y)
cv2.rectangle(roi, (x, y), (x + w, y + h), (0, 255, 0), 2)

curr_num = thre_mor[y:y + h, x:x + w]


curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h))
_, curr_num = cv2.threshold(curr_num, 30, 255,
cv2.THRESH_BINARY)
if first==0:
first=1
cv2.imshow("re_t-10",curr_num)
curr_num = np.array(curr_num, dtype=np.float32)
curr_num = curr_num.reshape(-1, digit_w * digit_h)
result = model_svm.predict(curr_num)[1]
#print(result)
result = int(result[0, 0])
if result <= 9: # Neu la so thi hien thi luon
result = str(result)
else: # Neu la chu thi chuyen bang ASCII
result = chr(result)
if(abs(max_y -y) >20):
plate_info=plate_info[:x_des]+result+plate_info[x_des:]
x_des+=1
else:
plate_info+=result

img_res = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)


cv2.imshow("ratio-8", crop_2)
cv2.imshow("pick_h-9", roi)
picture_2 = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(img_res))
window_.picture2 = picture_2
canv_2.create_image(0, 0, image=picture_2, anchor=tk.NW)
print(plate_info)
display.delete(0, END)
display.insert(0, plate_info)
except:
messagebox.showwarning("Warning","Select File!!")

def select():
global img
global dim
print("select")
window_.filename = filedialog.askopenfile(title="Select", filetypes=(("jpg",
"*.jpg"), ("All", "*.*")))
#print(window_.filename.name)
img = cv2.imread(window_.filename.name)
para_max = max(img.shape[1],img.shape[0])
if(para_max == img.shape[1]):
scale_percent = (int)(canv.winfo_width()/img.shape[1] *100)
else:
scale_percent = (int)(canv.winfo_height() / img.shape[0] * 100)
#print(scale_percent)
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)
# print(dim)
# print("size:",canv.winfo_width(),canv.winfo_height())
# resize image
img_res = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
#cv2.imshow("s",img)
#cv2.waitKey()
picture = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(img_res))
window_.picture=picture
canv.create_image(0, 0, image=picture, anchor=tk.NW)
myFont = font.Font(font='arial 15')
button_start=tk.Button(frame_button,command=start,bd=2,width=50,height=2,fg='white'
,bg='#6cbaea',activebackground="green",text="START")
button_measure=tk.Button(frame_button,text="SELECT",command=select,borderwidth=2,fg
='white',width=50,height=2,bg='#61a1ea',activebackground="green")
display=tk.Entry(frame_button,bd=20,width=100,justify='center')
display['font']=myFont
button_start['font']=myFont
button_measure['font']=myFont
button_measure.pack(pady=40)
button_start.pack(pady=10)
display.pack(side=BOTTOM)
frame_camera.pack(side=RIGHT,fill=BOTH,expand=True)
frame_camera.pack_propagate(0)
frame_button.pack(side=LEFT,fill=BOTH,expand=True)
frame_camera.pack_propagate(0)
canv.grid(column=0,row=0)
canv_2.grid(column=1,row=0)
window_.mainloop()

You might also like