def _init_widgets(self): if self._state.am_none(): return layout = QVBoxLayout() area = QScrollArea() area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setWidgetResizable(True) table = QTableWidget(0, 0) table.setColumnCount(len(self.COLUMNS)) table.setHorizontalHeaderLabels(self.COLUMNS) self.table = table layout.addWidget(table) # common ones layout.setSpacing(0) layout.addStretch(0) layout.setContentsMargins(2, 2, 2, 2) # the container container = QFrame() container.setAutoFillBackground(True) palette = container.palette() palette.setColor(container.backgroundRole(), Qt.white) container.setPalette(palette) container.setLayout(layout) area.setWidget(container) base_layout = QVBoxLayout() base_layout.addWidget(area) self.setLayout(base_layout)
def get_frame( self, value: Union[ Component, ComponentInfo, Transformation, LinkTransformation, TransformationsList, FileWriterModule, ], ): frame = QFrame() frame.setAutoFillBackground(True) SizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) SizePolicy.setHorizontalStretch(0) SizePolicy.setVerticalStretch(0) frame.setSizePolicy(SizePolicy) frame.setLayout(QVBoxLayout()) frame.layout().setContentsMargins(0, 0, 0, 0) if isinstance(value, Group): get_group_frame(frame, value) elif isinstance(value, TransformationsList): get_transformations_list_frame(frame) elif isinstance(value, ComponentInfo): get_group_info_frame(frame, value) elif isinstance(value, Transformation): get_transformation_frame(frame, self.model, value) elif isinstance(value, LinkTransformation): get_link_transformation_frame(frame, self.model, value) elif isinstance(value, FileWriterModule): get_module_frame(frame, self.model, value, self._use_simple_tree_view) return frame
def get_frame( self, value: Union[ Component, ComponentInfo, Transformation, LinkTransformation, TransformationsList, ], ): frame = QFrame() frame.setAutoFillBackground(True) SizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) SizePolicy.setHorizontalStretch(0) SizePolicy.setVerticalStretch(0) frame.setSizePolicy(SizePolicy) frame.setLayout(QVBoxLayout()) frame.layout().setContentsMargins(0, 0, 0, 0) if isinstance(value, Component): get_component_frame(frame, value) elif isinstance(value, TransformationsList): get_transformations_list_frame(frame) elif isinstance(value, ComponentInfo): get_component_info_frame(frame) elif isinstance(value, Transformation): get_transformation_frame(frame, self.instrument, value) elif isinstance(value, LinkTransformation): get_link_transformation_frame(frame, self.instrument, value) return frame
def _init_widgets(self): if self._state.am_none(): return if self._state.arch.name not in self.ARCH_REGISTERS: l.error( "Architecture %s is not listed in QRegisterViewer.ARCH_REGISTERS.", self._state.arch.name) return layout = QVBoxLayout() area = QScrollArea() area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) area.setWidgetResizable(True) regs = self.ARCH_REGISTERS[self._state.arch.name] # common ones common_regs = regs['common'] for reg_name in common_regs: sublayout = QHBoxLayout() lbl_reg_name = QLabel(self) lbl_reg_name.setProperty('class', 'reg_viewer_label') lbl_reg_name.setText(reg_name) lbl_reg_name.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sublayout.addWidget(lbl_reg_name) sublayout.addSpacing(10) reg_value = QASTViewer(None, parent=self, workspace=self.workspace) self._registers[reg_name] = reg_value sublayout.addWidget(reg_value) layout.addLayout(sublayout) layout.setSpacing(0) layout.addStretch(0) layout.setContentsMargins(2, 2, 2, 2) # the container container = QFrame() container.setAutoFillBackground(True) palette = container.palette() palette.setColor(container.backgroundRole(), Qt.white) container.setPalette(palette) container.setLayout(layout) area.setWidget(container) base_layout = QVBoxLayout() base_layout.addWidget(area) self.setLayout(base_layout)
def _load_tmps(self): state = self.state.am_obj layout = QVBoxLayout() self._tmps.clear() if state is None: tmps = {} else: tmps = state.scratch.temps # tmps for tmp_id, tmp_value in tmps.items(): sublayout = QHBoxLayout() lbl_tmp_name = QLabel(self) lbl_tmp_name.setProperty('class', 'reg_viewer_label') lbl_tmp_name.setText("tmp_%d" % tmp_id) lbl_tmp_name.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) sublayout.addWidget(lbl_tmp_name) sublayout.addSpacing(10) tmp_viewer = QASTViewer(tmp_value, workspace=self.workspace, parent=self) self._tmps[tmp_id] = tmp_viewer sublayout.addWidget(tmp_viewer) layout.addLayout(sublayout) layout.setSpacing(0) layout.addStretch(0) layout.setContentsMargins(2, 2, 2, 2) # the container container = QFrame() container.setAutoFillBackground(True) palette = container.palette() palette.setColor(container.backgroundRole(), Qt.white) container.setPalette(palette) container.setLayout(layout) self._area.setWidget(container)
class DisplayWidgetGroup(QWidget): def __init__(self, parent, id): super().__init__(parent) self.displays = [] self.groupID = id self.displayArea = parent self.minX = 1000000 self.minY = 1000000 self.maxX = 0 self.maxY = 0 self.labelFrame = QFrame(self) self.labelFrame.setFrameShape(QFrame.Box) self.labelFrame.setAutoFillBackground(True) p = self.labelFrame.palette() p.setColor(self.backgroundRole(), QColor(80, 80, 200, 20)) self.labelFrame.setPalette(p) self.label = QLabel(self.labelFrame) self.label.setText(self.groupID) self.label.setFont(QFont("arial", 32)) self.label.setAlignment(Qt.AlignCenter) self.globalBounds = [0, 0, self.width(), self.height()] self.widgetBounds = [0, 0, self.width(), self.height()] def AddDisplay(self, displayInfo): display = DisplayWidget(self, displayInfo) self.displays.append(display) dimensions = displayInfo["bounds"] self.minX = min(self.minX, dimensions[0]) self.minY = min(self.minY, dimensions[1]) self.maxX = max(self.maxX, (dimensions[2] + dimensions[0])) self.maxY = max(self.maxY, (dimensions[3] + dimensions[1])) self.labelFrame.raise_() self.UpdateDisplaysGroupBounds() def resizeEvent(self, event): self.labelFrame.setGeometry(0, 0, self.width(), self.height()) self.label.setGeometry(0, 0, self.width(), self.height()) f = QFont("ariel", self.FontSizeForWidth()) self.label.setFont(f) for display in self.displays: display.SetWidgetBounds([0, 0, self.width(), self.height()]) display.UpdateGeometry() return super().resizeEvent(event) def FontSizeForWidth(self): text = self.label.text() textSize = len(text) f = self.label.font() metrics = QFontMetrics(f) width = metrics.width(text) myWidth = self.label.width() size = 0 if width < myWidth: direction = 1 else: direction = -1 while (True): f = QFont("Ariel", size + 1) mf = QFontMetrics(f) self.label.setFont(f) width = mf.width(text) if direction > 0: if width >= myWidth: break else: if width <= myWidth: break size = f.pointSize() + direction return size def UpdateGlobalBounds(self, bounds): self.globalBounds = bounds.copy() def SetWidgetBounds(self, bounds): self.widgetBounds = bounds.copy() for display in self.displays: display.SetWidgetBounds([0, 0, self.width(), self.height()]) display.UpdateGeometry() def UpdateGeometry(self): scaleX = (self.widgetBounds[2] - self.widgetBounds[0]) / ( self.globalBounds[2] - self.globalBounds[0]) scaleY = (self.widgetBounds[3] - self.widgetBounds[1]) / ( self.globalBounds[3] - self.globalBounds[1]) posX = ( (self.minX - self.globalBounds[0]) * scaleX) + self.widgetBounds[0] posY = ( (self.minY - self.globalBounds[1]) * scaleY) + self.widgetBounds[1] width = (self.maxX - self.minX) * scaleX height = (self.maxY - self.minY) * scaleY self.setGeometry(posX, posY, width, height) def UpdateDisplaysGroupBounds(self): bounds = [ self.minX, self.minY, self.maxX - self.minX, self.maxY - self.minY ] for display in self.displays: display.SetGroupBounds(bounds) def GetGlobalOffset(self): scaleX = (self.globalBounds[2] - self.globalBounds[0]) / ( self.widgetBounds[2] - self.widgetBounds[0]) scaleY = (self.globalBounds[3] - self.globalBounds[0]) / ( self.widgetBounds[3] - self.widgetBounds[0]) posX = ((self.pos().x() - self.widgetBounds[0]) * scaleX) + self.globalBounds[0] posY = ((self.pos().y() - self.widgetBounds[1]) * scaleY) + self.globalBounds[1] return [posX, posY] def CollidesWith(self, widget): bounds = [ self.x(), self.y(), self.x() + self.width(), self.y() + self.height() ] other = [ widget.x(), widget.y(), widget.x() + widget.width(), widget.y() + widget.height() ] return not (other[0] > bounds[2] or other[2] < bounds[0] or\ other[1] > bounds[3] or other[3] < bounds[1]) def mouseMoveEvent(self, event): if self.oldPos: deltaPos = (event.globalPos() - self.oldPos) self.move(self.x() + deltaPos.x(), self.y() + deltaPos.y()) if self.displayArea.CheckCollision(self): self.move(self.x() - deltaPos.x(), self.y() - deltaPos.y()) self.oldPos = event.globalPos() return super().mouseMoveEvent(event) def mousePressEvent(self, event): self.oldPos = event.globalPos() return super().mousePressEvent(event) def mouseReleaseEvent(self, event): self.oldPos = None return super().mouseReleaseEvent(event)
class colorPicker(QDialog): "custom colorDialog from Orthallelous" currentColorChanged = Signal(QColor) colorSelected = Signal(QColor) def __init__(self, initial=None, parent=None): super(colorPicker, self).__init__(parent) self.setup() self.setColor(initial) def currentColor(self): return self._color def setColor(self, qcolor=None): if qcolor is None: self._color = QColor('#ffffff') else: self._color = QColor(qcolor) self._colorEdited() @staticmethod def getColor(initial=None, parent=None, title=None): dialog = colorPicker(initial, parent) if title: dialog.setWindowTitle(title) result = dialog.exec_() color = dialog._color return color def closeValid(self): "emits colorSelected signal with valid color on OK" self.currentColorChanged.emit(self._color) self.colorSelected.emit(self._color) self.close() def closeInvalid(self): "emits colorSelected signal with invalid color on Cancel" self._color = QColor() self.colorSelected.emit(QColor()) self.close() def setOption(self, option, Bool=True): if option == QColorDialog.NoButtons: if not Bool: self.dialogButtons.blockSignals(False) self.dialogButtons.setEnabled(True) self.dialogButtons.show() else: self.dialogButtons.blockSignals(True) self.dialogButtons.setEnabled(False) self.dialogButtons.hide() self.setFixedSize(self.sizeHint()) def _colorEdited(self): "internal color editing" sender, color = self.sender(), self._color for i in self.inputs: i.blockSignals(True) # get values if sender in self.rgbInputs: # RGB color.setRgb(*[i.value() for i in self.rgbInputs]) elif sender in self.hsvInputs: # HSV color.setHsv(*[i.value() for i in self.hsvInputs]) elif sender in self.cmykInputs: # CMYK color.setCmyk(*[i.value() for i in self.cmykInputs]) elif sender is self.htmlInput: # HTML color.setNamedColor('#' + str(self.htmlInput.text()).lower()) elif sender is self.colorWheel: # WHEEL color = self._color = self.colorWheel.getColor() elif sender is self.colorNamesCB: # NAMED dat = self.colorNamesCB.itemData(self.colorNamesCB.currentIndex()) try: color = self._color = QColor(dat.toString()) # PyQt except: color = self._color = QColor(str(dat)) # PySide self.colorNamesCB.setToolTip(self.colorNamesCB.currentText()) else: pass # set values for i, j in zip(color.getRgb()[:-1], self.rgbInputs): j.setValue(i) for i, j in zip(color.getHsv()[:-1], self.hsvInputs): j.setValue(i) for i, j in zip(color.getCmyk()[:-1], self.cmykInputs): j.setValue(i) self.htmlInput.setText(color.name()[1:]) self.colorWheel.setColor(color) idx = self.colorNamesCB.findData(color.name()) self.colorNamesCB.setCurrentIndex(idx) # will be blank if not in list pal = self.colorDisplay.palette() pal.setColor(self.colorDisplay.backgroundRole(), color) self.colorDisplay.setPalette(pal) #self.colorDisplay.setStyleSheet('background:' + color.name()) for i in self.inputs: i.blockSignals(False) self.currentColorChanged.emit(color) def pickColor(self): "pick a color on the screen, part 1" # screenshot desktop self._img = QApplication.primaryScreen().grabWindow(0) self._view = QGraphicsView(self) scene = QGraphicsScene(self) # display screenshot at full size self._view.setWindowFlags(Qt.FramelessWindowHint) self._view.setWindowFlags(Qt.WindowType_Mask) self._view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) scene.addPixmap(self._img) #; self._view.setScene(scene) self._mag = magnifier() self._mag.setBackground(self._img) self._mag.setSize(11, 11) scene.addItem(self._mag) self._view.setScene(scene) self._appview = QApplication self._appview.setOverrideCursor(Qt.CrossCursor) self._view.showFullScreen() self._view.mousePressEvent = self._pickedColor def _pickedColor(self, event): "pick a color on the screen, part 2" color = QColor(self._img.toImage().pixel(event.globalPos())) self._view.hide() self._appview.restoreOverrideCursor() self._color = color self._colorEdited() self._mag = self._appview = self._view = self._img = None def showColors(self): "show location of colors on color wheel" if self.showButton.isChecked(): self.colorWheel.showNamedColors(True) else: self.colorWheel.showNamedColors(False) def useRandom(self, state=True): "toggles show colors button and random color button" if state: self.showButton.blockSignals(True) self.showButton.setChecked(False) self.showButton.hide() self.showColors() self.rndButton.blockSignals(False) self.rndButton.show() else: self.showButton.blockSignals(False) self.showButton.show() self.rndButton.blockSignals(True) self.rndButton.hide() def randomColor(self): "select a random color" rand = random.randint col = QColor() col.setHsv(rand(0, 359), rand(0, 255), rand(0, 255)) #col.setRgb(rand(0, 255), rand(0, 255), rand(0, 255)) self.setColor(col) return col def getNamedColors(self): "returns a list [(name, #html)] from the named colors combobox" lst = [] for i in range(self.colorNamesCB.count()): name = str(self.colorNamesCB.itemText(i)) try: # PyQt html = str(self.colorNamesCB.itemData(i).toString()) except AttributeError: # PySide html = str(self.colorNamesCB.itemData(i)) lst.append((name, html)) return lst def addNamedColors(self, lst): "add a list [('name', '#html'), ] of named colors (repeats removed)" col = self.getNamedColors() + lst lst = [(i[0], QColor(i[1])) for i in col] sen = set() add = sen.add # http://stackoverflow.com/a/480227 uni = [x for x in lst if not (x[1].name() in sen or add(x[1].name()))] self.colorNamesCB.clear() for i, j in sorted(uni, key=lambda q: q[1].getHsv()): icon = QPixmap(16, 16) icon.fill(j) self.colorNamesCB.addItem(QIcon(icon), i, j.name()) self.colorWheel.setNamedColors([(i, j.name()) for i, j in uni]) self.cNameLabel.setToolTip('Named colors\n{:,} colors'.format( len(uni))) def setup(self): self.setAttribute(Qt.WA_DeleteOnClose) fixed = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) rightCenter = (Qt.AlignRight | Qt.AlignVCenter) # all the input boxes self.inputGrid = QGridLayout() self.inputGrid.setSpacing(5) h_spc = self.inputGrid.horizontalSpacing() v_spc = self.inputGrid.verticalSpacing() # RGB self.redInput = QSpinBox() self.grnInput = QSpinBox() self.bluInput = QSpinBox() self.rgbInputs = [self.redInput, self.grnInput, self.bluInput] self.redLabel = QLabel('&R:') self.redLabel.setToolTip('Red') self.grnLabel = QLabel('&G:') self.grnLabel.setToolTip('Green') self.bluLabel = QLabel('&B:') self.bluLabel.setToolTip('Blue') self.rgbLabels = [self.redLabel, self.grnLabel, self.bluLabel] self.redLabel.setBuddy(self.redInput) self.grnLabel.setBuddy(self.grnInput) self.bluLabel.setBuddy(self.bluInput) # HSV self.hueInput = QSpinBox() self.satInput = QSpinBox() self.valInput = QSpinBox() self.hsvInputs = [self.hueInput, self.satInput, self.valInput] self.hueInput.setWrapping(True) self.hueLabel = QLabel('&H:') self.hueLabel.setToolTip('Hue') self.satLabel = QLabel('&S:') self.satLabel.setToolTip('Saturation') self.valLabel = QLabel('&V:') self.valLabel.setToolTip('Value') self.hsvLabels = [self.hueLabel, self.satLabel, self.valLabel] self.hueLabel.setBuddy(self.hueInput) self.satLabel.setBuddy(self.satInput) self.valLabel.setBuddy(self.valInput) # CMYK self.cInput = QSpinBox() self.mInput = QSpinBox() self.yInput = QSpinBox() self.kInput = QSpinBox() self.cmykInputs = [self.cInput, self.mInput, self.yInput, self.kInput] self.cLabel = QLabel('&C:') self.cLabel.setToolTip('Cyan') self.mLabel = QLabel('&M:') self.mLabel.setToolTip('Magenta') self.yLabel = QLabel('&Y:') self.yLabel.setToolTip('Yellow') self.kLabel = QLabel('&K:') self.kLabel.setToolTip('Black') self.cmykLabels = [self.cLabel, self.mLabel, self.yLabel, self.kLabel] self.cLabel.setBuddy(self.cInput) self.mLabel.setBuddy(self.mInput) self.yLabel.setBuddy(self.yInput) self.kLabel.setBuddy(self.kInput) for i in self.rgbInputs + self.hsvInputs + self.cmykInputs: i.setRange(0, 255) i.setFixedSize(35, 22) i.setAlignment(Qt.AlignCenter) i.setButtonSymbols(QAbstractSpinBox.NoButtons) self.hueInput.setRange(0, 359) # HTML self.htmlInput = QLineEdit() self.htmlInput.setFixedSize(35 + 22 + h_spc, 22) # spans 2 cols self.htmlInput.setPlaceholderText('html') self.htmlInput.setAlignment(Qt.AlignCenter) regex = QRegExp('[0-9A-Fa-f]{1,6}') valid = QRegExpValidator(regex) self.htmlInput.setValidator(valid) self.htmlLabel = QLabel('&#') self.htmlLabel.setToolTip('Web color') self.htmlLabel.setBuddy(self.htmlInput) self.inputLabels = (self.rgbLabels + self.hsvLabels + self.cmykLabels + [ self.htmlLabel, ]) for i in self.inputLabels: i.setFixedSize(22, 22) i.setAlignment(rightCenter) #i.setFrameShape(QFrame.Box) self.inputs = self.rgbInputs + self.hsvInputs + self.cmykInputs for i in self.inputs: i.valueChanged.connect(self._colorEdited) self.htmlInput.editingFinished.connect(self._colorEdited) # picker button self.pickButton = QPushButton('&Pick') self.pickButton.setToolTip('Pick a color from the screen') self.pickButton.setFixedSize(35, 22) self.pickButton.clicked.connect(self.pickColor) # color display self.colorDisplay = QFrame() self.colorDisplay.setFixedSize(55, 4 * 22 + 3 * v_spc) # spans 4 rows self.colorDisplay.setFrameShape(QFrame.Panel) self.colorDisplay.setFrameShadow(QFrame.Sunken) self.colorDisplay.setAutoFillBackground(True) # show button / random button self.showButton = QPushButton('Sho&w') self.showButton.setToolTip('Show named colors on color wheel') self.showButton.setFixedSize(35, 22) self.showButton.setCheckable(True) self.showButton.clicked.connect(self.showColors) self.rndButton = QPushButton('R&and') self.rndButton.setToolTip('Select a random color') self.rndButton.setFixedSize(35, 22) self.rndButton.clicked.connect(self.randomColor) # color wheel self.colorWheel = wheel() self.colorWheel.setFixedSize(256, 256) #265, 265) self.colorWheel.currentColorChanged.connect(self.setColor) # named colors combo box self.colorNamesCB = QComboBox() self.colorNamesCB.setFixedSize(70 + 66 + 4 * h_spc, 22) # spans 5 cols #self.colorNamesCB.addItem('- Color Names -') self.cNameLabel = QLabel('&Named:') self.cNameLabel.setBuddy(self.colorNamesCB) self.cNameLabel.setAlignment(rightCenter) #self.cNameLabel.setFrameShape(QFrame.Box) self.cNameLabel.setFixedSize(55, 22) lst = [i for i in QColor.colorNames() if str(i) != 'transparent'] lst = [(i, QColor(i)) for i in lst] lst.append(('Cosmic latte', '#fff8e7')) lst.append(('rebeccapurple', '#663399')) self.addNamedColors(lst) self.colorNamesCB.currentIndexChanged.connect(self._colorEdited) self.inputs += [self.htmlInput, self.colorWheel, self.colorNamesCB] # ok/cancel buttons self.dialogButtons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.dialogButtons.accepted.connect(self.closeValid) self.dialogButtons.rejected.connect(self.closeInvalid) self.dialogButtons.setCenterButtons(True) # pass QColorDialog.NoButtons, False to setOption to remove # assemble grid! # 0 1 2 3 4 5 6 # # color wheeeeeeeeeeeeellll 0 # disp r: rrr h: hhh c: ccc 1 # disp g: ggg s: sss m: mmm 2 # disp b: bbb v: vvv y: yyy 3 # disp ## -html- pic k: kkk 4 # name coooommmboooobox rnd 5 #.addWidget(widget, row, col, rspan, cspan) self.inputGrid.addWidget(self.colorWheel, 0, 0, 1, 7) self.inputGrid.addWidget(self.colorDisplay, 1, 0, 4, 1) for i, lab in enumerate(self.rgbLabels, 1): self.inputGrid.addWidget(lab, i, 1, 1, 1) self.inputGrid.addWidget(self.htmlLabel, 4, 1, 1, 1) for i, wid in enumerate(self.rgbInputs, 1): self.inputGrid.addWidget(wid, i, 2) self.inputGrid.addWidget(self.htmlInput, 4, 2, 1, 2) for i, lab in enumerate(self.hsvLabels, 1): self.inputGrid.addWidget(lab, i, 3, 1, 1) for i, wid in enumerate(self.hsvInputs, 1): self.inputGrid.addWidget(wid, i, 4, 1, 1) self.inputGrid.addWidget(self.pickButton, 4, 4, 1, 1) for i, lab in enumerate(self.cmykLabels, 1): self.inputGrid.addWidget(lab, i, 5, 1, 1) for i, wid in enumerate(self.cmykInputs, 1): self.inputGrid.addWidget(wid, i, 6, 1, 1) self.inputGrid.addWidget(self.colorNamesCB, 5, 1, 1, 5) self.inputGrid.addWidget(self.cNameLabel, 5, 0, 1, 1) self.inputGrid.addWidget(self.showButton, 5, 6, 1, 1) self.inputGrid.addWidget(self.rndButton, 5, 6, 1, 1) self.inputGrid.addWidget(self.dialogButtons, 6, 0, 1, 7) self.setWindowTitle('Select color') ico = self.style().standardIcon(QStyle.SP_DialogResetButton) self.setWindowIcon(ico) self.setLayout(self.inputGrid) self.setFixedSize(self.sizeHint()) self.useRandom() #False)
class PreprocessingImageWindow(QMainWindow): def close_application(self): """ This function close the window. """ sys.exit() def save(self) : self.dico = saveColumn1Dataset (self.dataset_path) saveColumn2Dataset (self.training_data, self.dico, self.file_name) def showTable(self): """ This function display the corresponding matrix to an image """ self.tableWidget.setVisible (True) if hasattr (self, 'image') : self.image.setVisible (False) self.pushButton_table.setEnabled (False) self.pushButton_next.setEnabled(True) global index_data_pre self.frame_3.setGeometry (QtCore.QRect (10, 180, 1000, 450)) self.tableWidget.setRowCount(int (globals.height_m)) self.tableWidget.setColumnCount(int (globals.length_m)) matrix_image, id_class = self.training_data[globals.index_data_pre] for i, row in enumerate (matrix_image) : for j, val in enumerate (row) : self.tableWidget.setItem (i, j, QTableWidgetItem (str (val))) def preprocess(self): """ This function preprocess an image dataset. """ if self.dataset_path != None : if self.input_length.text() == "0" or self.input_length.text() == "": self.input_length.setText("30") if self.input_height.text() == "0" or self.input_height.text() == "": self.input_height.setText("30") # Setting values for matrix sizes global length_m global height_m globals.length_m = int(self.input_length.text()) globals.height_m = int(self.input_height.text()) ## Preprocessing global input_array global output_array f = open(self.dataset_path,'r') categories = list() f.readline() for ligne in f.readlines() : var=ligne.strip().split(',') classe=var[1] #class if classe not in categories : categories.append(classe) self.training_data = Preprocessing (self.dataset_path, self.file_path) for i in range (len (self.training_data)) : matrix, id_class = self.training_data[i] globals.input_array.append (matrix) globals.output_array.append (categories[id_class]) self.start.setEnabled (False) self.input_height.setEnabled(False) self.input_length.setEnabled (False) self.pushButton_table.setEnabled (True) self.pushButton_save.setEnabled (True) def open_dataset (self) : """ This function looks for the csv file and initializes the Window attributes. """ global dataset_name dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.selectNameFilter("Csv data files (*.csv)") dlg.setNameFilter("Arff data files (*.arff) ;; Csv data files (*.csv) ;; All files (*.*)") filenames = [] if dlg.exec_(): filenames = dlg.selectedFiles() f = open(filenames[0], 'r') self.dataset_path = str(filenames[0]) with f: self.textEdit.setText(filenames[0].split('/')[-1]) self.file_name = filenames[0].split('/')[-1].split('.')[0] if self.dataset_path != None : self.file_path = os.path.dirname(self.dataset_path) + globals.directory globals.dataset_name = self.file_name ## RESET global input_height global input_length global index_data global index_data_pre global input_array global output_array globals.input_height = 0 globals.input_length = 0 globals.index_data = 0 globals.index_data_pre = 0 globals.input_array = [] globals.output_array = [] self.frame_3.setGeometry(QtCore.QRect(10, 180, 1000, 450)) self.pushButton_next.setEnabled (False) self.pushButton_previous.setEnabled (False) self.start.setEnabled (False) self.valider.setEnabled(True) self.pushButton_save.setEnabled (False) self.pushButton_table.setEnabled (False) if hasattr (self, 'tableWidget') : self.tableWidget.setVisible (False) if hasattr (self, 'image') : self.image.setVisible (False) def get_dataset_information(self): """ This function gets information about the dataset such as the number of instances and the number of classes. """ text="Nombre d'instances: "+str(get_number_instances(self.dataset_path)) self.label_instances.setText(text) text = "Nombre de classes: " + str (get_number_class (self.dataset_path)) self.label_classes.setText(text) self.input_height.setEnabled(True) self.input_length.setEnabled(True) self.valider.setEnabled (False) self.start.setEnabled(True) self.pushButton_next.setEnabled (True) if hasattr (self, 'training_data') : self.pushButton_table.setEnabled (True) self.frame_3.setGeometry (QtCore.QRect (250, 180, 500, 450)) if not hasattr (self, 'image') : self.image = QLabel (self.frame_3) self.image.setGeometry (QtCore.QRect (0,0,500, 450)) self.image.setObjectName ("image") image_list = [] global index_data csv_file = open (self.dataset_path, "r") csv_file.readline() for line in csv_file.readlines() : var = line.strip().split(',') image_list.append (var[0]) csv_file.close() self.image.setPixmap (QtGui.QPixmap (self.file_path + image_list[globals.index_data]).scaled (500, 450)) self.image.show() def previous_state(self): """ This function returns to the previous instance in the dataset. """ global index_data global index_data_pre if self.pushButton_table.isEnabled() or not hasattr(self, 'training_data'): if globals.index_data - 1 >= 0 : globals.index_data -= 1 if globals.index_data - 1 < 0: self.pushButton_next.setEnabled(True) self.pushButton_previous.setEnabled(False) else : if globals.index_data_pre - 1 >= 0 : globals.index_data_pre -= 1 if globals.index_data_pre - 1 < 0: self.pushButton_next.setEnabled(True) self.pushButton_previous.setEnabled(False) if not self.valider.isEnabled () and not hasattr(self, "training_data"): if hasattr (self, 'training_data') and self.start.isEnabled(): self.pushButton_table.setEnabled(False) elif hasattr (self, 'training_data') : self.pushButton_table.setEnabled (True) self.frame_3.setGeometry (QtCore.QRect (250, 180, 500, 450)) if not hasattr (self, 'image') : self.image = QLabel (self.frame_3) self.image.setGeometry (QtCore.QRect (0,0,500, 450)) self.image.setObjectName ("image") image_list = [] global index_data csv_file = open (self.dataset_path, "r") csv_file.readline() for line in csv_file.readlines() : var = line.strip().split(',') image_list.append (var[0]) csv_file.close() self.image.setPixmap (QtGui.QPixmap (self.file_path + image_list[globals.index_data]).scaled (500, 450)) self.image.show() else : self.showTable() def next_state(self): """ This function goes to the next instance in the dataset. """ global index_data global index_data_pre if self.pushButton_table.isEnabled() or not hasattr( self, 'training_data' ): # Image Mode if globals.index_data + 1 < get_number_instances (self.dataset_path): globals.index_data += 1 if globals.index_data + 1 >= get_number_instances(self.dataset_path): self.pushButton_next.setEnabled(False) self.pushButton_previous.setEnabled(True) else : if globals.index_data_pre + 1 < get_number_instances (self.dataset_path) * 2: globals.index_data_pre += 1 if globals.index_data_pre + 1 >= get_number_instances(self.dataset_path): self.pushButton_next.setEnabled(False) self.pushButton_previous.setEnabled(True) if not self.valider.isEnabled () and not hasattr (self, "training_data"): if hasattr (self, 'training_data') and self.start.isEnabled(): self.pushButton_table.setEnabled(False) elif hasattr (self, 'training_data') : self.pushButton_table.setEnabled (True) self.frame_3.setGeometry (QtCore.QRect (250, 180, 500, 450)) if not hasattr (self, 'image') : self.image = QLabel (self.frame_3) self.image.setGeometry (QtCore.QRect (0,0,500, 450)) self.image.setObjectName ("image") image_list = [] global index_data csv_file = open (self.dataset_path, "r") csv_file.readline() for line in csv_file.readlines() : var = line.strip().split(',') image_list.append (var[0]) csv_file.close() self.image.setPixmap (QtGui.QPixmap (self.file_path + image_list[globals.index_data]).scaled (500, 450)) self.image.show() else : self.showTable () ## GUI def __init__(self, *args, **kwargs): super(PreprocessingImageWindow, self).__init__(*args, **kwargs) self.file_path = None self.file_name = None self.dataset_path = None self.setObjectName("self") self.resize(1280, 720) self.setAutoFillBackground(True) self.setFixedSize(1280, 720) self.centralwidget = QWidget(self) self.centralwidget.setAutoFillBackground(True) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.tabWidget = QTabWidget(self.centralwidget) self.tabWidget.setAutoFillBackground(True) self.tabWidget.setObjectName("tabWidget") ## INFO BOX: self.tab1 = QWidget() self.tab1.setAutoFillBackground(True) self.tab1.setObjectName("tab1") self.frame = QFrame(self.tab1) self.frame.setGeometry(QtCore.QRect(10, 60, 1000, 111)) self.frame.setAutoFillBackground(True) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.frame.setObjectName("frame") self.label_2 = QLabel(self.frame) self.label_2.setGeometry(QtCore.QRect(11, 10, 184, 17)) font = QtGui.QFont() font.setItalic(True) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.widget = QWidget(self.frame) self.widget.setGeometry(QtCore.QRect(100, 30, 301, 65)) self.widget.setObjectName("widget") self.verticalLayout = QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.label_instances = QLabel(self.widget) self.label_instances.setObjectName("label_instances") self.verticalLayout.addWidget(self.label_instances) self.label_classes = QLabel(self.widget) self.label_classes.setObjectName("label_classes") self.verticalLayout.addWidget(self.label_classes) ## Frame 2 PARAMETERS self.frame_2 = QFrame(self.tab1) self.frame_2.setGeometry(QtCore.QRect(1030, 60, 211, 261)) self.frame_2.setAutoFillBackground(True) self.frame_2.setFrameShape(QFrame.StyledPanel) self.frame_2.setFrameShadow(QFrame.Raised) self.frame_2.setObjectName("frame_2") self.toolBox = QToolBox(self.frame_2) self.toolBox.setGeometry(QtCore.QRect(10, 40, 191, 151)) self.toolBox.setObjectName("toolBox") self.page_resize = QWidget() self.page_resize.setGeometry(QtCore.QRect(100, 0, 191, 89)) self.page_resize.setObjectName("page_resize") self.layoutWidget = QWidget(self.page_resize) self.layoutWidget.setGeometry(QtCore.QRect(0, 0, 188, 52)) self.layoutWidget.setObjectName("layoutWidget") self.verticalLayout_2 = QVBoxLayout(self.layoutWidget) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.form = QFormLayout () self.input_length = QLineEdit() self.input_length.setValidator (QtGui.QIntValidator()) self.input_length.setObjectName("Choose_length") self.verticalLayout_2.addWidget(self.input_length) self.input_length.setEnabled (False) self.input_height = QLineEdit() self.input_height.setValidator (QtGui.QIntValidator()) self.input_height.setObjectName("Choose_height") self.verticalLayout_2.addWidget(self.input_height) self.input_height.setEnabled (False) self.form.addRow ("Length :", self.input_length) self.start = QPushButton(self.frame_2) self.start.setObjectName("pushButton_start") self.verticalLayout_2.addWidget(self.start) self.page_resize.setLayout (self.form) self.form.addRow ("height :", self.input_height) self.form.addRow (self.start) self.input_length.setText ("40") self.input_height.setText ("40") self.toolBox.addItem(self.page_resize, "") self.label_3 = QLabel(self.frame_2) self.label_3.setGeometry(QtCore.QRect(10, 10, 181, 17)) font = QtGui.QFont() font.setItalic(True) self.label_3.setFont(font) self.label_3.setObjectName("label_3") ## Frame 3 DISPLAY self.frame_3 = QFrame(self.tab1) self.frame_3.setGeometry(QtCore.QRect(10, 180, 1000, 450)) self.frame_3.setAutoFillBackground(True) self.frame_3.setFrameShape(QFrame.StyledPanel) self.frame_3.setFrameShadow(QFrame.Raised) self.frame_3.setObjectName("frame_3") ## Display matrix self.tableWidget = QTableWidget(self.frame_3) self.tableWidget.setGeometry(QtCore.QRect(0, 0, 1000, 450)) self.tableWidget.setAutoFillBackground(True) self.tableWidget.setObjectName("tableWidget") self.tableWidget.setColumnCount(0) self.tableWidget.setRowCount(0) ## Frame 4 VISUALIZATION self.frame_4 = QFrame(self.tab1) self.frame_4.setGeometry(QtCore.QRect(1030, 330, 211, 191)) self.frame_4.setFrameShape(QFrame.StyledPanel) self.frame_4.setFrameShadow(QFrame.Raised) self.frame_4.setObjectName("frame_4") ## BUTTON FOR VISUALIZATION self.pushButton_previous= QPushButton(self.frame_4) self.pushButton_previous.setGeometry(QtCore.QRect(50, 40, 121, 41)) self.pushButton_previous.setIconSize(QtCore.QSize(30, 30)) self.pushButton_previous.setAutoDefault(False) self.pushButton_previous.setDefault(False) self.pushButton_previous.setFlat(False) self.pushButton_previous.setObjectName("pushButton_previous") self.pushButton_next = QPushButton(self.frame_4) self.pushButton_next.setGeometry(QtCore.QRect(50, 85, 121, 41)) self.pushButton_next.setObjectName("pushButton_next") self.pushButton_table = QPushButton (self.frame_4) self.pushButton_table.setGeometry (QtCore.QRect (50, 130, 121, 41)) self.pushButton_table.setObjectName ("pushButton_table") ## SAVE self.frame_5 = QFrame(self.tab1) self.frame_5.setGeometry(QtCore.QRect(1080, 550, 121, 41)) self.frame_5.setFrameShape(QFrame.StyledPanel) self.frame_5.setFrameShadow(QFrame.Raised) self.frame_5.setObjectName("frame_5") self.pushButton_save = QPushButton (self.frame_5) self.pushButton_save.setGeometry (QtCore.QRect (0, 0, 121, 41)) self.pushButton_save.setObjectName ("pushButton_save") ## RETURN BUTTON self.frame_6 = QFrame(self.tab1) self.frame_6.setGeometry(QtCore.QRect(1080, 10, 121, 41)) self.frame_6.setFrameShape(QFrame.StyledPanel) self.frame_6.setFrameShadow(QFrame.Raised) self.frame_6.setObjectName("frame_6") self.pushButton_return = QPushButton (self.frame_6) self.pushButton_return.setGeometry (QtCore.QRect (0, 0, 121, 41)) self.pushButton_return.setObjectName ("pushButton_return") self.label_4 = QLabel(self.frame_4) self.label_4.setGeometry(QtCore.QRect(10, 10, 111, 17)) font = QtGui.QFont() font.setItalic(True) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.layoutWidget2 = QWidget(self.tab1) self.layoutWidget2.setGeometry(QtCore.QRect(10, 20, 611, 31)) self.layoutWidget2.setObjectName("layoutWidget2") self.horizontalLayout = QHBoxLayout(self.layoutWidget2) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.horizontalLayout.setObjectName("horizontalLayout") self.label = QLabel(self.layoutWidget2) font = QtGui.QFont() font.setItalic(True) self.label.setFont(font) self.label.setObjectName("label") self.horizontalLayout.addWidget(self.label) self.textEdit = QTextEdit(self.layoutWidget2) self.textEdit.setObjectName("textEdit") self.horizontalLayout.addWidget(self.textEdit) self.toolButton = QToolButton(self.layoutWidget2) self.toolButton.setObjectName("toolButton") self.horizontalLayout.addWidget(self.toolButton) self.valider = QPushButton(self.layoutWidget2) self.valider.setObjectName("valider") self.horizontalLayout.addWidget(self.valider) self.tabWidget.addTab(self.tab1, "") self.gridLayout.addWidget(self.tabWidget, 0, 1, 1, 1) self.setCentralWidget(self.centralwidget) self.lbl = QLabel(self.frame_3) self.lbl.setGeometry(QtCore.QRect(10, 180, 0, 381)) ## ACTIVATED OR NOT self.tableWidget.setVisible(False) self.pushButton_next.setEnabled(False) self.pushButton_previous.setEnabled(False) self.valider.setEnabled(False) self.start.setEnabled(False) self.pushButton_table.setEnabled (False) self.pushButton_save.setEnabled (False) self.toolButton.clicked.connect(self.open_dataset) self.start.clicked.connect(self.preprocess) self.pushButton_previous.clicked.connect(self.previous_state) self.pushButton_next.clicked.connect(self.next_state) self.valider.clicked.connect (self.get_dataset_information) self.pushButton_table.clicked.connect (self.showTable) self.pushButton_save.clicked.connect (self.save) p = QtGui.QPalette() p.setColor(QtGui.QPalette.Window, QtGui.QColor(133,132,130)) p.setColor(QtGui.QPalette.Button, QtGui.QColor(153,150,150)) p.setColor(QtGui.QPalette.WindowText, QtGui.QColor(13,13,12)) p.setColor(self.toolBox.backgroundRole(), QtGui.QColor(189,187,185)) p.setColor(QtGui.QPalette.ButtonText, QtGui.QColor(13,13,12)) self.setPalette(p) self.retranslateUi(self) self.tabWidget.setCurrentIndex(0) self.toolBox.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(self) def retranslateUi(self,MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Graphic Interface")) self.label_2.setText(_translate("MainWindow", "Dataset Information:")) self.label_instances.setText(_translate("MainWindow", "Number of instances:")) self.label_classes.setText(_translate("MainWindow", "Number of classes:")) self.label.setText(_translate("MainWindow", "Select a dataset:")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab1), _translate("MainWindow", "Preprocessing")) self.toolBox.setItemText(self.toolBox.indexOf(self.page_resize), _translate("MainWindow", "Resizing")) self.label_3.setText(_translate("MainWindow", "Preprocessing parameters:")) self.start.setText(_translate("MainWindow", "Start")) self.pushButton_previous.setText(_translate("MainWindow", "Previous image")) self.pushButton_next.setText(_translate("MainWindow", "Next image")) self.pushButton_table.setText (_translate ("MainWindow", "Show Matrix")) self.pushButton_save.setText (_translate ("MainWindow", "Save")) self.pushButton_return.setText (_translate ("MainWindow", "Back")) self.label_4.setText(_translate("MainWindow", "Visualization:")) self.toolButton.setText(_translate("MainWindow", "...")) self.valider.setText(_translate("MainWindow", "Validate"))