Ejemplo n.º 1
0
 def open_file_dialog(self):
     dialog = QFileDialog()
     dialog.setNameFilters(["PDF file (*.pdf)"])
     dialog.selectNameFilter("PDF file (*.pdf)")
     if dialog.exec_() == QDialog.Accepted:
         filename_list = dialog.selectedFiles()
         self.pdf_worker = Pdf2Txt(filename_list[0])
         self.ui.outPutText.setText(self.pdf_worker.get_text())
Ejemplo n.º 2
0
def load_image(parent, filename=None):
    nothing = [None] * 3
    settings = QSettings()
    if filename is None:
        dialog = QFileDialog(parent, parent.tr('Load image'),
                             settings.value('load_folder'))
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setViewMode(QFileDialog.Detail)
        mime_filters = [
            "image/jpeg", "image/png", "image/tiff", "image/gif", "image/bmp",
            "image/webp", "image/x-portable-pixmap",
            "image/x-portable-graymap", "image/x-portable-bitmap"
        ]
        mime_db = QMimeDatabase()
        mime_patterns = [
            mime_db.mimeTypeForName(mime).globPatterns()
            for mime in mime_filters
        ]
        all_formats = 'Supported formats ({})'.format(' '.join(
            [item for sub in mime_patterns for item in sub]))
        dialog.setMimeTypeFilters(mime_filters)
        name_filters = dialog.nameFilters()
        dialog.setNameFilters(name_filters + [all_formats])
        dialog.selectNameFilter(all_formats)
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
        else:
            return nothing
    if filename.endswith('.gif'):
        capture = cv.VideoCapture(filename)
        frames = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
        if frames > 1:
            QMessageBox.warning(
                parent, parent.tr('Warning'),
                parent.tr('Animated GIF: importing first frame'))
        result, image = capture.read()
        if not result:
            QMessageBox.critical(parent, parent.tr('Error'),
                                 parent.tr('Unable to decode GIF!'))
            return nothing
        if len(image.shape) == 2:
            image = cv.cvtColor(image, cv.COLOR_GRAY2BGR)
    else:
        image = cv.imread(filename, cv.IMREAD_COLOR)
    if image is None:
        QMessageBox.critical(parent, parent.tr('Error'),
                             parent.tr('Unable to load image!'))
        return nothing
    if image.shape[2] > 3:
        QMessageBox.warning(parent, parent.tr('Warning'),
                            parent.tr('Alpha channel discarded'))
        image = cv.cvtColor(image, cv.COLOR_BGRA2BGR)
    settings.setValue('load_folder', QFileInfo(filename).absolutePath())
    return filename, os.path.basename(filename), image
Ejemplo n.º 3
0
 def onClickOpenFileButton(self):
     fileDialog = QFileDialog()
     fileDialog.setNameFilters(self.fileFilter)
     fileDialog.selectNameFilter(self.fileFilter)
     fileName = fileDialog.getOpenFileName(self,
                                           'Media Browser',
                                           filter=self.fileFilter)
     if fileName[0] and path.exists(fileName[0]):
         # do something with the file
         self.imageFrame.setImage(fileName[0])
         # Also, assign your image here, right now there is a path
         self.currentImagePath = fileName[0]
