1. 車牌字元分割
1.1 實作思路
基于像素直方圖,實作字元分割:首先對圖檔進行二值化處理,統計水準方向和豎直方向上各行各列的黑色像素的個數,根據像素的特點确定分割位置,進而完成字元分割。
1.2 原圖
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwIjNx8CX39CXy8CXycXZpZVZnFWbp9zZuBnLzUGOlJTZzYDMzM2M0gjZ3kzM3MmZ5YzM4YjZxIjZxI2LcJTO5ADO5czLcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
1.3 使用OpenCV
1.3.1 導入包庫
import cv2
from matplotlib import pyplot as plt
複制
1.3.2 讀取圖像,并把圖像轉換為灰階圖像并顯示
img_ = cv2.imread('jingC5Q712.BMP') # 讀取圖檔
cv2.imshow("img",img_)
cv2.waitKey(0)
img_gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY) # 轉換了灰階化
複制
1.3.3 将灰階圖像二值化,設定門檻值是100
cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY_INV)
複制
1.3.4 分割字元
white = [] # 記錄每一列的白色像素總和
black = [] # ..........黑色.......
height = img_thre.shape[0]
width = img_thre.shape[1]
white_max = 0
black_max = 0
# 計算每一列的黑白色像素總和
for i in range(width):
s = 0 # 這一列白色總數
t = 0 # 這一列黑色總數
for j in range(height):
if img_thre[j][i] == 255:
s += 1
if img_thre[j][i] == 0:
t += 1
white_max = max(white_max, s)
black_max = max(black_max, t)
white.append(s)
black.append(t)
複制
1.3.5 分割圖像
def find_end(start_):
end_ = start_ + 1
for m in range(start_ + 1, width - 1):
if (black[m] if arg else white[m]) > (0.95 * black_max if arg else 0.95 * white_max): # 0.95這個參數請多調整,對應下面的0.05(針對像素分布調節)
end_ = m
break
return end_
複制
1.3.6 完整代碼
import cv2
from matplotlib import pyplot as plt
## 根據每行和每列的黑色和白色像素數進行圖檔分割。
# 1、讀取圖像,并把圖像轉換為灰階圖像并顯示
img_ = cv2.imread('jingC5Q712.BMP') # 讀取圖檔
img_gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY) # 轉換了灰階化
# cv2.imshow('gray', img_gray) # 顯示圖檔
# cv2.waitKey(0)
# 2、将灰階圖像二值化,設定門檻值是100
ret, img_thre = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY_INV)
# cv2.imshow('white_black image', img_thre) # 顯示圖檔
# cv2.waitKey(0)
# 4、分割字元
white = [] # 記錄每一列的白色像素總和
black = [] # ..........黑色.......
height = img_thre.shape[0]
width = img_thre.shape[1]
white_max = 0
black_max = 0
# 計算每一列的黑白色像素總和
for i in range(width):
s = 0 # 這一列白色總數
t = 0 # 這一列黑色總數
for j in range(height):
if img_thre[j][i] == 255:
s += 1
if img_thre[j][i] == 0:
t += 1
white_max = max(white_max, s)
black_max = max(black_max, t)
white.append(s)
black.append(t)
# print(s)
# print(t)
arg = False # False表示白底黑字;True表示黑底白字
if black_max > white_max:
arg = True
# 分割圖像
def find_end(start_):
end_ = start_ + 1
for m in range(start_ + 1, width - 1):
if (black[m] if arg else white[m]) > (0.95 * black_max if arg else 0.95 * white_max): # 0.95這個參數請多調整,對應下面的0.05(針對像素分布調節)
end_ = m
break
return end_
n = 1
start = 1
end = 2
word = []
while n < width - 2:
n += 1
if (white[n] if arg else black[n]) > (0.05 * white_max if arg else 0.05 * black_max):
# 上面這些判斷用來辨識是白底黑字還是黑底白字
# 0.05這個參數請多調整,對應上面的0.95
start = n
end = find_end(start)
n = end
if end - start > 5:
cj = img_[1:height, start:end]
cj = cv2.resize(cj, (15, 30))
word.append(cj)
print(len(word))
for i,j in enumerate(word):
plt.subplot(1,9,i+1)
plt.imshow(word[i],cmap='gray')
plt.show()
複制
2. 實驗結果
3. 參考
基于OpenCV和Python的車牌提取和字元分割