使用Qthreads PyQt5窗口和函数之间的交互?

时间:2019-06-15 04:37:13

标签: python python-3.x pyqt pyqt5

我用PyQt5 GUI和keras模型开发了一个图像伪造检测应用程序,但是我将CSV文件从Window发送到训练ML模型并返回Matplotlib路径的模块时遇到了问题。结果和保存的模型。

训练深度学习模型的功能

from sklearn.model_selection import train_test_split 
from sklearn.metrics import confusion_matrix 
from keras.utils.np_utils import to_categorical  
from keras.models import Sequential 
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D  
from keras.optimizers import RMSprop 
from keras.callbacks import EarlyStopping 
from pylab import * 
from PIL import Image, ImageChops,ImageEnhance 
import pandas as pd 
import numpy as np 
import itertools 
import matplotlib.pyplot as plt
import os 
import random

def train_Ela_Model(ELA_csv_file):
    def convert_to_ela_image(path, quality):
        filename = path
        resaved_filename = filename.split('.')[0] + '.resaved.jpg'
        # ELA_filename = filename.split('.')[0] + '.ela.png'
        im = Image.open(filename).convert('RGB')
        im.save(resaved_filename, 'JPEG', quality=quality)
        resaved_im = Image.open(resaved_filename)

        ela_im = ImageChops.difference(im, resaved_im)

        extrema = ela_im.getextrema()
        max_diff = max([ex[1] for ex in extrema])
        if max_diff == 0:
            max_diff = 1
        scale = 255.0 / max_diff

        ela_im = ImageEnhance.Brightness(ela_im).enhance(scale)
        return ela_im


    # 1 represents tampered and 0 represents real
    dataset = pd.read_csv(ELA_csv_file)
    X = []
    Y = []
    for index, row in dataset.iterrows():
        X.append(array(convert_to_ela_image(row[0], 90).resize((128, 128))).flatten() / 255.0)
        Y.append(row[1])

    X = np.array(X)
    Y = to_categorical(Y, 2)
    X = X.reshape(-1, 128, 128, 3)
    X_train, X_val, Y_train, Y_val = train_test_split(X, Y, test_size=0.1, random_state=5, shuffle=True)

    model = Sequential()

    model.add(Conv2D(filters=32, kernel_size=(5, 5), padding='valid', activation='relu', input_shape=(128, 128, 3)))
    model.add(Conv2D(filters=32, kernel_size=(5, 5), strides=(2, 2), padding='valid', activation='relu'))
    model.add(MaxPool2D(pool_size=2, strides=None, padding='valid', data_format='channels_last'))
    model.add(Dropout(0.25))

    model.add(Flatten())

    model.add(Dense(256, activation="relu"))
    model.add(Dropout(0.50))
    model.add(Dense(2, activation="softmax"))
    model.summary()

    optimizer = RMSprop(lr=0.0001, rho=0.9, epsilon=1e-08, decay=0.0)
    model.compile(optimizer=optimizer, loss="categorical_crossentropy", metrics=["accuracy"])

    #early_stopping = EarlyStopping(monitor='val_acc', min_delta=0, patience=2, verbose=0, mode='auto')

    epochs = 10
    batch_size = 5

    history = model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, validation_data=(X_val, Y_val), verbose=2)

    fig, ax = plt.subplots(3, 1)
    ax[0].plot(history.history['loss'], color='b', label="Training loss")
    ax[0].plot(history.history['val_loss'], color='r', label="validation loss", axes=ax[0])
    legend = ax[0].legend(loc='best', shadow=True)

    ax[1].plot(history.history['acc'], color='b', label="Training accuracy")
    ax[1].plot(history.history['val_acc'], color='r', label="Validation accuracy")
    legend_ = ax[1].legend(loc='best', shadow=True)


    def plot_confusion_matrix(cm_, classes, normalize=False, title_='Confusion matrix', cmap=cm.get_cmap("Spectral")):
        """
        This function prints and plots the confusion matrix.
        Normalization can be applied by setting `normalize=True`.
        """
        plt.imshow(cm_, interpolation='nearest', cmap=cmap)
        plt.title(title_)
        plt.colorbar()
        tick_marks = np.arange(len(classes))
        plt.xticks(tick_marks, classes)
        plt.yticks(tick_marks, classes)

        if normalize:
            cm_ = cm_.astype('float') / cm_.sum(axis=1)[:, np.newaxis]

        thresh = cm_.max() / 2.
        for i, j in itertools.product(range(cm_.shape[0]), range(cm_.shape[1])):
            plt.text(j, i, cm_[i, j],
                     horizontalalignment="center",
                     color="white" if cm_[i, j] thresh else "black")

        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label')


    Y_pred = model.predict(X_val)
    Y_pred_classes = np.argmax(Y_pred, axis=1)
    Y_true = np.argmax(Y_val, axis=1)

    confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
    plot_confusion_matrix(confusion_mtx, classes=range(2))

    #plt.show()
    image_path = os.getcwd()+"\\Figures"
    Models_path = os.getcwd()+"\\Re_Traind_Models"
    file_number =random.randint(1, 1000000)
    plot_Name = image_path+"\\ELA_"+str(file_number)+".png"
    Model_Name = Models_path+"\\ELA_"+str(file_number)+".h5"
    plt.savefig(plot_Name , transparent =True , bbox_incehs="tight" , pad_inches = 2 , dpi = 50)
    model.save(Model_Name)
    return plot_Name , Model_Name

