目錄
一、效果
1、成功案例
2、經典失敗案例(單字符識別成類似字符)
3、其他失敗案例
二、總結
三、車牌識別總代碼
一、效果
1、成功案例


2、經典失敗案例(單字符識別成類似字符)



3、其他失敗案例


二、總結
前面字符提取比較成功的,大多數的識別都沒太大問題,但是字符提取不到位,后面的識別作業自然也很難進行,這次的測驗失敗有很多都是前面的作業沒有做好,尤其是第一步的車牌提取,個人感覺車牌提取是本次專案最困難的地方,

三、車牌識別總代碼
# 車牌識別
import cv2 as cv
import numpy as np
import os
from matplotlib import pyplot as plt
from PIL import Image, ImageDraw, ImageFont
# 總檔案夾
List = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '云','京','冀','吉','寧','川','新','晉','桂','滬','津','浙','渝','湘','瓊',
'甘','皖','粵','蘇','蒙','藏','豫','貴','贛','遼','鄂','閩','陜','青','魯','黑']
# 車牌數字串列(10)
Num_List = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# 車牌英文串列(24)
Eng_List = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
# 車牌漢字串列(31)
Chinese_List = ['云','京','冀','吉','寧','川','新','晉','桂','滬','津','浙','渝','湘','瓊',
'甘','皖','粵','蘇','蒙','藏','豫','貴','贛','遼','鄂','閩','陜','青','魯','黑']
final_result = []
# 得到黑底白字(白色多則回傳真)
def IsWhiteMore(binary):
white = black = 0
height, width = binary.shape
# 遍歷每個像素
for i in range(height):
for j in range(width):
if binary[i,j]==0:
black+=1
else:
white+=1
if white >= black:
return True
else:
return False
# 限制影像大小(車牌)
def Limit(image):
height, width, channel = image.shape
# 設定權重
weight = width/300
# 計算輸出影像的寬和高
last_width = int(width/weight)
last_height = int(height/weight)
image = cv.resize(image, (last_width, last_height))
return image
# 二-5、統計白色像素點(分別統計每一行、每一列)
def White_Statistic(image):
ptx = [] # 每行白色像素個數
pty = [] # 每列白色像素個數
height, width = image.shape
# 逐行遍歷
for i in range(height):
num = 0
for j in range(width):
if(image[i][j]==255):
num = num+1
ptx.append(num)
# 逐列遍歷
for i in range(width):
num = 0
for j in range(height):
if (image[j][i] == 255):
num = num + 1
pty.append(num)
return ptx, pty
# 二-6、繪制直方圖
def Draw_Hist(ptx, pty):
# 依次得到各行、列
rows, cols = len(ptx), len(pty)
row = [i for i in range(rows)]
col = [j for j in range(cols)]
# 橫向直方圖
plt.barh(row, ptx, color='black', height=1)
# 縱 橫
# plt.show()
# 縱向直方圖
plt.bar(col, pty, color='black', width=1)
# 橫 縱
# plt.show()
# 二-7-2、橫向分割:上下邊框
def Cut_X(ptx, rows):
# 橫向切割(分為上下兩張圖,分別找其波谷,確定頂和底)
# 1、下半圖波谷
min, r = 300, 0
for i in range(int(rows / 2)):
if ptx[i] < min:
min = ptx[i]
r = i
h1 = r # 添加下行(作為頂)
# 2、上半圖波谷
min, r = 300, 0
for i in range(int(rows / 2), rows):
if ptx[i] < min:
min = ptx[i]
r = i
h2 = r # 添加上行(作為底)
return h1, h2
# 二-7-3、縱向分割:分割字符
def Cut_Y(pty, cols, h1, h2, binary):
global con, final_result
WIDTH = 33 # 經過測驗,一個字符寬度約為32
w = w1 = w2 = 0 # 前谷 字符開始 字符結束
begin = False # 字符開始標記
last = 10 # 上一次的值
con = 0 # 計數(字符)
final_result = [] # 清空已識別的車牌
# 縱向切割(正式切割字符)
for j in range(int(cols)):
# 0、極大值判斷
if pty[j] == max(pty):
if j < 30: # 左邊(跳過)
w2 = j
if begin == True:
begin = False
continue
elif j > 270: # 右邊(直接收尾)
if begin == True:
begin = False
w2 = j
b_copy = binary.copy()
b_copy = b_copy[h1:h2, w1:w2]
# cv.imshow('binary%d-%d' % (count, con), b_copy)
cv.imwrite('car_characters/image%d-%d.jpg' % (count, con), b_copy)
Template_Match(b_copy)
con += 1
break
# 1、前谷(前面的波谷)
if pty[j] < 12 and begin == False: # 前谷判斷:像素數量<12
last = pty[j]
w = j
# 2、字符開始(上升)
elif last < 12 and pty[j] > 20:
last = pty[j]
w1 = j
begin = True
# 3、字符結束
elif pty[j] < 13 and begin == True:
begin = False
last = pty[j]
w2 = j
width = w2 - w1
# 3-1、分割并顯示(排除過小情況)
if 10 < width < WIDTH + 3: # 要排除掉干擾,又不能過濾掉字符”1“
b_copy = binary.copy()
b_copy = b_copy[h1:h2, w1:w2]
# cv.imshow('binary%d-%d' % (count, con), b_copy)
cv.imwrite('car_characters/image%d-%d.jpg' % (count, con), b_copy)
Template_Match(b_copy)
con += 1
# 3-2、從多個貼合字符中提取單個字符
elif width >= WIDTH + 3:
# 統計貼合字符個數
num = int(width / WIDTH + 0.5) # 四舍五入
for k in range(num):
# w1和w2坐標向后移(用w3、w4代替w1和w2)
w3 = w1 + k * WIDTH
w4 = w1 + (k + 1) * WIDTH
b_copy = binary.copy()
b_copy = b_copy[h1:h2, w3:w4]
# cv.imshow('binary%d-%d' % (count, con), b_copy)
cv.imwrite('car_characters/image%d-%d.jpg' % (count, con), b_copy)
Template_Match(b_copy)
con += 1
# 4、分割尾部噪聲(距離過遠默認沒有字符了)
elif begin == False and (j - w2) > 30:
break
# 最后檢查收尾情況
if begin == True:
w2 = 295
b_copy = binary.copy()
b_copy = b_copy[h1:h2, w1:w2]
# cv.imshow('binary%d-%d' % (count, con), b_copy)
cv.imwrite('car_characters/image%d-%d.jpg' % (count, con), b_copy)
Template_Match(b_copy)
# 顯示識別結果(影像)
Show_Result_Image()
# 二-7、分割車牌影像(根據直方圖)
def Cut_Image(ptx, pty, binary, dilate):
h1 = h2 = 0
#頂 底
begin = False #標記開始/結束
# 1、依次得到各行、列
rows, cols = len(ptx), len(pty)
row = [i for i in range(rows)]
col = [j for j in range(cols)]
# 2、橫向分割:上下邊框
h1, h2 = Cut_X(ptx, rows)
# cut_x = binary[h1:h2, :]
# cv.imshow('cut_x', cut_x)
# 3、縱向分割:分割字符
Cut_Y(pty, cols, h1, h2, binary)
# 顯示文字(中文)(用的PIL,RGB正常顯示,即和opencv的RGB相反)
def Text(image, text, p, color, size):
# cv2讀取圖片
# BGR轉RGB:cv2和PIL中顏色的hex碼的儲存順序不同
cv2_image = cv.cvtColor(image, cv.COLOR_RGB2BGR)
pil_image = Image.fromarray(cv2_image)
# PIL圖片上列印漢字
draw = ImageDraw.Draw(pil_image) # 圖片上列印
font = ImageFont.truetype("./simhei.ttf", size, encoding="utf-8") # 引數1:字體檔案路徑,引數2:字體大小
draw.text((p[0]-60, p[1]-20), text, color, font=font)
# PIL圖片轉cv2 圖片
cv2_result = cv.cvtColor(np.array(pil_image), cv.COLOR_RGB2BGR)
# cv2.imshow("圖片", cv2_result) # 漢字視窗標題顯示亂碼
# cv.imshow("photo", cv2_result) # 輸出漢字
return cv2_result
# 顯示識別結果(文字)
def Show_Result_Words(index):
print(List[index])
final_result.append(List[index])
print(final_result)
# 顯示識別結果(影像)
def Show_Result_Image():
p = image_rect[0], image_rect[1]
w, h = image_rect[2] , image_rect[3]
# 框出車牌
cv.rectangle(img, (p[0],p[1]), (p[0]+w, p[1]+h), (0,0,255), 2)
# 輸出字符(中文)
result = Text(img, str(final_result), p, (255,0,0), 16)
cv.imshow('result-%d'%count, result)
# cv.waitKey(0)
# 一、形態學提取車牌
def Get_Licenses(image):
global image_rect #待回傳的矩形坐標
# 1、轉灰度圖
gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
# cv.imshow('gray', gray)
# 2、頂帽運算
# gray = cv.equalizeHist(gray)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (17,17))
tophat = cv.morphologyEx(gray, cv.MORPH_TOPHAT, kernel)
# cv.imshow('tophat', tophat)
# 3、Sobel算子提取y方向邊緣(揉成一坨)
y = cv.Sobel(tophat, cv.CV_16S, 1, 0)
absY = cv.convertScaleAbs(y)
# cv.imshow('absY', absY)
# 4、自適應二值化(閾值自己可調)
ret, binary = cv.threshold(absY, 75, 255, cv.THRESH_BINARY)
# cv.imshow('binary', binary)
# 5、開運算分割(縱向去噪,分隔)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, 15))
Open = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
# cv.imshow('Open', Open)
# 6、閉運算合并,把影像閉合、揉團,使影像區域化,便于找到車牌區域,進而得到輪廓
kernel = cv.getStructuringElement(cv.MORPH_RECT, (41, 15))
close = cv.morphologyEx(Open, cv.MORPH_CLOSE, kernel)
# cv.imshow('close', close)
# 7、膨脹/腐蝕(去噪得到車牌區域)
# 中遠距離車牌識別
kernel_x = cv.getStructuringElement(cv.MORPH_RECT, (25, 7))
kernel_y = cv.getStructuringElement(cv.MORPH_RECT, (1, 11))
# 近距離車牌識別
# kernel_x = cv.getStructuringElement(cv.MORPH_RECT, (79, 15))
# kernel_y = cv.getStructuringElement(cv.MORPH_RECT, (1, 31))
# 7-1、腐蝕、膨脹(去噪)
erode_y = cv.morphologyEx(close, cv.MORPH_ERODE, kernel_y)
# cv.imshow('erode_y', erode_y)
dilate_y = cv.morphologyEx(erode_y, cv.MORPH_DILATE, kernel_y)
# cv.imshow('dilate_y', dilate_y)
# 7-1、膨脹、腐蝕(連接)(二次縫合)
dilate_x = cv.morphologyEx(dilate_y, cv.MORPH_DILATE, kernel_x)
# cv.imshow('dilate_x', dilate_x)
erode_x = cv.morphologyEx(dilate_x, cv.MORPH_ERODE, kernel_x)
# cv.imshow('erode_x', erode_x)
# 8、腐蝕、膨脹:去噪
kernel_e = cv.getStructuringElement(cv.MORPH_RECT, (25, 9))
erode = cv.morphologyEx(erode_x, cv.MORPH_ERODE, kernel_e)
# cv.imshow('erode', erode)
kernel_d = cv.getStructuringElement(cv.MORPH_RECT, (25, 11))
dilate = cv.morphologyEx(erode, cv.MORPH_DILATE, kernel_d)
# cv.imshow('dilate', dilate)
# 9、獲取外輪廓
img_copy = image.copy()
# 9-1、得到輪廓
contours, hierarchy = cv.findContours(dilate, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# 9-2、畫出輪廓并顯示
cv.drawContours(img_copy, contours, -1, (255, 0, 255), 2)
# cv.imshow('Contours', img_copy)
# 10、遍歷所有輪廓,找到車牌輪廓
i = 0
for contour in contours:
# 10-1、得到矩形區域:左頂點坐標、寬和高
rect = cv.boundingRect(contour)
# 10-2、判斷寬高比例是否符合車牌標準,截取符合圖片
if rect[2]>rect[3]*3 and rect[2]<rect[3]*7:
# 截取車牌并顯示
print(rect)
image_rect = rect
img_copy = image.copy()
image = image[(rect[1]):(rect[1]+rect[3]), (rect[0]):(rect[0]+rect[2])] #高,寬
try:
# 限制大小(按照比例限制)
image = Limit(image)
cv.imshow('license plate%d-%d' % (count, i), image)
cv.imwrite('car_licenses/image%d-%d.jpg'%(count, i), image)
i += 1
return image
except:
pass
return image
# 二、直方圖提取字符
def Get_Character(image):
# 清空
final_result = []
# 1、中值濾波
mid = cv.medianBlur(image, 5)
# 2、灰度化
gray = cv.cvtColor(mid, cv.COLOR_BGR2GRAY)
# 3、二值化
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_OTSU)
# 統一得到黑底白字
if(IsWhiteMore(binary)): #白色部分多則為真,意味著背景是白色,需要黑底白字
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY_INV)
cv.imshow('binary', binary)
# 4、膨脹(粘貼橫向字符)
kernel = cv.getStructuringElement(cv.MORPH_RECT, (7,1)) #橫向連接字符
dilate = cv.dilate(binary, kernel)
# cv.imshow('dilate', dilate)
# 5、統計各行各列白色像素個數(為了得到直方圖橫縱坐標)
ptx, pty = White_Statistic(dilate)
# 6、繪制直方圖(橫、縱)
Draw_Hist(ptx, pty)
# 7、分割(橫、縱)(橫向分割邊框、縱向分割字符)
Cut_Image(ptx, pty, binary, dilate)
# cv.waitKey(0)
# 三、模板匹配
# 原圖和模板進行對比,越匹配,得分越大
def Template_Match(image):
# 單檔案夾內的最佳得分
best_score = []
# 遍歷所有檔案夾(每一個檔案夾匹配)
# (1) 漢字(首個位置只能是漢字(省))(為了節約時間)
if con == 0:
# 遍歷34——65檔案夾(漢字)
for i in range(34,65):
# 單個圖片的得分
score = []
ForderPath = 'Template/' + List[i]
# 遍歷單檔案夾(每一個檔案匹配)
for filename in os.listdir(ForderPath):
# 路徑
path = 'Template/' + List[i] + '/' + filename
# 1、得到模板
template = cv.imdecode(np.fromfile(path, dtype=np.uint8), 1) #彩(類似imread)
gray = cv.cvtColor(template, cv.COLOR_RGB2GRAY) #灰
ret, template = cv.threshold(gray, 0, 255, cv.THRESH_OTSU) #二值
# 2、原圖限定大小(和模板相似)
h, w = template.shape
image = cv.resize(image, (w, h))
# 3、模板匹配,得到得分(匹配度越高,得分越大)
result = cv.matchTemplate(image, template, cv.TM_CCOEFF)
score.append(result[0][0]) #得分(每張模板圖)
# 4、保存子檔案夾的最高得分(得分越高,匹配度越高)
best_score.append(max(score))
# 5、根據所有檔案夾的最佳得分確定下標
index = best_score.index(max(best_score))+34
# (2) 字母(第二個位置只能為字母)
elif con == 1:
# 遍歷10~34檔案夾(字母檔案夾)
for i in range(10,34):
# 單個圖片的得分
score = []
ForderPath = 'Template/' + List[i]
# 遍歷單檔案夾(每一個檔案匹配)
for filename in os.listdir(ForderPath):
# 路徑
path = 'Template/' + List[i] + '/' + filename
# 模板
template = cv.imdecode(np.fromfile(path, dtype=np.uint8), 1) #彩(類似imread)
gray = cv.cvtColor(template, cv.COLOR_RGB2GRAY) #灰
ret, template = cv.threshold(gray, 0, 255, cv.THRESH_OTSU) #二值
h, w = template.shape
image = cv.resize(image, (w, h))
# 模板匹配,得到得分(匹配度越高,得分越大)
result = cv.matchTemplate(image, template, cv.TM_CCOEFF)
score.append(result[0][0]) #得分(每張模板圖)
# 一個檔案夾的最高得分(得分越高,匹配度越高)
best_score.append(max(score))
# 根據所有檔案夾的最佳得分確定下標
index = best_score.index(max(best_score)) + 10
# (3) 數字+字母
else:
# 遍歷0~34檔案夾(數字+字母)
for i in range(34):
# 單個圖片的得分
score = []
ForderPath = 'Template/' + List[i]
# 遍歷單檔案夾(每一個檔案匹配)
for filename in os.listdir(ForderPath):
# 路徑
path = 'Template/' + List[i] + '/' + filename
# 模板
template = cv.imdecode(np.fromfile(path, dtype=np.uint8), 1) #彩(類似imread)
gray = cv.cvtColor(template, cv.COLOR_RGB2GRAY) #灰
ret, template = cv.threshold(gray, 0, 255, cv.THRESH_OTSU) #二值
h, w = template.shape
image = cv.resize(image, (w, h))
# 模板匹配,得到得分(匹配度越高,得分越大)
result = cv.matchTemplate(image, template, cv.TM_CCOEFF)
score.append(result[0][0]) #得分(每張模板圖)
# 一個檔案夾的最高得分(得分越高,匹配度越高)
best_score.append(max(score))
# 根據所有檔案夾的最佳得分確定下標
index = best_score.index(max(best_score))
# 顯示結果(文字)(每識別一個顯示一次)
Show_Result_Words(index)
if __name__ == '__main__':
global count, img
count=0 #計數:第幾張圖片
# cv.waitKey(0)
# 遍歷檔案夾中的每張圖片(車)
for car in os.listdir('cars'):
# 1、獲取路徑
path = 'cars/'+'car'+str(count)+'.jpg'
# 2、獲取圖片
img = cv.imread(path)
image = img.copy()
# cv.imshow('image', image)
# 3、提取車牌
image = Get_Licenses(image) #形態學提取車牌
# 4、分割字符
Get_Character(image)
count += 1
cv.waitKey(0)
一張車牌約20秒,這些演算法很多可能已經逐漸被淘汰了,這里只是作為學習用途,沒有太高的實際應用價值,(后期進軍深度學習/機器學習,可能會對這些進行優化),有什么好的建議大家可以提出來,共同進步,謝謝~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/298195.html
標籤:其他
