コード例 #1
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.signals = Signals()
        self.initUI()
        self.setSignals()
        self.decensor = Decensor(self)
        self.load_model()

    def initUI(self):

        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)
        self.setLayout(grid_layout)

        #Tutorial
        self.tutorialLabel = QLabel()
        self.tutorialLabel.setText(
            "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf."
        )
        self.tutorialLabel.setAlignment(Qt.AlignCenter)
        self.tutorialLabel.setFont(QFont('Sans Serif', 13))

        #Censor type group
        self.censorTypeGroupBox = QGroupBox('Censor Type')

        barButton = QRadioButton('Bar censor')
        mosaicButton = QRadioButton('Mosaic censor')
        barButton.setChecked(True)

        censorLayout = QVBoxLayout()
        censorLayout.addWidget(barButton)
        censorLayout.addWidget(mosaicButton)
        # censorLayout.addStretch(1)
        self.censorTypeGroupBox.setLayout(censorLayout)

        #Variation count group
        self.variationsGroupBox = QGroupBox('Number of Decensor Variations')

        var1Button = QRadioButton('1')
        var2Button = QRadioButton('2')
        var3Button = QRadioButton('4')
        var1Button.setChecked(True)

        varLayout = QVBoxLayout()
        varLayout.addWidget(var1Button)
        varLayout.addWidget(var2Button)
        varLayout.addWidget(var3Button)
        # varLayout.addStretch(1)
        self.variationsGroupBox.setLayout(varLayout)

        #Decensor button
        self.decensorButton = QPushButton('Decensor Your Images')
        self.decensorButton.clicked.connect(self.decensorClicked)
        self.decensorButton.setSizePolicy(QSizePolicy.Preferred,
                                          QSizePolicy.Preferred)

        #Progress message
        # self.progressGroupBox = QGroupBox('Progress')

        self.progressMessage = QTextEdit()
        self.progressCursor = QTextCursor(self.progressMessage.document())
        self.progressMessage.setTextCursor(self.progressCursor)
        self.progressMessage.setReadOnly(True)
        self.progressCursor.insertText(
            "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n"
        )

        # Progress Bar
        self.statusBar = QStatusBar(self)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(0)
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.statusLabel = QLabel("Showing Progress")

        self.statusBar.addWidget(self.statusLabel, 1)
        self.statusBar.addWidget(self.progressBar, 2)

        #put all groups into grid
        # addWidget(row, column, rowSpan, columnSpan)
        grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2)
        grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1)
        grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1)
        grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2)
        grid_layout.addWidget(self.progressMessage, 3, 0, 1, 2)
        grid_layout.addWidget(self.statusBar, 4, 0, 1, 2)

        #window size settings
        self.resize(900, 600)
        self.center()
        self.setWindowTitle('DeepCreamPy v2.2.0-beta')
        self.show()

    def load_model(self):
        # load model to make able to decensor several times
        self.decensorButton.setEnabled(False)
        self.decensorButton.setText(
            "Loading Machine Learning Model (Please Wait...)")
        self.decensor.start()
        self.decensor.signals = self.signals
        self.progressCursor.insertText(
            "Loading Decensor app consumes 6 GB memory at maximum")

    def setSignals(self):
        self.signals.update_decensorButton_Text.connect(
            self.decensorButton.setText)
        self.signals.update_decensorButton_Enabled.connect(
            self.decensorButton.setEnabled)
        self.signals.update_statusLabel_Text.connect(self.statusLabel.setText)
        self.signals.update_ProgressBar_SET_VALUE.connect(
            self.progressBar.setValue)
        self.signals.update_ProgressBar_MAX_VALUE.connect(
            self.progressBar.setMaximum)
        self.signals.update_ProgressBar_MIN_VALUE.connect(
            self.progressBar.setMinimum)
        # self.signals.insertText_progressCursor.connect(self.progressCursor.insertText)
        self.signals.insertText_progressCursor.connect(
            self.progressMessage.append)
        self.signals.clear_progressMessage.connect(self.progressMessage.clear)
        self.signals.appendText_progressMessage.connect(
            self.progressMessage.append)

    def decensorClicked(self):
        self.decensorButton.setEnabled(False)
        self.progressMessage.clear()
        self.progressCursor.insertText("Decensoring has begun!\n")

        # for now, decensor is initiated when this app is started
        # self.decensor = Decensor(text_edit = self.progressMessage, text_cursor = self.progressCursor, ui_mode = True)

        #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group
        #set decensor to right settings
        #censor type
        censorTypeElements = self.censorTypeGroupBox.children()
        censorButtons = [
            elem for elem in censorTypeElements
            if isinstance(elem, QRadioButton)
        ]
        for cb in censorButtons:
            if cb.isChecked():
                censorType = cb.text()
        if censorType == 'Bar censor':
            self.decensor.is_mosaic = False
        else:
            self.decensor.is_mosaic = True

        #variations count
        variationsElements = self.variationsGroupBox.children()
        variationsButtons = [
            elem for elem in variationsElements
            if isinstance(elem, QRadioButton)
        ]
        for vb in variationsButtons:
            if vb.isChecked():
                variations = int(vb.text())
        self.decensor.variations = variations

        self.decensorButton.setEnabled(False)
        self.decensor.start()
        # decensor.decensor_all_images_in_folder()

    # #centers the main window
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
コード例 #2
0
ファイル: snapApp.py プロジェクト: Jonny137/signal_monitor
class Widget(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        # Data for plotting and marker data storage
        self.data = {}
        self.slice_index = {
            'ind1': 0, 
            'ind2': 0
            }
        self.marker_id = 0
        self.marker_ind = []
        self.marker_setpoint = {
            'Marker1': 0, 
            'Marker2': 0, 
            }

        # Error message dialog widget
        self.error_popup = QErrorMessage()
        self.error_popup.setWindowTitle('Snap file error')

        # Left (List of Checkboxes)
        self.list_widget = QListWidget()
        #Resize width and height
        self.list_widget.setSizePolicy(QSizePolicy.Preferred, 
                                       QSizePolicy.Preferred)
        self.list_widget.setMinimumWidth(200)
        self.list_widget.setMaximumWidth(400)
        # self.list_widget.setMinimumHeight(300)
        self.list_widget.setMaximumHeight(500)

        # Signal groupbox
        self.signal_groupbox = QGroupBox('Available Signals')
        self.signal_groupbox.setMinimumWidth(200)
        self.signal_groupbox.setMaximumWidth(350)
        self.signal_groupbox.setMinimumHeight(100)
        self.sig_group_layout = QVBoxLayout()
        self.signal_groupbox.setLayout(self.sig_group_layout)
        # Statistics groupbox
        self.stats_groupbox = QGroupBox('Statistics')
        self.stats_groupbox.setMinimumWidth(200)
        self.stats_groupbox.setMaximumWidth(350)
        self.stats_groupbox.setMinimumHeight(240)
        self.stats_group_layout = QFormLayout()

        # Label initiation
        # Marker Time 1
        self.mark_one_time_label = QLabel('Marker1_time: ')
        self.mark_one_time_value = QLabel()
        # Marker Time 2
        self.mark_two_time_label = QLabel('Marker2_time: ')
        self.mark_two_time_value = QLabel()
        # On/Off labels for 0/1 signals counter
        self.on_off_label = QLabel('On/Off: ')
        self.on_off_value = QLabel()
        # Mean value
        self.mean_label = QLabel('Mean: ')
        self.mean_value = QLabel()
        # Standard deviation
        self.std_label = QLabel('Sigma(STD): ')
        self.std_value = QLabel()
        # Minimal value
        self.min_label = QLabel('Min: ')
        self.min_value = QLabel()
        # Maximual value
        self.max_label = QLabel('Max: ')
        self.max_value = QLabel()
        # Max - Min value
        self.val_diff_label = QLabel('Max-Min: ')
        self.val_diff_value = QLabel()
        # Time difference (X-axis)
        self.time_diff_label = QLabel('Time_diff: ')
        self.time_diff_value = QLabel('')

        # Row addition of labels
        self.stats_group_layout.addRow(self.mark_one_time_label, 
                                       self.mark_one_time_value)
        self.stats_group_layout.addRow(self.mark_two_time_label,
                                       self.mark_two_time_value)
        self.stats_group_layout.addRow(self.time_diff_label, 
                                       self.time_diff_value)
        self.stats_group_layout.addRow(self.on_off_label, self.on_off_value)
        self.stats_group_layout.addRow(self.mean_label, self.mean_value)
        self.stats_group_layout.addRow(self.std_label, self.std_value)
        self.stats_group_layout.addRow(self.min_label, self.min_value)
        self.stats_group_layout.addRow(self.max_label, self.max_value)
        self.stats_group_layout.addRow(self.val_diff_label, 
                                       self.val_diff_value)
        self.stats_groupbox.setLayout(self.stats_group_layout)

        # Set markers section of the application (bottom left)
        self.marker_grid = QGridLayout()
        self.marker_one_notice = QLabel()
        self.marker_two_notice = QLabel()
        self.set_marker_one_label = QLabel('Set Marker1:')
        self.set_marker_two_label = QLabel('Set Marker2:')
        self.set_marker_one_value = QLineEdit()
        self.set_marker_one_value.setMaximumWidth(100)
        self.set_marker_two_value = QLineEdit()
        self.set_marker_two_value.setMaximumWidth(100)

        self.marker_grid.addWidget(self.set_marker_one_label)
        self.marker_grid.addWidget(self.set_marker_one_value)
        self.marker_grid.addWidget(self.marker_one_notice)
        self.marker_grid.addWidget(self.set_marker_two_label)
        self.marker_grid.addWidget(self.set_marker_two_value)
        self.marker_grid.addWidget(self.marker_two_notice)
                                        
        # Leftside app layout
        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.list_widget)
        self.v_layout.addWidget(self.signal_groupbox)
        self.v_layout.addWidget(self.stats_groupbox)
        self.v_layout.addLayout(self.marker_grid)

        # Matplotlib figure
        self.fig = Figure(figsize=(5, 3))
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setSizePolicy(QSizePolicy.Expanding, 
                                  QSizePolicy.Expanding)
        self.ax = self.canvas.figure.subplots()
        self.ax.grid()
        self.ax.set_xlabel('Time[s]')
        self.fig.suptitle('Parameter Plot')
      
        # QWidget Layout
        self.h_layout = QHBoxLayout()
        self.h_layout.addLayout(self.v_layout)
        self.h_layout.addWidget(self.canvas)

        # Set the layout to the QWidget
        self.setLayout(self.h_layout)

        # ListWidget and plot connections
        self.list_widget.itemChanged.connect(self.item_changed)
        self.click_event = self.fig.canvas.mpl_connect('button_press_event',
                                                       self.on_click)
        self.set_marker_one_value.returnPressed.connect(
                                                lambda: self.add_marker('one'))
        self.set_marker_two_value.returnPressed.connect(
                                                lambda: self.add_marker('two'))
        
    # Add radio button when signal is checked for plotting
    def add_radio_button(self, name):
        self.rad_btn = QRadioButton(name)
        self.rad_btn.toggled.connect(self.calculate_signal_stats)
        self.sig_group_layout.addWidget(self.rad_btn)

    # Remove radio button when signal is unchecked for plotting
    def remove_radio_button(self, name):
        for item in self.signal_groupbox.children():
            try:
                if item.text() == name:
                    item.setParent(None)
            except AttributeError:
                pass
    
    # Remove all radiobuttons on new data load
    def clear_signals(self):
        count = 0
        for item in self.signal_groupbox.children():
            if count == 0:
                count = 1
                continue 
            else:
                item.setParent(None)  
    # Check state of all radiobuttons, if none is checked remove stats values
    def check_signals(self):
        count = 0
        num_of_check = 0
        for item in self.signal_groupbox.children():
            if count == 0:
                count = 1
                continue 
            else:
                if item.isChecked():
                    num_of_check += 1
        # If no radiobuttons are checked, remove stats
        if num_of_check == 0:
            self.mean_value.setText('') 
            self.std_value.setText('') 
            self.max_value.setText('') 
            self.min_value.setText('') 
            self.val_diff_value.setText('') 
            self.on_off_value.setText('')               

    # Item additon of listWidget
    def fill_list(self, list_items):
        self.list_widget.clear()

        for column in list_items:
            item = QListWidgetItem(column)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            self.list_widget.addItem(item)

        self.show()
    
    # If new data is loaded, replace the old one
    def replace_data(self, temp):
        if not temp == self.data:
            self.data = temp
            self.clear_signals()

    @Slot()
    # Item state changed in listWidget event handler
    def item_changed(self, item):
        if item.checkState() == Qt.Unchecked:
           self.remove_plot(item.text())
           self.remove_radio_button(item.text())
           self.check_signals()
        else:
            self.add_plot(self.data['Time'], 
                          self.data[item.text()], item.text())
            self.add_radio_button(item.text())
                
    # Method for plotting data
    def add_plot(self, x_data, y_data, name):
        self.ax.plot(x_data, y_data, label=name, picker=3)
        self.ax.grid(True)
        self.ax.relim()
        self.ax.set_xlabel('Time[s]')
        self.ax.autoscale_view()
        self.ax.legend(loc='upper right')
        self.canvas.draw()

    # Method for marker addition via QLineEdit
    def add_marker(self, label):
        # Check if any signal is plotted
        sig_count = 0
        for i in range(self.list_widget.count()):
            if self.list_widget.item(i).checkState() == Qt.Checked:
                sig_count += 1

        if sig_count == 0:
            self.marker_one_notice.setText('No active signal!')
            self.marker_two_notice.setText('No active signal!')
            return
        try:
            max_time = self.data['Time'][-1]
            min_time = self.data['Time'][0]
        except KeyError:
            self.marker_one_notice.setText('Signal data not loaded!')
            self.marker_two_notice.setText('Signal data not loaded!')
        if label == 'one':
            try:
                mark1_value = float(self.set_marker_one_value.text())
                if mark1_value < max_time and mark1_value > min_time:
                    if self.marker_id == 0:
                        self.marker_id += 1
                        label_id = self.marker_id
                    elif self.marker_id == 1:
                        self.marker_id += 1
                        label_id = self.marker_id
                        self.remove_marker('first')
                    else:
                        self.remove_marker('first')
                        label_id = 1

                    self.marker_one_notice.setText('')
                    self.marker_setpoint['Marker1'] = mark1_value
                    self.mark_one_time_value.setText(
                                            self.set_marker_one_value.text())
                    self.calculate_marker_stats()
                    self.calculate_signal_stats()
                    
                    # Draw the marker
                    L =  self.ax.axvline(
                                    x=float(self.set_marker_one_value.text()), 
                                    linestyle='dashed', 
                                    color='red', 
                                    label='_Marker' + str(label_id))
                    self.fig.canvas.draw()
                else:
                    self.marker_one_notice.setText('Marker1 out of bounds')
            except ValueError:
                self.marker_one_notice.setText('Non-Valid value entered!')
        else:
            try:
                mark2_value = float(self.set_marker_two_value.text()) 
                if mark2_value < max_time and mark2_value > min_time:
                    if self.marker_id == 1:
                        self.marker_id += 1
                        label_id = self.marker_id
                    elif self.marker_id == 2:
                        label_id = 2
                        self.remove_marker('second')
                    else:
                        self.marker_two_notice.setText('Marker1 not placed')
                    self.marker_two_notice.setText('')
                    self.marker_setpoint['Marker2'] = mark2_value
                    self.mark_two_time_value.setText(
                                            self.set_marker_two_value.text())
                    self.calculate_marker_stats()
                    self.calculate_signal_stats()
                    # Draw the marker
                    L =  self.ax.axvline(
                                    x=float(self.set_marker_two_value.text()), 
                                    linestyle='dashed', 
                                    color='red', 
                                    label='_Marker' + str(label_id))
                    self.fig.canvas.draw()
                else:
                    self.marker_two_notice.setText('Marker2 out of bounds')
            except:
                self.marker_two_notice.setText('Non-Valid value entered!')
    
    # Marker removal method
    def remove_marker(self, label):
        for item in self.ax.lines:
            if 'Marker' in item.get_label():
                self.marker_ind.append(item)

        # If there are two markers remove them from plot and adjust marker
        # time labels
        if label == 'both':
            self.marker_ind[0].remove()
            self.marker_ind[1].remove()
            self.marker_ind = []
            self.marker_setpoint['Marker1'] = 0
            self.marker_setpoint['Marker2'] = 0
            self.mark_one_time_value.setText('')
            self.mark_two_time_value.setText('')
            self.time_diff_value.setText('')
            self.marker_id = 0
        # Remove only marker1
        elif label == 'first':
            self.marker_ind[0].remove()
            self.marker_ind = []
            self.marker_setpoint['Marker1'] = 0
            self.mark_one_time_value.setText('')
            self.marker_id -= 1
        elif label == 'second':
            self.marker_ind[1].remove()
            self.marker_ind = []
            self.marker_setpoint['Marker2'] = 0
            self.mark_two_time_value.setText('')
            self.marker_id -= 1

        self.ax.set_xlabel('Time[s]')
        self.canvas.draw()
    
    # Method for plot removal
    def remove_plot(self, name):
        cnt = 0
        for item in self.ax.lines:
            if item.get_label() == name:
                self.ax.lines[cnt].remove()
            cnt += 1
        self.ax.relim()
        self.ax.autoscale_view()
        self.ax.legend(loc='upper right')
        self.ax.set_xlabel('Time[s]')
        self.canvas.draw()

        # Check if all elements are unticked
        counter = 0
        for i in range(self.list_widget.count()):
            if self.list_widget.item(i).checkState() == Qt.Checked:
                counter +=1
        if counter == 0:
            self.remove_marker('both')
            
    # On click event for plot, only two markers can be active at the time
    def on_click(self, event):
        try:
            # Catch left click event
            if event.button == 1:
                x = event.xdata
                if self.marker_id < 2:
                    if self.marker_id == 0:
                        self.marker_setpoint['Marker1'] = round(x)
                        self.mark_one_time_value.setText(
                                            str(self.marker_setpoint['Marker1']))
                        self.calculate_marker_stats()
                        self.calculate_signal_stats()
                    else:
                        self.marker_setpoint['Marker2'] = round(x)
                        self.mark_two_time_value.setText(
                                            str(self.marker_setpoint['Marker2']))
                        self.calculate_marker_stats()
                        self.calculate_signal_stats()
                    self.marker_id += 1
                    L =  self.ax.axvline(x=x, 
                                        linestyle='dashed', 
                                        color='red', 
                                        label='_Marker' + str(self.marker_id))
                    self.fig.canvas.draw()
            # Catch right click event
            elif event.button == 3:
                self.remove_marker('both')
        except TypeError:
            pass
    # Marker analysis method
    def calculate_marker_stats(self):
        if self.marker_setpoint['Marker2'] == 0:
            diff = self.data['Time'][-1] - self.marker_setpoint['Marker1']
            self.time_diff_value.setText(str(diff))
        else:
            diff = self.marker_setpoint['Marker2'] -  \
                   self.marker_setpoint['Marker1']
            
            self.time_diff_value.setText(convert_seconds(diff))
    # Signal analysis method
    def calculate_signal_stats(self):
        self.check_signals()
        selected_signal = ''
        signal_data = []
        num_off, num_on = 0, 0
        for item in self.signal_groupbox.children():
            try:
                if item.isChecked():
                    # Signal extraction block
                    selected_signal = item.text()
                    # If only one marker, Marker1 is placed on graph
                    if self.marker_setpoint['Marker2'] == 0 and self.marker_setpoint['Marker1'] != 0:
                        for i in range(len(self.data['Time'])):
                            if self.data['Time'][i] > self.marker_setpoint['Marker1']:
                                self.slice_index['ind1'] = i
                                break
                        signal_data = np.asarray(
                        self.data[selected_signal][self.slice_index['ind1']:], 
                                    dtype=np.float32)
                    # Both markers, Marker1 and Marker2 are present on graph
                    elif self.marker_setpoint['Marker1'] != 0 and self.marker_setpoint['Marker2'] != 0:
                        for i in range(len(self.data['Time'])):
                            if self.data['Time'][i] > self.marker_setpoint['Marker1']:
                                self.slice_index['ind1'] = i
                                break
                        for i in range(len(self.data['Time'])):
                            if self.data['Time'][len(self.data['Time']) - i - 1] < self.marker_setpoint['Marker2']:
                                self.slice_index['ind2'] = len(self.data['Time']) - i
                                break
                        signal_data = np.asarray(
                        self.data[selected_signal][self.slice_index['ind1']:self.slice_index['ind2'] - 1], 
                                                    dtype=np.float32)
                        
                    # No markers present, whole signal stats are showed
                    else:
                        signal_data = np.asarray(self.data[selected_signal], 
                                                    dtype=np.float32)
                    try:
                        # Signal mean calculation
                        self.mean_value.setText(str(np.mean(signal_data)))
                        # Standard deviation
                        self.std_value.setText(str(np.std(signal_data)))
                        # Maximum value
                        self.max_value.setText(str(np.max(signal_data)))
                        # Minimum value
                        self.min_value.setText(str(np.min(signal_data)))
                        # Max - Min
                        self.val_diff_value.setText(str(np.max(signal_data) - 
                                                    (np.min(signal_data))))
                        if np.max(signal_data) == 1.0:
                            for i in range(len(signal_data)):
                                if i != len(signal_data) - 1:
                                    temp = signal_data[i] - signal_data[i+1]
                                    if temp == 1:
                                        num_off += 1
                                    elif temp == -1:
                                        num_on += 1
                            self.on_off_value.setText(str(num_on) + 
                                                    '\\' + str(num_off))
                    except ValueError:
                        err_line1 = 'Missing data, result is empty array!'
                        err_line2 = '\n Please check snap file.' 
                        self.error_popup.showMessage(err_line1 + err_line2)
            except AttributeError:
                pass
