yuhai.china 发表于 2013-2-7 10:03:59

利用PIL做简单的图片数字识别

#coding:gbk'''Created on 2009-7-7@author: yuhai'''import StringIOimport Image,osimport editdistdic={} def readimg(imgpath):      buffer=StringIO.StringIO();      im = Image.open(imgpath)      for y in range(20):            for x in range(9):                v= im.getpixel((x,y))                if v<200:buffer.write('1')                else : buffer.write('0')      buffer.seek(0)      return buffer.read()def regimg(imgpath):    im = Image.open(imgpath).convert('L')    result=StringIO.StringIO()    for i in range(4):      tmp =im.crop((i*9,0,i*10+10,20))      s=StringIO.StringIO()      tmp.save(s,"JPEG")      s.seek(0)      v=readimg(s)      idx=0            score=editdist.distance(v,dic)      for j in range(1,10):            tmp=editdist.distance(v,dic)            if tmp<score:                score=tmp                idx=j      result.write(str(idx))    result.seek(0)    return result.read()def init():    f=open('./data','w')    for i in range(10):      dic= readimg('e:/'+str(i)+'.bmp')      f.write(dic)      f.write('\n')    f.close()def readdata():    f=open('./data','r')    i=0    for line in f.readlines():      dic= line.strip()      i=i+1    f.close()    def test():    files = os.listdir('e:/img/')   redic=[]    for f in files:         if f.find('.bmp') !=-1:            result=regimg('e:/img/'+f)            if f==result+'.bmp':                redic.append(f)                print f,result    print 'correct %s' % len(redic)                def getcontent(imgpath):    im = Image.open(imgpath).convert('L')    print im.size    box=(10,0,19,20)    t=im.crop(box)    t.save('e:/5.bmp', "JPEG")   if __name__ == '__main__':       #getcontent('e:/img/1560.bmp')    #init()    readdata()    test()
页: [1]
查看完整版本: 利用PIL做简单的图片数字识别