一、彩色图像转换
二、车牌数字分割
(一)图片
图片(目录不能有中文,不然后面会出错)
(二)完整代码
#导入包
import os
import shutil
import cv2
import numpy as np
file_path = "D:/jupyter/car/picture/"
licenses = os.listdir(file_path)
for license in licenses:
path = file_path+license
output_path = "D:/jupyter/car/"+license # 图片输出路径
# 如果该路径存在则删除
if os.path.isdir(output_path):
shutil.rmtree(output_path)
# 创建文件夹
os.mkdir(output_path)
# 1.读取图片
src = cv2.imread(path)
img = src.copy()
# 2.去除车牌上螺丝,将其替换为车牌底色
cv2.circle(img, (145, 20), 10, (255, 0, 0), thickness=-1)
cv2.circle(img, (430, 20), 10, (255, 0, 0), thickness=-1)
cv2.circle(img, (145, 170), 10, (255, 0, 0), thickness=-1)
cv2.circle(img, (430, 170), 10, (255, 0, 0), thickness=-1)
cv2.circle(img, (180, 90), 10, (255, 0, 0), thickness=-1)
# 3.灰度
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# 4.高斯滤波
GSblurred = cv2.GaussianBlur(gray, (5, 5), 12)
# 5.将灰度图二值化设定阈值
ret, thresh = cv2.threshold(GSblurred , 127, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
print("ret",ret)
# 6. 闭运算
kernel = np.ones((3, 3), int)
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel,iterations=2)
#二值化
ret, thresh = cv2.threshold(closed, 127, 255, cv2.THRESH_BINARY+ cv2.THRESH_OTSU)
# 7.分割字符
white = [] # 记录每一列的白色像素总和
black = [] # ..........黑色.......
height = thresh.shape[0]
width = thresh.shape[1]
white_max = 0
black_max = 0
# 计算每一列的黑白色像素总和
for i in range(width):
s = 0 # 这一列白色总数
t = 0 # 这一列黑色总数
for j in range(height):
if thresh[j][i] == 255:
s += 1
if thresh[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
i=0;
cj=[]
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.append(thresh[1:height, start:end])
cv2.imwrite(output_path + '/' + str(i) + '.jpg', cj[i])
i += 1;
(三)结果
参考文献
python中出现“Unexpected indent”的原因,已解决
|