Пример #1
0
 def __init__(self):
     QMainWindow.__init__(self)
     self.ui = loadUi('forms/mainwindow.ui', self)
     # self.ui = Ui_MainWindow()
     # self.ui.setupUi(self)
     self.input_name = None
     self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
     self.videoWidget = VideoWidget(self)
     self.detector = CellDetector()
     layout = QVBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.addWidget(self.videoWidget)
     self.ui.videoFrame.setLayout(layout)
     self.ui.playButton.setEnabled(False)
     self.ui.playButton.setIcon(self.style().standardIcon(
         QStyle.SP_MediaPlay))
     self.ui.playButton.clicked.connect(self.play)
     self.ui.openButton.clicked.connect(self.openFile)
     self.ui.saveButton.clicked.connect(self.saveFile)
     self.ui.saveButton.setEnabled(False)
     self.ui.timeSlider.sliderMoved.connect(self.setPosition)
     self.ui.modeCheckBox.stateChanged.connect(self.switchMode)
     self.ui.statusbar: QStatusBar
     self.ui.statusbar.showMessage("Init Model ...")
     # self.ui.statusbar.setLayout()
     self.mediaPlayer.setVideoOutput(self.videoWidget.videoSurface())
     self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
     self.mediaPlayer.positionChanged.connect(self.positionChanged)
     self.mediaPlayer.durationChanged.connect(self.durationChanged)
     self.mediaPlayer.setMuted(True)
     # shortcut
     QShortcut(QKeySequence('Space'), self).activated.connect(self.play)
Пример #2
0
class GetPicture(QWidget):
    """
    Controller class for the Get Picture window used to capture a new user's face.
    Attributes:
        face_recognizer         a FaceRecogniser object used to detect and record a new face for a new identity
        video_widget            custom widget to show the live feed from webcam
    """
    def __init__(self):
        """Class constructor that sets up the window layout and allocates attributes"""
        super().__init__()
        self.title = 'Database Manager - Take Photo'
        self.setFixedSize(600,400)

        self.face_recognizer = FaceRecogniser()
        self.video_widget = VideoWidget(self.face_recognizer)
        h = QHBoxLayout()
        h.addWidget(self.video_widget)
        self.setLayout(h)

    def activate(self):
        """Method to activate this widget and start face detection"""
        self.show()
        self.video_widget.activate()

    def deactivate(self):
        """Method to deactivate this widget and stop face detection"""
        self.hide()
        self.video_widget.deactivate()
Пример #3
0
    def __init__(self):
        """Class constructor that sets up the window layout and allocates attributes"""
        super().__init__()
        self.title = 'Database Manager - Take Photo'
        self.setFixedSize(600,400)

        self.face_recognizer = FaceRecogniser()
        self.video_widget = VideoWidget(self.face_recognizer)
        h = QHBoxLayout()
        h.addWidget(self.video_widget)
        self.setLayout(h)
Пример #4
0
	def paintEvent(self, event):
		VideoWidget.paintEvent(self, event)

		if not self.is_connected:
			return

		qp = QPainter(self)
		qp.setRenderHints(QPainter.Antialiasing)
		#painter.begin(self)
		qp.setPen(QtGui.QColor(255, 255, 0))
		self.drawCenterGrid(qp)
Пример #5
0
    def createLayout(self):
        """ Create the layout of the window. """
        centralWidget = QtGui.QWidget(self)
        self.mainLayout = QtGui.QVBoxLayout(centralWidget)
        self.videoWidget = VideoWidget()
        self.surface = self.videoWidget.videoSurface()
        self.videoWidget.setStringStartPosition(
            (self.videoWidget.size().width() * 0.9,
             self.videoWidget.size().height()))

        self.controlLayout = QtGui.QVBoxLayout()
        self.createInfoInterface()

        self.creatBasicControls()
        self.createOptionControls()

        self.mainLayout.addWidget(self.videoWidget)
        self.mainLayout.insertLayout(1, self.controlLayout)

        self.setCentralWidget(centralWidget)
        self.treatmentComboBox.currentIndexChanged.emit(0)
Пример #6
0
    def createLayout(self):
        """ Create the layout of the window. """
        centralWidget = QtGui.QWidget(self)
        self.mainLayout = QtGui.QVBoxLayout(centralWidget)
        self.videoWidget = VideoWidget()
        self.surface = self.videoWidget.videoSurface()
        self.videoWidget.setStringStartPosition((self.videoWidget.size().width()*0.9, self.videoWidget.size().height()))
        
        self.controlLayout = QtGui.QVBoxLayout()
        self.createInfoInterface()
        
        self.creatBasicControls()
        self.createOptionControls()
        
        self.mainLayout.addWidget(self.videoWidget)
        self.mainLayout.insertLayout(1, self.controlLayout)

        self.setCentralWidget(centralWidget)
        self.treatmentComboBox.currentIndexChanged.emit(0)
Пример #7
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = loadUi('forms/mainwindow.ui', self)
        # self.ui = Ui_MainWindow()
        # self.ui.setupUi(self)
        self.input_name = None
        self.mediaPlayer = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.videoWidget = VideoWidget(self)
        self.detector = CellDetector()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.videoWidget)
        self.ui.videoFrame.setLayout(layout)
        self.ui.playButton.setEnabled(False)
        self.ui.playButton.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPlay))
        self.ui.playButton.clicked.connect(self.play)
        self.ui.openButton.clicked.connect(self.openFile)
        self.ui.saveButton.clicked.connect(self.saveFile)
        self.ui.saveButton.setEnabled(False)
        self.ui.timeSlider.sliderMoved.connect(self.setPosition)
        self.ui.modeCheckBox.stateChanged.connect(self.switchMode)
        self.ui.statusbar: QStatusBar
        self.ui.statusbar.showMessage("Init Model ...")
        # self.ui.statusbar.setLayout()
        self.mediaPlayer.setVideoOutput(self.videoWidget.videoSurface())
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
        self.mediaPlayer.setMuted(True)
        # shortcut
        QShortcut(QKeySequence('Space'), self).activated.connect(self.play)
        # s_max = self.maximumSize()
        # # self.ui.statusBar.setSizeGripEnabled(False)
        # self.show()
        # self.setFixedSize(s_max)

    def showEvent(self, *args, **kwargs):
        self.detector.onInitModelSuccess.connect(
            lambda: self.ui.statusbar.showMessage("Ready"))
        self.detector.initModel()

    def closeEvent(self, *args, **kwargs):
        QApplication.closeAllWindows()

    def switchMode(self, state):
        self.detector.setMode(state)
        self.startProcess()

    def startProcess(self):
        if self.input_name:
            self.ui.listWidget.clear()
            self.sum_cells = 0
            self.log = []
            self.mediaPlayer.setMedia(
                QMediaContent(QUrl.fromLocalFile(self.input_name)))
            self.cap = cv2.VideoCapture(self.input_name)
            VideoInfo.init(self.cap)
            self.frameCount = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
            fps = np.ceil(self.cap.get(cv2.CAP_PROP_FPS))
            window_time = 2  # sec
            dialog = ProcessDialog(self)
            dialog.setMaximum(self.frameCount)
            map_worker = ObjectMapper(self.frameCount, fps)
            map_worker.onUpdateObject.connect(self.updateObject)
            map_worker.onUpdateProgress.connect(dialog.updateProgress)
            ppc_worker = PreprocessThread(self.input_name)
            ppc_worker.onFrameChanged.connect(map_worker.updateOpticalFlow)
            ppc_worker.onFrameChanged.connect(self.detector.updateOpticalFlow)
            ppc_worker.onBufferReady.connect(self.detector.detect)
            ppc_worker.onUpdateProgress.connect(dialog.updateProgress)
            map_worker.onNewDetectedCells.connect(self.updateDetectLog)
            map_worker.finished.connect(dialog.close)
            dialog.closed.connect(ppc_worker.quit)
            dialog.closed.connect(map_worker.quit)
            self.detector.onDetectSuccess.connect(map_worker.queueOutput)
            # ppc_worker.finished.connect(dialog.close)
            # dialog.onReady2Read.connect(self.setOutput)
            dialog.show()
            map_worker.start()
            ppc_worker.start()
            dialog.exec_()
            self.ui.playButton.setEnabled(True)
            self.ui.saveButton.setEnabled(True)

    def openFile(self):
        file_name = QFileDialog.getOpenFileName(self, "Open Video")[0]
        if os.path.exists(file_name):
            self.input_name = file_name
            self.startProcess()

    def saveFile(self):
        dialog = SaveDialog()
        dialog.exec_()
        head, tail = os.path.split(self.input_name)
        file_prefix = tail.split('.')[0]
        worker = VideoWriterThread(self.cap, self.frame_objects, self.log,
                                   file_prefix, dialog.getSaveDirectory(),
                                   dialog.isSaveImage, dialog.isSaveVideo)
        worker.start()

    def updateObject(self, frame_objects):
        self.frame_objects = frame_objects
        duration = self.mediaPlayer.duration()
        self.videoWidget.setOutput(frame_objects, duration / self.frameCount)
        self.ui.playButton.setEnabled(True)
        self.ui.saveButton.setEnabled(True)

    def updateDetectLog(self, detected_frame_id, cell_map, cell_count):
        # append log
        widget = QCustomQWidget()
        self.sum_cells += cell_count
        self.cap.set(cv2.CAP_PROP_POS_FRAMES, detected_frame_id)
        _, image = self.cap.read()
        _, min, sec = getHHMMSSFormat(self.mediaPlayer.duration() /
                                      self.frameCount * detected_frame_id)
        time_text = '{:02}-{:02}'.format(min, sec)
        self.log.append({
            "image": image.copy(),
            "detect_time": time_text,
            "cells": cell_map
        })
        drawBoxes(image, cell_map, (0, 255, 0))
        icon = imutils.resize(image, height=64)
        icon = toQImage(icon)
        widget.setPreviewImg(icon)
        widget.setCount(cell_count)
        widget.setDetectionFramePosition(self.mediaPlayer.duration() /
                                         self.frameCount * detected_frame_id)
        widget.setTimeText('{:02}:{:02}'.format(min, sec))
        # widget.onDoubleClick.connect(self.positionChanged)
        widget.onDoubleClick.connect(self.setPosition)
        list_widget_item = QListWidgetItem(self.ui.listWidget)
        list_widget_item.setSizeHint(widget.size())
        self.ui.listWidget.addItem(list_widget_item)
        self.ui.listWidget.setItemWidget(list_widget_item, widget)
        self.ui.totalNumber.display(self.sum_cells)

    def play(self):
        if self.mediaPlayer.state() == QMediaPlayer.PlayingState:
            self.mediaPlayer.pause()
        else:
            self.mediaPlayer.play()

    def mediaStateChanged(self, state):
        if state == QMediaPlayer.PlayingState:
            self.ui.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.ui.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.ui.timeSlider.setValue(position)
        duration = self.mediaPlayer.duration()
        _, dmin, dsec = getHHMMSSFormat(duration)
        _, pmin, psec = getHHMMSSFormat(position)
        self.ui.timeLabel.setText('{:02}:{:02}/{:02}:{:02}'.format(
            int(pmin), int(psec), int(dmin), int(dsec)))

    def durationChanged(self, duration):
        self.ui.timeSlider.setRange(0, duration)
        _, dmin, dsec = getHHMMSSFormat(duration)
        self.ui.timeLabel.setText('00:00/{:02}:{:02}'.format(
            int(dmin), int(dsec)))

    def setPosition(self, position):
        self.mediaPlayer.setPosition(position)
