# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Aplikasi(gui).ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import QFileDialog
from LocalBinaryPattern import LBP as localBinary #Library lbp
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas #nampilin histogram di gui
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar #nampilin histogram di gui
import os
import cv2
import pickle
import numpy as np
import matplotlib.pyplot as plt


class Ui_MainWindow(object):
    # Proses untuk open input citra
    def openCitra(self): #proses menyimpan gambar
        self.fname = QFileDialog.getOpenFileName(filter="Image (*.jpg *.png)")[0] #mengambil gambar
        try :
            image = cv2.imread(self.fname) #membaca gambar
            image = cv2.resize(image,(100, 200)) #menyesuaikan ukurab gambar di gui
            # Import gambar dalam format RGB
            rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            self.rgb_image = rgb; #menyimpan gambar rgb kedalam variabel self.rgb.image
            # Menampilkan input citra kedalam GUI
            image = QImage(rgb, rgb.shape[1], rgb.shape[0], rgb.strides[0], QImage.Format_RGB888) 
            self.input_citrargbjambu.setGeometry(QtCore.QRect(10, 20, rgb.shape[1], rgb.shape[0]))
            self.input_citrargbjambu.setPixmap(QtGui.QPixmap.fromImage(image))
        except Exception as e :
            print('Error : ', e)

    # Proses mereset semua proses
    def reset(self):
        try:
            self.rgb_image = None
            self.grayscale_image = None
            self.lbp_image = None
            self.hist_lbp = None
            self.input_citrargbjambu.clear()
            self.input_citragrayscale.clear()
            self.input_citralbp.clear()
            self.canvas.setParent(None)
            self.label_hasil.setText("")
            self.groupbox_histogramLayout.removeWidget()
        except Exception as e:
            print('Error : ', e)

    # Proses grayscale
    def grayscale(self):
        try :
            # Mengubah gambar rgb ke grayscale
            frame = cv2.cvtColor(self.rgb_image, cv2.COLOR_RGB2GRAY)
            self.grayscale_image = frame;
            # Menampilkan citra grayscale
            image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_Grayscale8)
            self.input_citragrayscale.setGeometry(QtCore.QRect(10, 20, frame.shape[1], frame.shape[0]))
            self.input_citragrayscale.setPixmap(QtGui.QPixmap.fromImage(image))
           # print(self.grayscale_image)
        except Exception as e :
            print('Error : ', e)

    # Proses LBP
    def lbp(self):
        try:
            # Mengubah gambar grayscale ke lbp
            lbp = localBinary()#library lbp
            frame = lbp.convert(self.grayscale_image) #proses grayscale ke lbp
            self.lbp_image = frame 
            #print(self.lbp_image)
            # Menampilkan citra lbp kedalam gui
            image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_Grayscale8)
            self.input_citralbp.setGeometry(QtCore.QRect(10, 20, frame.shape[1], frame.shape[0]))
            self.input_citralbp.setPixmap(QtGui.QPixmap.fromImage(image))
            ## Memanggil fungsi histogram(self)
            ## self.histogram()
        except Exception as e:
            print('Error : ', e)

    # Proses Histogram
    def histogram(self):
        try:
            # Proses histogram
            data = cv2.calcHist([self.lbp_image], [0], None, [256], [0, 256]) #calcHist proses membuat histogram
            self.hist_lbp = data
            # Menapilkan histogram ke GUI
            self.figure = plt.figure() #nampilin histogram ke gui
            self.canvas = FigureCanvas(self.figure) #nampilin histogram ke gui
            if(self.groupbox_histogramLayout.isEmpty()):
                self.groupbox_histogramLayout.addWidget(self.canvas)
            self.figure.clear(True)
            self.figure.subplots_adjust(left=0.35,right=0.85, bottom=0.2,top=0.8, hspace=0.2, wspace=0.2)
            ax = self.figure.add_subplot() #menambahkan plot histogram
            ax.plot(data, color="blue") #menampilkan warna histogram menjadi warna biru
            ax.set_title("Histogram") #judul histogram
            self.canvas.draw() #menampilkan histogram
        except Exception as e:
            print('Error : ', e)
            
    # Proses KNN
    def knn(self):
        try:
            model = pickle.load(open("model.sav", "rb")) #UNTUK MEMBUKA HASIL MODEL YANG TELAH DI TRAIN
            # Get Categories
            dir = os.path.abspath(os.getcwd()) #PROSES UNTUK MENYIMPAN SEMUA JENIS JAMBU 
            path = os.path.join(dir, 'data') #mengambil path folder "data"
            categories = [] #untuk menyimpan 3 kelas 
            for category in os.listdir(path): #proses menyimpan 3 kelas
                categories.append(category) #proses menyimpan 3 kelas
            # Proses klasifikasi
            image = cv2.imread(self.fname) #untuk membaca data
            rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #mengubah RGB ke grayscale (karena cv2 format default berupa RGB)
            frame = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #mengubah RGB ke grayscale (karena cv2 format default berupa RGB)
            lbp = localBinary() #memanggil fungsi LBP
            frame = lbp.convert(self.grayscale_image) #mengkonversi grayscale menjadi LBP
            hist_lbp = cv2.calcHist([frame], [0], None, [256], [0, 256]) #memanggil fungsi histogram
            data = [] #menyimpan array data
            data.append(hist_lbp) #menyimpan histogram kedalam array data
            data = np.array(data) #np.array data (array data yang dapat diolah)
            dataset_size = data.shape[0] #PROSES AGAR DAPAT DIBACA OLEH MODEL
            data = data.reshape(dataset_size,-1) #menyesuaikan array dataset dengan label
            prediction = model.predict(data) #proses menentukan klasfikasi daun jambu
            res = 'Jenis Jambu Air : '+categories[prediction[0]]
            self.label_hasil.setText(res)
        except Exception as e:
            print('Error : ', e)
    
        
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(801, 600)
        
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        
        self.btn_open = QtWidgets.QPushButton(self.centralwidget)
        self.btn_open.setGeometry(QtCore.QRect(20, 60, 81, 31))
        self.btn_open.setObjectName("btn_open")
        
        self.btn_reset = QtWidgets.QPushButton(self.centralwidget)
        self.btn_reset.setGeometry(QtCore.QRect(20, 100, 81, 31))
        self.btn_reset.setObjectName("btn_reset")
        
        self.btn_knn = QtWidgets.QPushButton(self.centralwidget)
        self.btn_knn.setGeometry(QtCore.QRect(20, 260, 81, 31))
        self.btn_knn.setObjectName("btn_knn")
        
        self.btn_grayscale = QtWidgets.QPushButton(self.centralwidget)
        self.btn_grayscale.setGeometry(QtCore.QRect(20, 140, 81, 31))
        self.btn_grayscale.setObjectName("btn_grayscale")
        
        self.btn_lbp = QtWidgets.QPushButton(self.centralwidget)
        self.btn_lbp.setGeometry(QtCore.QRect(20, 180, 81, 31))
        self.btn_lbp.setObjectName("btn_lbp")

        self.btn_histogram = QtWidgets.QPushButton(self.centralwidget)
        self.btn_histogram.setGeometry(QtCore.QRect(20, 220, 81, 31))
        self.btn_histogram.setObjectName("btn_histogram")
