You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.4 KiB

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