Пример #8
0
class Window(QtGui.QMainWindow):
    finishedWork = QtCore.pyqtSignal()
    """ This is the class which contains all the GUI."""
    
    def __init__(self):
        """ Create the view object."""
        super(Window, self).__init__()
        self.initUI()

    def initUI(self):
        """ Initialize the main windows of the application. """
        self.resize(640, 480)
        self.centerWindow()
        self.setWindowTitle('Line')
        self.setWindowIcon(QtGui.QIcon('Images/Icon.png')) 
        QtCore.QTextCodec.setCodecForCStrings(QtCore.QTextCodec.codecForName('UTF-8'))
        
        self.firstTimePlayed = True
        self.createMenuBar()
        self.createLayout()
        self.source = None
        self.lines = []
        self.rect= []
        self.point = []
        self.OutputFile=None
        self.InputFile=None
        self.statusBar().showMessage('Prêt')
        
    def centerWindow(self):
        """ Center the windows on the screen of the user. """
        windowsGeometry = self.frameGeometry()
        ScreenCenter = QtCore.QPoint(QtGui.QDesktopWidget().availableGeometry().center().x()/2, 0)
        windowsGeometry.moveCenter(ScreenCenter)
        self.move(windowsGeometry.center())       
     
    def createMenuBar(self):
        """ Create the Menu bar with its menu and add the actions to the menus. """
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&Fichiers')
        fileMenu.addAction(self.createAction('&Fermer', QtGui.qApp.quit, 'Ctrl+Q', 'Quitte application'))
        fileMenu.addAction(self.createAction('&Ouvrir', self.openFile, 'Ctrl+O', 'Ouvre un film'))
        self.printImageAction=self.createAction('&Sauver image', self.captureImage, 'Ctrl+S', 'Sauvegarde l\'image présente à l\'écran')
        fileMenu.addAction(self.printImageAction)
        self.printImageAction.setDisabled(True)
        helpMenu = menubar.addMenu('Aide')
        helpMenu.addAction(self.createAction('A propos', self.printAbout, 'Ctrl+?', 'A propos'))
        helpMenu.addAction(self.createAction('A propos de Qt', self.printAboutQt, 'A propos de qt'))
        
    def printAbout(self):
        """Display the information about the application"""
        QtGui.QMessageBox.about(self, 'A propos de Pyradius', '<p><strong>Pyradius V1.0</strong></p>\
        <p>Pyradius est un logiciel de traitement d\'images permettant l\'extraction de l\'angle de pennation et de la position de la jonction des aponévroses.</p>\
        <p>Copyright&copy; 2013 Yves-Rémi Van Eycke.</p>\
        <p>Ce logiciel est sous licence <a href=https://www.gnu.org/licenses/quick-guide-gplv3.fr.html>GNU GPLv3</a>.\
        Il a été rendu possible grâce à: \
        <a href=\'http://www.python.org/\'>Python</a>, <a href=\'http://www.cython.org/\'>Cython</a>, \
        <a href=\'http://www.riverbankcomputing.co.uk/software/pyqt\'>PyQt</a>, <a href=\'http://www.numpy.org/\'>Numpy</a>, \
        <a href=\'http://opencv.org/\'>OpenCV</a>, <a href=\'http://scikit-image.org/\'>scikit-image</a>, \
        <a href=\'https://bitbucket.org/zakhar/ffvideo/wiki/Home\'>FFVideo</a>, <a href=\'http://www.ffmpeg.org/\'>FFMpeg</a>, \
        <a href=\'http://pandas.pydata.org/\'>Pandas</a>.</p>\
        Le code source est disponible <a href=\'https://code.google.com/p/pyradius/\'>ici</a>.<p></p>')
        
    def printAboutQt(self):
        """Display the information about Qt"""
        QtGui.QMessageBox.aboutQt(self, 'A propos de Qt')
        
    def createAction(self, name, funct, shortcut='', statusTip=''):
        """Create the actions used, for example, in the menu bar and return it.
        
        :param name: The name of the action.
        :param funct: The function to be triggered by the action.
        :param shortcut: The shortcut for the action.
        :param statusTip: A tip which will appear when hovering the action.
        :return: The QAction object
        :raise: AttributeError: if there is the name or the function send is none.
        """
        
        if name != None:
            action = QtGui.QAction(name, self)
        else:
            raise AttributeError('The action need a name!')
            
        if shortcut != None:
            action.setShortcut(shortcut)
        
        if statusTip != None:
            action.setStatusTip(statusTip)
        
        if funct != None :
            action.triggered.connect(funct)
        else:
            raise AttributeError('The action need a callable or a signal for when triggered!')
        
        return action

    def createLayout(self):
        """ Create the layout of the window. """
        centralWidget = QtGui.QWidget(self)
        self.mainLayout = QtGui.QVBoxLayout(centralWidget)
        self.videoWidget = VideoWidget()
        self.surface = self.videoWidget.videoSurface()
        self.videoWidget.setStringStartPosition((self.videoWidget.size().width()*0.9, self.videoWidget.size().height()))
        
        self.controlLayout = QtGui.QVBoxLayout()
        self.createInfoInterface()
        
        self.creatBasicControls()
        self.createOptionControls()
        
        self.mainLayout.addWidget(self.videoWidget)
        self.mainLayout.insertLayout(1, self.controlLayout)

        self.setCentralWidget(centralWidget)
        self.treatmentComboBox.currentIndexChanged.emit(0)
    
    def creatBasicControls(self):
        """ Create the layout for the widgets controlling the video. """
        self.basicControlLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.basicControlLayout)
        
        self.playButton = QtGui.QPushButton(QtGui.QIcon("Images/play.png"), 'Commencer')
        self.playButton.resize(50, 50)
        self.progressBar = QtGui.QProgressBar()
        self.progressBar.setOrientation(QtCore.Qt.Horizontal)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.playButton.setEnabled(False)        
        
        self.playButton.clicked.connect(self.toggleProcessVideo)
        
        self.basicControlLayout.addWidget(self.playButton)
        self.basicControlLayout.addWidget(self.progressBar)
        
    def createOptionControls(self):
        """ Create the layout for the widgets common to all the treatments. """
        self.oLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.oLayout)
        
        self.OptionWidget = QtGui.QWidget(self)
        self.oLayout.addWidget(self.OptionWidget)
        
        
        self.OptionLayout = QtGui.QVBoxLayout()
        self.OptionWidget.setLayout(self.OptionLayout)
        self.OptionWidget.setContentsMargins(0, 0, 0, 0)
        self.OptionLayout.setContentsMargins(0, 0, 0, 0)
    
        self.basicOptionWidget = QtGui.QGroupBox("Options Générales", self.OptionWidget)
        self.OptionLayout.addWidget(self.basicOptionWidget)
        self.basicOptionLayout = QtGui.QHBoxLayout()
        self.basicOptionWidget.setLayout(self.basicOptionLayout)
        self.basicOptionWidget.setContentsMargins(0, 0, 0, 0)

        self.resetTreatmentButton = QtGui.QPushButton("Réinitialiser")
        self.resetTreatmentButton.setEnabled(False)
        
        self.treatmentComboBox = QtGui.QComboBox()
        self.treatmentComboBox.addItem('Lucas-Kanade')
        self.treatmentComboBox.addItem('Fit ellipsoïde')
        self.treatmentComboBox.addItem('Radon transform')
        self.treatmentComboBox.addItem('Seam Carving')
        
        self.SkipFrameLabel = QtGui.QLabel("Nombre d'images à passer:")
        self.SkipFrameLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        self.SkipFrameSpinBox = QtGui.QSpinBox()
        self.SkipFrameSpinBox.setMinimum(0)
        self.SkipFrameSpinBox.setMaximum(25)
        
        self.resetTreatmentButton.clicked.connect(self.changeTutorial)
        self.treatmentComboBox.currentIndexChanged.connect(self.loadCorrectInterface)
        
        self.basicOptionLayout.addStretch()
        self.basicOptionLayout.addWidget(self.resetTreatmentButton)
        self.basicOptionLayout.addWidget(self.treatmentComboBox)
        self.basicOptionLayout.addWidget(self.SkipFrameLabel)
        self.basicOptionLayout.addWidget(self.SkipFrameSpinBox)
        self.basicOptionLayout.addStretch()
        
        self.createEllipsoidMethodInterface()
        self.createRadonMethodInterface()
        self.createLKMethodInterface()
        self.createSCMethodInterface()
        
    def createInfoInterface(self):
        """ Create the layout for the labels displaying the extracted information. """
        self.infoInterfaceLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.infoInterfaceLayout)
        self.infoLabelList = []
        self.infoValueList = []
        
    def updateInfoInterface(self, infoNumber):
        """ Update the layout containing the labels displaying the extracted information. 
        
        :param infoNumber: The number of info to display (=the number of labels needed).
        :type infoNumber: int
        """
        for value, label in zip(self.infoValueList, self.infoLabelList):
            del(value)
            del(label)
            
        for i in range(infoNumber):
            self.infoLabelList.append(QtGui.QLabel())
            self.infoValueList.append(QtGui.QLabel())
            self.infoInterfaceLayout.addWidget(self.infoLabelList[i])
            self.infoInterfaceLayout.addWidget(self.infoValueList[i])
            self.infoLabelList[i].show()
            self.infoValueList[i].show()
    
    def updateInfo(self, info):
        """ Update the labels containing the extracted information. 
        
        :param info: The new extracted information.
        :type info: dictionary
        """
        infoNumber = len(info)
        if(infoNumber!=len(self.infoValueList)):
            self.updateInfoInterface(infoNumber)
        for i, key in enumerate(info):
            self.infoLabelList[i].setText(key + " : ")
            self.infoValueList[i].setText(str(info[key]))
            
    def createEllipsoidMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use ellipsoids. """
        self.ellipsoidOptionWidget = QtGui.QGroupBox()
        self.ellipsoidOptionWidget.hide()
        self.OptionLayout.addWidget(self.ellipsoidOptionWidget)
        self.ellipsoidOptionLayout = QtGui.QHBoxLayout()
        self.ellipsoidOptionWidget.setLayout(self.ellipsoidOptionLayout)
        self.ellipsoidOptionLayout.addStretch()
        self.ellipsoidOptionWidget.setContentsMargins(0, 0, 0, 0)
        
    def createRadonMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use the Radon transform. """
        self.radonOptionWidget = QtGui.QGroupBox()
        self.radonOptionWidget.hide()
        self.OptionLayout.addWidget(self.radonOptionWidget)
        self.radonOptionLayout = QtGui.QHBoxLayout()
        self.radonOptionWidget.setLayout(self.radonOptionLayout)
        self.multipleRadonLabel = QtGui.QLabel("Prendre plus d'échantillons:")
        self.multipleRadonLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        self.multipleRadonCheckBox = QtGui.QCheckBox()
        self.radonOptionLayout.addWidget(self.multipleRadonLabel)
        self.radonOptionLayout.addWidget(self.multipleRadonCheckBox)
        self.radonOptionLayout.addStretch()
        self.radonOptionWidget.setContentsMargins(0, 0, 0, 0)
                
    def createLKMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use Lucas-Kanade algorithm. """
        self.LKOptionWidget = QtGui.QGroupBox()
        self.LKOptionWidget.hide()
        self.OptionLayout.addWidget(self.LKOptionWidget)
        self.LKOptionLayout = QtGui.QHBoxLayout()
        self.LKOptionWidget.setLayout(self.LKOptionLayout)
        self.LKOptionLayout.addStretch()
        self.LKOptionWidget.setContentsMargins(0, 0, 0, 0)
    
    def createSCMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment extraction the junction position. """
        self.SCOptionWidget = QtGui.QGroupBox()
        self.SCOptionWidget.hide()
        self.OptionLayout.addWidget(self.SCOptionWidget)
        self.SCOptionLayout = QtGui.QHBoxLayout()
        self.SCOptionWidget.setLayout(self.SCOptionLayout)
        self.SCOptionWidget.setContentsMargins(0, 0, 0, 0)
        
    def loadCorrectInterface(self):
        """ Select the correct layout depending on the method chosen by the user. """
        self.hideAllInterface()
        self.basicOptionWidget.show()
        if(self.treatmentComboBox.currentIndex()==0):
            self.loadLKTransformInterface()
        if(self.treatmentComboBox.currentIndex()==1):
            self.loadEllipsoidTransformInterface()
        if(self.treatmentComboBox.currentIndex()==2):
            self.loadRadonTransformInterface()
        if(self.treatmentComboBox.currentIndex()==3):
            self.loadSCTransformInterface()
       
    def hideAllInterface(self):
        """ Hide all the layouts containing the treatment specific widgets. """
        for i in range(self.OptionLayout.count()):
            possibleWidget = self.OptionLayout.itemAt(i)
            if(possibleWidget.widget()):
                possibleWidget.widget().hide()
    
    def loadEllipsoidTransformInterface(self):
        """ Load the layout for the widgets specific to the treatment which use ellipsoids. """
        self.ellipsoidOptionWidget.show()
        
    def loadRadonTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment which use the Radon transform. """
        self.radonOptionWidget.show()
    
    def loadLKTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment which use Lucas-Kanade algorithm. """
        self.LKOptionWidget.show()
    
    def loadSCTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment extraction the junction position. """
        self.SCOptionWidget.show()
        
    def chooseOutputFile(self):  
        """ Show the dialog to let the user select the output file. """
        
        fileName = QtCore.QString(QtGui.QFileDialog.getSaveFileName(self, "Ouvrir le fichier de sortie", QtCore.QDir.homePath(), 'Fichiers Excel (*.xlsx *.xls);;Fichiers Texte (*.txt);;Fichiers CSV (*.csv)'))
        if (not (fileName.isEmpty())):
            self.OutputFile = (unicode(fileName))

    def chooseInputFile(self):  
        """ Show the dialog to let the user select the output file. """
        fileName = QtCore.QString(QtGui.QFileDialog.getOpenFileName(self, "Ouvrir le fichier d'entrée", QtCore.QDir.homePath(), 'Fichiers Excel (*.xlsx *.xls);;Fichiers Texte (*.txt);;Fichiers CSV (*.csv)'))
        if (not(fileName.isEmpty())):
            self.InputFile = (unicode(fileName))           

             
    def openFile(self):
        """ Show a dialog where there user can pick a file. """
        fileName = QtCore.QString(QtGui.QFileDialog.getOpenFileName(self, "ouvrir la vidéo", QtCore.QDir.homePath(), 'Fichiers vidéo (*.avi *.mpeg *.mpg);;Autres (*.*)'))
        if (not (fileName.isEmpty())):
            self.surface.stop()
            self.resetMovie()
            self.source.setMovie(unicode(fileName))
            self.filterApplied = Applier()
            self.filterApplied.frameComputed.connect(self.frameChanged)
            self.filterApplied.setSource(self.source)
            self.filterApplied.endOfProcessing.connect(self.finishVideo)
            self.firstTimePlayed = True;
            self.playButton.setEnabled(False)
            self.toggleProcessVideo()
            self.printImageAction.setEnabled(True)
            self.resetTreatmentButton.setEnabled(True)

    def resetMovie(self):
        """ Reset the movie. """
        if(self.source is not None):
            self.videoWidget.clicked.disconnect(self.getsurfacePosition)
            self.source.reset()
        else:
            self.source = Movie()
    def finishVideo(self):
        """ Close the video, ask the applier to write the output file if necessary and quit. """
        self.statusBar().showMessage('Traitement terminé')
        box = QtGui.QMessageBox(QtGui.QMessageBox.Information, 'Sauvegarde', 
                  '<p><strong>Le traitement est terminé! Voulez vous sauver les résultats?</strong></p> \
                  <p>Si vous sélectionnez oui, deux fenêtres de dialogue vont s\'ouvrir. \
                  <ul><li>La première va permettre de choisir un fichier d\'entrée si vous voulez fusionner les résultats avec d\'autres résultats que vous possèdez déjà. Dans le cas où vous ne désirez pas fusionner de résultats, fermez cette fenêtre sans choisir de fichier.</li>\
                  <li>La deuxième va permettre de choisir où les résultats seront sauvegardés.</li></ul></p>', 
                  QtGui.QMessageBox.Yes|QtGui.QMessageBox.No, self)
        self.treatmentComboBox.setEnabled(True)
        self.resetTreatmentButton.setEnabled(True)
        self.playButton.setEnabled(False)
        self.surface.stop()
        ret = box.exec_()
        if(ret==QtGui.QMessageBox.Yes):
            self.savingProcedure()
        box = QtGui.QMessageBox(QtGui.QMessageBox.Information, 'Fin du traitement', 
            'Travail terminé! Le programme va maintenant se fermer', 
            QtGui.QMessageBox.Ok, self)
        box.finished.connect(self.finishedWork.emit)
        box.buttonClicked.connect(self.finishedWork.emit)
        self.statusBar().showMessage('Fermeture du programme')
        box.show()
        
    def savingProcedure(self):
        """Save the results in a file"""
        cont=True
        while(cont):
            if(self.InputFile is None or not self.InputFile):
                self.chooseInputFile()
            if(self.OutputFile is None or not self.OutputFile):
                self.chooseOutputFile()
            if(self.OutputFile is None or not self.OutputFile):
                box = QtGui.QMessageBox(QtGui.QMessageBox.Information, 'Pas de fichier de sortie', 
                  'Vous n\'avez pas sélectionné de fichier de sortie. Les resultats ne seront donc pas sauvegardés. Êtes vous sûr de votre choix?', 
                  QtGui.QMessageBox.Yes|QtGui.QMessageBox.No, self)
                ret = box.exec_()
                if(ret==QtGui.QMessageBox.Yes):
                    cont=False
                else:
                    continue
            if(cont):
                self.statusBar().showMessage('Sauvegarde en cours')
                self.filterApplied.saveResult(self.InputFile, self.OutputFile)
                cont=False
                self.statusBar().showMessage('Sauvegarde terminée')
        
    def toggleProcessVideo(self):
        """Pause and play the video processing"""
        if(self.firstTimePlayed):
            self.firstTimePlayed = False
            self.filterApplied.applyOne()
            self.launchTutorial()
        else:
            self.playButton.setEnabled(True)
            self.filterApplied.toggle()
            if(self.filterApplied.wait):
                self.playButton.setIcon(QtGui.QIcon("Images/play.png"))
                self.playButton.setText("Continuer")
            if(not(self.filterApplied.wait) or not(self.filterApplied.isRunning())):
                    self.treatmentComboBox.setEnabled(False)
                    self.resetTreatmentButton.setEnabled(False)
                    self.SkipFrameSpinBox.setEnabled(False)
                    self.playButton.setIcon(QtGui.QIcon("Images/pause.png"))
                    self.playButton.setText("Pause")
                    self.filterApplied.start(QtCore.QThread.HighestPriority)
            
        
    def frameChanged(self):
        """ Update the view when the frame has changed. """
        frame = self.filterApplied.getLastComputedFrame()
        info = self.filterApplied.getLastInformation()
        if(info is not None):
            self.updateInfo(info)

        if (not(frame.isValid())):
            QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error', 'Frame not valid!', QtGui.QMessageBox.Ok, self).show()
            return False;
        currentFormat = self.surface.surfaceFormat()
        if (frame.pixelFormat() != currentFormat.pixelFormat() or frame.size() != currentFormat.frameSize()):
            fmt = QtMultimedia.QVideoSurfaceFormat(frame.size(), frame.pixelFormat())
            if (not(self.surface.start(fmt))):
                QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error', 'Surface could not start!', QtGui.QMessageBox.Ok, self).show()
                return False
        if (not(self.surface.present(frame))):
            self.surface.stop()
        self.progressBar.setValue((self.source.currentPositionRatio()*self.progressBar.maximum()))
        del(frame)

    def jumpToFrame(self, value):
        """ Jump to a position in the movie. 
        
        :param value: A value in the range of the slider.
        :raise: AttributeError: if value is to high or negative.
        """
        ratio = float(value)/float(self.progressBar.maximum())
        if(ratio<=1.0 and ratio>=0.0):
            self.source.jumpToFrame(ratio)
        else:
            raise ValueError("Trying to jump at a position which does not exists")
         
    def captureImage(self):
        """ Take a snapshot of the video and save it. """
        snapshot = self.filterApplied.getLastComputedImage()
        fileName = QtGui.QFileDialog.getSaveFileName(self, "save an image", QtCore.QDir.homePath(), 'Image (*.png *.PNG)')
        snapshot.save(fileName, "png")
        
    def getsurfacePosition(self):
        """Get the position of the cursor in the video and ask the surface to draw a shape if necessary."""
        p=QtGui.QCursor.pos()
        p=self.videoWidget.mapFromGlobal(p)
        shape=self.drawlist[0]
        if(shape=='point' or self.videoWidget.getPointNumbers() == 0):
            self.videoWidget.appendPoint(p) 
            if(shape=='point'):
                self.drawlist.pop(0)
        elif(shape=='rectangle' and self.videoWidget.getPointNumbers() == 1):
            p1 = self.videoWidget.popLastPoint()
            self.videoWidget.appendRect(p1, p)  
            self.drawlist.pop(0)
        elif(shape=='line' and self.videoWidget.getPointNumbers() == 1):
            p1 = self.videoWidget.popLastPoint()
            self.videoWidget.appendLine(p1, p)
            self.drawlist.pop(0)                  
        if(len(self.drawlist)==0):
            self.videoWidget.clicked.disconnect(self.getsurfacePosition)
            self.chooseTreatment(self.treatmentComboBox.currentIndex())
            self.videoWidget.resetShapes()
            self.statusBar().showMessage('Traitement en cours')
            self.toggleProcessVideo()
            
    def launchTutorial(self):
        """Launch a tutorial specific to the selected treatment."""
        self.statusBar().showMessage('En attente d\'informations de la part de l\'utilisateur')
        self.treatmentComboBox.currentIndexChanged.connect(self.changeTutorial)
        self.drawlist=[]
        self.tutorial=None
        if(self.treatmentComboBox.currentIndex() == 0):
            tutorial = Tutorial.MuscleTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 1):
            tutorial = Tutorial.LinesTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 2):
            tutorial = Tutorial.LinesTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 3):
            tutorial = Tutorial.JunctionTutorial(self)
        self.drawlist=tutorial.drawlist
        tutorial.displayIntroduction()
        self.videoWidget.clicked.connect(self.getsurfacePosition)
    
    def changeTutorial(self):
        """Reset the shapes drawn on the surface and reload a new tutorial specific to the selected treatment."""
        self.statusBar().showMessage('En attente d\'informations de la part de l\'utilisateur')
        self.videoWidget.clicked.disconnect(self.getsurfacePosition)
        self.drawlist=[]
        self.videoWidget.resetShapes()
        self.tutorial=None
        if(self.treatmentComboBox.currentIndex() == 0):
            tutorial = Tutorial.MuscleTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 1):
            tutorial = Tutorial.LinesTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 2):
            tutorial = Tutorial.LinesTutorial(self)
        if(self.treatmentComboBox.currentIndex() == 3):
            tutorial = Tutorial.JunctionTutorial(self)
        self.drawlist=tutorial.drawlist
        tutorial.displayIntroduction()
        self.videoWidget.clicked.connect(self.getsurfacePosition)            
                
    def chooseTreatment(self, index):
        """Add the chosen treatment to the Applier.
        
        :param index: The index inf the combobox used to select the treatment.
        :type index: int
        """
        if(index == 0):
            self.filterApplied.setParameters(self.source, nrSkipFrame = self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(TotalTreatments.LKMethod(Aponeurosises=l[0:2], fiber=l[2]))
        if(index == 1):
            self.filterApplied.setParameters(self.source, nrSkipFrame = self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(TotalTreatments.EllipseMethod(Aponeurosises = l))
        if(index == 2):
            self.filterApplied.setParameters(self.source, nrSkipFrame = self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(TotalTreatments.RadonMethod(Aponeurosises = l, manySamples=self.multipleRadonCheckBox.isChecked()))
        if(index == 3):
            self.filterApplied.setParameters(self.source,  nrSkipFrame = self.SkipFrameSpinBox.value())
            r = self.videoWidget.mapToVideo(self.videoWidget.getRect())[0]
            p = self.videoWidget.mapToVideo(self.videoWidget.getPoints())[0]
            self.filterApplied.setMethod(TotalTreatments.junctionComputation(limits=r, firstApproximation=p))
Пример #9
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(545, 315)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.video = QVid(self.centralwidget)
        self.video.setGeometry(QtCore.QRect(120, 10, 320, 240))
        self.video.setAutoFillBackground(False)
        self.video.setObjectName(_fromUtf8("video"))
        self.line = QtGui.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 290, 641, 16))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.setThreshold = QtGui.QPushButton(self.centralwidget)
        self.setThreshold.setGeometry(QtCore.QRect(230, 260, 98, 27))
        self.setThreshold.setObjectName(_fromUtf8("setThreshold"))
        self.color_picker = QtGui.QLabel(self.centralwidget)
        self.color_picker.setGeometry(QtCore.QRect(180, 310, 351, 111))
        self.color_picker.setMouseTracking(False)
        self.color_picker.setText(_fromUtf8(""))
        self.color_picker.setPixmap(QtGui.QPixmap(_fromUtf8("hsv.jpg")))
        self.color_picker.setScaledContents(True)
        self.color_picker.setObjectName(_fromUtf8("color_picker"))
        self.h_lbl = QtGui.QLabel(self.centralwidget)
        self.h_lbl.setGeometry(QtCore.QRect(180, 420, 16, 31))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.h_lbl.setFont(font)
        self.h_lbl.setScaledContents(True)
        self.h_lbl.setObjectName(_fromUtf8("h_lbl"))
        self.hue = QtGui.QSlider(self.centralwidget)
        self.hue.setGeometry(QtCore.QRect(200, 420, 331, 29))
        self.hue.setMaximum(180)
        self.hue.setSingleStep(5)
        self.hue.setOrientation(QtCore.Qt.Horizontal)
        self.hue.setObjectName(_fromUtf8("hue"))
        self.value = QtGui.QSlider(self.centralwidget)
        self.value.setGeometry(QtCore.QRect(150, 310, 29, 91))
        self.value.setMaximum(255)
        self.value.setSingleStep(5)
        self.value.setOrientation(QtCore.Qt.Vertical)
        self.value.setObjectName(_fromUtf8("value"))
        self.v_lbl = QtGui.QLabel(self.centralwidget)
        self.v_lbl.setGeometry(QtCore.QRect(160, 400, 21, 17))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.v_lbl.setFont(font)
        self.v_lbl.setScaledContents(True)
        self.v_lbl.setObjectName(_fromUtf8("v_lbl"))
        self.hue_label = QtGui.QLabel(self.centralwidget)
        self.hue_label.setGeometry(QtCore.QRect(0, 320, 41, 20))
        self.hue_label.setFrameShape(QtGui.QFrame.StyledPanel)
        self.hue_label.setFrameShadow(QtGui.QFrame.Plain)
        self.hue_label.setMidLineWidth(2)
        self.hue_label.setObjectName(_fromUtf8("hue_label"))
        self.sat_label = QtGui.QLabel(self.centralwidget)
        self.sat_label.setGeometry(QtCore.QRect(0, 350, 41, 21))
        self.sat_label.setFrameShape(QtGui.QFrame.StyledPanel)
        self.sat_label.setFrameShadow(QtGui.QFrame.Plain)
        self.sat_label.setMidLineWidth(2)
        self.sat_label.setObjectName(_fromUtf8("sat_label"))
        self.value_label = QtGui.QLabel(self.centralwidget)
        self.value_label.setGeometry(QtCore.QRect(0, 380, 41, 20))
        self.value_label.setFrameShape(QtGui.QFrame.StyledPanel)
        self.value_label.setFrameShadow(QtGui.QFrame.Plain)
        self.value_label.setMidLineWidth(2)
        self.value_label.setObjectName(_fromUtf8("value_label"))
        self.min_check = QtGui.QCheckBox(self.centralwidget)
        self.min_check.setGeometry(QtCore.QRect(6, 420, 111, 22))
        self.min_check.setChecked(True)
        self.min_check.setObjectName(_fromUtf8("min_check"))
        self.max_check = QtGui.QCheckBox(self.centralwidget)
        self.max_check.setGeometry(QtCore.QRect(6, 440, 111, 22))
        self.max_check.setObjectName(_fromUtf8("max_check"))
        self.line_4 = QtGui.QFrame(self.centralwidget)
        self.line_4.setGeometry(QtCore.QRect(140, 300, 20, 181))
        self.line_4.setFrameShape(QtGui.QFrame.VLine)
        self.line_4.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_4.setObjectName(_fromUtf8("line_4"))
        self.h_min_lbl = QtGui.QLabel(self.centralwidget)
        self.h_min_lbl.setGeometry(QtCore.QRect(50, 320, 31, 17))
        self.h_min_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.h_min_lbl.setObjectName(_fromUtf8("h_min_lbl"))
        self.s_min_lbl = QtGui.QLabel(self.centralwidget)
        self.s_min_lbl.setGeometry(QtCore.QRect(50, 350, 31, 17))
        self.s_min_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.s_min_lbl.setObjectName(_fromUtf8("s_min_lbl"))
        self.v_min_lbl = QtGui.QLabel(self.centralwidget)
        self.v_min_lbl.setGeometry(QtCore.QRect(50, 380, 31, 17))
        self.v_min_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.v_min_lbl.setObjectName(_fromUtf8("v_min_lbl"))
        self.h_max_lbl = QtGui.QLabel(self.centralwidget)
        self.h_max_lbl.setGeometry(QtCore.QRect(90, 320, 31, 17))
        self.h_max_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.h_max_lbl.setObjectName(_fromUtf8("h_max_lbl"))
        self.s_max_lbl = QtGui.QLabel(self.centralwidget)
        self.s_max_lbl.setGeometry(QtCore.QRect(90, 350, 31, 17))
        self.s_max_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.s_max_lbl.setObjectName(_fromUtf8("s_max_lbl"))
        self.v_max_lbl = QtGui.QLabel(self.centralwidget)
        self.v_max_lbl.setGeometry(QtCore.QRect(90, 380, 31, 17))
        self.v_max_lbl.setAlignment(QtCore.Qt.AlignCenter)
        self.v_max_lbl.setObjectName(_fromUtf8("v_max_lbl"))
        self.s_lbl = QtGui.QLabel(self.centralwidget)
        self.s_lbl.setGeometry(QtCore.QRect(180, 440, 16, 31))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.s_lbl.setFont(font)
        self.s_lbl.setScaledContents(True)
        self.s_lbl.setObjectName(_fromUtf8("s_lbl"))
        self.sat = QtGui.QSlider(self.centralwidget)
        self.sat.setGeometry(QtCore.QRect(200, 440, 331, 29))
        self.sat.setMaximum(255)
        self.sat.setSingleStep(5)
        self.sat.setOrientation(QtCore.Qt.Horizontal)
        self.sat.setObjectName(_fromUtf8("sat"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(80, 320, 10, 71))
        self.label.setObjectName(_fromUtf8("label"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 545, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.setThreshold.clicked.connect(self.video.set_thres)
        self.value.valueChanged.connect(self.video.setValue)
        self.hue.valueChanged.connect(self.video.setHue)
        self.sat.valueChanged.connect(self.video.setSatu)
        self.min_check.stateChanged.connect(self.video.set_Thres_Min)
        self.max_check.stateChanged.connect(self.video.set_Thres_Max)
Пример #10
0
class Window(QtGui.QMainWindow):
    finishedWork = QtCore.pyqtSignal()
    """ This is the class which contains all the GUI."""
    def __init__(self):
        """ Create the view object."""
        super(Window, self).__init__()
        self.initUI()

    def initUI(self):
        """ Initialize the main windows of the application. """
        self.resize(640, 480)
        self.centerWindow()
        self.setWindowTitle('Line')
        self.setWindowIcon(QtGui.QIcon('Images/Icon.png'))
        QtCore.QTextCodec.setCodecForCStrings(
            QtCore.QTextCodec.codecForName('UTF-8'))

        self.firstTimePlayed = True
        self.createMenuBar()
        self.createLayout()
        self.source = None
        self.lines = []
        self.rect = []
        self.point = []
        self.OutputFile = None
        self.InputFile = None
        self.statusBar().showMessage('Prêt')

    def centerWindow(self):
        """ Center the windows on the screen of the user. """
        windowsGeometry = self.frameGeometry()
        ScreenCenter = QtCore.QPoint(
            QtGui.QDesktopWidget().availableGeometry().center().x() / 2, 0)
        windowsGeometry.moveCenter(ScreenCenter)
        self.move(windowsGeometry.center())

    def createMenuBar(self):
        """ Create the Menu bar with its menu and add the actions to the menus. """
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&Fichiers')
        fileMenu.addAction(
            self.createAction('&Fermer', QtGui.qApp.quit, 'Ctrl+Q',
                              'Quitte application'))
        fileMenu.addAction(
            self.createAction('&Ouvrir', self.openFile, 'Ctrl+O',
                              'Ouvre un film'))
        self.printImageAction = self.createAction(
            '&Sauver image', self.captureImage, 'Ctrl+S',
            'Sauvegarde l\'image présente à l\'écran')
        fileMenu.addAction(self.printImageAction)
        self.printImageAction.setDisabled(True)
        helpMenu = menubar.addMenu('Aide')
        helpMenu.addAction(
            self.createAction('A propos', self.printAbout, 'Ctrl+?',
                              'A propos'))
        helpMenu.addAction(
            self.createAction('A propos de Qt', self.printAboutQt,
                              'A propos de qt'))

    def printAbout(self):
        """Display the information about the application"""
        QtGui.QMessageBox.about(
            self, 'A propos de Pyradius',
            '<p><strong>Pyradius V1.0</strong></p>\
        <p>Pyradius est un logiciel de traitement d\'images permettant l\'extraction de l\'angle de pennation et de la position de la jonction des aponévroses.</p>\
        <p>Copyright&copy; 2013 Yves-Rémi Van Eycke.</p>\
        <p>Ce logiciel est sous licence <a href=https://www.gnu.org/licenses/quick-guide-gplv3.fr.html>GNU GPLv3</a>.\
        Il a été rendu possible grâce à: \
        <a href=\'http://www.python.org/\'>Python</a>, <a href=\'http://www.cython.org/\'>Cython</a>, \
        <a href=\'http://www.riverbankcomputing.co.uk/software/pyqt\'>PyQt</a>, <a href=\'http://www.numpy.org/\'>Numpy</a>, \
        <a href=\'http://opencv.org/\'>OpenCV</a>, <a href=\'http://scikit-image.org/\'>scikit-image</a>, \
        <a href=\'https://bitbucket.org/zakhar/ffvideo/wiki/Home\'>FFVideo</a>, <a href=\'http://www.ffmpeg.org/\'>FFMpeg</a>, \
        <a href=\'http://pandas.pydata.org/\'>Pandas</a>.</p>\
        Le code source est disponible <a href=\'https://code.google.com/p/pyradius/\'>ici</a>.<p></p>'
        )

    def printAboutQt(self):
        """Display the information about Qt"""
        QtGui.QMessageBox.aboutQt(self, 'A propos de Qt')

    def createAction(self, name, funct, shortcut='', statusTip=''):
        """Create the actions used, for example, in the menu bar and return it.
        
        :param name: The name of the action.
        :param funct: The function to be triggered by the action.
        :param shortcut: The shortcut for the action.
        :param statusTip: A tip which will appear when hovering the action.
        :return: The QAction object
        :raise: AttributeError: if there is the name or the function send is none.
        """

        if name != None:
            action = QtGui.QAction(name, self)
        else:
            raise AttributeError('The action need a name!')

        if shortcut != None:
            action.setShortcut(shortcut)

        if statusTip != None:
            action.setStatusTip(statusTip)

        if funct != None:
            action.triggered.connect(funct)
        else:
            raise AttributeError(
                'The action need a callable or a signal for when triggered!')

        return action

    def createLayout(self):
        """ Create the layout of the window. """
        centralWidget = QtGui.QWidget(self)
        self.mainLayout = QtGui.QVBoxLayout(centralWidget)
        self.videoWidget = VideoWidget()
        self.surface = self.videoWidget.videoSurface()
        self.videoWidget.setStringStartPosition(
            (self.videoWidget.size().width() * 0.9,
             self.videoWidget.size().height()))

        self.controlLayout = QtGui.QVBoxLayout()
        self.createInfoInterface()

        self.creatBasicControls()
        self.createOptionControls()

        self.mainLayout.addWidget(self.videoWidget)
        self.mainLayout.insertLayout(1, self.controlLayout)

        self.setCentralWidget(centralWidget)
        self.treatmentComboBox.currentIndexChanged.emit(0)

    def creatBasicControls(self):
        """ Create the layout for the widgets controlling the video. """
        self.basicControlLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.basicControlLayout)

        self.playButton = QtGui.QPushButton(QtGui.QIcon("Images/play.png"),
                                            'Commencer')
        self.playButton.resize(50, 50)
        self.progressBar = QtGui.QProgressBar()
        self.progressBar.setOrientation(QtCore.Qt.Horizontal)
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.playButton.setEnabled(False)

        self.playButton.clicked.connect(self.toggleProcessVideo)

        self.basicControlLayout.addWidget(self.playButton)
        self.basicControlLayout.addWidget(self.progressBar)

    def createOptionControls(self):
        """ Create the layout for the widgets common to all the treatments. """
        self.oLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.oLayout)

        self.OptionWidget = QtGui.QWidget(self)
        self.oLayout.addWidget(self.OptionWidget)

        self.OptionLayout = QtGui.QVBoxLayout()
        self.OptionWidget.setLayout(self.OptionLayout)
        self.OptionWidget.setContentsMargins(0, 0, 0, 0)
        self.OptionLayout.setContentsMargins(0, 0, 0, 0)

        self.basicOptionWidget = QtGui.QGroupBox("Options Générales",
                                                 self.OptionWidget)
        self.OptionLayout.addWidget(self.basicOptionWidget)
        self.basicOptionLayout = QtGui.QHBoxLayout()
        self.basicOptionWidget.setLayout(self.basicOptionLayout)
        self.basicOptionWidget.setContentsMargins(0, 0, 0, 0)

        self.resetTreatmentButton = QtGui.QPushButton("Réinitialiser")
        self.resetTreatmentButton.setEnabled(False)

        self.treatmentComboBox = QtGui.QComboBox()
        self.treatmentComboBox.addItem('Lucas-Kanade')
        self.treatmentComboBox.addItem('Fit ellipsoïde')
        self.treatmentComboBox.addItem('Radon transform')
        self.treatmentComboBox.addItem('Seam Carving')

        self.SkipFrameLabel = QtGui.QLabel("Nombre d'images à passer:")
        self.SkipFrameLabel.setAlignment(QtCore.Qt.AlignRight
                                         | QtCore.Qt.AlignVCenter)
        self.SkipFrameSpinBox = QtGui.QSpinBox()
        self.SkipFrameSpinBox.setMinimum(0)
        self.SkipFrameSpinBox.setMaximum(25)

        self.resetTreatmentButton.clicked.connect(self.changeTutorial)
        self.treatmentComboBox.currentIndexChanged.connect(
            self.loadCorrectInterface)

        self.basicOptionLayout.addStretch()
        self.basicOptionLayout.addWidget(self.resetTreatmentButton)
        self.basicOptionLayout.addWidget(self.treatmentComboBox)
        self.basicOptionLayout.addWidget(self.SkipFrameLabel)
        self.basicOptionLayout.addWidget(self.SkipFrameSpinBox)
        self.basicOptionLayout.addStretch()

        self.createEllipsoidMethodInterface()
        self.createRadonMethodInterface()
        self.createLKMethodInterface()
        self.createSCMethodInterface()

    def createInfoInterface(self):
        """ Create the layout for the labels displaying the extracted information. """
        self.infoInterfaceLayout = QtGui.QHBoxLayout()
        self.controlLayout.addLayout(self.infoInterfaceLayout)
        self.infoLabelList = []
        self.infoValueList = []

    def updateInfoInterface(self, infoNumber):
        """ Update the layout containing the labels displaying the extracted information. 
        
        :param infoNumber: The number of info to display (=the number of labels needed).
        :type infoNumber: int
        """
        for value, label in zip(self.infoValueList, self.infoLabelList):
            del (value)
            del (label)

        for i in range(infoNumber):
            self.infoLabelList.append(QtGui.QLabel())
            self.infoValueList.append(QtGui.QLabel())
            self.infoInterfaceLayout.addWidget(self.infoLabelList[i])
            self.infoInterfaceLayout.addWidget(self.infoValueList[i])
            self.infoLabelList[i].show()
            self.infoValueList[i].show()

    def updateInfo(self, info):
        """ Update the labels containing the extracted information. 
        
        :param info: The new extracted information.
        :type info: dictionary
        """
        infoNumber = len(info)
        if (infoNumber != len(self.infoValueList)):
            self.updateInfoInterface(infoNumber)
        for i, key in enumerate(info):
            self.infoLabelList[i].setText(key + " : ")
            self.infoValueList[i].setText(str(info[key]))

    def createEllipsoidMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use ellipsoids. """
        self.ellipsoidOptionWidget = QtGui.QGroupBox()
        self.ellipsoidOptionWidget.hide()
        self.OptionLayout.addWidget(self.ellipsoidOptionWidget)
        self.ellipsoidOptionLayout = QtGui.QHBoxLayout()
        self.ellipsoidOptionWidget.setLayout(self.ellipsoidOptionLayout)
        self.ellipsoidOptionLayout.addStretch()
        self.ellipsoidOptionWidget.setContentsMargins(0, 0, 0, 0)

    def createRadonMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use the Radon transform. """
        self.radonOptionWidget = QtGui.QGroupBox()
        self.radonOptionWidget.hide()
        self.OptionLayout.addWidget(self.radonOptionWidget)
        self.radonOptionLayout = QtGui.QHBoxLayout()
        self.radonOptionWidget.setLayout(self.radonOptionLayout)
        self.multipleRadonLabel = QtGui.QLabel("Prendre plus d'échantillons:")
        self.multipleRadonLabel.setAlignment(QtCore.Qt.AlignRight
                                             | QtCore.Qt.AlignVCenter)
        self.multipleRadonCheckBox = QtGui.QCheckBox()
        self.radonOptionLayout.addWidget(self.multipleRadonLabel)
        self.radonOptionLayout.addWidget(self.multipleRadonCheckBox)
        self.radonOptionLayout.addStretch()
        self.radonOptionWidget.setContentsMargins(0, 0, 0, 0)

    def createLKMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment which use Lucas-Kanade algorithm. """
        self.LKOptionWidget = QtGui.QGroupBox()
        self.LKOptionWidget.hide()
        self.OptionLayout.addWidget(self.LKOptionWidget)
        self.LKOptionLayout = QtGui.QHBoxLayout()
        self.LKOptionWidget.setLayout(self.LKOptionLayout)
        self.LKOptionLayout.addStretch()
        self.LKOptionWidget.setContentsMargins(0, 0, 0, 0)

    def createSCMethodInterface(self):
        """ Create the layout for the widgets specific to the treatment extraction the junction position. """
        self.SCOptionWidget = QtGui.QGroupBox()
        self.SCOptionWidget.hide()
        self.OptionLayout.addWidget(self.SCOptionWidget)
        self.SCOptionLayout = QtGui.QHBoxLayout()
        self.SCOptionWidget.setLayout(self.SCOptionLayout)
        self.SCOptionWidget.setContentsMargins(0, 0, 0, 0)

    def loadCorrectInterface(self):
        """ Select the correct layout depending on the method chosen by the user. """
        self.hideAllInterface()
        self.basicOptionWidget.show()
        if (self.treatmentComboBox.currentIndex() == 0):
            self.loadLKTransformInterface()
        if (self.treatmentComboBox.currentIndex() == 1):
            self.loadEllipsoidTransformInterface()
        if (self.treatmentComboBox.currentIndex() == 2):
            self.loadRadonTransformInterface()
        if (self.treatmentComboBox.currentIndex() == 3):
            self.loadSCTransformInterface()

    def hideAllInterface(self):
        """ Hide all the layouts containing the treatment specific widgets. """
        for i in range(self.OptionLayout.count()):
            possibleWidget = self.OptionLayout.itemAt(i)
            if (possibleWidget.widget()):
                possibleWidget.widget().hide()

    def loadEllipsoidTransformInterface(self):
        """ Load the layout for the widgets specific to the treatment which use ellipsoids. """
        self.ellipsoidOptionWidget.show()

    def loadRadonTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment which use the Radon transform. """
        self.radonOptionWidget.show()

    def loadLKTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment which use Lucas-Kanade algorithm. """
        self.LKOptionWidget.show()

    def loadSCTransformInterface(self):
        """ Create the layout for the widgets specific to the treatment extraction the junction position. """
        self.SCOptionWidget.show()

    def chooseOutputFile(self):
        """ Show the dialog to let the user select the output file. """

        fileName = QtCore.QString(
            QtGui.QFileDialog.getSaveFileName(
                self, "Ouvrir le fichier de sortie", QtCore.QDir.homePath(),
                'Fichiers Excel (*.xlsx *.xls);;Fichiers Texte (*.txt);;Fichiers CSV (*.csv)'
            ))
        if (not (fileName.isEmpty())):
            self.OutputFile = (unicode(fileName))

    def chooseInputFile(self):
        """ Show the dialog to let the user select the output file. """
        fileName = QtCore.QString(
            QtGui.QFileDialog.getOpenFileName(
                self, "Ouvrir le fichier d'entrée", QtCore.QDir.homePath(),
                'Fichiers Excel (*.xlsx *.xls);;Fichiers Texte (*.txt);;Fichiers CSV (*.csv)'
            ))
        if (not (fileName.isEmpty())):
            self.InputFile = (unicode(fileName))

    def openFile(self):
        """ Show a dialog where there user can pick a file. """
        fileName = QtCore.QString(
            QtGui.QFileDialog.getOpenFileName(
                self, "ouvrir la vidéo", QtCore.QDir.homePath(),
                'Fichiers vidéo (*.avi *.mpeg *.mpg);;Autres (*.*)'))
        if (not (fileName.isEmpty())):
            self.surface.stop()
            self.resetMovie()
            self.source.setMovie(unicode(fileName))
            self.filterApplied = Applier()
            self.filterApplied.frameComputed.connect(self.frameChanged)
            self.filterApplied.setSource(self.source)
            self.filterApplied.endOfProcessing.connect(self.finishVideo)
            self.firstTimePlayed = True
            self.playButton.setEnabled(False)
            self.toggleProcessVideo()
            self.printImageAction.setEnabled(True)
            self.resetTreatmentButton.setEnabled(True)

    def resetMovie(self):
        """ Reset the movie. """
        if (self.source is not None):
            self.videoWidget.clicked.disconnect(self.getsurfacePosition)
            self.source.reset()
        else:
            self.source = Movie()

    def finishVideo(self):
        """ Close the video, ask the applier to write the output file if necessary and quit. """
        self.statusBar().showMessage('Traitement terminé')
        box = QtGui.QMessageBox(
            QtGui.QMessageBox.Information, 'Sauvegarde',
            '<p><strong>Le traitement est terminé! Voulez vous sauver les résultats?</strong></p> \
                  <p>Si vous sélectionnez oui, deux fenêtres de dialogue vont s\'ouvrir. \
                  <ul><li>La première va permettre de choisir un fichier d\'entrée si vous voulez fusionner les résultats avec d\'autres résultats que vous possèdez déjà. Dans le cas où vous ne désirez pas fusionner de résultats, fermez cette fenêtre sans choisir de fichier.</li>\
                  <li>La deuxième va permettre de choisir où les résultats seront sauvegardés.</li></ul></p>',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, self)
        self.treatmentComboBox.setEnabled(True)
        self.resetTreatmentButton.setEnabled(True)
        self.playButton.setEnabled(False)
        self.surface.stop()
        ret = box.exec_()
        if (ret == QtGui.QMessageBox.Yes):
            self.savingProcedure()
        box = QtGui.QMessageBox(
            QtGui.QMessageBox.Information, 'Fin du traitement',
            'Travail terminé! Le programme va maintenant se fermer',
            QtGui.QMessageBox.Ok, self)
        box.finished.connect(self.finishedWork.emit)
        box.buttonClicked.connect(self.finishedWork.emit)
        self.statusBar().showMessage('Fermeture du programme')
        box.show()

    def savingProcedure(self):
        """Save the results in a file"""
        cont = True
        while (cont):
            if (self.InputFile is None or not self.InputFile):
                self.chooseInputFile()
            if (self.OutputFile is None or not self.OutputFile):
                self.chooseOutputFile()
            if (self.OutputFile is None or not self.OutputFile):
                box = QtGui.QMessageBox(
                    QtGui.QMessageBox.Information, 'Pas de fichier de sortie',
                    'Vous n\'avez pas sélectionné de fichier de sortie. Les resultats ne seront donc pas sauvegardés. Êtes vous sûr de votre choix?',
                    QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, self)
                ret = box.exec_()
                if (ret == QtGui.QMessageBox.Yes):
                    cont = False
                else:
                    continue
            if (cont):
                self.statusBar().showMessage('Sauvegarde en cours')
                self.filterApplied.saveResult(self.InputFile, self.OutputFile)
                cont = False
                self.statusBar().showMessage('Sauvegarde terminée')

    def toggleProcessVideo(self):
        """Pause and play the video processing"""
        if (self.firstTimePlayed):
            self.firstTimePlayed = False
            self.filterApplied.applyOne()
            self.launchTutorial()
        else:
            self.playButton.setEnabled(True)
            self.filterApplied.toggle()
            if (self.filterApplied.wait):
                self.playButton.setIcon(QtGui.QIcon("Images/play.png"))
                self.playButton.setText("Continuer")
            if (not (self.filterApplied.wait)
                    or not (self.filterApplied.isRunning())):
                self.treatmentComboBox.setEnabled(False)
                self.resetTreatmentButton.setEnabled(False)
                self.SkipFrameSpinBox.setEnabled(False)
                self.playButton.setIcon(QtGui.QIcon("Images/pause.png"))
                self.playButton.setText("Pause")
                self.filterApplied.start(QtCore.QThread.HighestPriority)

    def frameChanged(self):
        """ Update the view when the frame has changed. """
        frame = self.filterApplied.getLastComputedFrame()
        info = self.filterApplied.getLastInformation()
        if (info is not None):
            self.updateInfo(info)

        if (not (frame.isValid())):
            QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error',
                              'Frame not valid!', QtGui.QMessageBox.Ok,
                              self).show()
            return False
        currentFormat = self.surface.surfaceFormat()
        if (frame.pixelFormat() != currentFormat.pixelFormat()
                or frame.size() != currentFormat.frameSize()):
            fmt = QtMultimedia.QVideoSurfaceFormat(frame.size(),
                                                   frame.pixelFormat())
            if (not (self.surface.start(fmt))):
                QtGui.QMessageBox(QtGui.QMessageBox.Critical, 'Error',
                                  'Surface could not start!',
                                  QtGui.QMessageBox.Ok, self).show()
                return False
        if (not (self.surface.present(frame))):
            self.surface.stop()
        self.progressBar.setValue(
            (self.source.currentPositionRatio() * self.progressBar.maximum()))
        del (frame)

    def jumpToFrame(self, value):
        """ Jump to a position in the movie. 
        
        :param value: A value in the range of the slider.
        :raise: AttributeError: if value is to high or negative.
        """
        ratio = float(value) / float(self.progressBar.maximum())
        if (ratio <= 1.0 and ratio >= 0.0):
            self.source.jumpToFrame(ratio)
        else:
            raise ValueError(
                "Trying to jump at a position which does not exists")

    def captureImage(self):
        """ Take a snapshot of the video and save it. """
        snapshot = self.filterApplied.getLastComputedImage()
        fileName = QtGui.QFileDialog.getSaveFileName(self, "save an image",
                                                     QtCore.QDir.homePath(),
                                                     'Image (*.png *.PNG)')
        snapshot.save(fileName, "png")

    def getsurfacePosition(self):
        """Get the position of the cursor in the video and ask the surface to draw a shape if necessary."""
        p = QtGui.QCursor.pos()
        p = self.videoWidget.mapFromGlobal(p)
        shape = self.drawlist[0]
        if (shape == 'point' or self.videoWidget.getPointNumbers() == 0):
            self.videoWidget.appendPoint(p)
            if (shape == 'point'):
                self.drawlist.pop(0)
        elif (shape == 'rectangle'
              and self.videoWidget.getPointNumbers() == 1):
            p1 = self.videoWidget.popLastPoint()
            self.videoWidget.appendRect(p1, p)
            self.drawlist.pop(0)
        elif (shape == 'line' and self.videoWidget.getPointNumbers() == 1):
            p1 = self.videoWidget.popLastPoint()
            self.videoWidget.appendLine(p1, p)
            self.drawlist.pop(0)
        if (len(self.drawlist) == 0):
            self.videoWidget.clicked.disconnect(self.getsurfacePosition)
            self.chooseTreatment(self.treatmentComboBox.currentIndex())
            self.videoWidget.resetShapes()
            self.statusBar().showMessage('Traitement en cours')
            self.toggleProcessVideo()

    def launchTutorial(self):
        """Launch a tutorial specific to the selected treatment."""
        self.statusBar().showMessage(
            'En attente d\'informations de la part de l\'utilisateur')
        self.treatmentComboBox.currentIndexChanged.connect(self.changeTutorial)
        self.drawlist = []
        self.tutorial = None
        if (self.treatmentComboBox.currentIndex() == 0):
            tutorial = Tutorial.MuscleTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 1):
            tutorial = Tutorial.LinesTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 2):
            tutorial = Tutorial.LinesTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 3):
            tutorial = Tutorial.JunctionTutorial(self)
        self.drawlist = tutorial.drawlist
        tutorial.displayIntroduction()
        self.videoWidget.clicked.connect(self.getsurfacePosition)

    def changeTutorial(self):
        """Reset the shapes drawn on the surface and reload a new tutorial specific to the selected treatment."""
        self.statusBar().showMessage(
            'En attente d\'informations de la part de l\'utilisateur')
        self.videoWidget.clicked.disconnect(self.getsurfacePosition)
        self.drawlist = []
        self.videoWidget.resetShapes()
        self.tutorial = None
        if (self.treatmentComboBox.currentIndex() == 0):
            tutorial = Tutorial.MuscleTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 1):
            tutorial = Tutorial.LinesTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 2):
            tutorial = Tutorial.LinesTutorial(self)
        if (self.treatmentComboBox.currentIndex() == 3):
            tutorial = Tutorial.JunctionTutorial(self)
        self.drawlist = tutorial.drawlist
        tutorial.displayIntroduction()
        self.videoWidget.clicked.connect(self.getsurfacePosition)

    def chooseTreatment(self, index):
        """Add the chosen treatment to the Applier.
        
        :param index: The index inf the combobox used to select the treatment.
        :type index: int
        """
        if (index == 0):
            self.filterApplied.setParameters(
                self.source, nrSkipFrame=self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(
                TotalTreatments.LKMethod(Aponeurosises=l[0:2], fiber=l[2]))
        if (index == 1):
            self.filterApplied.setParameters(
                self.source, nrSkipFrame=self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(
                TotalTreatments.EllipseMethod(Aponeurosises=l))
        if (index == 2):
            self.filterApplied.setParameters(
                self.source, nrSkipFrame=self.SkipFrameSpinBox.value())
            l = self.videoWidget.mapToVideo(self.videoWidget.getLines())
            self.filterApplied.setMethod(
                TotalTreatments.RadonMethod(
                    Aponeurosises=l,
                    manySamples=self.multipleRadonCheckBox.isChecked()))
        if (index == 3):
            self.filterApplied.setParameters(
                self.source, nrSkipFrame=self.SkipFrameSpinBox.value())
            r = self.videoWidget.mapToVideo(self.videoWidget.getRect())[0]
            p = self.videoWidget.mapToVideo(self.videoWidget.getPoints())[0]
            self.filterApplied.setMethod(
                TotalTreatments.junctionComputation(limits=r,
                                                    firstApproximation=p))
Пример #11
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle('DD监控室')
        self.resize(1600, 900)
        self.maximumToken = True
        if os.path.exists(r'utils/config.json'):
            self.config = json.loads(open(r'utils/config.json').read())
            while len(self.config['player']) < 9:
                self.config['player'].append(0)
        else:
            self.config = {
                'roomid': [21463219, 21501730, 21096962, 21449068],
                'layout': [(0, 0, 1, 1), (0, 1, 1, 1), (1, 0, 1, 1), (1, 1, 1, 1)],
                'player': [21463219, 21501730, 21096962, 21449068, 0, 0, 0, 0, 0],
                'quality': [80] * 9,
                'muted': [1] * 9,
                'volume': [25] * 9,
                'danmu': [True] * 9,
                'translator': [True] * 9,
                'globalVolume': 25,
                'control': True,
            }
        mainWidget = QWidget()
        self.setCentralWidget(mainWidget)
        self.mainLayout = QGridLayout(mainWidget)
        self.mainLayout.setSpacing(0)
        self.mainLayout.setContentsMargins(0, 0, 0, 0)
        self.layoutSettingPanel = LayoutSettingPanel()
        self.layoutSettingPanel.layoutConfig.connect(self.changeLayout)
        self.version = Version()

        self.videoWidgetList = []
        for i in range(9):
            self.videoWidgetList.append(VideoWidget(i))
            self.videoWidgetList[i].mutedChanged.connect(self.mutedChanged)
            self.videoWidgetList[i].volumeChanged.connect(self.volumeChanged)
            self.videoWidgetList[i].addMedia.connect(self.addMedia)
            self.videoWidgetList[i].deleteMedia.connect(self.deleteMedia)
            self.videoWidgetList[i].exchangeMedia.connect(self.exchangeMedia)
            self.videoWidgetList[i].setDanmu.connect(self.setDanmu)
            self.videoWidgetList[i].setTranslator.connect(self.setTranslator)
            self.videoWidgetList[i].changeQuality.connect(self.setQuality)
            self.videoWidgetList[i].popWindow.connect(self.popWindow)
            self.videoWidgetList[i].mediaMute(self.config['muted'][i], emit=False)
            self.videoWidgetList[i].player.setVolume(self.config['volume'][i])
            self.videoWidgetList[i].slider.setValue(self.config['volume'][i])
            self.videoWidgetList[i].quality = self.config['quality'][i]
            if self.config['danmu'][i]:
                self.videoWidgetList[i].textBrowser.show()
            else:
                self.videoWidgetList[i].textBrowser.hide()
            if self.config['translator'][i]:
                self.videoWidgetList[i].translator.show()
            else:
                self.videoWidgetList[i].translator.hide()
        self.popVideoWidgetList = []  # 置顶的悬浮窗
        for i in range(9):
            self.popVideoWidgetList.append(VideoWidget(i, True, '悬浮窗', [1280, 720]))
        self.setPlayer()


        self.controlBar = QToolBar()
        self.addToolBar(self.controlBar)
        self.controlBar.show() if self.config['control'] else self.controlBar.hide()

        self.globalPlayToken = True
        self.play = PushButton(self.style().standardIcon(QStyle.SP_MediaPause))
        self.play.clicked.connect(self.globalMediaPlay)
        self.controlBar.addWidget(self.play)
        self.reload = PushButton(self.style().standardIcon(QStyle.SP_BrowserReload))
        self.reload.clicked.connect(self.globalMediaReload)
        self.controlBar.addWidget(self.reload)
        self.globalMuteToken = False
        self.volume = PushButton(self.style().standardIcon(QStyle.SP_MediaVolume))
        self.volume.clicked.connect(self.globalMediaMute)
        self.controlBar.addWidget(self.volume)
        self.slider = Slider()
        self.slider.setValue(self.config['globalVolume'])
        self.slider.value.connect(self.globalSetVolume)
        self.controlBar.addWidget(self.slider)
        self.stop = PushButton(self.style().standardIcon(QStyle.SP_DialogCancelButton))
        self.stop.clicked.connect(self.globalMediaStop)
        self.controlBar.addWidget(self.stop)

        self.addButton = QPushButton('+')
        self.addButton.setFixedSize(160, 104)
        self.addButton.setStyleSheet('border:3px dotted #EEEEEE')
        self.addButton.setFont(QFont('Arial', 24, QFont.Bold))

        self.controlBar.addWidget(self.addButton)
        self.controlBar.addWidget(QLabel())

        self.scrollArea = ScrollArea()
        self.scrollArea.setStyleSheet('border-width:0px')
        self.scrollArea.setMinimumHeight(111)
        self.scrollArea.setMinimumWidth(1000)
        self.controlBar.addWidget(self.scrollArea)
        self.liverPanel = LiverPanel(self.config['roomid'])
        self.liverPanel.addLiverRoomWidget.getHotLiver.start()
        self.liverPanel.addToWindow.connect(self.addCoverToPlayer)
        self.scrollArea.setWidget(self.liverPanel)
        self.addButton.clicked.connect(self.liverPanel.openLiverRoomPanel)

        self.optionMenu = self.menuBar().addMenu('设置')
        self.controlBarToken = self.config['control']
        layoutConfigAction = QAction('布局方式', self, triggered=self.openLayoutSetting)
        self.optionMenu.addAction(layoutConfigAction)
        controlPanelAction = QAction('显示/隐藏控制条', self, triggered=self.openControlPanel)
        self.optionMenu.addAction(controlPanelAction)
        self.fullScreenAction = QAction('全屏显示 (Esc退出)', self, triggered=self.fullScreen)
        self.optionMenu.addAction(self.fullScreenAction)

        self.versionMenu = self.menuBar().addMenu('版本')
        versionAction = QAction('当前版本', self, triggered=self.openVersion)
        self.versionMenu.addAction(versionAction)
Пример #12
0
    def create_videos_list(self):
        self.create_videos_container()

        for video_file in self.video_files:
            video_widget = VideoWidget(self, video_file)
            self.videos_widget.add_video(video_widget)
Пример #13
0
except ImportError:
    qdark_present = False

from MainWindow import MainWindow
from VideoWidget import VideoWidget
from DialogWidget import DialogWidget
from FaceRecogniser import FaceRecogniser
from Speech_DialogManager import Speech_DialogManager

if __name__ == '__main__':
    app = QApplication(sys.argv)
    if qdark_present:  # load qdarkstyle if present
        app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

    face_recon = FaceRecogniser()
    speechManager = Speech_DialogManager()
    video = VideoWidget(face_recon)
    dialog = DialogWidget(speechManager)

    window = MainWindow(video, dialog)  # The view controller / view (GUI)

    # Qt Signals and slots connection
    video.face_recogniser.person_identified.connect(window.activate_dialog,
                                                    type=Qt.QueuedConnection)
    dialog.speech_dialog_manager.finished.connect(window.activate_video,
                                                  type=Qt.QueuedConnection)

    # Starts with the Face Recognition
    window.activate_video()

    sys.exit(app.exec_())
Пример #14
0
    def __init__(self, args):
        TouchApplication.__init__(self, args)

        # create the empty main window
        self.w = TouchWindow("Run JetsonEV")

        self.relative_path = os.path.dirname(os.path.realpath(__file__))
        self.script = os.path.join(self.relative_path, 'Run_car.py')
        self.grid = QGridLayout()
        self.grid.setSpacing(0)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.stdoutReady)
        self.process.readyReadStandardError.connect(self.stderrReady)

        self.play_btn = ShadowButton(os.path.join(self.relative_path, 'start'))
        self.play_btn.setText("Start")
        self.play_btn.clicked.connect(self.start_script)
        self.grid.addWidget(self.play_btn, 0, 0, 1, 1)
        self.grid.setColumnStretch(0, 1.25)

        self.imu_box = QCheckBox('IMU')
        self.imu_box.setChecked(True)
        self.camera_box = QCheckBox('Cam')
        self.camera_box.setChecked(False)
        self.lidar_box = QCheckBox('Lidar')
        self.lidar_box.setChecked(False)
        self.grid.addWidget(self.imu_box, 0, 1, 1, 1)
        self.grid.setColumnStretch(1, 1)
        self.grid.addWidget(self.camera_box, 0, 2, 1, 1)
        self.grid.setColumnStretch(2, 1)
        self.grid.addWidget(self.lidar_box, 0, 3, 1, 1)
        self.grid.setColumnStretch(3, 1.5)
        self.grid.setAlignment(Qt.AlignCenter)

        self.stop_btn = ShadowButton(os.path.join(self.relative_path, 'stop'))
        self.stop_btn.setText("Stop")
        self.stop_btn.clicked.connect(self.stop_script)
        self.grid.addWidget(self.stop_btn, 0, 4, 1, 1)
        self.grid.setRowStretch(1, 4)

        self.console_output = QPlainTextEdit()
        self.console_output.setReadOnly(True)
        console_style = "QPlainTextEdit {" \
                        "background-color: black;" \
                        "color: white;" \
                        "}"
        self.console_output.setFocusPolicy(Qt.NoFocus)
        self.console_output.setFrameStyle(3)
        self.console_output.setStyleSheet(console_style)

        self.grid.addWidget(self.console_output, 1, 0, 1, 5)

        self.w.centralWidget.setLayout(self.grid)
        self.w.centralWidget.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.w.centralWidget, event)
        self.w.centralWidget.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.w.centralWidget, event)
        self.w.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.w, event)
        self.w.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.w, event)
        self.play_btn.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.play_btn, event)
        self.play_btn.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.play_btn, event)
        self.stop_btn.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.stop_btn, event)
        self.stop_btn.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.stop_btn, event)

        self.imu_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.imu_box, event)
        self.imu_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.imu_box, event)
        self.camera_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.camera_box, event)
        self.camera_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.camera_box, event)
        self.lidar_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.lidar_box, event)
        self.lidar_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.lidar_box, event)

        self.xbox_controller = XBoxInput()
        self.xbox_controller.cycle_right.connect(self.cycle_right)
        self.xbox_controller.cycle_left.connect(self.cycle_left)

        self.speed_widget = SpeedWidget()
        self.grid.addWidget(self.speed_widget, 1, 0, 1, 5)
        self.speed_widget.hide()

        self.imu_widget = IMUWidget()
        self.grid.addWidget(self.imu_widget, 1, 0, 1, 5)
        self.imu_widget.hide()

        self.camera_widget = VideoWidget()
        self.grid.addWidget(self.camera_widget, 1, 0, 1, 5)
        self.camera_widget.hide()

        self.lidar_widget = LidarWidget()
        self.grid.addWidget(self.lidar_widget, 1, 0, 1, 5)
        self.lidar_widget.hide()

        self.widgets_to_show = []
        self.show_widget_index = 0
        self.w.show()
        self.aboutToQuit.connect(self.xbox_controller.xbox_controller.close)
        self.exec_()
