Commit a16ee9a8 authored by SCtom's avatar SCtom

optimize code

parent f6d01e6f
sessions/session-4/Test/temp.png

292 Bytes | W: | H:

sessions/session-4/Test/temp.png

343 Bytes | W: | H:

sessions/session-4/Test/temp.png
sessions/session-4/Test/temp.png
sessions/session-4/Test/temp.png
sessions/session-4/Test/temp.png
  • 2-up
  • Swipe
  • Onion skin
...@@ -2,6 +2,17 @@ from PyQt5.QtCore import Qt, QDir, QFile, QPoint, QRect, QSize ...@@ -2,6 +2,17 @@ from PyQt5.QtCore import Qt, QDir, QFile, QPoint, QRect, QSize
from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QLabel, QGridLayout from PyQt5.QtWidgets import QWidget, QPushButton, QLineEdit, QLabel, QGridLayout
from PyQt5.QtGui import QImage, QImageWriter, QPainter, QPen, qRgb, QPixmap from PyQt5.QtGui import QImage, QImageWriter, QPainter, QPen, qRgb, QPixmap
import os
import matplotlib.pyplot as plt
# Import datasets, classifiers and performance metrics
from sklearn import datasets, svm, metrics
from PIL import Image
import numpy as np
import math
from sklearn.metrics import accuracy_score
from sklearn.externals import joblib
class Button(QWidget): class Button(QWidget):
def __init__(self,parent=None, label="Button", on_click=None): def __init__(self,parent=None, label="Button", on_click=None):
super(Button,self).__init__(parent) super(Button,self).__init__(parent)
...@@ -128,4 +139,47 @@ class Board(QWidget): ...@@ -128,4 +139,47 @@ class Board(QWidget):
newImage.fill(qRgb(255,255,255)) newImage.fill(qRgb(255,255,255))
painter = QPainter(newImage) painter = QPainter(newImage)
painter.drawImage(QPoint(0,0), image) painter.drawImage(QPoint(0,0), image)
self.image = newImage self.image = newImage
\ No newline at end of file
def data_prep_test(self):
im = Image.open('Test/temp.png')
iar = np.array(im)
width, height = im.size
test_data = np.zeros(width*height)
test_data = np.zeros(64*64)
count = 0
for i in range(len(iar)):
for j in range(len(iar[i])):
test_data[count] = math.floor(((np.sum(iar[i][j][:3]/765))))
#print(test_data[count])
count+=1
return test_data
def data_prep_train(self):
print('preporcessing..')
folder_name = 'Image/'
list_of_label = os.listdir(folder_name)
digit_data = list()
digit_label = list()
for label in list_of_label:
label_path = folder_name+str(label)+'/'
list_of_data = os.listdir(label_path)
#print(list_of_data)
for data in list_of_data:
im = Image.open(label_path+'/'+data)
arr_im = np.array(im)
width, height = im.size
gen_data = np.zeros(width*height)
count = 0
for i in range(len(arr_im)):
for j in range(len(arr_im[i])):
#ทำ Normalize ด้วยการ (R+G+B) หาร 765 มาจาก (255+255+255)
gen_data[count] = math.floor(((np.sum(arr_im[i][j][:3]/765))))
count+=1
digit_data.append( gen_data )
digit_label.append( label )
digit_data = np.array(digit_data) #ข้อมูล
digit_label = np.array(digit_label) # label ของข้อมูล
return digit_data,digit_label
\ No newline at end of file
...@@ -5,14 +5,9 @@ from PyQt5.QtWidgets import (QAction, QApplication, QWidget,QGridLayout) ...@@ -5,14 +5,9 @@ from PyQt5.QtWidgets import (QAction, QApplication, QWidget,QGridLayout)
#from trainWidget import TrainWidget #from trainWidget import TrainWidget
#from testWidget import TestWidget #from testWidget import TestWidget
from ubuwidgets import (Button, ComboWidget, Board) from ubuwidgets import (Button, ComboWidget, Board)
import os
import matplotlib.pyplot as plt
# Import datasets, classifiers and performance metrics # Import datasets, classifiers and performance metrics
from sklearn import datasets, svm, metrics from sklearn import svm, metrics
from PIL import Image
import numpy as np
import math
from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score
from sklearn.externals import joblib from sklearn.externals import joblib
...@@ -24,6 +19,7 @@ class MainWindow(QWidget): ...@@ -24,6 +19,7 @@ class MainWindow(QWidget):
self.trainButton = Button(self, "Train", self.on_train) self.trainButton = Button(self, "Train", self.on_train)
self.saveCombo = ComboWidget(self, "Label: ", "Save", self.on_save) self.saveCombo = ComboWidget(self, "Label: ", "Save", self.on_save)
self.testCombo = ComboWidget(self, "Result: ", "Test", self.on_test, True) self.testCombo = ComboWidget(self, "Result: ", "Test", self.on_test, True)
grid = QGridLayout() grid = QGridLayout()
grid.addWidget(self.scribbleArea,1,0) grid.addWidget(self.scribbleArea,1,0)
grid.addWidget(self.clearButton,2,0) grid.addWidget(self.clearButton,2,0)
...@@ -37,54 +33,10 @@ class MainWindow(QWidget): ...@@ -37,54 +33,10 @@ class MainWindow(QWidget):
def on_clear(self): def on_clear(self):
self.scribbleArea.clearImage() self.scribbleArea.clearImage()
def data_prep_train(self):
print('preporcessing..')
list_of_label = os.listdir('Image/')
digit_data = list()
digit_label = list()
for label in list_of_label:
label_path = 'Image/'+str(label)+'/'
list_of_data = os.listdir(label_path)
#print(list_of_data)
for data in list_of_data:
im = Image.open(label_path+'/'+data)
arr_im = np.array(im)
#list_im = str(arr_im.tolist())
width, height = im.size
gen_data = np.zeros(width*height)
count = 0
for i in range(len(arr_im)):
for j in range(len(arr_im[i])):
#ทำ Normalize ด้วยการ (R+G+B) หาร 765 มาจาก (255+255+255)
gen_data[count] = math.floor(((np.sum(arr_im[i][j][:3]/765))))
count+=1
digit_data.append( gen_data )
digit_label.append( label )
digit_data = np.array(digit_data) #ข้อมูล
digit_label = np.array(digit_label) # label ของข้อมูล
return digit_data,digit_label
def data_prep_test(self):
im = Image.open('Test/temp.png')
iar = np.array(im)
#list_im = str(arr_im.tolist())
width, height = im.size
test_data = np.zeros(width*height)
test_data = np.zeros(64*64)
count = 0
for i in range(len(iar)):
for j in range(len(iar[i])):
test_data[count] = math.floor(((np.sum(iar[i][j][:3]/765))))
#print(test_data[count])
count+=1
return test_data
def on_train(self): def on_train(self):
digit_data, digit_label = self.data_prep_train() digit_data, digit_label = self.scribbleArea.data_prep_train()
print('training..') print('training..')
# Create a classifier: a support vector classifier # Create a classifier: a support vector classifier
...@@ -94,22 +46,23 @@ class MainWindow(QWidget): ...@@ -94,22 +46,23 @@ class MainWindow(QWidget):
classifier.fit(digit_data, digit_label) classifier.fit(digit_data, digit_label)
#save model #save model
joblib.dump(classifier, 'svmModel.pkl') joblib.dump(classifier, 'svmModel.pkl')
expected = digit_label
predicted = classifier.predict(digit_data) predicted = classifier.predict(digit_data)
print("Classification report for classifier %s:\n%s\n" print("Classification report for classifier %s:\n%s\n"
% (classifier, metrics.classification_report(expected, predicted))) % (classifier, metrics.classification_report(digit_label, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted)) print("Confusion matrix:\n%s" % metrics.confusion_matrix(digit_label, predicted))
print("\naccuracy = ",accuracy_score(digit_label, predicted)) print("\naccuracy = ",accuracy_score(digit_label, predicted))
def on_test(self): def on_test(self):
print("testing...") print("testing...")
clf = joblib.load('svmModel.pkl') clf = joblib.load('svmModel.pkl')
self.scribbleArea.saveImageTest() self.scribbleArea.saveImageTest()
test_data = self.data_prep_test() test_data = self.scribbleArea.data_prep_test()
predicted = clf.predict([test_data]) predicted = clf.predict([test_data])
print("ผลการทำนาย คือ", predicted) result = "ผลการทำนาย คือ "+predicted[0]
self.testCombo.set_text(result)
print("ผลการทำนาย คือ", predicted)
def on_save(self): def on_save(self):
print('on_save') print('on_save')
self.scribbleArea.saveImage(self.saveCombo.text()) self.scribbleArea.saveImage(self.saveCombo.text())
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment