Word recognition
#-*-coding:utf-8-*-"""Introduction: Training data with samples, re-identifying"""ImportCv2ImportNumPy as NP fromPILImportImage#Python Image LibImportSkimage.feature as Feature2dImportSklearn.neighbors as NHB fromSklearn.externalsImportJoblib#Save or read to the training model#Cvhog=cv2. Hogdescriptor ()#preprocessing Picturesdefimgprepare (filename): img=cv2.imread (filename,0) img=np.uint8 (IMG/IMG.PTP () *255) img=np.where (img>128,255, IMG) img=np.where (img<=128, 0,img) img=np.bitwise_not (IMG)returnimg#crosscuttingdefSplitchar (Img,axis=1): Idxrowb=np.all (img<64,axis=axis) Idxrowi=np.uint8 (IDXROWB). Ravel () Dy=idxrowi[1:]-idxrowi[:-1] #print (DY)Rowb=np.argwhere (dy==255). Ravel () Rowe=np.argwhere (dy==1). Ravel ()#print (Rowb,rowe) ifAxis==1: Imglines=[img[b:e+1,:] forB,einchzip (rowb,rowe)]Else: Imglines=[IMG[:,B:E+1] forB,einchzip (rowb,rowe)]returnImglines#DiceddefSplitbox (IMG): IDXROWB=np.all (Img<64,axis=1) Idxrowi=np.uint8 (IDXROWB). Ravel () Dy=idxrowi[1:]-idxrowi[:-1] #print (DY)Rowb=np.argwhere (dy==255). Ravel () Rowe=np.argwhere (dy==1). Ravel () b=0 E=-1ifLen (Rowe) >0:e=rowe[-1]+1ifLen (ROWB) >0:b=Rowb[0]returnimg[b:e,:]#make the picture the same sizedefMyresize (img,size= (48,48)): H,w=Img.shape BW=Max (h,w) BH=BW bimg=Np.zeros ((BH,BW), np.uint8)ifbw==W:DH= (bh-h)//2BIMG[DH:DH+h,:]=img[:,:]Else: DW= (bw-w)//2BIMG[:,DW:DW+w]=img[:,:] bimg=cv2.resize (bimg,size)returnbimg#get hog vector picture to vectordefGethog (Img,cell= (16,16), block= (3,3)): Vec=feature2d.hog (Img,12,cell,block,'L2') returnVEC#the main method of trainingGimg=imgprepare ('e:/sx.jpg') Lines=splitchar (Gimg,axis=1) Chars=[] forLineinchlines:charlist=splitchar (line,axis=0) Cchars=[Myresize (Splitbox (c)) forCinchcharlist] Chars.append (cchars) chars=Np.asarray (chars) X=[]y=[]y=0 forLinechinchchars: forChinchLinech:chhog=gethog (CH) x.append (Chhog) y.append (y) y+=1KNC=NHB. Kneighborsclassifier (algorithm='Ball_tree', n_neighbors=3) Knc.fit (x, y) joblib.dump (KNC,'KNC.KNN')#Main method of recognitiondefPredict (IMG): KNC=NHB. Kneighborsclassifier (algorithm='Ball_tree', n_neighbors=3) KNC=joblib.load ('KNC.KNN') Lines=splitchar (Img,axis=1) Chars=[] forLineinchlines:charlist=splitchar (line,axis=0) Cchars=[Myresize (Splitbox (c)) forCinchcharlist] Chars.append (cchars) chars=Np.asarray (chars) Y=[] forLinechinchchars:x=[] forChinchLinech:chhog=gethog (CH) x.append (chhog) y=knc.predict (x)Print(y) y.append (y)returnY
word recognition
Python_ Scientific Computing Library