Ejemplo n.º 4
0
def load_image(parent, filename=None):
    nothing = [None] * 3
    settings = QSettings()
    mime_filters = ['image/jpeg', 'image/png', 'image/tiff', 'image/gif', 'image/bmp', 'image/webp',
                    'image/x-portable-pixmap', 'image/x-portable-graymap', 'image/x-portable-bitmap',
                    'image/x-nikon-nef', 'image/x-fuji-raf', 'image/x-canon-cr2', 'image/x-adobe-dng',
                    'image/x-sony-arw', 'image/x-kodak-dcr', 'image/x-minolta-mrw', 'image/x-pentax-pef',
                    'image/x-canon-crw', 'image/x-sony-sr2', 'image/x-olympus-orf', 'image/x-panasonic-raw']
    mime_db = QMimeDatabase()
    mime_patterns = [mime_db.mimeTypeForName(mime).globPatterns() for mime in mime_filters]
    all_formats = 'Supported formats ({})'.format(' '.join([item for sub in mime_patterns for item in sub]))
    raw_exts = [p[0][-3:] for p in mime_patterns][-12:]
    if filename is None:
        dialog = QFileDialog(parent, parent.tr('Load image'), settings.value('load_folder'))
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setViewMode(QFileDialog.Detail)
        dialog.setMimeTypeFilters(mime_filters)
        name_filters = dialog.nameFilters()
        dialog.setNameFilters(name_filters + [all_formats])
        dialog.selectNameFilter(all_formats)
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
        else:
            return nothing
    ext = os.path.splitext(filename)[1][1:].lower()
    if ext in raw_exts:
        with rawpy.imread(filename) as raw:
            image = cv.cvtColor(raw.postprocess(use_auto_wb=True), cv.COLOR_RGB2BGR)
    elif ext == 'gif':
        capture = cv.VideoCapture(filename)
        frames = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
        if frames > 1:
            QMessageBox.warning(parent, parent.tr('Warning'), parent.tr('Animated GIF: importing first frame'))
        result, image = capture.read()
        if not result:
            QMessageBox.critical(parent, parent.tr('Error'), parent.tr('Unable to decode GIF!'))
            return nothing
        if len(image.shape) == 2:
            image = cv.cvtColor(image, cv.COLOR_GRAY2BGR)
    else:
        image = cv.imread(filename, cv.IMREAD_COLOR)
    if image is None:
        QMessageBox.critical(parent, parent.tr('Error'), parent.tr('Unable to load image!'))
        return nothing
    if image.shape[2] > 3:
        QMessageBox.warning(parent, parent.tr('Warning'), parent.tr('Alpha channel discarded'))
        image = cv.cvtColor(image, cv.COLOR_BGRA2BGR)
    settings.setValue('load_folder', QFileInfo(filename).absolutePath())
    return filename, os.path.basename(filename), image
 def getfile(self):
     dlg = QFileDialog()
     dlg.setFileMode(QFileDialog.AnyFile)
     dlg.selectNameFilter("Arff data files (*.arff)")
     dlg.setNameFilter(
         "Arff data files (*.arff) ;; Csv data files (*.csv) ;; All files (*.*)"
     )
     filenames = []
     if dlg.exec_():
         filenames = dlg.selectedFiles()
         f = open(filenames[0], 'r')
         self.file_path = str(filenames[0].encode('utf-8'))
         with f:
             self.textEdit.setText(filenames[0].split('/')[-1])
             self.file_name = filenames[0].split('/')[-1].split('.')[0]
     self.valider.setEnabled(True)
 def open_dataset (self) :
     """
         This function looks for the csv file and initializes the Window attributes.
     """
     global dataset_name
     dlg = QFileDialog()
     dlg.setFileMode(QFileDialog.AnyFile)
     dlg.selectNameFilter("Csv data files (*.csv)")
     dlg.setNameFilter("Arff data files (*.arff) ;; Csv data files (*.csv) ;; All files (*.*)")
     filenames = []
     if dlg.exec_():
         filenames = dlg.selectedFiles()
         f = open(filenames[0], 'r')
         self.dataset_path = str(filenames[0])
         with f:
             self.textEdit.setText(filenames[0].split('/')[-1])
             self.file_name = filenames[0].split('/')[-1].split('.')[0]
     if self.dataset_path != None :
         self.file_path = os.path.dirname(self.dataset_path) + globals.directory
         globals.dataset_name = self.file_name
 
     ## RESET
     global input_height
     global input_length
     global index_data
     global index_data_pre
     global input_array
     global output_array
 
     globals.input_height = 0
     globals.input_length = 0
     globals.index_data = 0
     globals.index_data_pre = 0
     globals.input_array = []
     globals.output_array = []
     self.frame_3.setGeometry(QtCore.QRect(10, 180, 1000, 450))
     self.pushButton_next.setEnabled (False)
     self.pushButton_previous.setEnabled (False)
     self.start.setEnabled (False)
     self.valider.setEnabled(True)
     self.pushButton_save.setEnabled (False)
     self.pushButton_table.setEnabled (False)
     if hasattr (self, 'tableWidget') :
         self.tableWidget.setVisible (False)
     if hasattr (self, 'image') :
         self.image.setVisible (False)
