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

Code

This Python code recognizes license plates from images using OpenCV. It takes an image as input, detects the license plate region using contour detection, extracts characters using SVM classification, and displays the recognized plate characters. It has a graphical user interface to select an image, start recognition, and display results. The code preprocesses the image, finds contours, extracts characters, recognizes with a pre-trained SVM model, and displays the output.

Uploaded by

Thinh Hoang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Code

This Python code recognizes license plates from images using OpenCV. It takes an image as input, detects the license plate region using contour detection, extracts characters using SVM classification, and displays the recognized plate characters. It has a graphical user interface to select an image, start recognition, and display results. The code preprocesses the image, finds contours, extracts characters, recognizes with a pre-trained SVM model, and displays the output.

Uploaded by

Thinh Hoang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
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)
gray = cv2.bilateralFilter(gray, 13, 15, 15)
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]
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
if screenCnt is None:
detected = 0
print("No contour detected")
else:
detected = 1
if detected == 1:
cv2.drawContours(img, [screenCnt], -1, (255, 0, 0), 3)
mask = np.zeros(gray.shape, np.uint8)
new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, )
new_image = cv2.bitwise_and(img, img, mask=mask)
(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]
#new_image=cv2.convertScaleAbs(new_image, alpha=(255.0))
roi=Cropped

digit_w = 30
digit_h = 60
model_svm = cv2.ml.SVM_load('D:/file_D/File_/svm.xml')
binary = cv2.threshold(Cropped,120, 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)
plate_info = ""
max_y=0
min_x=100
y_list=[]
x_list=[]
x_des =0
max_height = 0.5 #0.4->0.7 #para3
for c in sort_contours(cont):
(x, y, w, h) = cv2.boundingRect(c)

ratio = h / w
#print(ratio)
if 1 <= ratio <= 4.5:

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


60% 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)
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)
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