class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.find_button.clicked.connect(self.retrieve_data) self.ui.pair_button.clicked.connect(self.pair_cases) self.ui.button_update.clicked.connect(self.update_data) self.ui.button_del.clicked.connect(self.delete_data) self.ui.button_off.clicked.connect(self.add_detective) def pair_cases(self): self.pair = pair_win() self.pair.show() def retrieve_data(self): self.retrieve = retrieve_win() self.retrieve.show() def update_data(self): self.update = update_win() self.update.show() def delete_data(self): self.delete_w = delete_win() self.delete_w.show() def add_detective(self): self.detective = detective_win() self.detective.show()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("骚话王阿福") self.ui.pushButton.clicked.connect(self.btn_clicked) self.ui.action_2.triggered.connect(self.about_clicked)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # setup ui self.ui = Ui_MainWindow() self.ui.setupUi(self) # read namespace self.namespace = utils.read_ini() # other attributes self.dirname = None self.datapath = None self.jss = None # None, or PBS/LSF self.datapathtype = True # True: dir--runs_dir--datafile False: dir--datafile self.data_format = None # see self.namespace['data_format'] self.num_running_jobs = 0 # process_data is table infomation, the keys are run number, and first column stores raw data path # , other columns are consistent with tableWidget self.columnCount = self.ui.tableWidget.columnCount() self.process_data = None self.rawdata_changelog = None self.JobCenter = None # tag_buffer is {assignments:{run_name:tag_remarks}, ...} self.tag_buffer = None # setup triggers self.ui.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui.comboBox_2.currentIndexChanged.connect(self.js_changed) self.ui.comboBox.currentIndexChanged.connect(self.assignments_changed) self.ui.comboBox_3.currentIndexChanged.connect(self.decomp_changed) self.ui.pushButton.clicked.connect(self.view_job) # self.ui.pushButton_2.clicked.connect(self.view_history) self.ui.pushButton_3.clicked.connect(partial(process.parameters_setting, self)) self.ui.pushButton_6.clicked.connect(self.refresh_table) self.ui.checkBox_3.stateChanged.connect(self.autorefresh) self.ui.tableWidget.customContextMenuRequested.connect(self.table_menu) self.ui.tableWidget.cellDoubleClicked.connect(self.cell_dclicked)
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.find_button.clicked.connect(self.retrieve_data) self.ui.pair_button.clicked.connect(self.pair_cases) self.ui.button_update.clicked.connect(self.update_data) self.ui.button_del.clicked.connect(self.delete_data) self.ui.button_off.clicked.connect(self.add_detective)
def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # event self.btnGenerate.clicked.connect(self.btnGenerate_Clicked) self.btnFind.clicked.connect(self.btnFind_Clicked) self.cbxShowSteps.stateChanged.connect(self.cbxShowSteps_Clicked) self.lineEditPoint.textChanged.connect(self.lineEditPoint_TextChanged) self.lineEditLine.textChanged.connect(self.lineEditLine_TextChanged) self.countPoints = self.lineEditPoint.text() self.countLines = self.lineEditLine.text()
def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # event self.btnGenerate.clicked.connect(self.btnGenerate_Clicked) self.btnFind.clicked.connect(self.btnFind_Clicked) self.cbxShowSteps.stateChanged.connect(self.cbxShowSteps_Clicked) self.lineEditPoint.textChanged.connect(self.lineEditPoint_TextChanged) self.lineEditLine.textChanged.connect(self.lineEditLine_TextChanged) self.countPoints = self.lineEditPoint.text() self.countLines = self.lineEditLine.text() self.RADIUS = 20 self.RADIUS2 = self.RADIUS * 2 self.RADIUS3 = self.RADIUS + 3 self.SIZE = 150 self.countPoint, self.countLine, self.countStep, self.maxStep = 0, 0, 0, 0 self.newDistance, self.listSteps, self.listPath = [], [], [] self.points = [QPoint(0, 0) for i in range(20)] self.listLine = [QPoint(0, 0) for i in range(400)] self.distance = np.empty((20, 20), dtype=object) self.lines = np.empty((20, 20), dtype=Pair) self.start, self.end = -1, -1 self.isDone, self.isFounded = False, False self.chooseState = 0 self.textChoose = [ 'vuongdq85', 'Choose point start...', 'Choose point end...' ] pen = QPen(Qt.black, 2) penStart = QPen(Qt.darkGreen, 4) penDest = QPen(Qt.darkRed, 4) pencil = QPen(Qt.red, 4) # draw canvas self.scene = QGraphicsScene() self.scene.addLine(400, 100, 100, 100, pencil) self.graphicsViewPaint.setScene(self.scene) # self.reset() self.generate()
def __init__(self): """ def __init__(self): -> QMainWindow initialize the main gui """ # init super; main window QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) # remove title bar self.setWindowFlag(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # hide unrequited gui components self.ui.disable_background_frame.hide() self.ui.downloading_frame.hide() self.ui.error_frame.hide() self.ui.download_button.setEnabled(False) # import shadows self.ss = ui_shadows # set shadows self.ui.main_frame.setGraphicsEffect(self.ss.main_window_shadow) self.ui.error_frame.setGraphicsEffect(self.ss.error_frame_shadow) self.ui.downloading_frame.setGraphicsEffect( self.ss.download_frame_shadow) # connect buttons to functions self.ui.save_path_button.clicked.connect(self.openSavePath) self.ui.refresh_video_preview_button.clicked.connect(self.getVideoData) self.ui.close_button.clicked.connect(self.closeProgram) self.ui.download_button.clicked.connect(self.downloadVideoTest) self.ui.mp3_radio_button.clicked.connect(self.videoTypeAudio) self.ui.mp4_radio_button.clicked.connect(self.videoTypeVideo) self.ui.close_error_frame_button.clicked.connect(self.closeErrorFrame) self.ui.button_240p.clicked.connect(self.setQuality240p) self.ui.button_360p.clicked.connect(self.setQuality360p) self.ui.button_480p.clicked.connect(self.setQuality480p) self.ui.button_720p.clicked.connect(self.setQuality720p) self.ui.button_1080p.clicked.connect(self.setQuality1080p) # on line edit edited self.ui.video_link_line_edit.textEdited.connect(self.checkFolderValid)
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("骚话王阿福") self.ui.pushButton.clicked.connect(self.btn_clicked) self.ui.action_2.triggered.connect(self.about_clicked) def btn_clicked(self): with open(r'dict_cn_en.txt', 'r', encoding='utf-8') as fp: all_words_list = fp.readlines() random_index = random.randint(0, len(all_words_list)) self.ui.textBrowser.setText(all_words_list[random_index]) def about_clicked(self): self.new_dialog = AboutDialog() self.new_dialog.show()
def login(self): correct_user_name = "HOTEL" #User name correct_password = "******" #Password user_name = self.txt_user_name.text() password = self.txt_password.text() if (user_name == correct_user_name and password == correct_password): Dialog.hide() self.window = QtWidgets.QMainWindow() self.ui1 = Ui_MainWindow() self.ui1.setupUi(self.window) self.window.show() elif (user_name == correct_user_name): self.txt_password.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Password") msg.setIcon(QMessageBox.Critical) msg.exec_() elif (password == correct_password): self.txt_user_name.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Username") msg.setIcon(QMessageBox.Critical) msg.exec_() else: self.txt_user_name.setText("") self.txt_password.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Username\nWrong Password") msg.setIcon(QMessageBox.Critical) msg.exec_()
def __init__(self, parent=None): """ Initialize the Planetary System LRGB Aligner environment. :param parent: None """ # The (generated) QtGui class is contained in module main_gui.py. QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Insert the photo viewer into the main GUI. self.ImageWindow = PhotoViewer(self) self.ImageWindow.setObjectName("ImageWindow") self.ui.verticalLayout_3.insertWidget(1, self.ImageWindow, stretch=1) # Connect main GUI events with method invocations. self.ui.buttonLoadBW.clicked.connect(self.load_bw_image) self.ui.buttonLoadColor.clicked.connect(self.load_color_image) self.ui.buttonRegistration.clicked.connect(self.compute_registration) self.ui.buttonComputeLRGB.clicked.connect(self.compute_lrgb) self.ui.buttonSetConfigParams.clicked.connect(self.edit_configuration) self.ui.buttonSaveRegisteredColorImage.clicked.connect( self.save_registered_image) self.ui.buttonSaveLRGB.clicked.connect(self.save_lrgb_image) self.ui.buttonExit.clicked.connect(self.closeEvent) self.ui.radioShowBW.clicked.connect( lambda: self.show_pixmap(pixmap_index=0)) self.ui.radioShowColorOrig.clicked.connect( lambda: self.show_pixmap(pixmap_index=1)) self.ui.radioShowColorRigidTransform.clicked.connect( lambda: self.show_pixmap(pixmap_index=2)) self.ui.radioShowMatches.clicked.connect( lambda: self.show_pixmap(pixmap_index=3)) self.ui.radioShowColorOptFlow.clicked.connect( lambda: self.show_pixmap(pixmap_index=4)) self.ui.radioShowLRGB.clicked.connect( lambda: self.show_pixmap(pixmap_index=5)) # Initialize the path to the home directory. self.current_dir = str(Path.home()) # Initialize instance variables. self.image_reference = None self.image_reference_8bit_gray = None self.image_target = None self.image_target_8bit_gray = None self.image_dewarped = None self.image_lrgb = None self.pixmaps = [None, None, None, None, None, None] self.current_pixmap_index = None # Initialize status variables self.status_list = [ False, False, False, False, False, False, False, False ] self.status_pointer = { "initialized": 0, "bw_loaded": 1, "color_loaded": 2, "rigid_transformed": 3, "optical_flow_computed": 4, "lrgb_computed": 5, "results_saved": 6 } self.radio_buttons = [ self.ui.radioShowBW, # 0 self.ui.radioShowColorOrig, # 1 self.ui.radioShowColorRigidTransform, # 2 self.ui.radioShowMatches, # 3 self.ui.radioShowColorOptFlow, # 4 self.ui.radioShowLRGB ] # 5 self.control_buttons = [ self.ui.buttonSetConfigParams, # 0 self.ui.buttonLoadBW, # 1 self.ui.buttonLoadColor, # 2 self.ui.buttonRegistration, # 3 self.ui.buttonSaveRegisteredColorImage, # 4 self.ui.buttonComputeLRGB, # 5 self.ui.buttonSaveLRGB, # 6 self.ui.buttonExit ] # 7 self.max_button = [0, 1, 2, 4, 5, 6, 6] self.max_control_button = [2, 3, 4, 4, 6, 7, 8] self.status_busy = False # Create configuration object and set configuration parameters to standard values. self.configuration = Configuration() # Write the program version into the window title. self.setWindowTitle(self.configuration.version) # Start the workflow thread. It controls the computations and control of external devices. # By decoupling those activities from the main thread, the GUI is kept from freezing during # long-running activities. self.workflow = Workflow(self) sleep(self.configuration.wait_for_workflow_initialization) # The workflow thread sends signals during computations. Connect those signals with the # appropriate GUI activity. self.workflow.set_status_busy_signal.connect(self.set_busy) self.workflow.set_status_signal.connect(self.set_status) self.workflow.set_error_signal.connect(self.show_error_message) # Reset downstream status flags. self.set_status(0)
class LrgbAligner(QtWidgets.QMainWindow): """ This class is the main class of the "Planetary System LRGB Aligner" software. It implements the main GUI for the communication with the user. It creates the workflow thread which controls all program activities asynchronously. """ def __init__(self, parent=None): """ Initialize the Planetary System LRGB Aligner environment. :param parent: None """ # The (generated) QtGui class is contained in module main_gui.py. QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Insert the photo viewer into the main GUI. self.ImageWindow = PhotoViewer(self) self.ImageWindow.setObjectName("ImageWindow") self.ui.verticalLayout_3.insertWidget(1, self.ImageWindow, stretch=1) # Connect main GUI events with method invocations. self.ui.buttonLoadBW.clicked.connect(self.load_bw_image) self.ui.buttonLoadColor.clicked.connect(self.load_color_image) self.ui.buttonRegistration.clicked.connect(self.compute_registration) self.ui.buttonComputeLRGB.clicked.connect(self.compute_lrgb) self.ui.buttonSetConfigParams.clicked.connect(self.edit_configuration) self.ui.buttonSaveRegisteredColorImage.clicked.connect( self.save_registered_image) self.ui.buttonSaveLRGB.clicked.connect(self.save_lrgb_image) self.ui.buttonExit.clicked.connect(self.closeEvent) self.ui.radioShowBW.clicked.connect( lambda: self.show_pixmap(pixmap_index=0)) self.ui.radioShowColorOrig.clicked.connect( lambda: self.show_pixmap(pixmap_index=1)) self.ui.radioShowColorRigidTransform.clicked.connect( lambda: self.show_pixmap(pixmap_index=2)) self.ui.radioShowMatches.clicked.connect( lambda: self.show_pixmap(pixmap_index=3)) self.ui.radioShowColorOptFlow.clicked.connect( lambda: self.show_pixmap(pixmap_index=4)) self.ui.radioShowLRGB.clicked.connect( lambda: self.show_pixmap(pixmap_index=5)) # Initialize the path to the home directory. self.current_dir = str(Path.home()) # Initialize instance variables. self.image_reference = None self.image_reference_8bit_gray = None self.image_target = None self.image_target_8bit_gray = None self.image_dewarped = None self.image_lrgb = None self.pixmaps = [None, None, None, None, None, None] self.current_pixmap_index = None # Initialize status variables self.status_list = [ False, False, False, False, False, False, False, False ] self.status_pointer = { "initialized": 0, "bw_loaded": 1, "color_loaded": 2, "rigid_transformed": 3, "optical_flow_computed": 4, "lrgb_computed": 5, "results_saved": 6 } self.radio_buttons = [ self.ui.radioShowBW, # 0 self.ui.radioShowColorOrig, # 1 self.ui.radioShowColorRigidTransform, # 2 self.ui.radioShowMatches, # 3 self.ui.radioShowColorOptFlow, # 4 self.ui.radioShowLRGB ] # 5 self.control_buttons = [ self.ui.buttonSetConfigParams, # 0 self.ui.buttonLoadBW, # 1 self.ui.buttonLoadColor, # 2 self.ui.buttonRegistration, # 3 self.ui.buttonSaveRegisteredColorImage, # 4 self.ui.buttonComputeLRGB, # 5 self.ui.buttonSaveLRGB, # 6 self.ui.buttonExit ] # 7 self.max_button = [0, 1, 2, 4, 5, 6, 6] self.max_control_button = [2, 3, 4, 4, 6, 7, 8] self.status_busy = False # Create configuration object and set configuration parameters to standard values. self.configuration = Configuration() # Write the program version into the window title. self.setWindowTitle(self.configuration.version) # Start the workflow thread. It controls the computations and control of external devices. # By decoupling those activities from the main thread, the GUI is kept from freezing during # long-running activities. self.workflow = Workflow(self) sleep(self.configuration.wait_for_workflow_initialization) # The workflow thread sends signals during computations. Connect those signals with the # appropriate GUI activity. self.workflow.set_status_busy_signal.connect(self.set_busy) self.workflow.set_status_signal.connect(self.set_status) self.workflow.set_error_signal.connect(self.show_error_message) # Reset downstream status flags. self.set_status(0) def edit_configuration(self): """ This method is invoked with the "Set configuration parameters" GUI button. Open the configuration editor. If the configuration is changed, reset the workflow status to invalidate the computations done so far. :return: - """ editor = ConfigurationEditor(self.configuration) editor.exec_() if editor.configuration_changed: # If parameters have changed, a new alignment has to be computed. If both images are # available, set process status to 2. if self.current_status > 2: self.set_status(2) def load_bw_image(self): """ Load the B/W reference image from a file. Keep it together with a grayscale version. :return: - """ try: self.image_reference, self.image_reference_8bit_gray, self.image_reference_8bit_color = \ self.load_image("Load B/W reference image", 0, color=False) self.ui.radioShowBW.setChecked(True) # Set the index of the image viewer to the B/W image. The pixmap with this index will # be loaded into the viewer with the "set_status" method. self.current_pixmap_index = 0 self.set_status(1) except Exception as e: self.show_error_message( "Error in reading B/W image. Detailed message: " + str(e)) def load_color_image(self): """ Load the color target image from a file. Keep it together with a grayscale version. :return: - """ try: self.image_target, self.image_target_8bit_gray, self.image_target_8bit_color = \ self.load_image("Load color image to be registered", 1, color=True) self.ui.radioShowColorOrig.setChecked(True) self.current_pixmap_index = 1 self.set_status(2) except Exception as e: self.show_error_message( "Error in reading color image. Detailed message: " + str(e)) def load_image(self, message, pixmap_index, color=False): """ Read an image from a file. Convert it to color mode if optional parameter is set to True. :param pixmap_index: Index into the list of pixel maps used to show images in GUI. :param color: If True, convert image to color mode. If False, convert it to grayscale. :return: 3-tupel with numpy arrays with image data in three versions: - Original depth and color / grayscale - 8bit grayscale - 8bit color """ options = QtWidgets.QFileDialog.Options() filename = QtWidgets.QFileDialog.getOpenFileName( self, message, self.current_dir, "Images (*.tif *.tiff *.png *.jpg)", options=options) file_name = filename[0] if file_name == '': raise Exception("File dialog aborted") # Remember the current directory for next file dialog. self.current_dir = str(Path(file_name).parents[0]) if color: image_read = cv2.imread(file_name, cv2.IMREAD_UNCHANGED) if image_read.dtype == np.uint16: image_read_8bit_color = (image_read / 256).astype('uint8') else: image_read_8bit_color = image_read image_read_8bit_gray = cv2.cvtColor(image_read_8bit_color, cv2.COLOR_BGR2GRAY) else: image_read = cv2.imread(file_name, cv2.IMREAD_ANYDEPTH) # If color image, convert to grayscale. if len(image_read.shape) == 3: image_read = cv2.cv2.cvtColor(image_read, cv2.COLOR_BayerRG2GRAY) if image_read.dtype == np.uint16: image_read_8bit_gray = cv2.convertScaleAbs(image_read, alpha=(255.0 / 65535.0)) else: image_read_8bit_gray = image_read image_read_8bit_color = cv2.cvtColor(image_read_8bit_gray, cv2.COLOR_GRAY2BGR) # Convert image into QT pixmel map, store it in list and load it into GUI viewer. self.pixmaps[pixmap_index] = self.create_pixmap(image_read_8bit_color) self.ImageWindow.setPhoto(self.pixmaps[pixmap_index]) self.ImageWindow.fitInView() return image_read, image_read_8bit_gray, image_read_8bit_color def create_pixmap(self, cv_image): """ Transform an image in OpenCV color representation (BGR) into a QT pixmap :param cv_image: Image array :return: QT QPixmap object """ return QtGui.QPixmap( QtGui.QImage(cv_image, cv_image.shape[1], cv_image.shape[0], cv_image.shape[1] * 3, QtGui.QImage.Format_RGB888).rgbSwapped()) def show_pixmap(self, pixmap_index=None): """ Load a pixmap into the GUI image viewer. Adapt the view scale according to the relative sizes of the new and old pixmaps. :param pixmap_index: Index of the selected pixmap in the list. If not selected, the current index is taken. :return: - """ if pixmap_index is None: pixmap_index = self.current_pixmap_index if self.pixmaps[pixmap_index] is not None: self.current_pixmap_index = pixmap_index # Get the ratio of old pixmap and viewport sizes. factor_old = self.ImageWindow.fitInView(scale=False) # Load the new pixmap. self.ImageWindow.setPhoto(self.pixmaps[pixmap_index]) # Get the ratio of new pixmap and viewport sizes. factor_new = self.ImageWindow.fitInView(scale=False) if factor_old is not None: # Scale the view by the relative size factors. factor = factor_new / factor_old self.ImageWindow.scale(factor, factor) def compute_registration(self): """ If both B/W and color images are available, start the registration process. :return: - """ if self.image_reference is not None and self.image_target is not None: # Tell the workflow thread to compute a new alignment. self.workflow.compute_alignment_flag = True def compute_lrgb(self): """ If both B/W and color images are available, start the registration process. :return: - """ if self.image_reference is not None and self.image_dewarped is not None: # Tell the workflow thread to compute a new alignment. self.workflow.compute_lrgb_flag = True def save_registered_image(self): """ Open a file chooser dialog and save the de-warped image. :return: - """ try: self.save_image( "Select location to store the registered color image", self.image_dewarped) # Udpate the status line. self.set_status(6) except: pass def save_lrgb_image(self): """ Open a file chooser dialog and save the combined LRBG image. :return: - """ try: self.save_image("Select location to store the combined LRGB image", self.image_lrgb) # Udpate the status line. self.set_status(6) except: pass def save_image(self, message, image): """ Open a file chooser. If a valid file name is selected, store the image to that location. :param message: Text to be displayed in the file chooser window. :param image: Image file :return: - """ options = QtWidgets.QFileDialog.Options() filename = QtWidgets.QFileDialog.getSaveFileName( self, message, self.current_dir, "Images (*.tif *.tiff *.png *.jpg)", options=options) # Store image only if the chooser did not return with a cancel. file_name = filename[0] if file_name != "": my_file = Path(file_name) # Remember the current directory for next file dialog. self.current_dir = str(my_file.parents[0]) if my_file.is_file(): os.remove(str(my_file)) if my_file.suffix == '.tif' or my_file.suffix == '.tiff': cv2.imwrite(file_name, image) elif image.dtype == np.uint16: image_8bit = (image / 256).astype('uint8') cv2.imwrite(file_name, image_8bit) else: cv2.imwrite(file_name, image) else: raise Exception("File dialog aborted") def set_busy(self, busy): """ Set the "busy" status flag and update the status bar. :param busy: True, if the workflow thread is active in a computation. False, otherwise. :return: - """ if busy: for button in self.control_buttons[0:7]: button.setEnabled(False) else: self.set_status(self.current_status) self.status_busy = busy self.set_statusbar() def set_status(self, status): """ Enable radio buttons to show images in GUI and set the status bar according to the workflow status. :param status: Status variable :return: - """ # Store current status. self.current_status = status # Set the current status. self.status_list[status] = True # Reset all downstream status variables to False. self.status_list[status + 1:] = [False] * (len(self.status_list) - status - 1) if status != 6: # Enable radio buttons which can be used at this point: for button in self.radio_buttons[:self.max_button[status]]: button.setEnabled(True) # Disable the radio buttons for showing images which do not exist at this point. for button in self.radio_buttons[self.max_button[status]:]: button.setEnabled(False) if not self.status_busy: # Enable control buttons which can be used at this point: for button in self.control_buttons[:self. max_control_button[status]]: button.setEnabled(True) # Disable the control buttons which do not make sense at this point. for button in self.control_buttons[ self.max_control_button[status]:-1]: button.setEnabled(False) if self.configuration.skip_rigid_transformation: self.ui.radioShowColorRigidTransform.setEnabled(False) self.ui.radioShowMatches.setEnabled(False) if self.configuration.skip_optical_flow: self.ui.radioShowColorOptFlow.setEnabled(False) # Refresh the image viewer. if self.current_pixmap_index is not None: self.show_pixmap() # Update the status bar. self.set_statusbar() def set_statusbar(self): """ The status bar at the bottom of the main GUI summarizes various infos on the process status. Read out flags to decide which infos to present. The status information is concatenated into a single "status_text" which eventually is written into the main GUI status bar. :return: - """ status_text = "" # Tell if input images are loaded. if self.status_list[self.status_pointer["initialized"]]: status_text += "Process initialized" # Tell if input images are loaded. if self.status_list[self.status_pointer["bw_loaded"]]: if self.status_list[self.status_pointer["color_loaded"]]: status_text += ", B/W reference and color frames loaded" else: status_text += ", B/W reference frame loaded" # Tell if rigid transformation is done. if not self.configuration.skip_rigid_transformation: if self.status_list[self.status_pointer["rigid_transformed"]]: status_text += ", rigid transformation computed" # Tell if optical flow has been computed. if not self.configuration.skip_optical_flow: if self.status_list[self.status_pointer["optical_flow_computed"]]: status_text += ", images pixel-wise aligned" # Tell if the LRGB image is computed. if self.status_list[self.status_pointer["lrgb_computed"]]: status_text += ", LRGB image computed" # Tell if results are written to disk. if self.status_list[self.status_pointer["results_saved"]]: status_text += ", results written to disk" # Tell if the workflow thread is busy at this point. if self.status_busy: status_text += ", busy" # Write the complete message to the status bar. self.ui.statusbar.showMessage(status_text) def show_error_message(self, message): """ Show an error message. This method is invoked from the workflow thread via the "set_error_signal" signal. :param message: Error message to be displayed :return: - """ error_dialog = QtWidgets.QErrorMessage(self) error_dialog.setMinimumSize(400, 0) error_dialog.setWindowTitle(self.configuration.version) error_dialog.showMessage(message) def closeEvent(self, evnt): """ This event is triggered when the user closes the main window by clicking on the cross in the window corner. :param evnt: event object :return: - """ self.workflow.exiting = True sleep(4. * self.configuration.polling_interval) sys.exit(0)
class Window(QMainWindow): """class Window(QMainWindow): -> QMainWindow main widow for app.""" def __init__(self): """ def __init__(self): -> QMainWindow initialize the main gui """ # init super; main window QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) # remove title bar self.setWindowFlag(QtCore.Qt.FramelessWindowHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) # hide unrequited gui components self.ui.disable_background_frame.hide() self.ui.downloading_frame.hide() self.ui.error_frame.hide() self.ui.download_button.setEnabled(False) # import shadows self.ss = ui_shadows # set shadows self.ui.main_frame.setGraphicsEffect(self.ss.main_window_shadow) self.ui.error_frame.setGraphicsEffect(self.ss.error_frame_shadow) self.ui.downloading_frame.setGraphicsEffect( self.ss.download_frame_shadow) # connect buttons to functions self.ui.save_path_button.clicked.connect(self.openSavePath) self.ui.refresh_video_preview_button.clicked.connect(self.getVideoData) self.ui.close_button.clicked.connect(self.closeProgram) self.ui.download_button.clicked.connect(self.downloadVideoTest) self.ui.mp3_radio_button.clicked.connect(self.videoTypeAudio) self.ui.mp4_radio_button.clicked.connect(self.videoTypeVideo) self.ui.close_error_frame_button.clicked.connect(self.closeErrorFrame) self.ui.button_240p.clicked.connect(self.setQuality240p) self.ui.button_360p.clicked.connect(self.setQuality360p) self.ui.button_480p.clicked.connect(self.setQuality480p) self.ui.button_720p.clicked.connect(self.setQuality720p) self.ui.button_1080p.clicked.connect(self.setQuality1080p) # on line edit edited self.ui.video_link_line_edit.textEdited.connect(self.checkFolderValid) ##################### ### WIP FUNCTIONS ### ##################### def videoTypeVideo(self): """def videoTypeVideo(self): -> self download the video as a mp4 file. WIP""" global video_type video_type = "mp4" print(video_type) def videoTypeAudio(self): """def videoTypeAudio(self): -> self download the video as a mp3 file. WIP""" global video_type video_type = "mp3" print(video_type) #################### ### UI FUNCTIONS ### #################### def setQuality240p(self): """def setQuality240p(self): -> self set video quality to 240p""" # globals global video_quality_new global video_quality_current video_quality_new = "240p" if video_quality_current != video_quality_new: self.animateVideoQuality() def setQuality360p(self): """def setQuality360p(self): -> self set video quality to 360p""" # globals global video_quality_new global video_quality_current video_quality_new = "360p" if video_quality_current != video_quality_new: self.animateVideoQuality() def setQuality480p(self): """def setQuality480p(self): -> self set video quality to 480p""" # globals global video_quality_new global video_quality_current video_quality_new = "480p" if video_quality_current != video_quality_new: self.animateVideoQuality() def setQuality720p(self): """def setQuality720p(self): -> self set video quality to 720p""" # globals global video_quality_new global video_quality_current video_quality_new = "720p" if video_quality_current != video_quality_new: self.animateVideoQuality() def setQuality1080p(self): """def setQuality1080p(self): -> self set video quality to 1080p""" # globals global video_quality_new global video_quality_current video_quality_new = "1080p" if video_quality_current != video_quality_new: self.animateVideoQuality() def openSavePath(self): """def openSavePath(self): -> self open the file dialog frame on button press""" # globals global video_folder_path global video_link # file dialog dialog = QtWidgets.QFileDialog() self.video_save_path = dialog.getExistingDirectory( None, "Select Folder") folder_name = os.path.basename(self.video_save_path) # get folder name video_folder_path = self.video_save_path # set folder text in gui username = getpass.getuser() # get username self.ui.file_location_line_edit.setText("C:\\Users\\" + str(username) + "\\...\\" + folder_name) video_link = self.ui.video_link_line_edit.text() # set download button enabled self.ui.download_button.setEnabled(True) def openDownloadedVideo(self): """def openDownloadedVideo(self): -> self open the file the download video is located in after downloading is complete.""" # globals global video_folder_path global video_valid if video_valid: # open folder import os os.startfile(str(video_folder_path)) video_valid = False def checkFolderValid(self): """def checkFolderValid(self): -> self check if file path is valid.""" # globals global video_folder_path global video_link video_link = self.ui.video_link_line_edit.text() if video_folder_path is not None: self.ui.download_button.setEnabled(True) def closeProgram(self): """def closeProgram(self): -> self exit the program""" app.quit() # quit def updateBar(self): """def updateBar(self): -> self update the video download progress bar.""" global video_progress self.ui.video_downloading_progress_bar.setValue(video_progress) def showErrorFrame(self): """def showErrorFrame(self): -> self show error frame.""" self.ui.downloading_frame.hide() self.ui.disable_background_frame.show() self.ui.error_frame.show() self.ui.error_message_line_edit.setText("Invalid Link!") def showErrorFrameQuality(self): """def showErrorFrame(self): -> self show error frame.""" self.ui.downloading_frame.hide() self.ui.disable_background_frame.show() self.ui.error_frame.show() self.ui.error_message_line_edit.setText("Video Quality Too High!") def closeErrorFrame(self): """def closeErrorFrame(self): -> self close the error frame.""" # globals global video_quality_array global max_video_quality self.ui.disable_background_frame.hide() self.ui.error_frame.hide() self.thread.quit() video_quality_array = [] max_video_quality = 0 ################## ### ANIMATIONS ### ################## def animateVideoQuality(self): """def animateVideoQuality(self): -> self animate the highlight QRect over the current selected video quality.""" # globals global video_quality_current global video_quality_new global quality_x_pos # animation self.animation = QPropertyAnimation( self.ui.video_quality_highlighter_frame, b"geometry") self.animation.setDuration(300) self.animation.setStartValue( QRect(int(quality_x_pos[str(video_quality_current)]), 4, 40, 42)) self.animation.setEndValue( QRect(int(quality_x_pos[str(video_quality_new)]), 4, 40, 42)) self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart) self.animation.start() # finish video_quality_current = video_quality_new ################## ### SUBPROCESS ### ################## def downloadVideoTest(self): """def downloadVideoTest(self): -> self run the subprocess to download videos.""" # globals global video_link global video_title global video_views global video_author global video video_link = self.ui.video_link_line_edit.text() self.thread = QThread() self.worker = DownloadVideo() self.worker.moveToThread(self.thread) # connect subprocess functions self.thread.started.connect(self.worker.run) self.worker.finished.connect(self.thread.quit) self.worker.finished.connect(self.worker.deleteLater) self.thread.finished.connect(self.thread.deleteLater) self.worker.progress.connect(self.updateBar) # run subprocess self.thread.start() self.ui.downloading_frame.show() self.ui.disable_background_frame.show() self.worker.invalid.connect(self.showErrorFrame) self.worker.quality.connect(self.showErrorFrameQuality) self.thread.finished.connect(lambda: self.ui.downloading_frame.hide()) self.thread.finished.connect( lambda: self.ui.disable_background_frame.hide()) self.thread.finished.connect( lambda: self.ui.video_downloading_progress_bar.setValue(0)) self.thread.finished.connect(self.openDownloadedVideo) def getVideoDataSubprocess(self): """def getVideoDataSubprocess(self): start the subprocess to get youtube video data.""" # globals global video_author global video_title global video_views # init subprocess self.video_data_thread = QThread() self.video_data_worker = GetVideoInfo() self.video_data_worker.moveToThread(self.video_data_thread) # connect subprocess functions self.video_data_thread.started.connect(self.video_data_worker.run) # self.video_data_thread.started.connect(self.update) self.video_data_worker.finished.connect(self.video_data_thread.quit) self.video_data_worker.finished.connect( self.video_data_worker.deleteLater) self.video_data_thread.finished.connect( self.video_data_thread.deleteLater) # run subprocess self.video_data_thread.start() self.ui.download_button.setEnabled(False) # on subprocess finished connect self.video_data_thread.finished.connect( lambda: self.ui.download_button.setEnabled(True)) self.video_data_thread.finished.connect( lambda: self.ui.video_author_text.setText(video_author)) self.video_data_thread.finished.connect( lambda: self.ui.video_title_text.setText(video_title)) self.video_data_thread.finished.connect( lambda: self.ui.views_text.setText(str(video_views))) def getVideoData(self): """def getVideoData(self): -> self check if link is valid to get video data if true start subprocess else display error.""" # globals global video_link global video_folder_path video_link = self.ui.video_link_line_edit.text() # get video link if not isLinkValid(video_link): self.ui.video_title_text.setText("Invalid Youtube Video Link!") self.ui.video_author_text.setText("") self.ui.views_text.setText("") else: self.ui.video_title_text.setText("Fetching Data...") self.ui.video_author_text.setText("") self.ui.views_text.setText("") self.getVideoDataSubprocess()
ui.valBidding.setText(summary_data[1]) ui.valWon.setText(summary_data[2]) ui.valNotWon.setText(summary_data[3]) ui.valPurchases.setText(summary_data[4]) ui.valInvoices.setText(summary_data[5]) # Change status bar message def status_msg(msg): ui.statusbar.showMessage(msg) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() connections() # Load credentials from file. with open("login.txt") as f: credentials = f.readline().strip().split(":") # Login, download summary, then refresh the UI. b = Biddergy(credentials[0], credentials[1]) request_queue = queue.Queue() bw = BiddergyWrapper(request_queue) bw.start() # Run QApplication
import ml_models as md from main_gui import QtCore, QtWidgets, Ui_MainWindow from controller import ViewController import controller import sys app = QtCore.QCoreApplication.instance() if app is None: app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) user_ML_model = md.machineLearningModel() view_controller = ViewController(ui, user_ML_model) MainWindow.show() sys.exit(app.exec_())
class SPIPY_MAIN(QtGui.QMainWindow, QtCore.QEvent): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) # setup ui self.ui = Ui_MainWindow() self.ui.setupUi(self) # read namespace self.namespace = utils.read_ini() # other attributes self.dirname = None self.datapath = None self.jss = None # None, or PBS/LSF self.datapathtype = True # True: dir--runs_dir--datafile False: dir--datafile self.data_format = None # see self.namespace['data_format'] self.num_running_jobs = 0 # process_data is table infomation, the keys are run number, and first column stores raw data path # , other columns are consistent with tableWidget self.columnCount = self.ui.tableWidget.columnCount() self.process_data = None self.rawdata_changelog = None self.JobCenter = None # tag_buffer is {assignments:{run_name:tag_remarks}, ...} self.tag_buffer = None # setup triggers self.ui.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.ui.comboBox_2.currentIndexChanged.connect(self.js_changed) self.ui.comboBox.currentIndexChanged.connect(self.assignments_changed) self.ui.comboBox_3.currentIndexChanged.connect(self.decomp_changed) self.ui.pushButton.clicked.connect(self.view_job) # self.ui.pushButton_2.clicked.connect(self.view_history) self.ui.pushButton_3.clicked.connect(partial(process.parameters_setting, self)) self.ui.pushButton_6.clicked.connect(self.refresh_table) self.ui.checkBox_3.stateChanged.connect(self.autorefresh) self.ui.tableWidget.customContextMenuRequested.connect(self.table_menu) self.ui.tableWidget.cellDoubleClicked.connect(self.cell_dclicked) def setup(self, workpath, datapath, jss, datapathtype, format_index): self.jss = jss self.dirname = workpath self.datapath = datapath self.datapathtype = datapathtype self.data_format = self.namespace['data_format'][format_index] # setup job center self.JobCenter = jobc.JobCenter(self.jss, self.dirname, self.data_format, self) # load table self.process_data = utils.load_table(os.path.join(self.dirname, self.namespace['project_structure'][0])) # load table change log, if there exists self.rawdata_changelog = utils.load_changelog(os.path.join(self.dirname, self.namespace['project_structure'][0])) # set up tag_buffer self.tag_buffer = {} for assm in self.namespace['process_assignments']: self.tag_buffer[assm] = {} # write jss to UI if self.jss is not None: self.ui.comboBox_2.addItem(self.jss) # setup all tabWidgets # setup process for assm in self.namespace['process_assignments']: self.ui.comboBox.addItem(assm) self.ui.tableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Interactive) self.ui.label_73.setText( utils.fmt_process_status(self.data_format) ) self.ui.pushButton_2.setVisible(False) # setup classify for decp in self.namespace['classify_decomp']: self.ui.comboBox_3.addItem(decp) self.ui.lineEdit.setText(os.path.join(os.path.join(self.dirname, \ self.namespace['project_structure'][0]), self.namespace['process_HF'])) self.ui.lineEdit_2.setText("Hits/data") self.ui.widget_12.setVisible(False) self.ui.widget_11.setVisible(False) # setup merge for sym in self.namespace['merge_sym']: self.ui.comboBox_5.addItem(sym) # setup phasing for method in self.namespace['phasing_method']: self.ui.comboBox_9.addItem(method) self.ui.comboBox_10.addItem(method) self.ui.comboBox_11.addItem(method) # setup monitors self.table_monitor = None # draw table self.refresh_table() def closeEvent(self, event): #self.JobCenter.write_job_hub() utils.print2projectLog(self.dirname, "Close spipy GUI.") QtGui.qApp.quit() def js_changed(self, index): if self.ui.comboBox_2.itemText(index) == "PBS": if not utils.check_PBS(): utils.show_message("No PBS detected !") self.ui.comboBox_2.setCurrentIndex(0) else: self.jss = str(self.ui.comboBox_2.currentText()) else: pass self.JobCenter.setjss(self.jss) """ Process Tab """ # ----------------------------------- # # tag remarks format processing start # # run folder name format: # .../run.tag.remarks/... # ------------------------------------ # def get_existing_runtags(self, assignments, run_name): ''' return [['tag','remarks'], ...] ''' module_name = self.namespace['project_structure'][0] path = os.path.join(self.dirname, module_name, '%s/%s.*' % (assignments, run_name)) tags = glob.glob(path) tags = [os.path.split(tmp)[-1].split('.')[1:] for tmp in tags] return tags def get_latest_runtag(self, assignments, run_name): ''' return ['tag','remarks'] ''' module_name = self.namespace['project_structure'][0] path = os.path.join(self.dirname, module_name, '%s/%s.*' % (assignments, run_name)) tags = glob.glob(path) latest = "--" time = 0 for tag in tags: timestamp = os.path.getmtime(tag) if timestamp > time: time = timestamp latest = tag if latest == "--": return latest else: return os.path.split(latest)[-1].split('.')[1:] def is_existed_runtag(self, assignments, run_name, run_tag_remarks): try: tag, remarks = self.split_tag_remarks(run_tag_remarks) except: return False module_name = self.namespace['project_structure'][0] path = os.path.join(self.dirname, module_name, '%s/%s.%s.%s' % (assignments, run_name, tag, remarks)) if os.path.isdir(path): return True else: return False def combine_tag_remarks(self, tag_remarks): if type(tag_remarks) == str: return tag_remarks else: return tag_remarks[0] + '.' + tag_remarks[1] def split_tag_remarks(self, tag_remarks): return tag_remarks.split('.') # --------------------------------- # # tag remarks format processing end # # --------------------------------- # def assignments_changed(self, index): # change combobox in table # refresh table ? self.refresh_table() def cell_dclicked(self, row, column): '''table cell double clicked run tag changing ''' if column != 1: return assignments = str(self.ui.comboBox.currentText()) #if assignments != self.namespace['process_HF']: # return run_name = str(self.ui.tableWidget.item(row, 0).text()) run_tag_remarks = self.get_existing_runtags(assignments, run_name) choices = [] for tmp in run_tag_remarks: choices.append(self.combine_tag_remarks(tmp)) ret = [None] chosebox.show_chosebox("Tags", choices, ret, "%s.%s" % (run_name, assignments)) if ret[0] is not None: self.process_data[run_name][1] = choices[ret[0]] self.draw_table(sel_rows = [row]) def table_menu(self, position): """ entrance to submit jobs """ # selected cells selected_runs = [] selected_tag_remarks = {} selected_datafile = {} for pos in self.ui.tableWidget.selectionModel().selection().indexes(): row = pos.row() run_name = str(self.ui.tableWidget.item(row, 0).text()) if len(self.process_data[run_name][0]) == 0: utils.show_message("Run %s does not contain any data. Skip." % run_name) continue tag_remarks_name = str(self.ui.tableWidget.item(row, 1).text()) selected_runs.append(run_name) selected_tag_remarks[run_name] = self.split_tag_remarks(tag_remarks_name) selected_datafile[run_name] = self.process_data[run_name][0] # show menu if len(selected_runs) > 0: # get assignments assignments = str(self.ui.comboBox.currentText()) # show menu menu = QtGui.QMenu() a1 = menu.addAction("Run %s" % assignments) menu.addSeparator() # a2 = menu.addAction("Terminate all") menu_sub = menu.addMenu("Terminate") b = [] if len(selected_runs) > 1: for assign in self.namespace['process_assignments']: b.append(menu_sub.addAction(assign)) if selected_tag_remarks[selected_runs[0]][0] != "--": menu.addSeparator() a4 = menu.addAction("Open %s results in data viewer" % assignments) elif len(selected_runs) == 1: run_tag_remarks = self.get_existing_runtags(assignments, selected_runs[0]) for tr in run_tag_remarks: tr_status = self.JobCenter.get_run_status(selected_runs[0], self.namespace['project_structure'][0], assignments, tr[0], tr[1]) if tr_status == self.JobCenter.RUN: b.append( menu_sub.addAction("%s.%s.%s.%s" % (assignments, selected_runs[0], tr[0], tr[1])) ) menu.addSeparator() if selected_tag_remarks[selected_runs[0]][0] == "darkcal": a4 = menu.addAction("Set as current darkcal") elif selected_tag_remarks[selected_runs[0]][0] != "--": a4 = menu.addAction("Open %s results in data viewer" % assignments) else: a4 = 0 else: pass # exec action = menu.exec_(self.ui.tableWidget.mapToGlobal(position)) # parse selection job_type = self.namespace['project_structure'][0] + "/" + assignments if action == a1: utils.print2projectLog(self.dirname, "Choose %s on %s" % (assignments, str(selected_runs))) self.JobCenter.TableRun_showoff(job_type, selected_runs, selected_datafile, selected_tag_remarks) #elif action == a2: # print("Terminate all jobs of %s" % str(selected_runs)) elif len(selected_runs) == 1 and action == a4: if selected_tag_remarks[selected_runs[0]][0] == "darkcal": # re-link current-darkcal.h5 tmp_darkfile = utils.fmt_job_dir(selected_runs[0], \ selected_tag_remarks[selected_runs[0]][0], selected_tag_remarks[selected_runs[0]][1]) tmp_darkfile = os.path.join(self.dirname, self.namespace['project_structure'][0], self.namespace['process_HF'], tmp_darkfile) try: tmp_darkfile = glob.glob(os.path.join(tmp_darkfile, "*darkcal.h5"))[0] except: utils.show_message("I cannot find ?.darkcal.h5 in this run. Fail to set current darkcal.") return tmp_curr_darklink = os.path.join(self.dirname, self.namespace['project_structure'][0], self.namespace['process_HF'], self.namespace['darkcal']) prev_dark_run = None if os.path.exists(tmp_curr_darklink): prev_dark_run = subprocess.check_output("ls -l %s | awk -F'->' '{print $2}' | tr -d ' '" % tmp_curr_darklink, shell=True) prev_dark_run = os.path.split(prev_dark_run.strip("\n"))[-1].split('.')[0] subprocess.check_call("ln -fs %s %s" % (tmp_darkfile, tmp_curr_darklink), shell=True) # refresh table info if prev_dark_run is not None: self.process_data[prev_dark_run][6] = "--" self.process_data[selected_runs[0]][6] = "Current-Darkcal" utils.print2projectLog(self.dirname, "Set %s as current darkcal" % selected_runs[0]) # draw table self.draw_table() else: # open data viewer and add files tmp = utils.fmt_job_dir(selected_runs[0], \ selected_tag_remarks[selected_runs[0]][0], selected_tag_remarks[selected_runs[0]][1]) tmp = os.path.join(self.dirname, self.namespace['project_structure'][0], assignments, tmp, '*.h5') tmp = glob.glob(tmp) if not data_viewer.is_shown(): data_viewer.show_data_viewer(self) data_viewer.add_files(tmp) utils.print2projectLog(self.dirname, "Add %s results of %s to data viewer." % (assignments, selected_runs[0])) elif len(selected_runs) == 1 and action in b: tmp = str(action.text()).split('.') jid = self.JobCenter.get_jid(tmp[0], tmp[1], tmp[2], tmp[3]) re = utils.show_warning("Terminate job %d of %s ?" % (jid, str(selected_runs))) if re == 1: tmp = self.JobCenter.kill_job(jid) if tmp[0] == 1: utils.print2projectLog(self.dirname, "Terminate job %d of %s" % (jid, str(selected_runs))) utils.show_message("Job %s is successfully terminated" % str(action.text())) else: utils.print2projectLog(self.dirname, "Fail to terminate job %d of %s" % (jid, str(selected_runs))) utils.show_message("**FAIL** to terminate job !" % str(action.text())) # refresh self.update_table_runs() self.draw_table() elif len(selected_runs) > 1 and action in b: assign = str(action.text()) all_jid = [] for run_name in selected_runs: tag_remarks = self.get_existing_runtags(assign, run_name) for tr in tag_remarks: tr_status = self.JobCenter.get_run_status(run_name, self.namespace['project_structure'][0], assign, tr[0], tr[1]) if tr_status == self.JobCenter.RUN: tmp_jid = self.JobCenter.run_view[utils.fmt_runview_key(assign, run_name, tr[0], tr[1])] all_jid.append(tmp_jid) re = utils.show_warning("Terminate all these %d jobs ?" % len(all_jid)) if re == 1: killed = 0 for tmp_jid in all_jid: killed += self.JobCenter.kill_job(jid) utils.print2projectLog("Terminate %d %s jobs of %s" % (killed, assign, str(selected_runs))) utils.show_message("Successfully terminate %d jobs" % killed) # refresh self.update_table_runs() self.draw_table() elif len(selected_runs) > 1 and action == a4: if not data_viewer.is_shown(): data_viewer.show_data_viewer(self) for selected_run in selected_runs: tmp = utils.fmt_job_dir(selected_run, \ selected_tag_remarks[selected_run][0], selected_tag_remarks[selected_run][1]) tmp = os.path.join(self.dirname, self.namespace['project_structure'][0], assignments, tmp, '*.h5') tmp = glob.glob(tmp) data_viewer.add_files(tmp) utils.print2projectLog(self.dirname, "Add %s results of %s to data viewer." % (assignments, str(selected_runs))) else: pass else: menu = QtGui.QMenu() if self.ui.tableWidget.horizontalHeader().resizeMode(0) == QtGui.QHeaderView.Stretch: a1 = menu.addAction("Unfill table window") else: a1 = menu.addAction("Fill table window") menu.addSeparator() a2 = menu.addAction("Set 'force overwrite' to %s" % str(not self.JobCenter.force_overwrite)) action = menu.exec_(self.ui.tableWidget.mapToGlobal(position)) if action == a1: if self.ui.tableWidget.horizontalHeader().resizeMode(0) == QtGui.QHeaderView.Stretch: self.ui.tableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Interactive) else: self.ui.tableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) elif action == a2: self.JobCenter.reverseForceOverwrite() else: pass def update_table_runs(self): if not os.path.isdir(self.datapath): utils.show_message("Data directory is invalid, please reopen the software.") return # subdir ? if not self.datapathtype: all_in_dir = utils.parse_multi_runs_nosubdir(self.datapath, self.data_format) else: all_in_dir = [f for f in os.listdir(self.datapath) if "." not in f and f[0]!="$" \ and os.path.isdir(os.path.join(self.datapath, f))] prev_runs = self.process_data.keys() prev_runs_checked = [0] * len(prev_runs) run_name = "" run_streams_num = "0" # go through alll files/dirs # detect raw data status for d in all_in_dir: # parse run name if not self.datapathtype: tmp = d.split("?_?^=^") # this magic code, defined in utils.parse_multi_runs_nosubdir run_name = tmp[0] run_streams_num = tmp[1] else: run_name = d # check avaliable if run_name not in prev_runs: # init process_data & rawdata_changelog self.process_data[run_name] = ['--'] * self.columnCount self.rawdata_changelog[run_name] = {} # update process_data if not self.datapathtype: self.process_data[run_name][0] = utils.parse_multi_run_streams(self.datapath, run_name, self.data_format, False) self.process_data[run_name][2] = self.namespace['process_status'][0] + " (%s)" % run_streams_num else: subpath = os.path.join(self.datapath, d) datafile = utils.parse_multi_run_streams(subpath, run_name, self.data_format) if len(datafile) >= 1: self.process_data[run_name][0] = datafile run_streams_num = str(len(datafile)) self.process_data[run_name][2] = self.namespace['process_status'][0] + " (%s)" % run_streams_num else: self.process_data[run_name][0] = [] self.process_data[run_name][2] = self.namespace['process_status'][5] else: prevdatafile = self.process_data[run_name][0] if not self.datapathtype: datafile = utils.parse_multi_run_streams(self.datapath, run_name, self.data_format, False) run_streams_num = str(len(datafile)) if len(datafile) == 0: # deleted tmp = self.process_data.pop(run_name) self.rawdata_changelog[run_name].update(utils.rawdata_changelog(prevdatafile, None)) elif len( (set(datafile) | set(prevdatafile)) - (set(datafile) & set(prevdatafile)) ) != 0: # changed self.process_data[run_name][2] = self.namespace['process_status'][6] + " (%s)" % run_streams_num self.process_data[run_name][0] = datafile self.rawdata_changelog[run_name].update(utils.rawdata_changelog(prevdatafile, datafile)) else: # stays still self.process_data[run_name][2] = self.namespace['process_status'][0] + " (%s)" % run_streams_num self.process_data[run_name][0] = datafile else: subpath = os.path.join(self.datapath, d) datafile = utils.parse_multi_run_streams(subpath, run_name, self.data_format) run_streams_num = str(len(datafile)) if len(datafile) == 0: # no data self.process_data[run_name][0] = [] self.process_data[run_name][2] = self.namespace['process_status'][5] self.rawdata_changelog[run_name].update(utils.rawdata_changelog(prevdatafile, None)) elif len( (set(datafile) | set(prevdatafile)) - (set(datafile) & set(prevdatafile)) ) != 0: # changed self.process_data[run_name][2] = self.namespace['process_status'][6] + " (%s)" % run_streams_num self.process_data[run_name][0] = datafile self.rawdata_changelog[run_name].update(utils.rawdata_changelog(prevdatafile, datafile)) else: # stays still self.process_data[run_name][2] = self.namespace['process_status'][0] + " (%s)" % run_streams_num self.process_data[run_name][0] = datafile prev_runs_checked[prev_runs.index(run_name)] = 1 for i,c in enumerate(prev_runs_checked): if c == 0 : run_name = prev_runs[i] tmp = self.process_data.pop(run_name) self.rawdata_changelog[run_name].update(utils.rawdata_changelog(tmp[0], "This run is Deleted")) # go through all job dir # detect job status # self.process_data[run_name][1] shows only hit-finding prev_runs = self.process_data.keys() hf_module = self.namespace['project_structure'][0] self.num_running_jobs = 0 for i,run_name in enumerate(prev_runs): self.process_data[run_name][3:6] = ['--'] * 3 # get tag # assignments = self.namespace['process_HF'] assignments = str(self.ui.comboBox.currentText()) if not (self.tag_buffer[assignments].has_key(run_name) and self.is_existed_runtag(assignments, run_name, self.tag_buffer[assignments][run_name])): tag_remarks = self.get_latest_runtag(str(assignments), run_name) self.process_data[run_name][1] = self.combine_tag_remarks(tag_remarks) else: self.process_data[run_name][1] = self.tag_buffer[assignments][run_name] # get jobs status for aindex in range(self.ui.comboBox.count()): assignments_tmp = str(self.ui.comboBox.itemText(aindex)) # get tag from processe_data or tag_buffer or fresh data ? if assignments_tmp == assignments: tag_remarks = self.split_tag_remarks(self.process_data[run_name][1]) else: try: tag_remarks = self.split_tag_remarks(self.tag_buffer[assignments_tmp][run_name]) except: tag_remarks = self.get_latest_runtag(assignments_tmp, run_name) # tag_remarks is ['tag','remarks'] if type(tag_remarks) != list or len(tag_remarks) != 2: continue job_status = self.JobCenter.get_run_status(run_name, hf_module, assignments_tmp, tag_remarks[0], tag_remarks[1]) if job_status is None: job_status = "--" elif job_status == self.JobCenter.RUN: self.num_running_jobs += 1 else: pass if assignments_tmp == self.namespace['process_HF']: self.process_data[run_name][3] = job_status elif assignments_tmp == self.namespace['process_FA']: self.process_data[run_name][4] = job_status elif assignments_tmp == self.namespace['process_FAA']: self.process_data[run_name][4] = job_status elif assignments_tmp == self.namespace['process_AP']: self.process_data[run_name][5] = job_status else: pass # get hit rate # output status format : see scripts/HitFinder.py if assignments != self.namespace['process_HF']: try: tag_remarks = self.tag_buffer[self.namespace['process_HF']][run_name] tag_remarks = self.split_tag_remarks(tag_remarks) except: tag_remarks = '--' else: tag_remarks = self.split_tag_remarks(self.process_data[run_name][1]) if type(tag_remarks) != list or len(tag_remarks) < 2: self.process_data[run_name][6] = '--' continue elif tag_remarks[0].lower() == "darkcal": if self.process_data[run_name][6] != "Current-Darkcal": self.process_data[run_name][6] = '--' continue hf_status = os.path.join(self.dirname, hf_module, '%s/%s.%s.%s/status' % \ (self.namespace['process_HF'], run_name, tag_remarks[0], tag_remarks[1])) if not os.path.isdir(hf_status): self.process_data[run_name][6] = '--' continue elif os.path.exists(os.path.join(hf_status, 'summary.txt')): summary = utils.read_status(os.path.join(hf_status, 'summary.txt')) thishits = int(summary['hits']) thisprocessed = int(summary['processed']) self.process_data[run_name][6] = "%.2f%% (%d/%d)" % (100*float(thishits)/(thisprocessed+1e-6), thishits, thisprocessed) else: status_files = glob.glob(os.path.join(hf_status, 'status*')) thishits = 0 thisprocessed = 0 for status_file in status_files: summary = utils.read_status(status_file) thishits += int(summary['hits']) thisprocessed += int(summary['processed']) self.process_data[run_name][6] = "%.2f%% (%d/%d)" % (100*float(thishits)/(thisprocessed+1e-6), thishits, thisprocessed) def draw_table(self, sel_rows = None): # sel_rows : [row1, row2 , ...] '''NOTE If sel_rows is not None, then only the ROWs in sel_rows will be updated. Please make sure no rows are added or deleted in self.process_data if sel_rows is not None ! ''' runs = self.process_data.keys() runs.sort() hits = 0 patterns = 0 for i,r in enumerate(runs): infomation = self.process_data[r] # cal hits and patterns hitinfo = utils.findnumber(infomation[6]) if len(hitinfo) == 3: hits += int(hitinfo[1]) patterns += int(hitinfo[2]) # judge if it is selected if sel_rows is not None and i not in sel_rows : continue # insert row ? if i >= self.ui.tableWidget.rowCount(): self.ui.tableWidget.insertRow(i) # set run name newitem = QtGui.QTableWidgetItem(str(r)) newitem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) self.ui.tableWidget.setItem(i, 0, newitem) # set others for j,info in enumerate(infomation[1:self.columnCount]): j = j + 1 newitem = QtGui.QTableWidgetItem(info) if j == 1: assignments = str(self.ui.comboBox.currentText()) self.tag_buffer[assignments][r] = info if j in [2,3,4,5] and info != "--": cindex = self.namespace['process_status'].index(info.split(" ")[0]) color = self.namespace['process_colors'][cindex] newitem.setBackgroundColor(QtGui.QColor(color[0], color[1], color[2], 127)) newitem.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter) self.ui.tableWidget.setItem(i, j, newitem) # write other ctrls self.ui.label_73.setText( utils.fmt_process_status(self.data_format, hits, patterns) ) self.ui.lcdNumber.display(self.num_running_jobs) # logging table utils.logging_table(self.process_data, self.rawdata_changelog, \ os.path.join(self.dirname, self.namespace['project_structure'][0])) def refresh_table(self): # lock button self.ui.pushButton_6.setEnabled(False) # refresh self.update_table_runs() self.draw_table() # utils.print2projectLog(self.dirname, "Table updated.") # unlock button self.ui.pushButton_6.setEnabled(True) def autorefresh(self, state): if state == QtCore.Qt.Checked: self.table_monitor = utils.TableMonitor(self.namespace['monitor_time'], self.refresh_table) self.refresh_table() self.table_monitor.start() else: self.table_monitor.stop() del self.table_monitor self.table_monitor = None """ Classify Tab """ def decomp_changed(self, index): if self.ui.comboBox_3.itemText(index) == self.namespace['classify_LLE']: self.ui.widget_11.setVisible(True) self.ui.widget_12.setVisible(True) else: self.ui.widget_11.setVisible(False) self.ui.widget_12.setVisible(False) def view_job(self): jobview.show_jobView(self) utils.print2projectLog(self.dirname, "Open job viewer.") def view_history(self): pass '''
class MainProgram(QtWidgets.QMainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionOpen.triggered.connect(self.clicked_open) self.ui.actionMirror.triggered.connect(self.clicked_mirror) self.ui.actionFlip_Upside_Down.triggered.connect(self.clicked_flip) self.ui.actionBrightness_Increase.triggered.connect( self.clicked_brightnessup) self.ui.actionBrightness_Decrease.triggered.connect( self.clicked_brightnessdown) self.ui.actionContrast_Increase.triggered.connect( self.clicked_contrastup) self.ui.actionContrast_Decrease.triggered.connect( self.clicked_contrastdown) self.ui.actionRed_Green.triggered.connect(self.clicked_swap_rg) self.ui.actionGreen_Blue.triggered.connect(self.clicked_swap_gb) self.ui.actionBlue_Red.triggered.connect(self.clicked_swap_br) self.ui.actionNegative.triggered.connect(self.clicked_negative) self.ui.actionBlack_and_White.triggered.connect( self.clicked_converttobw) self.ui.actionReplace_Color.triggered.connect( self.clicked_replacecolor) self.ui.actionMedian.triggered.connect(self.clicked_blur_median) self.ui.actionGaussian_2.triggered.connect(self.clicked_blur_gaussian) self.ui.actionAverage.triggered.connect(self.clicked_blur_average) self.ui.actionIntensity_Map.triggered.connect( self.clicked_intensity_map) self.ui.actionPixelate.triggered.connect(self.clicked_pixelate) self.ui.actionCartoonify.triggered.connect(self.clicked_cartoonify) self.ui.actionGamma_Correction.triggered.connect(self.clicked_gamma) self.ui.actionDithering.triggered.connect(self.clicked_dither) self.ui.actionEdge_Detection.triggered.connect(self.clicked_canny) self.ui.actionGaussian.triggered.connect(self.clicked_gaussian_noise) self.ui.actionVertical_Bands.triggered.connect( self.clicked_vertical_noise_bands) self.ui.actionHorizontal_Bands.triggered.connect( self.clicked_horizontal_noise_bands) self.ui.actionExtract_Color.triggered.connect( self.clicked_extract_color) self.ui.actionAdd_Border.triggered.connect(self.clicked_add_border) self.ui.actionHistogram_Equalization.triggered.connect( self.clicked_histogramequalization) self.ui.actionImage_Histogram.triggered.connect( self.clicked_image_histogram) self.ui.actionSave.triggered.connect(self.clicked_save) self.ui.actionPyramid.triggered.connect( self.clicked_pyramid_blending_loadfiles) self.ui.actionAlpha.triggered.connect(self.clicked_alpha_blending) self.ui.actionResize.triggered.connect(self.resize_image) self.ui.actionRotate.triggered.connect(self.clicked_rotate_image) self.ui.actionApply_Mask.triggered.connect(self.clicked_apply_mask) self.ui.actionExit.triggered.connect(self.clicked_exit) self.ui.actionUndo.triggered.connect(self.clicked_undo) self.ui.actionRedo.triggered.connect(self.clicked_redo) self.original = None #Original Image self.current = None # this is the image in progress self.redo = None self.currentminusone = None self.counter_undo = 0 self.counter_redo = 0 def perform_updates(self, current_): print('inside perform updates') if self.current is not None: self.update_current_minus_one(self.current.copy()) elif self.current is None: self.update_current_minus_one(current_) self.update_current(current_) print('progressing inside perform updates') self.update_imagebox() def update_current_minus_one(self, image): self.currentminusone = image # def update_for_redo(self): # self.redo_image = self.current def clicked_undo(self): # if self.counter_redo == self.counter_undo and self.current is not None and self.currentminusone is not None: if self.current is not None and self.currentminusone is not None: self.redo = self.current.copy() self.update_current(self.currentminusone) self.update_imagebox() self.counter_undo += 1 def clicked_redo(self): if self.counter_undo != 0 and self.counter_undo > self.counter_redo: self.currentminusone = self.current.copy() self.update_current(self.redo) self.update_imagebox() self.counter_redo += 1 def update_current(self, image): self.current = image def clicked_exit(self): sys.exit() def update_imagebox(self): print('inside updatebox') if len(self.current.shape) == 3: #for color images copyofcurrent = self.current.copy() # copyofcurrent[:,:,[0,2]] = copyofcurrent[:,:,[2,0]] print(copyofcurrent.dtype) self.updated_pic = QtGui.QImage( copyofcurrent, copyofcurrent.shape[1], copyofcurrent.shape[0], copyofcurrent.shape[1] * 3, QtGui.QImage.Format_BGR888) #QtGui.QImage.Format_BGR888) elif len(self.current.shape) == 2: #for color images print('here') copyofcurrent = self.current.copy() self.updated_pic = QtGui.QImage( copyofcurrent, copyofcurrent.shape[1], copyofcurrent.shape[0], copyofcurrent.shape[1] * 1, QtGui.QImage.Format_Grayscale8) #.QtGui.QImage.rgbSwapped() self.updated_pic = QtGui.QPixmap(self.updated_pic) self.ui.label_imagebox.setPixmap(self.updated_pic) def check_canvas(self): if self.current is None: QtWidgets.QMessageBox.warning(self, 'No image found', 'Please load an image first.') return return 1 def get_filename(self, msg): print('get file name') options = QtWidgets.QFileDialog.Options() fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, msg, "", "All Files (*)", options=options) return fileName def clicked_open(self): # options = QtWidgets.QFileDialog.Options() # fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "", "All Files (*)", # options=options) fileName = self.get_filename('Load image') if len(fileName) == 0: return self.original = cv2.imread(fileName) #.astype(np.float32) self.update_current(self.original) print(self.original.dtype) self.pixmap = QtGui.QPixmap(fileName) self.ui.label_imagebox.setPixmap(self.pixmap) def clicked_save(self): if self.current is None: QtWidgets.QMessageBox.warning(self, "No file to save", "File can't be saved.") return filePath, _ = QtWidgets.QFileDialog.getSaveFileName( self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ") print('filepath') print(len(filePath)) print(filePath) print('_') print(_) if len(filePath) != 0: cv2.imwrite(filePath, self.current) def clicked_mirror(self): if self.check_canvas() == None: return img = image_editor.mirror(self.current) # self.update_current_minus_one(self.current.copy()) # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_flip(self): if self.check_canvas() == None: return img = image_editor.flip_upsidedown(self.current) # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_brightnessup(self): img = image_editor.brightness_contrast(self.current, 1, 1) self.perform_updates(img) def clicked_brightnessdown(self): img = image_editor.brightness_contrast(self.current, 1, -1) # img = image_editor.brightness_down(self.current, 1, 1) self.perform_updates(img) def clicked_contrastup(self): img = image_editor.brightness_contrast(self.current, 1.01, 0) self.perform_updates(img.astype(np.uint8)) def clicked_contrastdown(self): img = image_editor.brightness_contrast(self.current, 0.99, 0) self.perform_updates(img) def clicked_swap_rg(self): if self.check_canvas() == None: return if len(self.current.shape) == 2: error = 'No colors to swap.' QtWidgets.QMessageBox.warning(self, 'Image is grayscale.', error) else: img = image_editor.swap_gr(self.current) # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_swap_gb(self): if self.check_canvas() == None: return if len(self.current.shape) == 2: error = 'No colors to swap.' QtWidgets.QMessageBox.warning(self, 'Image is grayscale.', error) else: img = image_editor.swap_bg(self.current) # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_swap_br(self): if self.check_canvas() == None: return if len(self.current.shape) == 2: error = 'No colors to swap.' QtWidgets.QMessageBox.warning(self, 'Image is grayscale.', error) else: img = image_editor.swap_rb(self.current) # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_negative(self): if self.check_canvas() == None: return img = image_editor.negative_color_picture(self.current) self.perform_updates(img) def clicked_converttobw(self): if self.check_canvas() == None: return img = image_editor.convert_to_bw(self.current) self.perform_updates(img) def clicked_replacecolor(self): if self.check_canvas() == None: return Dialog_replacecolor = QtWidgets.QDialog() dialog = replace_color.Ui_Dialog_replacecolor() dialog.setupUi(Dialog_replacecolor) Dialog_replacecolor.show() result = Dialog_replacecolor.exec_() if dialog.radioButton_greater.isChecked(): operator = '>' elif dialog.radioButton_lesser.isChecked(): operator = '<' else: operator = '=' if result: img = image_editor.replace_color(self.current, dialog.lineEdit.text(), dialog.lineEdit_2.text(), operator) self.perform_updates(img) def clicked_blur_median(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = blur_median.Ui_Dialog() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result == False: print('rejected') return elif result and (int(ui.spinBox_kernelsize.text()) == 0 or int(ui.spinBox_numberofapplications.text()) == 0): return elif result and int(ui.spinBox_kernelsize.text()) % 2 == 0: print('try again') error = 'Kernel size can only be odd.' QtWidgets.QMessageBox.warning(self, 'Error', error) self.clicked_blur_median() elif result: img = image_editor.median_blur( self.current, ui.spinBox_kernelsize.text(), ui.spinBox_numberofapplications.text()) print('accepted') # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_blur_gaussian(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = blur_gaussian.Ui_Dialog() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result == False: print('rejected') return elif result and (int(ui.spinBox_kernelsize.text()) == 0 or int(ui.spinBox_numberofapplications.text()) == 0): return elif result and int(ui.spinBox_kernelsize.text()) % 2 == 0: print('try again') error = 'Kernel size can only be odd.' QtWidgets.QMessageBox.warning(self, 'Error', error) self.clicked_blur_gaussian() elif result: img = image_editor.gaussian_blur( self.current, ui.spinBox_kernelsize.text(), ui.spinBox_numberofapplications.text()) print('accepted') # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_blur_average(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = blur_average.Ui_Dialog_avgblur() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result == False: print('rejected') return if result and (int(ui.spinBox_kernelsize.text()) == 0 or int(ui.spinBox_numberofapplications.text() == 0)): return elif result: img = image_editor.avg_blur(self.current, ui.spinBox_kernelsize.text(), ui.spinBox_numberofapplications.text()) print('accepted') # self.update_current(img) # self.update_imagebox() self.perform_updates(img) def clicked_intensity_map(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = heatmap.Ui_Dialog_heatmap() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.intensity_map(self.current, ui.comboBox_heatmap.currentText()) self.perform_updates(img) def clicked_pixelate(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = pixelate.Ui_Dialog_pixelate() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: if ui.spinBox_pixelate.text() == 0: return img = image_editor.pixelate(self.current, ui.spinBox_pixelate.text()) self.perform_updates(img) def clicked_cartoonify(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = cartoonify.Ui_Dialog_cartoonify() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.cartoonify(self.current, ui.spinBox_thresh1.text(), ui.spinBox_thresh2.text()) self.perform_updates(img) def clicked_gamma(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = gamma.Ui_Dialog() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.gamma_correction(self.current, ui.doubleSpinBox_gamma.text()) self.perform_updates(img) def clicked_dither(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = dither.Ui_Dialog_dither() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.dither(self.current, ui.spinBox_order.text()) self.perform_updates(img) def clicked_canny(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = canny.Ui_Dialog_canny() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result and int(ui.spinBox_kernelsize.text()) % 2 == 0: print('try again') error = 'Kernel size can only be odd.' QtWidgets.QMessageBox.warning(self, 'Error', error) self.clicked_canny() elif result and int(ui.spinBox_thresh1.text()) == int( ui.spinBox_thresh2.text()): print('try again') error = 'Thresholds cannot be equal.' QtWidgets.QMessageBox.warning(self, 'Error', error) self.clicked_canny() elif result: img = image_editor.edge_detection(self.current, ui.spinBox_thresh1.text(), ui.spinBox_thresh2.text(), ui.spinBox_kernelsize.text(), ui.comboBox.currentText()) self.perform_updates(img) def clicked_gaussian_noise(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = noise_gaussian.Ui_Dialog_gaussian_noise() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.add_Gaussian_noise( self.current, ui.doubleSpinBox_sigma.text(), ui.comboBox_channel.currentText()) # self.update_current(img) # self.update_imagebox() self.perform_updates(img.astype(np.uint8)) def clicked_vertical_noise_bands(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = verticalnoisebands.Ui_Dialog_noiseband_vertical() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: if float(ui.spinBox_width.text()) == 0 or float( ui.spinBox_period.text()) == 0 or float( ui.spinBox_magnitude.text()) == 0: return img = image_editor.band_noise_vertical(self.current, ui.spinBox_width.text(), ui.spinBox_period.text(), ui.spinBox_magnitude.text()) self.perform_updates(img) def clicked_horizontal_noise_bands(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = horizontalnoisebands.Ui_Dialog_horizontalnoise() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: if float(ui.spinBox_width.text()) == 0 or float( ui.spinBox_period.text()) == 0 or float( ui.spinBox_magnitude.text()) == 0: return img = image_editor.band_noise_horizontal( self.current, ui.spinBox_width.text(), ui.spinBox_period.text(), ui.spinBox_magnitude.text()) self.perform_updates(img) def clicked_extract_color(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = extractcolor.Ui_Dialog_extractcolor() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: img = image_editor.extract_color(self.current, ui.lineEdit_extractcolor.text()) self.perform_updates(img) def clicked_add_border(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = addborder.Ui_Dialog_addborder() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: top = int(ui.spinBox_top.text()) bottom = int(ui.spinBox_bottom.text()) left = int(ui.spinBox_left.text()) right = int(ui.spinBox_right.text()) value = [ int(ui.spinBox_blue.text()), int(ui.spinBox_green.text()), int(ui.spinBox_red.text()) ] if top == 0 and bottom == 0 and left == 0 and right == 0: return img = image_editor.add_border(self.current, top=top, bottom=bottom, left=left, right=right, bordertype=ui.comboBox.currentText(), value=value) self.perform_updates(img) def clicked_histogramequalization(self): if self.check_canvas() == None: return img = image_editor.histogram_equalization_bw(self.current) self.perform_updates(img) def clicked_image_histogram(self): if self.check_canvas() == None: return img = image_editor.image_histogram(self.current) # img[:,:,[0,3]] = img[:,:,[3,0]] print(img[:, :, 0].max()) print(img[:, :, 1].max()) print(img[:, :, 2].max()) print(img[:, :, 3].max()) print(img.dtype) # img[:,:,3] = np.ones_like(img[:,:,3]) * 255 win = QtWidgets.QDialog() ui_ = image_histogram.Ui_Dialog() ui_.setupUi(win) hist_ = QtGui.QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 4, QtGui.QImage.Format_RGBX8888) hist = QtGui.QPixmap(hist_) ui_.label_hist.setPixmap(hist) win.show() win.exec_() def clicked_pyramid_blending_loadfiles(self): self.filenames_pyramidblend = self.get_filenames( 'Load three images: two for blending and one mask') while len(self.filenames_pyramidblend) != 3 and len( self.filenames_pyramidblend ) != 0: #program continues if user selects none or 2 error = 'Please load exactly three files.' QtWidgets.QMessageBox.warning(self, 'Error loading files', error) self.filenames_pyramidblend = self.get_filenames( 'Load three images: two for blending and one mask') if len(self.filenames_pyramidblend) == 0: return self.image0 = cv2.imread(self.filenames_pyramidblend[0]) self.image1 = cv2.imread(self.filenames_pyramidblend[1]) self.image2 = cv2.imread(self.filenames_pyramidblend[2]) self.clicked_pyramid_blending() def clicked_pyramid_blending(self): Dialog = QtWidgets.QDialog() ui = pyramidblending_modified.Ui_Dialog() ui.setupUi(Dialog) ui.label_image0.setText('....' + self.filenames_pyramidblend[0][-30:]) ui.label_image1.setText('....' + self.filenames_pyramidblend[1][-30:]) ui.label_image2.setText('....' + self.filenames_pyramidblend[2][-30:]) Dialog.show() result = Dialog.exec_() if result and (ui.comboBox_image0.currentText() == ui.comboBox_image1.currentText() or \ ui.comboBox_image1.currentText() == ui.comboBox_image2.currentText() or \ ui.comboBox_image2.currentText() == ui.comboBox_image0.currentText()): QtWidgets.QMessageBox.warning( self, 'Error', 'An image could either be Top, Bottom or Mask') return self.clicked_pyramid_blending() levels = int(ui.spinBox_levels.text()) choice_dict = { ui.comboBox_image0.currentText(): self.image0, ui.comboBox_image1.currentText(): self.image1, ui.comboBox_image2.currentText(): self.image2 } if result: img = image_editor.blending_pyramids(choice_dict['Top'], choice_dict['Bottom'], choice_dict['Mask'], levels) cv2.imwrite('saved_image.png', img) self.perform_updates(img) def get_filenames(self, msg): filenames, _ = QtWidgets.QFileDialog.getOpenFileNames( self, msg, '', ) print(filenames) return filenames def clicked_alpha_blending(self): filenames = self.get_filenames('Load two images only') while len(filenames) != 2 and len( filenames) != 0: #program continues if user selects none or 2 error = 'Please load exactly two files.' QtWidgets.QMessageBox.warning(self, 'Error loading files', error) filenames = self.get_filenames('Load two images only') if len(filenames) == 0: return image1 = cv2.imread(filenames[0]) image2 = cv2.imread(filenames[1]) if image1.shape != image2.shape: QtWidgets.QMessageBox.warning(self, 'Cannot blend files', 'Images are not the same shape.') return Dialog = QtWidgets.QDialog() ui = alphablending.Ui_Dialog_alphablending() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() if result: alpha = float(ui.doubleSpinBox_alpha.text()) img = image_editor.blend_images(image1, image2, alpha) self.perform_updates(img.astype(np.uint8)) def resize_image(self): if self.check_canvas() == None: return Dialog = QtWidgets.QDialog() ui = resize_ui.Ui_Dialog_resize() ui.setupUi(Dialog) Dialog.show() result = Dialog.exec_() h = ui.doubleSpinBox_height.text() w = ui.doubleSpinBox_width.text() if result: try: img = image_editor.resize_image(self.current, w, h) except: QtWidgets.QMessageBox.warning(self, "Can't resize image.", 'Please try again.') return self.perform_updates(img) def clicked_rotate_image(self): if self.check_canvas() == None: return img = image_editor.rotate_image(self.current) self.perform_updates(img) def clicked_apply_mask(self): if self.check_canvas() == None: return 1 filename = self.get_filename('Load mask image') if len(filename) == 0: return mask = cv2.imread(filename, 0) if (self.current.shape[0], self.current.shape[1]) != (mask.shape[0], mask.shape[1]): QtWidgets.QMessageBox.warning(self, "Can't apply mask", 'Images are not the same shape.') return if len(self.current.shape) > 2: img = image_editor.mask_result_color(self.current, mask) else: img = image_editor.mask_result_bw(self.current, mask) self.perform_updates(img)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.actionOpen.triggered.connect(self.clicked_open) self.ui.actionMirror.triggered.connect(self.clicked_mirror) self.ui.actionFlip_Upside_Down.triggered.connect(self.clicked_flip) self.ui.actionBrightness_Increase.triggered.connect( self.clicked_brightnessup) self.ui.actionBrightness_Decrease.triggered.connect( self.clicked_brightnessdown) self.ui.actionContrast_Increase.triggered.connect( self.clicked_contrastup) self.ui.actionContrast_Decrease.triggered.connect( self.clicked_contrastdown) self.ui.actionRed_Green.triggered.connect(self.clicked_swap_rg) self.ui.actionGreen_Blue.triggered.connect(self.clicked_swap_gb) self.ui.actionBlue_Red.triggered.connect(self.clicked_swap_br) self.ui.actionNegative.triggered.connect(self.clicked_negative) self.ui.actionBlack_and_White.triggered.connect( self.clicked_converttobw) self.ui.actionReplace_Color.triggered.connect( self.clicked_replacecolor) self.ui.actionMedian.triggered.connect(self.clicked_blur_median) self.ui.actionGaussian_2.triggered.connect(self.clicked_blur_gaussian) self.ui.actionAverage.triggered.connect(self.clicked_blur_average) self.ui.actionIntensity_Map.triggered.connect( self.clicked_intensity_map) self.ui.actionPixelate.triggered.connect(self.clicked_pixelate) self.ui.actionCartoonify.triggered.connect(self.clicked_cartoonify) self.ui.actionGamma_Correction.triggered.connect(self.clicked_gamma) self.ui.actionDithering.triggered.connect(self.clicked_dither) self.ui.actionEdge_Detection.triggered.connect(self.clicked_canny) self.ui.actionGaussian.triggered.connect(self.clicked_gaussian_noise) self.ui.actionVertical_Bands.triggered.connect( self.clicked_vertical_noise_bands) self.ui.actionHorizontal_Bands.triggered.connect( self.clicked_horizontal_noise_bands) self.ui.actionExtract_Color.triggered.connect( self.clicked_extract_color) self.ui.actionAdd_Border.triggered.connect(self.clicked_add_border) self.ui.actionHistogram_Equalization.triggered.connect( self.clicked_histogramequalization) self.ui.actionImage_Histogram.triggered.connect( self.clicked_image_histogram) self.ui.actionSave.triggered.connect(self.clicked_save) self.ui.actionPyramid.triggered.connect( self.clicked_pyramid_blending_loadfiles) self.ui.actionAlpha.triggered.connect(self.clicked_alpha_blending) self.ui.actionResize.triggered.connect(self.resize_image) self.ui.actionRotate.triggered.connect(self.clicked_rotate_image) self.ui.actionApply_Mask.triggered.connect(self.clicked_apply_mask) self.ui.actionExit.triggered.connect(self.clicked_exit) self.ui.actionUndo.triggered.connect(self.clicked_undo) self.ui.actionRedo.triggered.connect(self.clicked_redo) self.original = None #Original Image self.current = None # this is the image in progress self.redo = None self.currentminusone = None self.counter_undo = 0 self.counter_redo = 0
class Ui_Dialog(object): def login(self): correct_user_name = "HOTEL" #User name correct_password = "******" #Password user_name = self.txt_user_name.text() password = self.txt_password.text() if (user_name == correct_user_name and password == correct_password): Dialog.hide() self.window = QtWidgets.QMainWindow() self.ui1 = Ui_MainWindow() self.ui1.setupUi(self.window) self.window.show() elif (user_name == correct_user_name): self.txt_password.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Password") msg.setIcon(QMessageBox.Critical) msg.exec_() elif (password == correct_password): self.txt_user_name.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Username") msg.setIcon(QMessageBox.Critical) msg.exec_() else: self.txt_user_name.setText("") self.txt_password.setText("") msg = QMessageBox() msg.setWindowTitle("Error") msg.setText("Wrong Username\nWrong Password") msg.setIcon(QMessageBox.Critical) msg.exec_() def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(580, 501) self.txt_user_name = QtWidgets.QLineEdit(Dialog) self.txt_user_name.setGeometry(QtCore.QRect(220, 120, 300, 51)) font = QtGui.QFont() font.setPointSize(15) self.txt_user_name.setFont(font) self.txt_user_name.setText("") self.txt_user_name.setObjectName("txt_user_name") self.lbl_username = QtWidgets.QLabel(Dialog) self.lbl_username.setGeometry(QtCore.QRect(46, 120, 151, 51)) font = QtGui.QFont() font.setPointSize(20) self.lbl_username.setFont(font) self.lbl_username.setObjectName("lbl_username") self.txt_password = QtWidgets.QLineEdit(Dialog) self.txt_password.setGeometry(QtCore.QRect(224, 210, 300, 51)) font = QtGui.QFont() font.setPointSize(15) self.txt_password.setFont(font) #self.txt_password.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor)) #self.txt_password.setFocusPolicy(QtCore.Qt.StrongFocus) self.txt_password.setToolTip("") self.txt_password.setText("") self.txt_password.setObjectName("txt_password") self.txt_password.setEchoMode(QtWidgets.QLineEdit.Password) self.lbl_password = QtWidgets.QLabel(Dialog) self.lbl_password.setGeometry(QtCore.QRect(50, 210, 151, 51)) font = QtGui.QFont() font.setPointSize(20) self.lbl_password.setFont(font) self.lbl_password.setObjectName("lbl_password") self.btn_login = QtWidgets.QPushButton(Dialog) self.btn_login.setGeometry(QtCore.QRect(224, 302, 151, 51)) font = QtGui.QFont() font.setPointSize(20) self.btn_login.setFont(font) self.btn_login.setObjectName("btn_login") self.btn_login.clicked.connect(self.login) self.retranslateUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): _translate = QtCore.QCoreApplication.translate Dialog.setWindowTitle(_translate("Dialog", "Dialog")) self.lbl_username.setText(_translate("Dialog", "User Name")) self.lbl_password.setText(_translate("Dialog", "Password")) self.btn_login.setText(_translate("Dialog", "Login"))