知足常乐|最优!python+opencv实现蓝色车牌字符分割( 二 )


#---第4步:定义函数找到结束点---def find_end(start,arg,black,white,width,black_max,white_max):end=start+1for m in range(start+1,width-1):#0.98与下面的0.02对应if (black[m] if arg else white[m])>(0.98*black_max if arg else 0.98*white_max):end=mbreakreturn end4.5 第5步:分割字符和保存字符 , 注意cv2格式的显示、保存和操作enter下一步 。
n=1start=1end=2word = []while n(0.02*white_max if arg else 0.02*black_max):start=n#调用前面的函数 , 找结束点endend=find_end(start,arg,black,white,width,black_max,white_max)n=endif end-start>5:cj=img_thre[1:height,start:end]#保存分割的图片cv2.imwrite("/home/xgj/Desktop/carcut/result/%s.jpg" % (n),cj)cv2.imshow('solocutlicense',cj)word.append(cj)cv2.waitKey(0)cv2.waitKey(0)cv2.destroyAllWindows()4.6 第6步:用matplotlib将汽车车牌在一张图中并排显示 , 顺带复习matplotlib 。
from matplotlib import pyplot as plt#这个可以放在前面for i,j in enumerate(word):plt.subplot(1,8,i+1)plt.imshow(word[i],cmap='gray')plt.show()5 完整代码:
#---第1步:导出模块---import cv2import numpy as np#---第2步:图片的预处理---# 2-1:读取抠出来的蓝色车牌img=cv2.imread('/home/xgj/Desktop/carcut/1.png')cv2.imshow('carblurpai',img)cv2.waitKey(0)# 2-2:图像归一化img_resize = cv2.resize(img,(136,36),interpolation=cv2.INTER_AREA)# 2-3:灰度化+二值化img_gray_1 = cv2.cvtColor(img_resize,cv2.COLOR_BGR2GRAY)ret1,img_thre_1 = cv2.threshold(img_gray_1,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)# 2-4:高斯模糊img_gaus = cv2.GaussianBlur(img_resize,(3,5),0) # 2-5:灰度处理img_gray = cv2.cvtColor(img_gaus,cv2.COLOR_BGR2GRAY) # 2-6:图像黑白的二值化ret,img_thre = cv2.threshold(img_gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #---第3步:判断底色和字色---# 3-1:初始化定义列表white=[]black=[]height=img_thre.shape[0]width=img_thre.shape[1] white_max=0black_max=0# 3-2:计算每一列的黑白像素总和for i in range(width):line_white=0line_black=0for j in range(height):if img_thre[j][i]==255:line_white+=1if img_thre[j][i]==0:line_black+=1white_max=max(white_max,line_white)black_max=max(black_max,line_black)white.append(line_white)black.append(line_black)# 3-3:arg为true表示黑底白字 , False为白底黑字arg=Trueif black_max(0.98*black_max if arg else 0.98*white_max):end=mbreakreturn end#---第5步:分割字符并保存字符---n=1start=1end=2word = []while n(0.02*white_max if arg else 0.02*black_max):start=n#调用前面的函数 , 找结束点endend=find_end(start,arg,black,white,width,black_max,white_max)n=endif end-start>5:cj=img_thre[1:height,start:end]#保存分割的图片cv2.imwrite("/home/xgj/Desktop/carcut/result/%s.jpg" % (n),cj)cv2.imshow('solocutlicense',cj)word.append(cj)cv2.waitKey(0)cv2.waitKey(0)cv2.destroyAllWindows()#---第6步:---再加用matplotlib展示from matplotlib import pyplot as plt#这个可以放在前面for i,j in enumerate(word):plt.subplot(1,8,i+1)plt.imshow(word[i],cmap='gray')plt.show()


推荐阅读