Ejemplo n.º 7
0
class PreferencesDialog(QDialog):
    def __init__(self, parent=None, *args, **kwargs):
        global preferences
        super().__init__(parent=parent, *args, **kwargs)
        self.setWindowTitle("Preference Settings")
        self.app_window = parent
        #
        if not pathlib.Path(preferences['chess_engine_exe_path']).is_file():
            preferences['chess_engine_exe_path'] = None
            self.app_window.UI.advise_next_pushbutton.setEnabled(False)
            self.app_window.UI.self_play_pushbutton.setEnabled(False)
        self.chess_engine_exe_path_label = QLabel(
            '- Chess engine (stockfish) executable path:', parent=self)
        self.chess_engine_exe_path_pushbutton = QPushButton(
            f"{preferences['chess_engine_exe_path']}", parent=self)
        self.chess_engine_exe_path_pushbutton.clicked.connect(
            self._change_chess_engine_path)
        #
        self.chess_engine_hash_size_MB_label = QLabel(
            '- Chess engine hash size (MB):', parent=self)
        self.chess_engine_hash_size_MB_lineedit = QLineEdit(parent=self)
        self.chess_engine_hash_size_MB_lineedit.setText(
            f"{preferences['chess_engine_hash_size']}")
        self.chess_engine_hash_size_MB_lineedit.textChanged.connect(
            self._change_chess_engine_hash_size)
        #
        self.chess_engine_search_time_label = QLabel(
            '- Chess engine search time (sec):', parent=self)
        self.chess_engine_search_time_lineedit = QLineEdit(parent=self)
        self.chess_engine_search_time_lineedit.setText(
            f"{preferences['chess_engine_search_time']}")
        self.chess_engine_search_time_lineedit.textChanged.connect(
            self._change_chess_engine_search_time)
        #
        self.evaluate_position_label = QLabel('- Evaluation positions?',
                                              parent=self)
        self.evaluate_position_checkbox = QCheckBox('Yes', parent=self)
        self.evaluate_position_checkbox.setChecked(
            preferences['evaluate_position'])
        self.evaluate_position_checkbox.stateChanged.connect(
            self._evaluate_position_checkbox_state_changed)
        #
        self.play_sound_label = QLabel('- Play sound effect?', parent=self)
        self.play_sound_checkbox = QCheckBox('Yes', parent=self)
        self.play_sound_checkbox.setChecked(preferences['play_sound'])
        self.play_sound_checkbox.stateChanged.connect(
            self._play_sound_checkbox_state_changed)
        #
        self.layout = QGridLayout()
        self.layout.addWidget(self.chess_engine_exe_path_label, 0, 0)
        self.layout.addWidget(self.chess_engine_exe_path_pushbutton, 0, 1)
        self.layout.addWidget(self.chess_engine_hash_size_MB_label, 1, 0)
        self.layout.addWidget(self.chess_engine_hash_size_MB_lineedit, 1, 1)
        self.layout.addWidget(self.chess_engine_search_time_label, 2, 0)
        self.layout.addWidget(self.chess_engine_search_time_lineedit, 2, 1)
        self.layout.addWidget(self.evaluate_position_label, 3, 0)
        self.layout.addWidget(self.evaluate_position_checkbox, 3, 1)
        self.layout.addWidget(self.play_sound_label, 4, 0)
        self.layout.addWidget(self.play_sound_checkbox, 4, 1)
        self.setLayout(self.layout)
        #
        self.chess_engine_exe_path_filedialog = QFileDialog(parent=self)
        self.chess_engine_exe_path_filedialog.setNameFilters([
            "All files (*.*)",
        ])
        self.chess_engine_exe_path_filedialog.selectNameFilter(
            "All files (*.*)")

    def _change_chess_engine_path(self):
        global preferences
        self.chess_engine_exe_path_filedialog.exec_()
        selectedFiles = self.chess_engine_exe_path_filedialog.selectedFiles()
        if len(selectedFiles) > 0:
            try:
                preferences[
                    'chess_engine_exe_path'] = self.chess_engine_exe_path_filedialog.selectedFiles(
                    )[0]
            except:
                raise RuntimeError('Error')
            self.chess_engine_exe_path_pushbutton.setText(
                f"{preferences['chess_engine_exe_path']}")
            self.app_window.UI.advise_next_pushbutton.setEnabled(True)
            self.app_window.UI.self_play_pushbutton.setEnabled(True)

    def _change_chess_engine_hash_size(self, new_text):
        global preferences
        try:
            preferences['chess_engine_hash_size'] = int(new_text)
        except:
            raise RuntimeError('Error')

    def _change_chess_engine_search_time(self, new_text):
        global preferences
        try:
            preferences['chess_engine_search_time'] = float(new_text)
        except:
            raise RuntimeError('Error')

    def _play_sound_checkbox_state_changed(self, state: int):
        global preferences
        try:
            preferences['play_sound'] = self.play_sound_checkbox.isChecked()
        except:
            raise RuntimeError('Error')

    def _evaluate_position_checkbox_state_changed(self, state: int):
        global preferences
        try:
            preferences[
                'evaluate_position'] = self.evaluate_position_checkbox.isChecked(
                )
        except:
            raise RuntimeError('Error')
