class MainView(ZApplicationView): # Class variables # ClassifierView Constructor def __init__(self, title, x, y, width, height): super(MainView, self).__init__(title, x, y, width, height) self.font = QFont("Arial", 10) self.setFont(self.font) # 1 Add a labeled combobox to top dock area self.add_datasets_combobox() # 2 Add a textedit to the left pane of the center area. self.text_editor = QTextEdit() self.text_editor.setLineWrapColumnOrWidth(600) self.text_editor.setLineWrapMode(QTextEdit.FixedPixelWidth) # 3 Add a description to display dataset.DESCR. self.description = QTextEdit() self.description.setLineWrapColumnOrWidth(600) self.description.setLineWrapMode(QTextEdit.FixedPixelWidth) # 4 Add a tabbed_window to the tabbed_window. self.tabbed_window = ZTabbedWindow(self, 0, 0, width / 2, height) # 5 Add a figure_view to the tabbed_window. self.figure_view = ZScalableScrolledFigureView(self, 0, 0, width / 2, height) self.add(self.text_editor) self.add(self.tabbed_window) self.tabbed_window.add("Description", self.description) self.tabbed_window.add("ConfusionMatrix", self.figure_view) self.figure_view.hide() self.show() def add_datasets_combobox(self): self.dataset_id = Iris self.datasets_combobox = ZLabeledComboBox(self, "Datasets", Qt.Horizontal) # We use the following datasets of sklearn to test XGBClassifier. self.datasets = { "Iris": Iris, "Digits": Digits, "Wine": Wine, "BreastCancer": BreastCancer } title = self.get_title() self.setWindowTitle("Iris" + " - " + title) self.datasets_combobox.add_items(self.datasets.keys()) self.datasets_combobox.add_activated_callback(self.datasets_activated) self.datasets_combobox.set_current_text(self.dataset_id) self.start_button = ZPushButton("Start", self) self.clear_button = ZPushButton("Clear", self) self.start_button.add_activated_callback(self.start_button_activated) self.clear_button.add_activated_callback(self.clear_button_activated) self.datasets_combobox.add(self.start_button) self.datasets_combobox.add(self.clear_button) self.set_top_dock(self.datasets_combobox) def write(self, text): self.text_editor.append(text) self.text_editor.repaint() def datasets_activated(self, text): self.dataset_id = self.datasets[text] title = self.get_title() self.setWindowTitle(text + " - " + title) def start_button_activated(self, text): self.model = LightGBMClassifierModel(self.dataset_id, self) self.start_button.setEnabled(False) self.clear_button.setEnabled(False) try: self.model.run() except: pass self.start_button.setEnabled(True) self.clear_button.setEnabled(True) def clear_button_activated(self, text): self.text_editor.setText("") self.description.setText("") self.figure_view.hide() plt.close() def visualize(self, cmatrix): self.figure_view.show() plt.close() sns.set() df = pd.DataFrame(cmatrix) sns.heatmap(df, annot=True, fmt="d") # Set a new figure to the figure_view. self.figure_view.set_figure(plt)
class MainView(ZApplicationView): # MainView Constructor def __init__(self, title, x, y, width, height): super(MainView, self).__init__(title, x, y, width, height) self.font = QFont("Arial", 10) self.setFont(self.font) # 1 Add a labeled combobox to top dock area self.add_datasets_combobox() # 2 Add a textedit to the left pane of the center area. self.text_editor = QTextEdit() self.text_editor.setFont(self.font) self.text_editor.setLineWrapColumnOrWidth(600) self.text_editor.setLineWrapMode(QTextEdit.FixedPixelWidth) self.description = QTextEdit() self.description.setFont(self.font) self.description.setLineWrapColumnOrWidth(600) self.description.setLineWrapMode(QTextEdit.FixedPixelWidth) # 3 Add a tabbled_window to the right pane of the center area. self.tabbed_window = ZTabbedWindow(self, 0, 0, width/2, height) # 4 Add a figure_view to the tabbed_window self.figure_view = ZScalableScrolledFigureView(self, 0, 0, width/2, height) self.add(self.text_editor) self.add(self.tabbed_window) self.tabbed_window.add("Description", self.description) self.tabbed_window.add("Importances", self.figure_view) self.figure_view.hide() self.show() def add_datasets_combobox(self): self.dataset_id = Boston self.datasets_combobox = ZLabeledComboBox(self, "Datasets", Qt.Horizontal) # We use the following datasets of sklearn to test RandomForestRegressor. self.datasets = {"Boston": Boston, "Diabetes": Diabetes} title = self.get_title() self.setWindowTitle( "Boston" + " - " + title) self.datasets_combobox.add_items(self.datasets.keys()) self.datasets_combobox.add_activated_callback(self.datasets_activated) self.datasets_combobox.set_current_text(self.dataset_id) self.start_button = ZPushButton("Start", self) self.clear_button = ZPushButton("Clear", self) self.start_button.add_activated_callback(self.start_button_activated) self.clear_button.add_activated_callback(self.clear_button_activated) self.datasets_combobox.add(self.start_button) self.datasets_combobox.add(self.clear_button) self.set_top_dock(self.datasets_combobox) def write(self, text): self.text_editor.append(text) self.text_editor.repaint() def datasets_activated(self, text): self.dataset_id = self.datasets[text] title = self.get_title() self.setWindowTitle(text + " - " + title) def start_button_activated(self, text): self.model = RandomForestRegressorModel(self.dataset_id, self) self.start_button.setEnabled(False) self.clear_button.setEnabled(False) try: self.model.run() except: pass self.start_button.setEnabled(True) self.clear_button.setEnabled(True) def file_new(self): self.text_editor.setText("") self.description.setText("") self.figure_view.hide() plt.close() def clear_button_activated(self, text): self.file_new() def visualize(self, importances): self.figure_view.show() plt.close() plt.title("Importances in Regression Model") importances.plot(kind = "barh") self.figure_view.set_figure( plt)
class MainView(ZApplicationView): IMAGE_COUNT = 25 IMAGE_COUNT_PERLINE = 5 # MainView Constructor def __init__(self, title, x, y, width, height): super(MainView, self).__init__(title, x, y, width, height, Z.Vertical) self.get_layout().setSpacing(0) self.scale = 50 self.get_layout().setContentsMargins(0, 0, 0, 0) self.scale_combobox = ZScaleComboBox(None, "Scale") self.scale_combobox.current_scale(self.scale) self.add(self.scale_combobox) self.image_views = [None] * self.IMAGE_COUNT # filename = "../images/Car_101.png" # 1. Create our default ImageDataGenerator with rotation_range self.generator = self.create_generator() # 2 Create an inner widget. self.inner = QWidget(self.main_layouter) # 3 Set QSizePolicy.Expanding to the self.inner self.inner.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # 4 Create a grid layout for the inner widget. self.grid = QGridLayout(self.inner) # 5 Add an instance of ZImageView to the grid. try: self.size = (224, 224) # Get an image cropped with max square region and scaled with self.size image = self.load_cropped_scaled_image(filename, self.size) # (height, width, channles) to (1, height, width, channels) self.data = image.reshape((1, ) + image.shape) # 6 Get flow from the self.generator flow = self.generator.flow(self.data, batch_size=1) # 7 Get generated images from the flow. for i in range(self.IMAGE_COUNT): # 8 Create an instance of ZImageView self.image_views[i] = ZImageView(self, 0, 0, 300, 300) # 9 Get a generated image from the flow. batches = next(flow) generated = batches[0].astype(np.uint8) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) x = int(i % self.IMAGE_COUNT_PERLINE) y = int(i / self.IMAGE_COUNT_PERLINE) self.grid.addWidget(self.image_views[i], y, x) self.set_filenamed_title(filename) except: traceback.print_exc() # 10 Add the inner to the self. self.add(self.inner) # 11 Add scale_changed callback to the self.scale_combobox. self.scale_combobox.add_activate_callback(self.scale_changed) self.show() def create_generator(self): # Create an instance ImageDataGenerator from self.*_range's return ImageDataGenerator( rotation_range=self.rotation_range.get_value(), width_shift_range=self.width_shift_range.get_value(), height_shift_range=self.height_shift_range.get_value(), shear_range=self.shear_range.get_value(), zoom_range=self.zoom_range.get_value(), brightness_range=[ self.brightness_low_range.get_value(), self.brightness_high_range.get_value() ], channel_shift_range=self.channel_shift_range.get_value(), horizontal_flip=self.horizontal_flip.is_checked(), vertical_flip=self.vertical_flip.is_checked()) def add_control_pane(self, fixed_width=200): self.vpane = ZVerticalPane(self, fixed_width) # Create preview PushButton self.preview = ZPushButton("Preview", self.vpane) self.preview.add_activated_callback(self.do_preview) self.vpane.add(self.preview) self.spacing = QLabel(" ") self.vpane.add(self.spacing) self.label = QLabel("ImageDataGenerator Parameters:") self.vpane.add(self.label) #self.groupBox.setLayout(self.vpane.get_layout()) self.rotation_range = ZLabeledDoubleSpinBox(self.vpane, "rotation_range", 0, 30, 20, step=1.0) self.width_shift_range = ZLabeledDoubleSpinBox(self.vpane, "width_shift_range", 0, 2.0, 1.0, step=0.1) self.height_shift_range = ZLabeledDoubleSpinBox(self.vpane, "height_shift_range", 0, 2.0, 0.3, step=0.1) self.shear_range = ZLabeledDoubleSpinBox(self.vpane, "shear_range", 0, 2.0, 0.4, step=0.1) self.zoom_range = ZLabeledDoubleSpinBox(self.vpane, "zoom_range", 0, 2.0, 0.3, step=0.1) self.channel_shift_range = ZLabeledDoubleSpinBox(self.vpane, "channel_shift", 0, 3.0, 2.0, step=0.1) self.brightness_low_range = ZLabeledDoubleSpinBox( self.vpane, "brightness_low_range", 0.5, 1.0, 0.7, step=0.1) self.brightness_high_range = ZLabeledDoubleSpinBox( self.vpane, "brightness_high_range", 1.0, 1.5, 1.2, step=0.1) self.horizontal_flip = ZLabeledCheckBox(self.vpane, "horizontal_flip") self.vertical_flip = ZLabeledCheckBox(self.vpane, "vertical_flip") self.vpane.add(self.rotation_range) self.vpane.add(self.width_shift_range) self.vpane.add(self.height_shift_range) self.vpane.add(self.shear_range) self.vpane.add(self.zoom_range) self.vpane.add(self.channel_shift_range) self.vpane.add(self.brightness_low_range) self.vpane.add(self.brightness_high_range) self.vpane.add(self.horizontal_flip) self.vpane.add(self.vertical_flip) self.set_right_dock(self.vpane) # Callback to the preview PushButton def do_preview(self): self.inner.hide() try: # 1. Create a new instance of ImageDataGenerator. self.generator = self.create_generator() # 2 Get a flow from the self.generator flow = self.generator.flow(self.data, batch_size=1) # 3 Get generated images from the flow. for i in range(self.IMAGE_COUNT): batches = next(flow) generated = batches[0].astype(np.uint8) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) except: traceback.print_exc() self.grid.update() self.inner.show() #2019/05/20 Updated def load_file(self, filename): self.inner.hide() # Get an image cropped with max square region and scaled with scale image = self.load_cropped_scaled_image(filename, self.size) # (height, width, channles) to (1, height, width, channels) self.data = image.reshape((1, ) + image.shape) flow = self.generator.flow(self.data, batch_size=1) for i in range(self.IMAGE_COUNT): batches = next(flow) generated = batches[0].astype(np.uint8) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) self.grid.update() self.inner.show() def load_cropped_scaled_image(self, filename, size): reader = ZOpenCVCroppedImageReader() image = reader.read(filename) return reader.crop_max_square_region(image, size) # Scale changed callback def scale_changed(self, text): text = text.replace("%", "") scale = int(text) # percentage # Hide self.inner to avoid the flickering of image_views self.inner.hide() for i in range(self.IMAGE_COUNT): self.image_views[i].rescale(scale) # You should call update method of self.grid layout self.grid.update() self.inner.show() def file_open(self): options = QFileDialog.Options() filename, _ = QFileDialog.getOpenFileName( self, "FileOpenDialog", "", "All Files (*);;Image Files (*.png;*jpg;*.jpeg)", options=options) if filename: self.load_file(filename) self.set_filenamed_title(filename) def file_save(self): # 1 Show a folderDialog to select a folder to save generated images folder = QFileDialog.getExistingDirectory(self, "OpenFolder", os.path.expanduser('.'), QFileDialog.ShowDirsOnly) if folder: #dir = dir.replace('/', os.sep) print("Folder button clicked {}".format(folder)) self.inner.hide() try: # 1. Create a new instance of ImageDataGenerator. self.generator = self.create_generator() # 2 Get a flow from the self.generator flow = self.generator.flow(self.data, batch_size=1, save_to_dir=folder, save_prefix="gen", save_format="png") # 3 Get generated images from the flow. for i in range(self.IMAGE_COUNT): batches = next(flow) generated = batches[0].astype(np.uint8) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) except: traceback.print_exc() self.grid.update() self.inner.show()
class MainView(ZApplicationView): IMAGE_COUNT = 25 IMAGE_COUNT_PERLINE = 5 CROP_SIZE = 224 # MainView Constructor def __init__(self, title, x, y, width, height): super(MainView, self).__init__(title, x, y, width, height, Z.Vertical) self.get_layout().setSpacing(0) self.scale = 50 self.get_layout().setContentsMargins(0, 0, 0, 0) self.scale_combobox = ZScaleComboBox(None, "Scale") self.scale_combobox.current_scale(self.scale) self.add(self.scale_combobox) self.image_views = [None] * self.IMAGE_COUNT # self.filename = "./girl.jpg" # 1. Create our default ZCutomImageDataGenerator with rotation_range self.generator = self.create_generator() # 2 Create an inner widget. self.inner = QWidget(self.main_layouter) # 3 Set QSizePolicy.Expanding to the self.inner self.inner.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # 4 Create a grid layout for the inner widget. self.grid = QGridLayout(self.inner) # 5 Add an instance of ZImageView to the grid. try: self.size = (self.CROP_SIZE, self.CROP_SIZE) self.image = Image.open(self.filename) # 6 Get flow from the self.generator flow = self.generator.flow(self.image, n_augmentation=self.IMAGE_COUNT) # 7 Get generated images from the flow. for i in range(self.IMAGE_COUNT): # 8 Create an instance of ZImageView self.image_views[i] = ZImageView(self, 0, 0, 300, 300) # 9 Get a generated image from the flow. cropped_image = next(flow) generated = np.asarray(cropped_image) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) x = int(i % self.IMAGE_COUNT_PERLINE) y = int(i / self.IMAGE_COUNT_PERLINE) self.grid.addWidget(self.image_views[i], y, x) self.set_filenamed_title(self.filename) except: traceback.print_exc() # 10 Add the inner to the self. self.add(self.inner) # 11 Add scale_changed callback to the self.scale_combobox. self.scale_combobox.add_activate_callback(self.scale_changed) self.show() def create_generator(self): # Create an instance ZImageDataGenerator. return ZCustomImageDataGenerator( crop_size=self.CROP_SIZE, rotation_angle=self.rotation_range.get_value(), left_top_shift=(self.left_shift_range.get_value(), self.top_shift_range.get_value()), shrink_ratio=(self.width_shrink_range.get_value(), self.height_shrink_range.get_value()), contrast=self.contrast.get_value(), saultpepper_noise=self.saultpepper_noise.get_value(), horizontal_flip=self.horizontal_flip.is_checked(), vertical_flip=self.vertical_flip.is_checked()) def add_control_pane(self, fixed_width=200): self.vpane = ZVerticalPane(self, fixed_width) # Create preview PushButton self.preview = ZPushButton("Preview", self.vpane) self.preview.add_activated_callback(self.do_preview) self.vpane.add(self.preview) self.spacing = QLabel(" ") self.vpane.add(self.spacing) self.label = QLabel("ImageDataGenerator Parameters:") self.vpane.add(self.label) #self.groupBox.setLayout(self.vpane.get_layout()) self.rotation_range = ZLabeledDoubleSpinBox(self.vpane, "rotation_range", 0, 20.0, 10.0, step=1.0) self.left_shift_range = ZLabeledDoubleSpinBox(self.vpane, "left_shift_range", 0, 20.0, 10.0, step=1.0) self.top_shift_range = ZLabeledDoubleSpinBox(self.vpane, "top_shift_range", 0, 20.0, 10.0, step=1.0) self.width_shrink_range = ZLabeledDoubleSpinBox(self.vpane, "width_shrink_range", 0.80, 0.99, 0.90, step=0.01) self.height_shrink_range = ZLabeledDoubleSpinBox(self.vpane, "height_shrink_range", 0.80, 0.99, 0.90, step=0.01) #self.channel_shift_range = ZLabeledDoubleSpinBox(self.vpane, "channel_shift", # 0, 3.0, 2.0, step=0.1) self.contrast = ZLabeledDoubleSpinBox(self.vpane, "contrast", 0.01, 0.06, 0.02, step=0.01) self.saultpepper_noise = ZLabeledDoubleSpinBox(self.vpane, "saultpepper_noise", 0.01, 0.05, 0.02, step=0.01) self.horizontal_flip = ZLabeledCheckBox(self.vpane, "horizontal_flip") #self.horizontal_flip.set_check() self.vertical_flip = ZLabeledCheckBox(self.vpane, "vertical_flip") self.vpane.add(self.rotation_range) self.vpane.add(self.left_shift_range) self.vpane.add(self.top_shift_range) self.vpane.add(self.width_shrink_range) self.vpane.add(self.height_shrink_range) self.vpane.add(self.contrast) self.vpane.add(self.saultpepper_noise) self.vpane.add(self.horizontal_flip) self.vpane.add(self.vertical_flip) self.set_right_dock(self.vpane) # Callback to the preview PushButton def do_preview(self): self.inner.hide() try: self.size = (self.CROP_SIZE, self.CROP_SIZE) self.image = Image.open(self.filename) self.generator = self.create_generator() # 1 Get flow from the self.generator flow = self.generator.flow(self.image, n_augmentation=self.IMAGE_COUNT) # 2 Get generated images from the flow. for i in range(self.IMAGE_COUNT): # 3 Get a generated image from the flow. cropped_image = next(flow) generated = np.asarray(cropped_image) self.image_views[i].set_image(generated) self.image_views[i].rescale(self.scale) x = int(i % self.IMAGE_COUNT_PERLINE) y = int(i / self.IMAGE_COUNT_PERLINE) self.grid.addWidget(self.image_views[i], y, x) self.set_filenamed_title(self.filename) except: traceback.print_exc() self.grid.update() self.inner.show() def load_file(self, filename): self.do_preview() # Scale changed callback def scale_changed(self, text): text = text.replace("%", "") scale = int(text) # percentage # Hide self.inner to avoid the flickering of image_views self.inner.hide() for i in range(self.IMAGE_COUNT): self.image_views[i].rescale(scale) # You should call update method of self.grid layout self.grid.update() self.inner.show() def file_open(self): options = QFileDialog.Options() self.filename, _ = QFileDialog.getOpenFileName( self, "FileOpenDialog", "", "All Files (*);;Image Files (*.png;*jpg;*.jpeg)", options=options) if self.filename: self.load_file(self.filename) self.set_filenamed_title(self.filename) def file_save(self): # 1 Show a folderDialog to select a folder to save generated images folder = QFileDialog.getExistingDirectory(self, "OpenFolder", os.path.expanduser('.'), QFileDialog.ShowDirsOnly) if folder: #dir = dir.replace('/', os.sep) print("Folder button clicked {}".format(folder)) self.inner.hide() try: self.generator = self.create_generator() # Get a flow from the self.generator flow = self.generator.flow_from_directory( self.filename, save_folder=folder, save_format="jpg", n_augmentation=self.IMAGE_COUNT) # Get generated images from the flow. for i in flow: image = next(flow) print("generated {} image size: {}".format(i, image.size)) except: traceback.print_exc() self.grid.update() self.inner.show()
class ZImageClassifierView(ZApplicationView): # Class variables # ClassifierView Constructor def __init__(self, title, x, y, width, height, datasets={"ImageModel": 0}): super(ZImageClassifierView, self).__init__(title, x, y, width, height) self.font = QFont("Arial", 10) self.setFont(self.font) self.datasets = datasets self.model_loaded = False self.class_names_set = [None, None] # Image filename to be classified self.filename = None # Target image to be classified self.image = None # 1 Add a labeled combobox to top dock area self.add_datasets_combobox() # 2 Add a textedit to the left pane of the center area. self.text_editor = QTextEdit() self.text_editor.setLineWrapColumnOrWidth(600) self.text_editor.setLineWrapMode(QTextEdit.FixedPixelWidth) self.text_editor.setGeometry(0, 0, width/2, height) # 3 Add a tabbed_window the rigth pane of the center area. self.tabbed_window = ZTabbedWindow(self, 0, 0, width/2, height) # 4 Add a imageview to the tabbed_window. self.image_view = ZScalableScrolledImageView(self, 0, 0, width/3, height/3) self.tabbed_window.add("SourceImage", self.image_view) # 5 Add a test_imageview to the right pane of the center area. self.test_image_view = ZScalableScrolledImageView(self, 0, 0, width/3, height/3) self.tabbed_window.add("TestImage", self.test_image_view) self.add(self.text_editor) self.add(self.tabbed_window) def add_datasets_combobox(self): datasetkey = list(self.datasets.keys())[0] self.dataset_id = self.datasets[datasetkey] print("Current combobox item {} {}".format(datasetkey, self.dataset_id)) self.datasets_combobox = ZLabeledComboBox(self, "Datasets", Qt.Horizontal) self.datasets_combobox.setFont(self.font) title = self.get_title() self.setWindowTitle(self.__class__.__name__ + " - " + title) self.datasets_combobox.add_items(self.datasets.keys()) self.datasets_combobox.add_activated_callback(self.datasets_activated) self.datasets_combobox.set_current_text(self.dataset_id) self.classifier_button = ZPushButton("Classify", self) self.classifier_button.setEnabled(False) self.clear_button = ZPushButton("Clear", self) self.classifier_button.add_activated_callback(self.classifier_button_activated) self.clear_button.add_activated_callback(self.clear_button_activated) self.datasets_combobox.add(self.classifier_button) self.datasets_combobox.add(self.clear_button) self.set_top_dock(self.datasets_combobox) def write(self, text): self.text_editor.append(text) self.text_editor.repaint() def datasets_activated(self, text): pass # Show FileOpenDialog and select an image file. def file_open(self): if self.model_loaded: options = QFileDialog.Options() filename, _ = QFileDialog.getOpenFileName(self,"FileOpenDialog", "", "All Files (*);;Image Files (*.png;*jpg;*.jpeg)", options=options) if filename: self.filename = filename self.load_file(filename) self.classifier_button.setEnabled(True) else: QMessageBox.warning(self, "ImageClassifier: Weight File Missing", "Please run: python RoadSignsModel.py " + str(self.dataset_id)) def remove_alpha_channel(self, array): shape = array.shape if len(shape) ==3: w, h, c = shape if c == 4: #(w, h, 4) -> (w, h, 3) #print("Remove the alpha channel of array") array = array[:,:,:3] return array def load_file(self, filename): from keras.preprocessing.image import load_img, img_to_array try: image_cropper = ZPILImageCropper(filename) # 1 Crop larget_central square region from an image of filename. cropped_image = image_cropper.crop_largest_central_square_region() # 2 Load an image from the cropped_fle. self.image_view.set_image(img_to_array(cropped_image)) self.image_view.update_scale() self.set_filenamed_title(filename) # 3 Resize the cropped_image self.image = cropped_image.resize(self.image_size) # 4 Convert the self.image to numpy ndarray and remove alpha channel. self.image = self.remove_alpha_channel(img_to_array(self.image)) # 5 Set self.nadarryy to the test_image_view. self.test_image_view.set_image(self.image) # 6 Convert self.image in range[0-1.0] self.image = self.image.astype('float32')/255.0 # 7 Expand the dimension of the self.image self.image = np.expand_dims(self.image, axis=0) #print(self.image.shape) except: self.write(formatted_traceback()) def classifier_button_activated(self, text): self.classifier_button.setEnabled(False) self.clear_button.setEnabled(False) try: self.classify() except: self.write(formatted_traceback()) self.classifier_button.setEnabled(True) self.clear_button.setEnabled(True) def get_top_five(self, predictions, classes, K=5): pred = predictions[0] indices = np.argpartition(pred, -K)[-K:] results = [] for i in indices: results.append([pred[i], classes[i]]) results = sorted(results, reverse=True) return results def get_class_names(self, path="./class_names.txt"): classes = [] with open(path, "r") as file: classes = [s.strip() for s in file.readlines()] return classes def classify(self): self.write("------------------------------------------------------------") self.write("classify start") self.write(self.filename) prediction = self.model.predict(self.image) pred = np.argmax(prediction, axis=1) #self.write("Prediction: index " + str(pred)) class_names = self.model.classes if pred >0 or pred <len(class_names): self.write("Prediction:" + class_names[int(pred)]) self.write("classify end") def clear_button_activated(self, text): self.text_editor.setText("") pass
class ZScalableScrolledImageView(QWidget): def __init__(self, parent, x, y, width, height): super(QWidget, self).__init__(parent) self.vlayout = QVBoxLayout(self) self.vlayout.setSpacing(0) self.vlayout.setContentsMargins(0, 0, 0, 0) self.scale_combobox = ZScaleComboBox(self, "Scale") self.save_button = ZPushButton("Save", self.scale_combobox) self.scale_combobox.add(self.save_button) self.save_button.add_activated_callback(self.save_button_activated) self.vlayout.addWidget(self.scale_combobox) self.image_view = ZScrolledImageView(parent, x, y, width, height) self.vlayout.addWidget(self.image_view) self.scale_combobox.add_activate_callback(self.scale_changed) def load_image(self, filename): self.image_view.load_image(filename) # def set_plotted_figure(self): filename = "~temp.png" current_dir = os.path.dirname(os.path.abspath(__file__)) full_path = os.path.join(current_dir, filename) plt.savefig(fullpath) plt.close() sef.image_view.load_image(fullpath) os.remove(fullpath) def get_image_view(self): return self.image_view def scale_changed(self, text): text = text.replace("%", "") scale = int(text) # percentage self.image_view.rescale(scale) def update_scale(self): text = self.scale_combobox.get_combobox().currentText() self.scale_changed(str(text)) def get_image(self, width, height): return self.image_view.get_image(width, height) def save_button_activated(self): #print("SaveButton clicked") abs_current_path = os.path.abspath(os.path.curdir) abs_current_path = os.path.abspath(os.path.curdir) files_types = "All Files (*);;Image Files (*.png;*jpg;*.jpeg)" filename, _ = QFileDialog.getSaveFileName( self, "FileSaveDialog", os.path.join(abs_current_path, "image.png"), files_types) if filename: self.image_view.file_save(filename) def set_image(self, ndarray): self.image_view.set_image(ndarray)