#grupbox
        self.groupbox_citrargbjambu = QtWidgets.QGroupBox(self.centralwidget)
        self.groupbox_citrargbjambu.setGeometry(QtCore.QRect(130, 50, 120, 230))
        self.groupbox_citrargbjambu.setObjectName("groupbox_citrargbjambu")
#output        
        self.input_citrargbjambu = QtWidgets.QLabel(self.groupbox_citrargbjambu)
        self.input_citrargbjambu.setGeometry(QtCore.QRect(10, 20, 100, 200))
        self.input_citrargbjambu.setAutoFillBackground(False)
        self.input_citrargbjambu.setFrameShape(QtWidgets.QFrame.Box)
        self.input_citrargbjambu.setFrameShadow(QtWidgets.QFrame.Plain)
        self.input_citrargbjambu.setText("")
        self.input_citrargbjambu.setObjectName("input_citrargbjambu")
        
        self.groupbox_hasil = QtWidgets.QGroupBox(self.centralwidget)
        self.groupbox_hasil.setGeometry(QtCore.QRect(130, 300, 271, 71))
        self.groupbox_hasil.setObjectName("groupbox_hasil")
        
        self.label_hasil = QtWidgets.QLabel(self.groupbox_hasil)
        self.label_hasil.setGeometry(QtCore.QRect(10, 20, 251, 41))
        self.label_hasil.setAutoFillBackground(False)
        self.label_hasil.setFrameShape(QtWidgets.QFrame.Box)
        self.label_hasil.setFrameShadow(QtWidgets.QFrame.Plain)
        self.label_hasil.setText("")
        self.label_hasil.setObjectName("label_hasil")
        
        self.groupbox_citragrayscale = QtWidgets.QGroupBox(self.centralwidget)
        self.groupbox_citragrayscale.setGeometry(QtCore.QRect(280, 50, 120, 230))
        self.groupbox_citragrayscale.setObjectName("groupbox_citragrayscale")
        
        self.input_citragrayscale = QtWidgets.QLabel(self.groupbox_citragrayscale)
        self.input_citragrayscale.setGeometry(QtCore.QRect(10, 20, 100, 200))
        self.input_citragrayscale.setAutoFillBackground(False)
        self.input_citragrayscale.setFrameShape(QtWidgets.QFrame.Box)
        self.input_citragrayscale.setFrameShadow(QtWidgets.QFrame.Plain)
        self.input_citragrayscale.setText("")
        self.input_citragrayscale.setObjectName("input_citragrayscale")
        
        self.groupbox_citralbp = QtWidgets.QGroupBox(self.centralwidget)
        self.groupbox_citralbp.setGeometry(QtCore.QRect(430, 50, 120, 230))
        self.groupbox_citralbp.setObjectName("groupbox_citralbp")
        
        self.input_citralbp = QtWidgets.QLabel(self.groupbox_citralbp)
        self.input_citralbp.setGeometry(QtCore.QRect(10, 20, 100, 200))
        self.input_citralbp.setAutoFillBackground(False)
        self.input_citralbp.setFrameShape(QtWidgets.QFrame.Box)
        self.input_citralbp.setFrameShadow(QtWidgets.QFrame.Plain)
        self.input_citralbp.setText("")
        self.input_citralbp.setObjectName("input_citralbp")
        
        self.groupbox_histogram = QtWidgets.QGroupBox(self.centralwidget)
        self.groupbox_histogram.setGeometry(QtCore.QRect(580, 50, 180, 230))
        self.groupbox_histogram.setObjectName("groupbox_histogram")
        
        self.input_histogram = QtWidgets.QLabel(self.groupbox_histogram)
        self.input_histogram.setGeometry(QtCore.QRect(10, 20, 160, 200))
        self.input_histogram.setAutoFillBackground(False)
        self.input_histogram.setFrameShape(QtWidgets.QFrame.Box)
        self.input_histogram.setFrameShadow(QtWidgets.QFrame.Plain)
        self.input_histogram.setText("")
        self.input_histogram.setObjectName("input_histogram")
        
        self.groupbox_histogramLayout = QtWidgets.QVBoxLayout(self.input_histogram)
        self.groupbox_histogramLayout.setContentsMargins(0, 0, 0, 0)
        self.groupbox_histogramLayout.setObjectName("histogramLayout")
        
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 10, 691, 20))
        self.label.setObjectName("label")
        
        self.groupbox_hasil.raise_()
        self.groupbox_citrargbjambu.raise_()
        
        self.btn_open.raise_()
        self.btn_reset.raise_()
        self.btn_knn.raise_()
        self.btn_grayscale.raise_()
        self.btn_lbp.raise_()
        self.btn_histogram.raise_()

        self.groupbox_citragrayscale.raise_()
        self.groupbox_citralbp.raise_()
        self.groupbox_histogram.raise_()
        self.label.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 801, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # Button event listener
        self.btn_open.clicked.connect(self.openCitra)
        self.btn_grayscale.clicked.connect(self.grayscale)
        self.btn_reset.clicked.connect(self.reset)
        self.btn_lbp.clicked.connect(self.lbp)
        self.btn_knn.clicked.connect(self.knn)
        self.btn_histogram.clicked.connect(self.histogram)
        

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Klasifikasi Bismillah"))
        self.btn_open.setText(_translate("MainWindow", "Open"))
        self.btn_reset.setText(_translate("MainWindow", "Reset"))
        self.btn_knn.setText(_translate("MainWindow", "KNN"))
        self.btn_grayscale.setText(_translate("MainWindow", "Grayscale"))
        self.btn_lbp.setText(_translate("MainWindow", "LBP"))
        self.btn_histogram.setText(_translate("MainWindow", "Histogram"))
        self.groupbox_citrargbjambu.setTitle(_translate("MainWindow", "Citra Daun Jambu Air"))
        self.groupbox_hasil.setTitle(_translate("MainWindow", "Hasil Klasifikasi"))
        self.groupbox_citragrayscale.setTitle(_translate("MainWindow", "Citra Grayscale"))
        self.groupbox_citralbp.setTitle(_translate("MainWindow", "Citra LBP"))
        self.groupbox_histogram.setTitle(_translate("MainWindow", "Histogram"))
        self.label.setText(_translate("MainWindow", "KLASIFIKASI JENIS DAUN JAMBU AIR MENGGUNAKAN ALGORITMA K-NEAREST NEIGHBOR DENGAN EKSTRAKSI FITUR LOCAL BINARY PATTERN "))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