Ejemplo n.º 8
0
class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.load_ui()
        self.figlabels()
        self.imgs = []
        self.subj = []
        # self.figlabels = cv2.imread('figlabels.png')
        self.make_connect()
        self.inputExists = False
        self.defaultDirectoryExists = False
        self.annotationExists: False
        self.isSegmented = False
        self.files = None
        self.temperaturesWereAcquired = False

    def load_ui(self):
        loader = QUiLoader()
        path = os.fspath(Path(__file__).resolve().parent / "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        self.ui_window = loader.load(ui_file, self)
        ui_file.close()

    def make_connect(self):
        QObject.connect(self.ui_window.actionCargar_imagen,
                        SIGNAL('triggered()'), self.openImage)
        QObject.connect(self.ui_window.actionCargar_carpeta,
                        SIGNAL('triggered()'), self.openFolder)
        QObject.connect(self.ui_window.segButton, SIGNAL('clicked()'),
                        self.segment)
        QObject.connect(self.ui_window.tempButton, SIGNAL('clicked()'),
                        self.temp_extract)
        QObject.connect(self.ui_window.manualSegButton, SIGNAL('clicked()'),
                        self.manual_segment)
        QObject.connect(self.ui_window.refreshTimePlot, SIGNAL('clicked()'),
                        self.makeTimePlot)
        QObject.connect(self.ui_window.nextImageButton, SIGNAL('clicked()'),
                        self.nextImage)
        QObject.connect(self.ui_window.previousImageButton,
                        SIGNAL('clicked()'), self.previousImage)
        QObject.connect(self.ui_window.saveButton, SIGNAL('clicked()'),
                        self.saveImage)
        QObject.connect(self.ui_window.fullPlotButton, SIGNAL('clicked()'),
                        self.fullPlot)
        QObject.connect(self.ui_window.reportButton, SIGNAL('clicked()'),
                        self.exportReport)

    def messagePrint(self, message):
        #INPUT: string to print
        #OUTPUT: none
        #ACTION: generate out.html file and refresh it in Messages QTextArea
        log_path = "outputs/logs.html"
        out_file = open(log_path, "w")
        out_file.write(message)
        out_file.close()
        self.ui_window.textBrowser.setSource(log_path)
        self.ui_window.textBrowser.reload()

    def findImages(self):
        self.fileList = []
        for root, dirs, files in os.walk(self.defaultDirectory):
            for file in files:
                if (file.endswith(".jpg")):
                    self.fileList.append(os.path.join(root, file))
        self.imageQuantity = len(self.fileList)
        self.imageIndex = 0
        self.files = files
        self.sortFiles()
        self.outfiles = []
        for i in range(len(files)):
            self.outfiles.append("outputs/" +
                                 files[i])  #Creating future output file names
        self.ui_window.inputLabel.setText(self.files[self.imageIndex])

    def sortFiles(self):
        """Sort file list to an alphanumeric reasonable sense"""
        convert = lambda text: int(text) if text.isdigit() else text
        alphanum_key = lambda key: [
            convert(c) for c in re.split('([0-9]+)', key)
        ]
        self.fileList = sorted(self.fileList, key=alphanum_key)
        self.files = sorted(self.files, key=alphanum_key)

    def getTimes(self):
        """
        Converts standarized names of file list into a list of 
        integers with time capture in minutes
        """
        if (type(self.fileList) == str):
            self.timeList = int(self.fileList).rsplit(".")[0][1:]
        elif type(self.fileList) == list:
            out_list = []
            for i in range(len(self.fileList)):
                out_list.append(int(self.files[i].rsplit(".")[0][1:]))
            self.timeList = out_list
        else:
            return None

    def nextImage(self):
        if self.imageIndex < len(self.fileList) - 1:
            self.imageIndex += 1
            self.ui_window.inputImg.setPixmap(self.fileList[self.imageIndex])
            self.opdir = self.fileList[self.imageIndex]
            self.ui_window.inputLabel.setText(self.files[self.imageIndex])

            if self.sessionIsSegmented:
                #Sentences to display next output image if session was already
                #segmented
                self.showOutputImageFromSession()
                if self.temperaturesWereAcquired:
                    self.messagePrint(
                        "La temperatura media es: " +
                        str(self.meanTemperatures[self.imageIndex]))
                    self.ui_window.temperatureLabel.setText(
                        str(np.round(self.meanTemperatures[self.imageIndex],
                                     3)))

    def previousImage(self):
        if self.imageIndex >= 1:
            self.imageIndex -= 1
            self.ui_window.inputImg.setPixmap(self.fileList[self.imageIndex])
            self.opdir = self.fileList[self.imageIndex]
            self.ui_window.inputLabel.setText(self.files[self.imageIndex])

            if self.sessionIsSegmented:
                #Sentences to display next output image if session was already
                #segmented
                self.showOutputImageFromSession()
                if self.temperaturesWereAcquired:
                    self.messagePrint(
                        "La temperatura media es: " +
                        str(self.meanTemperatures[self.imageIndex]))
                    self.ui_window.temperatureLabel.setText(
                        str(np.round(self.meanTemperatures[self.imageIndex],
                                     3)))

    def saveImage(self):
        #Saves segmented image
        pass

    def feetSegment(self):
        self.messagePrint("Segmentando imagen")
        self.i2s = ImageToSegment()
        self.i2s.setPath(self.opdir)
        self.i2s.extract()
        self.showSegmentedImage()
        self.isSegmented = True
        self.messagePrint("Imagen segmentada exitosamente")

    def sessionSegment(self):
        self.messagePrint("Segmentando toda la sesion...")
        self.s2s = SessionToSegment()
        self.s2s.setPath(self.defaultDirectory)
        self.s2s.whole_extract(self.fileList)
        self.produceSegmentedSessionOutput()
        self.showOutputImageFromSession()
        self.messagePrint("Se ha segmentado exitosamente la sesion")
        self.sessionIsSegmented = True

    def showSegmentedImage(self):
        #Applies segmented zone to input image, showing only feet
        threshold = 0.5
        img = plt.imread(self.opdir) / 255
        Y = self.i2s.Y_pred
        Y = Y / Y.max()
        Y = np.where(Y >= threshold, 1, 0)
        self.Y = remove_small_objects(
            Y[0])  #Eventually required by temp_extract
        Y = cv2.resize(
            Y[0], (img.shape[1], img.shape[0]),
            interpolation=cv2.INTER_NEAREST
        )  # Resize the prediction to have the same dimensions as the input
        plt.imsave("outputs/output.jpg", Y * img[:, :, 0], cmap='gray')
        self.ui_window.outputImg.setPixmap("outputs/output.jpg")

    def produceSegmentedSessionOutput(self):
        #Recursively applies showSegmentedImage to whole session
        self.Y = []
        for i in range(len(self.outfiles)):
            threshold = 0.5
            img = plt.imread(self.fileList[i]) / 255
            Y = self.s2s.Y_pred[i]
            Y = Y / Y.max()
            Y = np.where(Y >= threshold, 1, 0)
            self.Y.append(
                remove_small_objects(Y))  #Eventually required by temp_extract
            Y = cv2.resize(
                Y, (img.shape[1], img.shape[0]),
                interpolation=cv2.INTER_NEAREST
            )  # Resize the prediction to have the same dimensions as the input
            plt.imsave(self.outfiles[i], Y * img[:, :, 0], cmap='gray')

    def showOutputImageFromSession(self):
        self.ui_window.outputImg.setPixmap(self.outfiles[self.imageIndex])

    def segment(self):
        if self.ui_window.sessionCheckBox.isChecked():

            if self.defaultDirectoryExists:
                self.sessionSegment()
                print("Entering session segment")
            else:
                self.messagePrint("No se ha seleccionado sesion de entrada")
        else:
            if self.inputExists:
                self.feetSegment()
                print("Entering image segment")
            else:
                self.messagePrint("No se ha seleccionado sesion de entrada")

    def manual_segment(self):
        print("Se abrirá diálogo de extracción manual")
        self.manual = manualSeg()
        self.manual.show()
        return

    def temp_extract(self):
        if (self.inputExists
                and (self.isSegmented or self.sessionIsSegmented)):
            if self.ui_window.sessionCheckBox.isChecked(
            ):  #If segmentation was for full session
                self.meanTemperatures = [
                ]  #Whole feet mean temperature for all images in session
                for i in range(len(self.outfiles)):
                    self.meanTemperatures.append(
                        mean_temperature(self.s2s.Xarray[i, :, :, 0],
                                         self.Y[i][:, :, 0],
                                         plot=False))
                self.messagePrint("La temperatura media es: " +
                                  str(self.meanTemperatures[self.imageIndex]))
                self.temperaturesWereAcquired = True
            else:  #If segmentation was for single image
                mean = mean_temperature(self.i2s.Xarray[:, :, 0],
                                        self.Y[:, :, 0],
                                        plot=False)
                self.messagePrint("La temperatura media es: " + str(mean))

            if (self.ui_window.plotCheckBox.isChecked()
                ):  #If user asked for plot
                self.messagePrint("Se generara plot de temperatura...")
                self.getTimes()
                print(self.timeList)
                self.tempPlot()

        elif self.inputExists:
            self.messagePrint("No se ha segmentado previamente la imagen ")
        else:
            self.messagePrint("No se han seleccionado imagenes de entrada")

    def tempPlot(self):
        plt.figure()
        plt.plot(self.timeList, self.meanTemperatures, '-o')
        plt.title("Temperatura media de pies")
        plt.xlabel("Tiempo (s)")
        plt.ylabel("Temperatura (°C)")
        plt.grid()
        plt.show()
        #Produce plot

    def figlabels(self):
        #  Get info from directory path name and obtain time indexes based on name
        pass

    def openImage(self):
        self.fileDialog = QFileDialog(self)
        if self.defaultDirectoryExists:
            self.fileDialog.setDirectory(self.defaultDirectory)
        else:
            self.fileDialog.setDirectory(QDir.currentPath())
        filters = ["*.png", "*.xpm", "*.jpg"]
        self.fileDialog.setNameFilters("Images (*.png *.jpg)")
        self.fileDialog.selectNameFilter("Images (*.png *.jpg)")
        #self.fileDialog.setFilter(self.fileDialog.selectedNameFilter())
        self.opdir = self.fileDialog.getOpenFileName()[0]
        self.imagesDir = os.path.dirname(self.opdir)
        if self.opdir:
            self.inputExists = True
            self.ui_window.inputImg.setPixmap(self.opdir)

    def openFolder(self):
        self.folderDialog = QFileDialog(self)
        self.folderDialog.setDirectory(QDir.currentPath())
        self.folderDialog.setFileMode(QFileDialog.FileMode.Directory)
        self.defaultDirectory = self.folderDialog.getExistingDirectory()
        self.imagesDir = self.defaultDirectory
        if self.defaultDirectory:
            self.defaultDirectoryExists = True
            first_image = str(self.defaultDirectory + "/t0.jpg")
            print(first_image)
            self.ui_window.inputImg.setPixmap(first_image)
            self.opdir = first_image
            self.inputExists = True
            self.findImages()

    def makeTimePlot(self):
        if self.inputExists:
            x = np.array([0, 1, 5, 10, 15, 20])
            y = np.array([35.5, 35.7, 36, 37.2, 37.3, 37.5])
            fig = plt.figure(figsize=(9.6, 4))
            plt.plot(x, y, label='Paciente 1')
            plt.legend()
            plt.grid()
            plt.xlabel("Tiempo [minutos]")
            plt.ylabel("Temperatura [°C]")
            plt.title("Time plot")
            #plt.show()
            plt.savefig('/ouputs/fresh.png')
            self.ui_window.timePlot.setPixmap('/outputs/outputs//fresh.png')
            self.messagePrint("Se ha actualizado el TimePlot")
        else:
            self.messagePrint(
                "No se puede actualizar el TimePlot. No se ha seleccionado una imagen de entrada"
            )

    def fullPlot(self):
        self.messagePrint("Preparando full plot...")
        #show_temperatures("paciente" , fn="mean" , range_ = [22.5 , 33.5])
        self.messagePrint("Full plot generado exitosamente")
        pass

    def exportReport(self):
        self.messagePrint("Generando reporte...")
        #GENERATE A PDF REPORT FOR THE PATIENT
        #INPUT: SELF, PATIENT DIR
        #RETURN: NONE
        #ACTION: COMPILE PDF TEXT BASED ON
        self.messagePrint("Reporte generado exitosamente")
        pass

    def animate(self):
        """
        Produces gif animation based on mean temperatures for whole session
        Initially, all feet has same color, for section segmentation has been not implemented yet
        """
        self.messagePrint("Iniciando animacion...")
        pass
Ejemplo n.º 9
0
class Stats:

    def __init__(self):
        self.regpath = "SOFTWARE\\zylTemp\\"
        self.ui = QUiLoader().load('ExcelPicker.ui')
        self.ui.operatorBox.addItems(['不是', '是', '包含', '大于', '大于等于', '小于', '小于等于', '等于', '不等于'])
        self.ui.loadButton.clicked.connect(self.loadExcelEvent)
        self.ui.anlzButton.clicked.connect(self.doExcel)
        self.ui.titleButton.clicked.connect(self.tips)

    def loadExcelEvent(self):
        # 初始化fileDialog
        self.fileDialog = QFileDialog()
        self.fileDialog.setNameFilter('Excel|*.xls')
        self.fileDialog.selectNameFilter('Images|*.xls')
        # self.fileDialog.getOpenFileName(self, '打开Excel', 'C:', 'Excel(*.xls)')
        name_ = self.fileDialog.getOpenFileName()[0]
        if name_ != '':
            self.fileDialog.fileSelected.connect(self.getExcelFullPath(name_))
        else:
            return
        # 包装工作簿
        try:
            self.wizard = SheetWizard(self.ui.pathLabel.text())
        except Exception:
            return
        self.firstRowList = self.wizard.get_row_by_index(0)
        self.ui.conditionBox.addItems(self.firstRowList)
        # for node in self.firstRowList:
        #     checkBox = QCheckBox(self.verticalLayoutWidget)
        #     checkBox.setObjectName(node)
        #     checkBox.setText(node)
        #     checkBox.toggled.connect(lambda: self.checkBoxClicked(node))
        #     self.verticalLayout_2.addWidget(checkBox)
        # QMessageBox.about(self.window, 'Hey', '我猜这不是一个Excel')
        # self.comboBox.

    def getExcelFullPath(self, fileName):
        self.ui.pathLabel.setText(fileName)

    def doExcel(self):
        # 获得主工作表
        main_sheet = self.wizard.get_main_sheet()
        # 根据条件获取符合条件的行号
        try:
            rows = self.wizard.get_rows_by_condition(main_sheet, self.ui.conditionBox.currentText(),
                                                     self.ui.operatorBox.currentText(), self.ui.valueEdit.text())
        except TypeError:
            QMessageBox.about(self.ui, 'warning', '你输入的条件貌似不合适')
            return
        textList = self.ui.plainTextEdit.toPlainText()[:-1].split()
        if len(textList) == 0:
            QMessageBox.about(self.ui, 'warning', '得有生成依据才行~')
            return
        # 根据需要的列名获取列索引
        cols = self.wizard.get_cols_by_col_names(textList)
        # 根据行和列获取全部值
        values = self.wizard.get_values_by_coordinate(rows, cols)
        # 写入Excel
        book = self.wizard.write_excel(values, '新的应收工作表')
        # 保存
        try:
            self.wizard.save_book(book)
        except PermissionError:
            QMessageBox.about(self.ui, 'tips', '你需要先关闭生成的工作簿')
            return
        print(rows)
        print(cols)
        print(values)
        QMessageBox.about(self.ui, 'success!', '成功啦!')

    def tips(self):
        reg = CreateKey(HKEY_CURRENT_USER, self.regpath)
        value = '0'
        try:
            value = QueryValue(reg, 'index')
            SetValue(reg, 'index', REG_SZ, str(int(value) + 1))
        except Exception:
            SetValue(reg, 'index', REG_SZ, '1')
        if '' != value and int(value) == 100:
            self.ui.titleButton.setIcon(QIcon('sources/ico/smile.ico'))
            SetValue(reg, 'index', REG_SZ, str(100))
            return
        elif '' == value or int(value) % 10 == 0:
            QMessageBox.about(self.ui, 'tips', '选择"加载Excel" 选中一个XLS工作表')
        # elif int(value) == 13:
        #     question = QMessageBox.question(self.ui, 'ask', 'do you have a boyfriend?')
        #     if question == QMessageBox.Yes:
        #         SetValue(reg, 'index', REG_SZ, str(100))
        #         QMessageBox.about(self.ui, 'tips', '嗯... 当然...')
        #         send_sms('yes i have.. sorry..')
        #     else:
        #         SetValue(reg, 'index', REG_SZ, str(100))
        #         QMessageBox.about(self.ui, 'tips', '(๑•̀ㅂ•́)و✧')
        #         send_sms('of course no! hahaha')
        elif int(value) % 10 == 1:
            QMessageBox.about(self.ui, 'tips', '在第一个下拉框中选择过滤条件 填入阈值')
        elif int(value) % 10 == 2:
            QMessageBox.about(self.ui, 'tips', '在第二个下拉框中选择操作类型\n注意: 除了"是"和"不是"之外 其他选项都是针对数字的')
        elif int(value) % 10 == 3:
            QMessageBox.about(self.ui, 'tips', '在文本框中填入数字或文本\nagain: [是不是]对应文本\n[等不等于]对应数字')
        elif int(value) % 10 == 4:
            QMessageBox.about(self.ui, 'tips', '如果一切顺利 新的工作簿会被保存在桌面 名字就叫"新的工作簿"')
        elif int(value) % 10 == 5:
            QMessageBox.about(self.ui, 'tips', '时间仓促 bug好多 出现崩溃? 重开试试!')
        elif int(value) % 10 == 6:
            QMessageBox.about(self.ui, 'tips', '不要吐槽本作品的UI 我很丑但我很温柔')
        elif int(value) % 10 == 7:
            QMessageBox.about(self.ui, 'tips', '加载完Excel后复制主Sheet中你想要的汇总的标题行')
        elif int(value) % 10 == 8:
            QMessageBox.about(self.ui, 'tips', '最后一步 点击解析Excel 会生成你想要的结果')
        elif int(value) % 10 == 9:
            QMessageBox.about(self.ui, 'tips', '不要吐槽本作品的UI 我很丑但我很温柔')
Ejemplo n.º 10
0
class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.load_ui()
        self.figlabels()
        self.imgs = []
        self.subj = []
        # self.figlabels = cv2.imread('figlabels.png')
        self.make_connect()
        self.inputExists = False
        self.defaultDirectoryExists = False
        self.annotationExists: False
        self.isSegmented = False

    def load_ui(self):
        loader = QUiLoader()
        path = os.fspath(Path(__file__).resolve().parent / "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        self.ui_window = loader.load(ui_file, self)
        ui_file.close()

    def make_connect(self):
        QObject.connect(self.ui_window.actionCargar_imagen,
                        SIGNAL('triggered()'), self.openImage)
        QObject.connect(self.ui_window.actionCargar_carpeta,
                        SIGNAL('triggered()'), self.openFolder)
        QObject.connect(self.ui_window.segButton, SIGNAL('clicked()'),
                        self.segment)
        QObject.connect(self.ui_window.tempButton, SIGNAL('clicked()'),
                        self.temp_extract)
        QObject.connect(self.ui_window.manualSegButton, SIGNAL('clicked()'),
                        self.manual_segment)
        QObject.connect(self.ui_window.refreshTimePlot, SIGNAL('clicked()'),
                        self.makeTimePlot)
        QObject.connect(self.ui_window.nextImageButton, SIGNAL('clicked()'),
                        self.nextImage)
        QObject.connect(self.ui_window.previousImageButton,
                        SIGNAL('clicked()'), self.previousImage)
        QObject.connect(self.ui_window.saveButton, SIGNAL('clicked()'),
                        self.saveImage)
        QObject.connect(self.ui_window.fullPlotButton, SIGNAL('clicked()'),
                        self.fullPlot)
        QObject.connect(self.ui_window.reportButton, SIGNAL('clicked()'),
                        self.exportReport)

    def messagePrint(self, message):
        #INPUT: string to print
        #OUTPUT: none
        #ACTION: generate out.html file and refresh it in Messages QTextArea
        log_path = "outputs/logs.html"
        out_file = open(log_path, "w")
        out_file.write(message)
        out_file.close()
        self.ui_window.textBrowser.setSource(log_path)
        self.ui_window.textBrowser.reload()

    def findImages(self):
        self.fileList = []
        for root, dirs, files in os.walk(self.defaultDirectory):
            for file in files:
                if (file.endswith(".jpg")):
                    self.fileList.append(os.path.join(root, file))
        self.fileList.sort()
        self.imageQuantity = fileList.size()
        self.imageIndex = 0

    def nextImage(self):
        if self.imageIndex < len(self.fileList) - 1:
            self.imageIndex += 1
            self.ui_window.inputImg.setPixmap(self.fileList[self.imageIndex])
            self.opdir = self.fileList[self.imageIndex]

    def previousImage(self):
        if self.imageIndex > 1:
            self.imageIndex -= 1
            self.ui_window.inputImg.setPixmap(self.fileList[self.imageIndex])
            self.opdir = self.fileList[self.imageIndex]

    def saveImage(self):
        #Saves segmented image
        pass

    def feet_segment(self, full=False):
        if full:
            pass
        else:
            self.i2s = Image_2_seg()
            self.i2s.setPath(self.opdir)
            self.i2s.extract()
            threshold = 0.5
            img = plt.imread(self.opdir) / 255
            Y = self.i2s.Y_pred
            Y = Y / Y.max()
            Y = np.where(Y >= threshold, 1, 0)
            self.Y = Y[0]
            Y = cv2.resize(
                Y[0], (img.shape[1], img.shape[0]),
                interpolation=cv2.INTER_NEAREST
            )  # Resize the prediction to have the same dimensions as the input
            plt.imsave("outputs/output.jpg", Y * img[:, :, 0], cmap='gray')
            self.ui_window.outputImg.setPixmap("outputs/output.jpg")
            self.messagePrint("Se ha segmentado exitosamente la imagen")
            self.isSegmented = True

    def sessionSegment(self):
        self.messagePrint("Segmentando toda la sesion...")

    def segment(self):
        if self.ui_window.sessionCheckBox:
            if self.defaultDirectoryExists:
                self.sessionSegment()
            else:
                self.messagePrint("No se ha seleccionado sesion de entrada")
        else:
            if self.inputExists:
                self.feet_segment()
            else:
                self.messagePrint("No se ha seleccionado sesion de entrada")

    def manual_segment(self):
        print("Se abrirá diálogo de extracción manual")
        self.manual = manualSeg()
        self.manual.show()
        return

    def temp_extract(self):
        #print(self.ui_window.plotCheckBox.isChecked())
        if (self.ui_window.plotCheckBox.isChecked()):
            pass
        else:
            if (self.inputExists and self.isSegmented):
                mean = mean_temperature(self.i2s.Xarray[:, :, 0],
                                        self.Y[:, :, 0],
                                        plot=True)
                self.messagePrint("La temperatura media es: " + str(mean))
            elif self.inputExists:
                self.messagePrint(
                    "No se ha segmentado previamente la imagen. Segmentando..."
                )
                self.segment()
                self.temp_extract()
            else:
                self.messagePrint(
                    "No se han seleccionado imagenes de entrada...")
                self.openFolder()
                self.segment()
                self.temp_extract()

    def tempPlot(self):
        means = []
        for i in range(self.imageQuantity):
            means.append(0)

    def figlabels(self):
        #  Get info from directory path name and obtain time indexes based on name
        pass

    def openImage(self):
        self.fileDialog = QFileDialog(self)
        if self.defaultDirectoryExists:
            self.fileDialog.setDirectory(self.defaultDirectory)
        else:
            self.fileDialog.setDirectory(QDir.currentPath())
        filters = ["*.png", "*.xpm", "*.jpg"]
        self.fileDialog.setNameFilters("Images (*.png *.jpg)")
        self.fileDialog.selectNameFilter("Images (*.png *.jpg)")
        #self.fileDialog.setFilter(self.fileDialog.selectedNameFilter())
        self.opdir = self.fileDialog.getOpenFileName()[0]
        self.imagesDir = os.path.dirname(self.opdir)
        if self.opdir:
            self.inputExists = True
            self.ui_window.inputImg.setPixmap(self.opdir)

    def openFolder(self):
        self.folderDialog = QFileDialog(self)
        self.folderDialog.setDirectory(QDir.currentPath())
        self.folderDialog.setFileMode(QFileDialog.FileMode.Directory)
        self.defaultDirectory = self.folderDialog.getExistingDirectory()
        self.imagesDir = self.defaultDirectory
        if self.defaultDirectory:
            self.defaultDirectoryExists = True
            first_image = str(self.defaultDirectory + "/t0.jpg")
            print(first_image)
            self.ui_window.inputImg.setPixmap(first_image)
            self.opdir = first_image
            self.inputExists = True
            self.findImages()

    def makeTimePlot(self):
        if self.inputExists:
            x = np.array([0, 1, 5, 10, 15, 20])
            y = np.array([35.5, 35.7, 36, 37.2, 37.3, 37.5])
            fig = plt.figure(figsize=(9.6, 4))
            plt.plot(x, y, label='Paciente 1')
            plt.legend()
            plt.grid()
            plt.xlabel("Tiempo [minutos]")
            plt.ylabel("Temperatura [°C]")
            plt.title("Time plot")
            #plt.show()
            plt.savefig('/ouputs/fresh.png')
            self.ui_window.timePlot.setPixmap('/outputs/outputs//fresh.png')
            self.messagePrint("Se ha actualizado el TimePlot")
        else:
            self.messagePrint(
                "No se puede actualizar el TimePlot. No se ha seleccionado una imagen de entrada"
            )

    def fullPlot(self):
        self.messagePrint("Preparando full plot...")
        #show_temperatures("paciente" , fn="mean" , range_ = [22.5 , 33.5])
        self.messagePrint("Full plot generado exitosamente")
        pass

    def exportReport(self):
        self.messagePrint("Generando reporte...")
        #GENERATE A PDF REPORT FOR THE PATIENT
        #INPUT: SELF, PATIENT DIR
        #RETURN: NONE
        #ACTION: COMPILE PDF TEXT BASED ON
        self.messagePrint("Reporte generado exitosamente")
        pass

    def animate(self):
        self.messagePrint("Iniciando animacion...")
        pass