Пример #15
0
class FtcGuiApplication(TouchApplication):
    def __init__(self, args):
        TouchApplication.__init__(self, args)

        # create the empty main window
        self.w = TouchWindow("Run JetsonEV")

        self.relative_path = os.path.dirname(os.path.realpath(__file__))
        self.script = os.path.join(self.relative_path, 'Run_car.py')
        self.grid = QGridLayout()
        self.grid.setSpacing(0)
        self.process = QProcess()
        self.process.readyReadStandardOutput.connect(self.stdoutReady)
        self.process.readyReadStandardError.connect(self.stderrReady)

        self.play_btn = ShadowButton(os.path.join(self.relative_path, 'start'))
        self.play_btn.setText("Start")
        self.play_btn.clicked.connect(self.start_script)
        self.grid.addWidget(self.play_btn, 0, 0, 1, 1)
        self.grid.setColumnStretch(0, 1.25)

        self.imu_box = QCheckBox('IMU')
        self.imu_box.setChecked(True)
        self.camera_box = QCheckBox('Cam')
        self.camera_box.setChecked(False)
        self.lidar_box = QCheckBox('Lidar')
        self.lidar_box.setChecked(False)
        self.grid.addWidget(self.imu_box, 0, 1, 1, 1)
        self.grid.setColumnStretch(1, 1)
        self.grid.addWidget(self.camera_box, 0, 2, 1, 1)
        self.grid.setColumnStretch(2, 1)
        self.grid.addWidget(self.lidar_box, 0, 3, 1, 1)
        self.grid.setColumnStretch(3, 1.5)
        self.grid.setAlignment(Qt.AlignCenter)

        self.stop_btn = ShadowButton(os.path.join(self.relative_path, 'stop'))
        self.stop_btn.setText("Stop")
        self.stop_btn.clicked.connect(self.stop_script)
        self.grid.addWidget(self.stop_btn, 0, 4, 1, 1)
        self.grid.setRowStretch(1, 4)

        self.console_output = QPlainTextEdit()
        self.console_output.setReadOnly(True)
        console_style = "QPlainTextEdit {" \
                        "background-color: black;" \
                        "color: white;" \
                        "}"
        self.console_output.setFocusPolicy(Qt.NoFocus)
        self.console_output.setFrameStyle(3)
        self.console_output.setStyleSheet(console_style)

        self.grid.addWidget(self.console_output, 1, 0, 1, 5)

        self.w.centralWidget.setLayout(self.grid)
        self.w.centralWidget.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.w.centralWidget, event)
        self.w.centralWidget.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.w.centralWidget, event)
        self.w.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.w, event)
        self.w.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.w, event)
        self.play_btn.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.play_btn, event)
        self.play_btn.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.play_btn, event)
        self.stop_btn.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.stop_btn, event)
        self.stop_btn.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.stop_btn, event)

        self.imu_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.imu_box, event)
        self.imu_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.imu_box, event)
        self.camera_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.camera_box, event)
        self.camera_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.camera_box, event)
        self.lidar_box.keyReleaseEvent = lambda event: self.filter_out_arrow_release_keys(
            self.lidar_box, event)
        self.lidar_box.keyPressEvent = lambda event: self.filter_out_arrow_press_keys(
            self.lidar_box, event)

        self.xbox_controller = XBoxInput()
        self.xbox_controller.cycle_right.connect(self.cycle_right)
        self.xbox_controller.cycle_left.connect(self.cycle_left)

        self.speed_widget = SpeedWidget()
        self.grid.addWidget(self.speed_widget, 1, 0, 1, 5)
        self.speed_widget.hide()

        self.imu_widget = IMUWidget()
        self.grid.addWidget(self.imu_widget, 1, 0, 1, 5)
        self.imu_widget.hide()

        self.camera_widget = VideoWidget()
        self.grid.addWidget(self.camera_widget, 1, 0, 1, 5)
        self.camera_widget.hide()

        self.lidar_widget = LidarWidget()
        self.grid.addWidget(self.lidar_widget, 1, 0, 1, 5)
        self.lidar_widget.hide()

        self.widgets_to_show = []
        self.show_widget_index = 0
        self.w.show()
        self.aboutToQuit.connect(self.xbox_controller.xbox_controller.close)
        self.exec_()

    def cycle_right(self, axis):
        last_index = self.show_widget_index
        self.show_widget_index += 1
        if self.show_widget_index >= len(self.widgets_to_show):
            self.show_widget_index = 0
        self.widgets_to_show[last_index].hide()
        self.widgets_to_show[self.show_widget_index].show()

    def cycle_left(self, axis):
        last_index = self.show_widget_index
        self.show_widget_index -= 1
        if self.show_widget_index < 0:
            self.show_widget_index = len(self.widgets_to_show) - 1
        self.widgets_to_show[last_index].hide()
        self.widgets_to_show[self.show_widget_index].show()

    def start_script(self):
        self.widgets_to_show = [self.console_output, self.speed_widget]
        flags = ['-u', self.script]
        self.speed_widget.start(port=4021)

        if self.imu_box.isChecked():
            print('starting imu socket')
            self.imu_widget.start(port=9009)
            self.widgets_to_show.append(self.imu_widget)
            flags.extend(['--enable-imu'])
        if self.lidar_box.isChecked():
            print('starting lidar socket')
            self.lidar_widget.start(port=9010)
            self.widgets_to_show.append(self.lidar_widget)
            flags.extend(['--enable-lidar'])
        if self.camera_box.isChecked():
            print('starting camera socket')
            self.camera_widget.start(port=9011)
            self.widgets_to_show.append(self.camera_widget)
            flags.extend(['--enable-camera'])
        self.process.start('python3', flags)

    def stop_script(self):
        self.imu_widget.shutdown()
        self.camera_widget.shutdown()
        self.lidar_widget.shutdown()
        self.speed_widget.shutdown()
        self.process.terminate()

    def fwd_output(self, text):
        self.console_output.appendPlainText(text)
        cursor = self.console_output.textCursor()
        cursor.movePosition(cursor.End)

    def stdoutReady(self):
        text = str(self.process.readAllStandardOutput(), encoding='utf8')
        self.fwd_output(text)

    def stderrReady(self):
        text = str(self.process.readAllStandardError(), encoding='utf8')
        self.fwd_output(text)

    def filter_out_arrow_release_keys(self, widget, event):
        if event.key() == Qt.Key_Up:
            self.console_output.verticalScrollBar().triggerAction(
                QAbstractSlider.SliderSingleStepSub)
        elif event.key() == Qt.Key_Down:
            self.console_output.verticalScrollBar().triggerAction(
                QAbstractSlider.SliderSingleStepAdd)
        else:
            type(widget).keyReleaseEvent(widget, event)

    def filter_out_arrow_press_keys(self, widget, event):
        if event.key() == Qt.Key_Up:
            self.console_output.verticalScrollBar().triggerAction(
                QAbstractSlider.SliderSingleStepSub)
        elif event.key() == Qt.Key_Down:
            self.console_output.verticalScrollBar().triggerAction(
                QAbstractSlider.SliderSingleStepAdd)
        else:
            type(widget).keyPressEvent(widget, event)
Пример #16
0
	def __init__(self, parent=None):
		VideoWidget.__init__(self, parent)