fork download
  1. import tkinter as tk
  2. import tkinter.filedialog as fd
  3. import PIL.Image
  4. import PIL.ImageTk
  5.  
  6. # 機械学習で使うモジュ-ル
  7. import sklearn.datasets
  8. import sklearn.svm
  9. import PIL.Image
  10. import numpy
  11.  
  12. # 画像ファイルを数値リストに変換
  13. def imageToData(filename):
  14. # 画像を8×8のグレ-スケ-ルに変換
  15. grayImage = PIL.Image.open(filename).convert("L")
  16. grayImage = grayImage.resize((8,8),PIL.Image.ANTIALIAS)
  17.  
  18. # その画像を表示
  19. dispImage = PIL.ImageTk.PhotoImage(grayImage.resize((300,300)))
  20. imageLabel.configure(image = dispImage)
  21. imageLabel.image = dispImage
  22.  
  23. # 数値リストに変換
  24. numImage = numpy.asarray(grayImage, dtype = float)
  25. numImage = numpy.floor(16 - 16 * (numImage / 256))
  26. numImage = numImage.flatten()
  27.  
  28. return numImage
  29.  
  30. # 数字を予測する
  31. def predictDigits(data):
  32. # 学習用デ-タを読み込む
  33. digits = sklearn.datasets.load_digits()
  34. # 機械学習する
  35. clf = sklearn.svm.SVC(gamma = 0.001)
  36. clf.fit(digits.data,digits.target)
  37. # 予測結果を表示
  38. n = clf.predict([data])
  39. textLabel.configure(text = "この画像は"+str(n)+"です!")
  40.  
  41. # ファイルダイアログを開く
  42. def openFile():
  43. fpath = fd.askopenfilename()
  44. if fpath:
  45. # 画像ファイルを数値リストに変換
  46. data = imageToData(fpath)
  47. # 数字を予測
  48. predictDigits(data)
  49.  
  50.  
  51. # ウィンドウを作る
  52. root = tk.Tk()
  53. root.geometry("400x400")
  54.  
  55. btn = tk.Button(root, text="ファイルを開く", command = openFile )
  56.  
  57.  
  58. imageLabel = tk.Label()
  59.  
  60.  
  61. btn.pack()
  62. imageLabel.pack()
  63.  
  64.  
  65. # 予測結果を表示
  66. textLabel = tk.Label(text="手書き数字を認識!")
  67. textLabel.pack()
  68.  
  69. tk.mainloop()
  70.  
Runtime error #stdin #stdout #stderr 0.03s 81920KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "./prog.py", line 4, in <module>
ImportError: No module named 'PIL.ImageTk'