您好,欢迎访问三七文档
当前位置:首页 > 行业资料 > 国内外标准规范 > 车牌识别Python程序
#-*-coding:utf-8-*-__author__='d1bysj'importpymysqldb=pymysql.connect(host='',#远程主机的ip地址,user='',#MySQL用户名db='',#database名passwd='',#数据库密码port=3306,#数据库监听端口,默认3306charset=utf8)#指定utf8编码的连接cur=db.cursor()sql=select*fromsextry:cur.execute(sql)re=cur.fetchall()foritinre:name=it[0]num=it[1]print(name,num)exceptExceptionase:raiseefinally:db.close()importcv2importnumpyasnpfromnumpy.linalgimportnormimportsysimportosimportjsonSZ=20#训练图片长宽MAX_WIDTH=1000#原始图片最大宽度Min_Area=2000#车牌区域允许最大面积PROVINCE_START=1000#读取图片文件defimreadex(filename):returncv2.imdecode(np.fromfile(filename,dtype=np.uint8),cv2.IMREAD_COLOR)defpoint_limit(point):ifpoint[0]0:point[0]=0ifpoint[1]0:point[1]=0#根据设定的阈值和图片直方图,找出波峰,用于分隔字符deffind_waves(threshold,histogram):up_point=-1#上升点is_peak=Falseifhistogram[0]threshold:up_point=0is_peak=Truewave_peaks=[]fori,xinenumerate(histogram):ifis_peakandxthreshold:ifi-up_point2:is_peak=Falsewave_peaks.append((up_point,i))elifnotis_peakandx=threshold:is_peak=Trueup_point=iifis_peakandup_point!=-1andi-up_point4:wave_peaks.append((up_point,i))returnwave_peaks#根据找出的波峰,分隔图片,从而得到逐个字符图片defseperate_card(img,waves):part_cards=[]forwaveinwaves:part_cards.append(img[:,wave[0]:wave[1]])returnpart_cards#来自opencv的sample,用于svm训练defdeskew(img):m=cv2.moments(img)ifabs(m['mu02'])1e-2:returnimg.copy()skew=m['mu11']/m['mu02']M=np.float32([[1,skew,-0.5*SZ*skew],[0,1,0]])img=cv2.warpAffine(img,M,(SZ,SZ),flags=cv2.WARP_INVERSE_MAP|cv2.INTER_LINEAR)returnimg#来自opencv的sample,用于svm训练defpreprocess_hog(digits):samples=[]forimgindigits:gx=cv2.Sobel(img,cv2.CV_32F,1,0)gy=cv2.Sobel(img,cv2.CV_32F,0,1)mag,ang=cv2.cartToPolar(gx,gy)bin_n=16bin=np.int32(bin_n*ang/(2*np.pi))bin_cells=bin[:10,:10],bin[10:,:10],bin[:10,10:],bin[10:,10:]mag_cells=mag[:10,:10],mag[10:,:10],mag[:10,10:],mag[10:,10:]hists=[np.bincount(b.ravel(),m.ravel(),bin_n)forb,minzip(bin_cells,mag_cells)]hist=np.hstack(hists)#transformtoHellingerkerneleps=1e-7hist/=hist.sum()+epshist=np.sqrt(hist)hist/=norm(hist)+epssamples.append(hist)returnnp.float32(samples)#不能保证包括所有省份provinces=[zh_cuan,川,zh_e,鄂,zh_gan,赣,zh_gan1,甘,zh_gui,贵,zh_gui1,桂,zh_hei,黑,zh_hu,沪,zh_ji,冀,zh_jin,津,zh_jing,京,zh_jl,吉,zh_liao,辽,zh_lu,鲁,zh_meng,蒙,zh_min,闽,zh_ning,宁,zh_qing,靑,zh_qiong,琼,zh_shan,陕,zh_su,苏,zh_sx,晋,zh_wan,皖,zh_xiang,湘,zh_xin,新,zh_yu,豫,zh_yu1,渝,zh_yue,粤,zh_yun,云,zh_zang,藏,zh_zhe,浙]classStatModel(object):defload(self,fn):self.model=self.model.load(fn)defsave(self,fn):self.model.save(fn)classSVM(StatModel):def__init__(self,C=1,gamma=0.5):self.model=cv2.ml.SVM_create()self.model.setGamma(gamma)self.model.setC(C)self.model.setKernel(cv2.ml.SVM_RBF)self.model.setType(cv2.ml.SVM_C_SVC)#训练svmdeftrain(self,samples,responses):self.model.train(samples,cv2.ml.ROW_SAMPLE,responses)#字符识别defpredict(self,samples):r=self.model.predict(samples)returnr[1].ravel()classCardPredictor:def__init__(self):#车牌识别的部分参数保存在js中,便于根据图片分辨率做调整f=open('config.js')j=json.load(f)forcinj[config]:print(c)ifc[open]:self.cfg=c.copy()breakelse:raiseRuntimeError('没有设置有效配置参数')def__del__(self):self.save_traindata()deftrain_svm(self):#识别英文字母和数字self.model=SVM(C=1,gamma=0.5)#识别中文self.modelchinese=SVM(C=1,gamma=0.5)ifos.path.exists(svm.dat):self.model.load(svm.dat)else:chars_train=[]chars_label=[]forroot,dirs,filesinos.walk(train\\chars2):iflen(os.path.basename(root))1:continueroot_int=ord(os.path.basename(root))forfilenameinfiles:filepath=os.path.join(root,filename)digit_img=cv2.imread(filepath)digit_img=cv2.cvtColor(digit_img,cv2.COLOR_BGR2GRAY)chars_train.append(digit_img)#chars_label.append(1)chars_label.append(root_int)chars_train=list(map(deskew,chars_train))chars_train=preprocess_hog(chars_train)#chars_train=chars_train.reshape(-1,20,20).astype(np.float32)chars_label=np.array(chars_label)print(chars_train.shape)self.model.train(chars_train,chars_label)ifos.path.exists(svmchinese.dat):self.modelchinese.load(svmchinese.dat)else:chars_train=[]chars_label=[]forroot,dirs,filesinos.walk(train\\charsChinese):ifnotos.path.basename(root).startswith(zh_):continuepinyin=os.path.basename(root)index=provinces.index(pinyin)+PROVINCE_START+1#1是拼音对应的汉字forfilenameinfiles:filepath=os.path.join(root,filename)digit_img=cv2.imread(filepath)digit_img=cv2.cvtColor(digit_img,cv2.COLOR_BGR2GRAY)chars_train.append(digit_img)#chars_label.append(1)chars_label.append(index)chars_train=list(map(deskew,chars_train))chars_train=preprocess_hog(chars_train)#chars_train=chars_train.reshape(-1,20,20).astype(np.float32)chars_label=np.array(chars_label)print(chars_train.shape)self.modelchinese.train(chars_train,chars_label)defsave_traindata(self):ifnotos.path.exists(svm.dat):self.model.save(svm.dat)ifnotos.path.exists(svmchinese.dat):self.modelchinese.save(svmchinese.dat)defaccurate_place(self,card_img_hsv,limit1,limit2,color):row_num,col_num=card_img_hsv.shape[:2]xl=col_numxr=0yh=0yl=row_num#col_num_limit=self.cfg[col_num_limit]row_num_limit=self.cfg[row_num_limit]col_num_limit=col_num*0.8ifcolor!=greenelsecol_num*0.5#绿色有渐变foriinrange(row_num):count=0forjinrange(col_num):H=c
本文标题:车牌识别Python程序
链接地址:https://www.777doc.com/doc-7319209 .html