numberImgRecognition/pythonVersion/imgrec.py
pythonVersion/imgrec.pyRaw
1from PIL import Image
2import numpy as np
3import matplotlib.pyplot as plt
4import time
5from collections import Counter
6import operator
7
8def createExamples():
9 numberArrayExamples = open('numArEx.txt', 'a')
10 numbersWeHave = range(1,10)
11 versionsWeHave = range(1,10)
12
13 for eachNum in numbersWeHave:
14 for eachVer in versionsWeHave:
15 #print str(eachNum) + '.' + str(eachVer)
16 imgFilePath = 'images/numbers/' + str(eachNum) + '.' + str(eachVer) + '.png'
17 ei = Image.open(imgFilePath)
18 eiar = np.array(ei)
19 eiar1 = str(eiar.tolist())
20
21 lineToWrite = str(eachNum) + '::' + eiar1 + '\n'
22 numberArrayExamples.write(lineToWrite)
23
24
25def threshold(imageArray):
26 balanceAr = []
27 newAr = imageArray
28
29 for eachRow in imageArray:
30 for eachPix in eachRow:
31 avgNum = reduce(lambda x, y: x+y, eachPix[:3])/len(eachPix[:3])
32 balanceAr.append(avgNum)
33
34 balance = reduce(lambda x, y: x + y, balanceAr)/len(balanceAr)
35
36 for eachRow in newAr:
37 for eachPix in eachRow:
38 if reduce(lambda x, y: x+y, eachPix[:3])/len(eachPix[:3]) > balance:
39 eachPix[0] = 255
40 eachPix[1] = 255
41 eachPix[2] = 255
42 eachPix[3] = 255
43 else:
44 eachPix[0] = 0
45 eachPix[1] = 0
46 eachPix[2] = 0
47 eachPix[3] = 255
48
49 return newAr
50
51def whatNumIsThis(filePath):
52 matchedAr = []
53 loadExamps = open('numArEx.txt', 'r').read()
54 loadExamps = loadExamps.split('\n')
55
56 i = Image.open(filePath)
57 iar = np.array(i)
58 iarl = iar.tolist()
59
60 inQuestion = str(iarl)
61
62 for eachExample in loadExamps:
63 if len(eachExample) > 3:
64 splitEx = eachExample.split('::')
65 currentNum = splitEx[0]
66 currentAr = splitEx[1]
67
68 eachPixEx = currentAr.split('],')
69
70 eachPixInQ = inQuestion.split('],')
71
72 x=0
73
74 while x < len(eachPixEx):
75 if eachPixEx[x] == eachPixInQ[x]:
76 matchedAr.append(int(currentNum))
77
78 x += 1
79
80 #print matchedAr
81 x = Counter(matchedAr)
82 #print x
83 numb = max(x.iteritems(), key=operator.itemgetter(1))[0]
84 #print numb
85 return numb, x
86
87
88
89n, counts = whatNumIsThis('images/test.png')
90print n
91print counts