和窗口的PyQt5代码

from PyQt5.QtWidgets import QApplication , QFileDialog  ,
QFrame,QComboBox,  QLineEdit , QLabel, QHBoxLayout,
QAction,QRadioButton , QMainWindow, QMenu, QVBoxLayout, QSizePolicy,
QMessageBox, QWidget, QPushButton 
from PyQt5.QtCore import *

from PyQt5 import QtGui 
from PyQt5 import QtCore 
from PyQt5.QtCore import QThread , pyqtSignal , Qt 
from PyQt5.QtGui import QPixmap 
from PIL import Image, ImageChops, ImageEnhance 
from pylab import * 
from PyQt5.QtCore import pyqtSignal 
from PIL import Image 
import numpy as np 
import sys 
import os 
from keras.models import load_model 
import Result_Window 
from ELA_Training_Module import *

class Test_window(QWidget):
    def __init__(self, parent = None):
        super().__init__()
        #self.on_click.clicked.connect(self.Qthread.onButtonPress)
        self.title = "IFD Application"
        self.top = 200
        self.left = 500
        self.width = 550
        self.height = 345
        self.file_path = ""
        self.init_window()

    def init_window(self):
        self.setWindowTitle(self.title)
        self.setWindowIcon(QtGui.QIcon("icons8-cbs-512.ico")) #icon Pic File name
        self.setGeometry(self.left , self.top , self.width , self.height)
        self.setFixedSize(self.width , self.height)
        self.label = QLabel(self)
        self.label2 = QLabel(self)
        self.label3 = QLabel(self)
        self.label4 = QLabel(self)

        quit = QAction("Quit", self)
        #quit.triggered.connect(self.closex)


        #Label
        label = QLabel(self)
        label.move(10,44)
        label.setText('Image Name ')
        label.setFont(QtGui.QFont("Sanserif" , 8))
        #layout.addWidget(label)

        #text Box
        self.line_edit = QLineEdit(self)
        self.line_edit.setReadOnly(True)
        self.line_edit.setFont(QtGui.QFont("Sanserif", 8))
        self.line_edit.setGeometry(QRect(80, 40, 365, 20))
        self.line_edit.setPlaceholderText("image Name here!")
        #layout.addWidget(self.line_edit)

        #Button
        self.button = QPushButton("Browse", self)
        self.button.setGeometry(QRect(450, 40, 90, 20))
        self.button.setToolTip("<h5>Browse image from your computer to start test!<h5>")  # Notice using h2 tags From Html
        self.button.setIcon(QtGui.QIcon("698831-icon-105-folder-add-512.png"))
#icon Pic File name
        self.button.setIconSize(QtCore.QSize(15, 15))  # to change icon Size
        self.button.clicked.connect(self.getfiles)

        #Button
        self.button = QPushButton("Test", self)
        self.button.setGeometry(QRect(270, 310, 90, 20))
        self.button.setToolTip("<h5>test image either Forged or Not Forged!<h5>")  # Notice using h2 tags From Html
        self.button.setIcon(QtGui.QIcon("698827-icon-101-folder-search-512.png"))
