Handwriting Number Recognition Using Python 2.7.11

来源:互联网 发布:网络销售股票怎么赚钱 编辑:程序博客网 时间:2024/05/22 01:52

The code blow comes from the Sentdex video on youtube, which I have changed a little bit.
It’s easy to understand with basic Python knowledge.

Now is the function and script:

# coding = utf-8# from sentdex video: image recognition# 2016-3-12from PIL import Imageimport numpy as npimport matplotlib.pyplot as pltimport timefrom collections import Counter# create a txt file of pixel of example imagesdef createExample():    numberArrayExamples = open('numArEx.txt', 'a')    numbersWeHave = range(0,6)    versionsWeHave = range(1,3)    for eachNum in numbersWeHave:        for eachVer in versionsWeHave:            print str(eachNum)+'.'+str(eachVer)            imgFilePath='Images/'+str(eachNum)+'.'+str(eachVer)+'.png'            ei = Image.open(imgFilePath)            eiar = np.array(ei)            eiar1 = str(eiar.tolist())            lineToWrite = str(eachNum)+'::'+eiar1+'\n'            print lineToWrite            numberArrayExamples.write(lineToWrite)    numberArrayExamples.close()# using threshold to transform images into 0-1 formatdef threshold(imageArray):    blanceAr = []    newAr = imageArray    for eachRow in imageArray:        for eachPix in eachRow:            print eachPix[:3]            print len(eachPix[:3])            avgNum = reduce(lambda x, y: x+y, eachPix[:3])/len(eachPix[:3])            blanceAr.append(avgNum)    balance = reduce(lambda x,y: x+y, blanceAr)/len(blanceAr)    for eachRow in newAr:        for eachPix in eachRow:            if reduce(lambda x, y: x+y, eachPix[:3]/len(eachPix[:3])) > balance:                eachPix[0]=255                eachPix[1]=255                eachPix[2]=255            else:                eachPix[0]=0                eachPix[1]=0                eachPix[2]=0    return newAr# Base on the example images, justify the number of input imagesdef whatNumIsThis(filePath):    matchedAr = []    loadExample = open('numArEx.txt','r').read()    loadExample = loadExample.split('\n')    i = Image.open(filePath)    iar = np.array(i)    iar1 = iar.tolist()    inQuestion = str(iar1)    for eachExample in loadExample:        if len(eachExample) > 3:            splitEx = eachExample.split('::')            currentNum = splitEx[0]            currentAr = splitEx[1]            eachPixEx = currentAr.split('],')            eachPixInQ = inQuestion.split('],')            x = 0            EqualPix = 0            # here change the code            # if the input image is 80% similar to the current labeled image,            # then append the label to matchedAr. In Counter(), get the number of similar images            # Or, you can counter the equal pixel of two images totolly in the for loop            # then use Counter() to get the most frequent number            while x<len(eachPixEx):                if eachPixEx[x] == eachPixInQ[x]:                    EqualPix+=1                x+=1            if EqualPix>len(eachPixEx)*0.8:                matchedAr.append(int(currentNum))    # print matchedAr    x = Counter(matchedAr)# counter the numbers# running scriptcreateExample()whatNumIsThis('Images/5.3.png')# below is test for function# i1 = Image.open('Fig0646(a)(lenna_original_RGB).tif')# iar1 = np.array(i1)# i2 = Image.open('Fig0648(a)(lenna-noise-R-gauss-mean0-var800).tif')# iar2 = np.array(i2)# print iar2# i3 = Image.open('Fig0648(b)(lenna-noise-G-gauss-mean0-var800).tif')# iar3 = np.array(i3)# i4 = Image.open('Fig0648(c)(lenna-noise-B-gauss-mean0-var800).tif')# iar4 = np.array(i4)## threshold(iar1)# threshold(iar2)# threshold(iar3)# threshold(iar4)## fig = plt.figure()# ax1 = plt.subplot2grid((8,6),(0,0),rowspan=4,colspan=3)# ax2 = plt.subplot2grid((8,6),(4,0),rowspan=4,colspan=3)# ax3 = plt.subplot2grid((8,6),(0,3),rowspan=4,colspan=3)# ax4 = plt.subplot2grid((8,6),(4,3),rowspan=4,colspan=3)## ax1.imshow(iar1)# ax2.imshow(iar2)# ax3.imshow(iar3)# ax4.imshow(iar4)## plt.show()

The Structure of Pycharm Project

0 0
原创粉丝点击