コード例 #3
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)
        self.setLayout(grid_layout)

        #Tutorial
        self.tutorialLabel = QLabel()
        self.tutorialLabel.setText(
            "Welcome to DeepCreamPy!\n\nIf you're new to DCP, please read the README.\nThis program does nothing without the proper setup of your images.\n\nReport any bugs you encounter to me on Github or Twitter @deeppomf."
        )
        self.tutorialLabel.setAlignment(Qt.AlignCenter)
        self.tutorialLabel.setFont(QFont('Sans Serif', 13))

        #Censor type group
        self.censorTypeGroupBox = QGroupBox('Censor Type')

        barButton = QRadioButton('Bar censor')
        mosaicButton = QRadioButton('Mosaic censor')
        barButton.setChecked(True)

        censorLayout = QVBoxLayout()
        censorLayout.addWidget(barButton)
        censorLayout.addWidget(mosaicButton)
        # censorLayout.addStretch(1)
        self.censorTypeGroupBox.setLayout(censorLayout)

        #Variation count group
        self.variationsGroupBox = QGroupBox('Number of Decensor Variations')

        var1Button = QRadioButton('1')
        var2Button = QRadioButton('2')
        var3Button = QRadioButton('4')
        var1Button.setChecked(True)

        varLayout = QVBoxLayout()
        varLayout.addWidget(var1Button)
        varLayout.addWidget(var2Button)
        varLayout.addWidget(var3Button)
        # varLayout.addStretch(1)
        self.variationsGroupBox.setLayout(varLayout)

        #Decensor button
        self.decensorButton = QPushButton('Decensor Your Images')
        self.decensorButton.clicked.connect(self.decensorClicked)
        self.decensorButton.setSizePolicy(QSizePolicy.Preferred,
                                          QSizePolicy.Preferred)

        #Progress message
        # self.progressGroupBox = QGroupBox('Progress')

        self.progressMessage = QTextEdit()
        self.progressCursor = QTextCursor(self.progressMessage.document())
        self.progressMessage.setTextCursor(self.progressCursor)
        self.progressMessage.setReadOnly(True)
        self.progressCursor.insertText(
            "After you prepared your images, click on the decensor button once to begin decensoring.\nPlease be patient.\nDecensoring will take time.\n"
        )

        #put all groups into grid
        grid_layout.addWidget(self.tutorialLabel, 0, 0, 1, 2)
        grid_layout.addWidget(self.censorTypeGroupBox, 1, 0, 1, 1)
        grid_layout.addWidget(self.variationsGroupBox, 1, 1, 1, 1)
        grid_layout.addWidget(self.decensorButton, 2, 0, 1, 2)
        grid_layout.addWidget(self.progressMessage, 3, 0, 4, 2)

        #window size settings
        self.resize(500, 500)
        self.center()
        self.setWindowTitle('DeepCreamPy v2.2.0-beta')
        self.show()

    def decensorClicked(self):
        self.decensorButton.setEnabled(False)
        self.progressMessage.clear()
        self.progressCursor.insertText("Decensoring has begun!\n")

        decensor = Decensor(text_edit=self.progressMessage,
                            text_cursor=self.progressCursor,
                            ui_mode=True)
        #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group
        #set decensor to right settings
        #censor type
        censorTypeElements = self.censorTypeGroupBox.children()
        censorButtons = [
            elem for elem in censorTypeElements
            if isinstance(elem, QRadioButton)
        ]
        for cb in censorButtons:
            if cb.isChecked():
                censorType = cb.text()
        if censorType == 'Bar censor':
            decensor.is_mosaic = False
        else:
            decensor.is_mosaic = True

        #variations count
        variationsElements = self.variationsGroupBox.children()
        variationsButtons = [
            elem for elem in variationsElements
            if isinstance(elem, QRadioButton)
        ]
        for vb in variationsButtons:
            if vb.isChecked():
                variations = int(vb.text())
        decensor.variations = variations

        self.decensorButton.setEnabled(True)
        self.hide()
        self.progress = ProgressWindow(self, decensor=decensor)
        # decensor.decensor_all_images_in_folder()

        # self.progress.hide()
        # self.show()

    # def showAbout(self):
    # 	QMessageBox.about(self, 'About', "DeepCreamPy v2.2.0 \n Developed by deeppomf")

    # #centers the main window
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
コード例 #4
0
ファイル: main.py プロジェクト: Yodamt/DeepCreamPy
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)
        self.setLayout(grid_layout)

        #Censor type group
        self.censorTypeGroupBox = QGroupBox('Censor Type')

        barButton = QRadioButton('Bar censor')
        mosaicButton = QRadioButton('Mosaic censor')
        barButton.setChecked(True)

        censorLayout = QVBoxLayout()
        censorLayout.addWidget(barButton)
        censorLayout.addWidget(mosaicButton)
        censorLayout.addStretch(1)
        self.censorTypeGroupBox.setLayout(censorLayout)

        #Variation count group
        self.variationsGroupBox = QGroupBox('Number of Decensor Variations')

        var1Button = QRadioButton('1')
        var2Button = QRadioButton('2')
        var3Button = QRadioButton('4')
        var1Button.setChecked(True)

        varLayout = QVBoxLayout()
        varLayout.addWidget(var1Button)
        varLayout.addWidget(var2Button)
        varLayout.addWidget(var3Button)
        varLayout.addStretch(1)
        self.variationsGroupBox.setLayout(varLayout)

        #button
        decensorButton = QPushButton('Decensor Your Images')
        decensorButton.clicked.connect(self.decensorClicked)

        #put all groups into grid
        grid_layout.addWidget(self.censorTypeGroupBox, 0, 0, 1, 1)
        grid_layout.addWidget(self.variationsGroupBox, 0, 1, 1, 1)
        grid_layout.addWidget(decensorButton, 1, 0, 1, 2)

        #window size settings
        self.resize(300, 200)
        self.center()
        self.setWindowTitle('DeepCreamPy v2.2.0')
        self.show()

    def decensorClicked(self):
        decensor = Decensor()
        #https://stackoverflow.com/questions/42349470/pyqt-find-checked-radiobutton-in-a-group
        #set decensor to right settings
        #censor type
        censorTypeElements = self.censorTypeGroupBox.children()
        censorButtons = [
            elem for elem in censorTypeElements
            if isinstance(elem, QRadioButton)
        ]
        for cb in censorButtons:
            if cb.isChecked():
                censorType = cb.text()
        if censorType == 'Bar censor':
            decensor.is_mosaic = False
        else:
            decensor.is_mosaic = True

        #variations count
        variationsElements = self.variationsGroupBox.children()
        variationsButtons = [
            elem for elem in variationsElements
            if isinstance(elem, QRadioButton)
        ]
        for vb in variationsButtons:
            if vb.isChecked():
                variations = int(vb.text())
        decensor.variations = variations

        decensor.decensor_all_images_in_folder()

    # def showAbout(self):
    # 	QMessageBox.about(self, 'About', "DeepCreamPy v2.2.0 \n Developed by deeppomf")

    # #centers the main window
    def center(self):

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
コード例 #5
0
class SettingsDialog(CustomDialog):
    def __init__(self, parent=None):
        super(SettingsDialog, self).__init__(parent, "Settings")

        mouse_box = QGroupBox("Mouse", self)
        mouse_box.setLayout(QVBoxLayout())

        label = QLabel("Scroll objects with mouse wheel:")
        label.setToolTip(
            "Select an object and scroll up and down to change its type.")
        self._scroll_check_box = QCheckBox("Enabled")
        self._scroll_check_box.setChecked(SETTINGS["object_scroll_enabled"])
        self._scroll_check_box.toggled.connect(self._update_settings)

        scroll_layout = QHBoxLayout()
        scroll_layout.addWidget(label)
        scroll_layout.addStretch(1)
        scroll_layout.addWidget(self._scroll_check_box)

        label = QLabel("Show object names on hover:")
        label.setToolTip(
            "When hovering your cursor over an object in a level, its name and position is shown in a tooltip."
        )
        self._tooltip_check_box = QCheckBox("Enabled")
        self._tooltip_check_box.setChecked(SETTINGS["object_tooltip_enabled"])
        self._tooltip_check_box.toggled.connect(self._update_settings)

        tooltip_layout = QHBoxLayout()
        tooltip_layout.addWidget(label)
        tooltip_layout.addStretch(1)
        tooltip_layout.addWidget(self._tooltip_check_box)

        self.lmb_radio = QRadioButton("Left Mouse Button")
        rmb_radio = QRadioButton("Right Mouse Button")

        self.lmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_LEFT_CLICK)
        rmb_radio.setChecked(SETTINGS["resize_mode"] == RESIZE_RIGHT_CLICK)

        self.lmb_radio.toggled.connect(self._update_settings)

        radio_group = QButtonGroup()
        radio_group.addButton(self.lmb_radio)
        radio_group.addButton(rmb_radio)

        resize_layout = QHBoxLayout()
        resize_layout.addWidget(QLabel("Object resize mode:"))
        resize_layout.addStretch(1)
        resize_layout.addWidget(self.lmb_radio)
        resize_layout.addWidget(rmb_radio)

        mouse_box.layout().addLayout(scroll_layout)
        mouse_box.layout().addLayout(tooltip_layout)
        mouse_box.layout().addLayout(resize_layout)

        # -----------------------------------------------
        # GUI theme section

        self.gui_style_box = QGroupBox("GUI", self)
        QHBoxLayout(self.gui_style_box)

        self.gui_style_box.layout().addWidget(QLabel("Style:"))

        for gui_style in GUI_STYLE.keys():
            gui_style = gui_style.capitalize()

            style_radio_button = QRadioButton(gui_style)
            style_radio_button.setChecked(
                SETTINGS["gui_style"] == GUI_STYLE[gui_style.upper()]())
            style_radio_button.toggled.connect(self._update_settings)

            self.gui_style_box.layout().addWidget(style_radio_button)

        # -----------------------------------------------
        # emulator command

        self.emulator_command_input = QLineEdit(self)
        self.emulator_command_input.setPlaceholderText("Path to emulator")
        self.emulator_command_input.setText(SETTINGS["instaplay_emulator"])

        self.emulator_command_input.textChanged.connect(self._update_settings)

        self.emulator_path_button = QPushButton(icon("folder.svg"), "", self)
        self.emulator_path_button.pressed.connect(self._get_emulator_path)

        self.command_arguments_input = QLineEdit(self)
        self.command_arguments_input.setPlaceholderText("%f")
        self.command_arguments_input.setText(SETTINGS["instaplay_arguments"])

        self.command_arguments_input.textEdited.connect(self._update_settings)

        self.command_label = QLabel()

        command_box = QGroupBox("Emulator", self)
        command_layout = QVBoxLayout(command_box)

        command_layout.addWidget(QLabel('Emulator command or "path to exe":'))

        command_input_layout = QHBoxLayout()
        command_input_layout.addWidget(self.emulator_command_input)
        command_input_layout.addWidget(self.emulator_path_button)

        command_layout.addLayout(command_input_layout)
        command_layout.addWidget(
            QLabel("Command arguments (%f will be replaced with rom path):"))
        command_layout.addWidget(self.command_arguments_input)
        command_layout.addWidget(QLabel("Command used to play the rom:"))
        command_layout.addWidget(self.command_label)

        command_layout.addWidget(HorizontalLine())

        command_layout.addWidget(
            QLabel("Power up of Mario when playing level:"))
        self.powerup_combo_box = QComboBox()

        for name, x, y, value, p_wing in POWERUPS:
            powerup_icon = self._load_from_png(x, y)

            self.powerup_combo_box.addItem(powerup_icon, name)

        self.powerup_combo_box.currentIndexChanged.connect(
            self._update_settings)

        self.powerup_combo_box.setCurrentIndex(SETTINGS["default_powerup"])

        command_layout.addWidget(self.powerup_combo_box)

        # ----------------------

        layout = QVBoxLayout(self)
        layout.addWidget(mouse_box)
        layout.addWidget(self.gui_style_box)
        layout.addWidget(command_box)

        self.update()

    def update(self):
        self.command_label.setText(
            f" > {SETTINGS['instaplay_emulator']} {SETTINGS['instaplay_arguments']}"
        )

    def _update_settings(self, _):
        SETTINGS["instaplay_emulator"] = self.emulator_command_input.text()
        SETTINGS["instaplay_arguments"] = self.command_arguments_input.text()

        if self.lmb_radio.isChecked():
            SETTINGS["resize_mode"] = RESIZE_LEFT_CLICK
        else:
            SETTINGS["resize_mode"] = RESIZE_RIGHT_CLICK

        # setup style sheets
        for child_widget in self.gui_style_box.children():
            if isinstance(child_widget, QRadioButton):
                if child_widget.isChecked():
                    selected_gui_style = child_widget.text().upper()

                    loaded_style_sheet = GUI_STYLE[selected_gui_style]()
                    SETTINGS["gui_style"] = loaded_style_sheet

                    self.parent().setStyleSheet(SETTINGS["gui_style"])
                    break

        SETTINGS["object_scroll_enabled"] = self._scroll_check_box.isChecked()
        SETTINGS["object_tooltip_enabled"] = self._tooltip_check_box.isChecked(
        )

        SETTINGS["default_powerup"] = self.powerup_combo_box.currentIndex()

        self.update()

    def _get_emulator_path(self):
        path_to_emulator, _ = QFileDialog.getOpenFileName(
            self, caption="Select emulator executable")

        if not path_to_emulator:
            return

        self.emulator_command_input.setText(path_to_emulator)

    @staticmethod
    def _load_from_png(x: int, y: int) -> QIcon:
        image = png.copy(
            QRect(x * Block.SIDE_LENGTH, y * Block.SIDE_LENGTH,
                  Block.SIDE_LENGTH, Block.SIDE_LENGTH))
        mask = image.createMaskFromColor(
            QColor(*MASK_COLOR).rgb(), Qt.MaskOutColor)
        image.setAlphaChannel(mask)

        pixmap = QPixmap.fromImage(image)
        icon_from_png = QIcon(pixmap)

        return icon_from_png

    def on_exit(self):
        save_settings()

        super(SettingsDialog, self).on_exit()
コード例 #6
0
class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.setStyleSheet("background-color:white; font-size:24px;")

        # Icon
        self.top_icon = QPixmap("ivs.jpg")
        self.top_icon_label = QLabel()
        self.top_icon_label.setAlignment(Qt.AlignCenter)
        self.top_icon_label.setPixmap(
            self.top_icon.scaled(256, 256, Qt.KeepAspectRatio))

        # Title
        title_font = QFont("Helvatica", 24, QFont.Bold)
        self.title = QLabel("Intelligent Video Summarization")
        self.title.setFont(title_font)

        # Desired Objects
        self.desired_objects_checkbox = [
            QCheckBox("car", self),
            QCheckBox("motor-bike", self),
            QCheckBox("rickshaw", self),
            QCheckBox("cycle", self),
            QCheckBox("person", self)
        ]
        self.desired_objects_label = QLabel("Select the desired objects")
        self.desired_objects = QGroupBox()
        self.desired_objects.setTitle("Select Desired Objects")

        # Add Options (Checkboxes) in Desired Objects
        self.desired_objects_layout = QVBoxLayout()
        self.desired_objects.setStyleSheet("font-weight:bold;")
        for checkbox in self.desired_objects_checkbox:
            self.desired_objects_layout.addWidget(checkbox)
        self.desired_objects.setLayout(self.desired_objects_layout)

        self.button = QPushButton("Select Video")
        self.button.setStyleSheet("background-color:blue; color:white;")

        self.start_button = QPushButton("Start")
        self.start_button.setStyleSheet("background-color:red; color:white;")

        # Detector
        self.detectors_list = [
            QRadioButton("yolo", self),
            QRadioButton("frcc", self),
            QRadioButton("pseudo", self)
        ]
        self.detectors = QGroupBox()
        self.detectors.setTitle("Select Detection Algorithm")
        self.detectors_layout = QVBoxLayout()
        self.detectors.setStyleSheet("font-weight:bold;")

        for radio_button in self.detectors_list:
            self.detectors_layout.addWidget(radio_button)

        self.detectors.setLayout(self.detectors_layout)

        # Main Layout
        self.layout = QFormLayout()
        self.layout.addRow(self.top_icon_label)
        self.layout.addRow(self.title)
        self.layout.addRow(self.button)
        self.layout.addRow(self.desired_objects)
        self.layout.addRow(self.detectors)
        self.layout.addRow(self.start_button)
        self.setLayout(self.layout)

        # Connecting the signal
        self.button.clicked.connect(self.add_video_path)
        self.start_button.clicked.connect(self.start_summarizing)

    @Slot()
    def add_video_path(self):
        self.video_file_path = QFileDialog.getOpenFileName(
            self, "Select Video", str(Path.home()),
            "Video File (*.mp4, *.m4v)")
        # Update the text of button only if the selected video path is not empty
        if self.video_file_path[0]:
            self.button.setText(self.video_file_path[0])

    @Slot()
    def start_summarizing(self):
        _desired_objects = []
        _detection_algorithm = ""

        # get desired objects
        for child in self.desired_objects.children():
            if hasattr(child, "isChecked") and child.isChecked():
                _desired_objects.append(child)
                print(child.text())

        # get detection algorithm
        for child in self.detectors.children():
            if hasattr(child, "isChecked") and child.isChecked():
                _detection_algorithm = child.text()

        print(dir(self.video_file_path[0]))
        subprocess.run([
            "python3", "main.py", "--video", self.video_file_path[0],
            "--detector", _detection_algorithm
        ])