#icon Pic File name
        self.button.setIconSize(QtCore.QSize(15, 15))  # to change icon Size
        self.button.clicked.connect(self.on_click)

        label = QLabel(self)
        label.setText('Model ')
        label.setFont(QtGui.QFont("Sanserif", 8))
        label.move(10, 20)


        self.combo = QComboBox(self)
        self.combo.addItem("Error Level Analysis")
        self.combo.setToolTip("<h5>ELA<h5>")
        self.combo.addItem("VGG16")
        self.combo.setToolTip("<h5>VGG16<h5>")

        self.combo.addItem("VGG19")
        self.combo.setToolTip("<h5>VGG19<h5>")

        self.combo.addItem("SVM")
        self.combo.setToolTip("<h5>SVM<h5>")

        self.combo.setGeometry(QRect(80, 15,460 , 20))

        """
        label = QLabel(self)
        label.setText('Image Informations')
        label.setFont(QtGui.QFont("Sanserif", 8))
        label.move(50, 75)

        topleft = QFrame(self)
        topleft.setFrameShape(QFrame.StyledPanel)
        topleft.setGeometry(QRect(10, 90,175 , 200))

        label = QLabel(self)
        label.setText('Image')
        label.setFont(QtGui.QFont("Sanserif", 8))
        label.move(290, 75)



        topleft = QFrame(self)
        topleft.setFrameShape(QFrame.StyledPanel)
        topleft.setGeometry(QRect(200, 90,200 , 200))
        """
        self.show()


    @pyqtSlot()
    def getfiles(self):
        fileName , extention= QFileDialog.getOpenFileName(self, 'Single File', 'C:\'')
        self.file_path = fileName
        """
        if self.file_path != "":
            head, tail = os.path.split(fileName)
            self.line_edit.setText(tail)

            self.label.hide()
            self.label2.hide()
            self.label3.hide()
            self.label4.hide()

            pixmap = QPixmap(self.file_path)
            self.label.setPixmap(pixmap)
            self.label.resize(190, 190)
            self.label.move(205, 95)
            self.label.setPixmap(pixmap.scaled(self.label.size(), Qt.IgnoreAspectRatio))

            #image information
            image = Image.open(self.file_path)
            width, height = image.size
            resolution = "Resolution "+str(width)+"X"+str(height)
            self.label2.setText(resolution)
            self.label2.setFont(QtGui.QFont("Sanserif", 8))
            self.label2.move(15,100)

            head, tail = os.path.split(self.file_path)
            tail2 = tail.split('.')[1]
            file_type = "Item Type "+str(tail2)
            self.label3.setText(file_type)
            self.label3.setFont(QtGui.QFont("Sanserif", 8))
            self.label3.move(15,112)


            size = os.path.getsize(self.file_path)
            size = np.int(size/1000)
            text = str(size) + "KB"
            self.label4.setText(text)
            self.label4.setFont(QtGui.QFont("Sanserif", 8))
            self.label4.move(15,124)


            self.label2.show()
            self.label3.show()
            self.label4.show()
            self.label.show()
        else:
            pass
        """

    @pyqtSlot()
    def on_click(self):
        if self.file_path == "":
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Choose image from your computer !")
            msg.setWindowTitle("Error")
            msg.setWindowIcon(QtGui.QIcon("icons8-cbs-512.ico"))
            msg.exec_()
        else:
            if str(self.combo.currentText()) == "Error Level Analysis" :

                #code here to Run Deep leraning Models


if __name__ == "__main__":
    App = QApplication(sys.argv)
    App.setStyle('Fusion')
    window = Test_window()
    sys.exit(App.exec())

问题是当我运行Windows程序Forzen

from ELA_Training_Module import * 

class Test_window(QWidget):
    def __init__(self, parent = None):
        """constructor to create a new window with charactersitis after create object from class window"""
        super().__init__()
        #self.on_click.clicked.connect(self.Qthread.onButtonPress)
        self.title = "IFD Application"
        self.top = 200
        self.left = 500
        self.width = 550
        self.height = 345
        self.file_path = ""
        self.init_window()

    def init_window(self):

        #text Box
        self.line_edit = QLineEdit(self)
        self.line_edit.setReadOnly(True)
        self.line_edit.setFont(QtGui.QFont("Sanserif", 8))
        self.line_edit.setGeometry(QRect(80, 40, 365, 20))
        self.line_edit.setPlaceholderText("image Name here!")
        #layout.addWidget(self.line_edit)

        #Button
        self.button = QPushButton("Browse", self)
        self.button.setGeometry(QRect(450, 40, 90, 20))
        self.button.setToolTip("<h5>Browse image from your computer to start test!<h5>")  # Notice using h2 tags From Html
        self.button.setIcon(QtGui.QIcon("698831-icon-105-folder-add-512.png"))
#icon Pic File name
        self.button.setIconSize(QtCore.QSize(15, 15))  # to change icon Size
        self.button.clicked.connect(self.getfiles)

        #Button
        self.button = QPushButton("Test", self)
        self.button.setGeometry(QRect(270, 310, 90, 20))
        self.button.setToolTip("<h5>test image either Forged or Not Forged!<h5>")  # Notice using h2 tags From Html
        self.button.setIcon(QtGui.QIcon("698827-icon-101-folder-search-512.png"))
#icon Pic File name
        self.button.setIconSize(QtCore.QSize(15, 15))  # to change icon Size
        self.button.clicked.connect(self.on_click)

        label = QLabel(self)
        label.setText('Model ')
        label.setFont(QtGui.QFont("Sanserif", 8))
        label.move(10, 20)


        self.combo = QComboBox(self)
        self.combo.addItem("Error Level Analysis")
        self.combo.setToolTip("<h5>ELA<h5>")
        self.combo.addItem("VGG16")
        self.combo.setToolTip("<h5>VGG16<h5>")

        self.combo.addItem("VGG19")
        self.combo.setToolTip("<h5>VGG19<h5>")

        self.combo.addItem("SVM")
        self.combo.setToolTip("<h5>SVM<h5>")

        self.combo.setGeometry(QRect(80, 15,460 , 20))


        self.show()


    @pyqtSlot()
    def getfiles(self):
        fileName , extention= QFileDialog.getOpenFileName(self, 'Single File', 'C:\'')
        self.file_path = fileName
        """
        if self.file_path != "":
            head, tail = os.path.split(fileName)
            self.line_edit.setText(tail)

            self.label.hide()
            self.label2.hide()
            self.label3.hide()
            self.label4.hide()

            pixmap = QPixmap(self.file_path)
            self.label.setPixmap(pixmap)
            self.label.resize(190, 190)
            self.label.move(205, 95)
            self.label.setPixmap(pixmap.scaled(self.label.size(), Qt.IgnoreAspectRatio))

            #image information
            image = Image.open(self.file_path)
            width, height = image.size
            resolution = "Resolution "+str(width)+"X"+str(height)
            self.label2.setText(resolution)
            self.label2.setFont(QtGui.QFont("Sanserif", 8))
            self.label2.move(15,100)

            head, tail = os.path.split(self.file_path)
            tail2 = tail.split('.')[1]
            file_type = "Item Type "+str(tail2)
            self.label3.setText(file_type)
            self.label3.setFont(QtGui.QFont("Sanserif", 8))
            self.label3.move(15,112)


            size = os.path.getsize(self.file_path)
            size = np.int(size/1000)
            text = str(size) + "KB"
            self.label4.setText(text)
            self.label4.setFont(QtGui.QFont("Sanserif", 8))
            self.label4.move(15,124)


            self.label2.show()
            self.label3.show()
            self.label4.show()
            self.label.show()
        else:
            pass
        """

    @pyqtSlot()
    def on_click(self):
        if self.file_path == "":
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Choose image from your computer !")
            msg.setWindowTitle("Error")
            msg.setWindowIcon(QtGui.QIcon("icons8-cbs-512.ico"))
            msg.exec_()
        else:
            if str(self.combo.currentText()) == "Error Level Analysis" :

                #code here to Run Deep leraning Models

0 个答案:

没有答案