def showogrenci(self): try: ogrenci = OgrenciGoster(self.parent) self.parent.mdi.addSubWindow(ogrenci) ogrenci.show() data = self.sender().data ogrenci.ad.setText(data[1]) ogrenci.soyad.setText(data[2]) ogrenci.anneadi.setText(data[4]) ogrenci.babaadi.setText(data[5]) gp = QGraphicsScene(self) ogrenci.graphicsView.setScene(gp) ogrenci.graphicsView.setFixedHeight(100) ogrenci.graphicsView.setFixedWidth(100) if data[8] is not None: gp.addPixmap(QPixmap("db/%s" % data[8])) ogrenci.graphicsView.show() nots = self.parent.db.getNot(data[0]) ogrenci.tableWidget.setRowCount(len(nots)) ogrenci.tableWidget.setColumnCount(1) ogrenci.tableWidget.setHorizontalHeaderLabels(["Notlar"]) z = 0 for i in nots: ogrenci.tableWidget.setItem(z,0,QTableWidgetItem(i[2])) z +=1 except Exception as e: print(e)
def _update_background_preview(self): scene = QGraphicsScene() qpixmap = QPixmap(self.file_edit.text()) scene.addPixmap(qpixmap) self.background_preview.setScene(scene) self.background_preview.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
def __init__(self, conf, defeat): self.config = conf super().__init__() self.setWindowTitle(conf.get_text('victory')) self.setFixedSize(QSize(640, 480)) self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowTitleHint | Qt.FramelessWindowHint) button = QPushButton(conf.get_text('close'), self) button.setCheckable(True) button.setFixedSize(QSize(640, 30)) button.move(0, 450) # noinspection PyUnresolvedReferences button.clicked.connect(self.close) result_output = QTextEdit(self) result_output.setReadOnly(True) result_output.setFixedSize(QSize(640, 200)) result_output.move(0, 250) result_output.setLineWrapMode(QTextEdit.NoWrap) result_output.insertHtml(self.generate_result_text()) gview = QGraphicsView(self) scene = QGraphicsScene() if defeat: img = conf.theme_selected.get_defeat_pixmap() text = conf.get_text('defeat') else: img = conf.theme_selected.get_victory_pixmap() text = conf.get_text('victory') scene.addPixmap(img.scaled(QSize(640, 220))) gview.move(0, 30) gview.setScene(scene) label_title = QLabel(self) label_title.setText(text) label_title.setFixedSize(QSize(640, 30)) label_title.setAlignment(Qt.AlignCenter) label_title.setFont(self.get_font_title())
def random_glitch(self): if not hasattr(self, 'inputfilename'): QMessageBox.critical(self, "Error", "Load an image first!", QMessageBox.Ok) return scene = QGraphicsScene() bytes = None tries = 1 maxtry = 3 pm = QPixmap() while True: bytes = glitch_file(self.inputfilename, self.sliderNumGlitch.value()) success = pm.loadFromData(bytes) if success: break else: print("Glitch was too strong!") print("Trying again %d / %d" % (tries, maxtry)) tries += 1 bytes = glitch_file(self.inputfilename, self.sliderNumGlitch.value()) if tries > maxtry: QMessageBox.critical( self, "Error", "Glitching was too strong, unable to load image.\nYou can try again or you may need to lower the glitching-slider if this keeps happening.", QMessageBox.Ok) break self.glitchbytes = bytes self.glitchmap = pm scene.addPixmap(pm) self.imgOutput.setScene(scene)
def display_svg(self): # Create a temp file for this thumbnail image new_file, tmp_filename = tempfile.mkstemp() tmp_filename = "%s.png" % tmp_filename # Create a clip object and get the reader clip = openshot.Clip(self.filename) reader = clip.Reader() # Open reader reader.Open() # Save thumbnail image and close readers reader.GetFrame(1).Thumbnail(tmp_filename, self.graphicsView.width(), self.graphicsView.height(), "", "", "#000", False, "png", 85, 0.0) reader.Close() clip.Close() # Display temp image scene = QGraphicsScene(self) view = self.graphicsView svg = QtGui.QPixmap(tmp_filename) svg_scaled = svg.scaled(self.graphicsView.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) scene.addPixmap(svg_scaled) view.setScene(scene) view.show()
class SampleImageWidget(QWidget): def __init__(self, parent=None): super(SampleImageWidget, self).__init__(parent) self.graphicsScene = QGraphicsScene(self) self.graphicsView = SampleGraphicsView(self.graphicsScene) def setSampleImage(self, pathToFile): self.graphicsView.hide() #clear scene self.graphicsScene.clear() #load file tmpImage = QImage(pathToFile) self.originalHeight = tmpImage.height() self.originalWidth = tmpImage.width() tmpPixmap = QPixmap(1) tmpPixmap.convertFromImage(tmpImage.scaledToWidth(300)) self.scaledHeight = tmpPixmap.height() self.scaledWidth = tmpPixmap.width() #add to scene and show self.graphicsScene.addPixmap(tmpPixmap) self.graphicsView.show()
def showogrenci(self): try: ogrenci = OgrenciGoster(self.parent) self.parent.mdi.addSubWindow(ogrenci) ogrenci.show() data = self.sender().data ogrenci.ad.setText(data[1]) ogrenci.soyad.setText(data[2]) ogrenci.anneadi.setText(data[4]) ogrenci.babaadi.setText(data[5]) gp = QGraphicsScene(self) ogrenci.graphicsView.setScene(gp) ogrenci.graphicsView.setFixedHeight(100) ogrenci.graphicsView.setFixedWidth(100) if data[8] is not None: gp.addPixmap(QPixmap("db/%s" % data[8])) ogrenci.graphicsView.show() nots = self.parent.db.getNot(data[0]) ogrenci.tableWidget.setRowCount(len(nots)) ogrenci.tableWidget.setColumnCount(1) ogrenci.tableWidget.setHorizontalHeaderLabels(["Notlar"]) z = 0 for i in nots: ogrenci.tableWidget.setItem(z, 0, QTableWidgetItem(i[2])) z += 1 except Exception as e: print(e)
def on_imagesTree_currentItemChanged(self, current, previous): """ Private slot to show a preview of the selected image. @param current current image entry (QTreeWidgetItem) @param previous old current entry (QTreeWidgetItem) """ if current is None: return imageUrl = QUrl(current.text(1)) if not imageUrl.host(): imageUrl.setHost(QUrl(self.siteAddressLabel.text()).host()) imageUrl.setScheme(QUrl(self.siteAddressLabel.text()).scheme()) import Helpviewer.HelpWindow cache = Helpviewer.HelpWindow.HelpWindow.networkAccessManager().cache() if cache: cacheData = cache.data(imageUrl) else: cacheData = None pixmap = QPixmap() invalidPixmap = False scene = QGraphicsScene(self.imagePreview) if not cacheData: invalidPixmap = True else: pixmap.loadFromData(cacheData.readAll()) if pixmap.isNull(): invalidPixmap = True if invalidPixmap: scene.addText(self.tr("Preview not available.")) else: scene.addPixmap(pixmap) self.imagePreview.setScene(scene)
def _display_stylized_image(self, path): if path is not None: pix_map = self._read_input_pixmap(path) if pix_map is not None: scene = QGraphicsScene() scene.addPixmap(pix_map) self.ui.styleImageView.setScene(scene)
class ImageWidgetFullScreen(QGraphicsView): def __init__(self, ui, path): super(ImageWidgetFullScreen, self).__init__() self.setAlignment(Qt.AlignCenter) self.setStyleSheet("".join([styles.window, styles.graphicsView])) self.ui = ui self.scene = QGraphicsScene() self.scene.addPixmap(QPixmap(path)) self.setGeometry(QRect(0, 0, *self.ui.sWH)) self.setScene(self.scene) QShortcut(QKeySequence("Escape"), self).activated.connect(self.close) def wheelEvent(self, event): if event.modifiers() == Qt.ControlModifier: self.scale(math.pow(2, event.angleDelta().y() / 1000), math.pow(2, event.angleDelta().y() / 1000)) else: return QGraphicsView.wheelEvent(self, event) def contextMenuEvent(self, event): contextMenu = ContextMenuWidget(self, self.ui.RobotoLight, [[ QAction(QIcon(assetsPath.delete), "Close", self), self.close, False ]]) contextMenu.exec_(self.mapToGlobal(event.pos()))
def openfile(self): """ 打开图片,并且保存在self.srcImg中 """ # 获得图片地址,图片类型 imgName, imgType = QFileDialog.getOpenFileName( self, "打开图片", "", "*.jpg;;*.png;;All Files(*)") if imgType != "*.jpg" and imgType != "*.png": return print(imgName, imgType) # 利用OpenCV读入图片并存入self.srcImg中 self.srcImg = cv2.imread(imgName) # 缩放图像为适应窗口的大小 # 获得缩放比例 width = self.picview_source.width() height = self.picview_source.height() row, col = self.srcImg.shape[1], self.srcImg.shape[0] a = float(width / row) b = float(height / col) if a < b: scale = a else: scale = b dim = (int(row * scale), int(col * scale)) # 缩放图像 tmpImg = cv2.resize(self.srcImg, dim) # 将OpenCV格式储存的图片转换为QT可处理的图片类型 qimg = self.cvPic2Qimg(tmpImg) # 将图片放入图片显示窗口 scene = QGraphicsScene() scene.addPixmap(QPixmap.fromImage(qimg)) self.picview_source.setScene(scene) self.hasOpen = True self.label_2.setText("处理图像")
def oncle(self): if self.statusbar.currentMessage() != '': if self.comboBox.currentText() == "YOLO": parser = argparse.ArgumentParser() parser.add_argument('--weights', default="YOLO_small.ckpt", type=str) parser.add_argument('--weight_dir', default='weights', type=str) parser.add_argument('--data_dir', default="data", type=str) parser.add_argument('--gpu', default='', type=str) args = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu yolo = YOLONet(False) weight_file = os.path.join(args.data_dir, args.weight_dir, args.weights) detector = Detector(yolo, weight_file) # detect from camera # cap = cv2.VideoCapture(-1) # detector.camera_detector(cap) # detect from image file imname = self.file detector.image_detector(imname) scene = QGraphicsScene() pixmap = QPixmap("D:\\result.jpg") scene.addPixmap(pixmap) self.graphicsView_2.setScene(scene) elif self.comboBox.currentText() == "MaskRCNN": self.maskRCNN = demo.MaskRCNN() self.maskRCNN.detect(self.file) scene = QGraphicsScene() pixmap = QPixmap("D:\\result3.jpg") scene.addPixmap(pixmap) self.graphicsView_2.setScene(scene)
def __init__(self, sesion, pasajero=None, parent=None): super(InfoPasajero, self).__init__(parent) self.setupUi(self) self.sesion = sesion self.centerOnScreen() dicECivil = {0: "Soltero", 1: "Casado", 2: "Viudo", 3: "Separado"} if pasajero is not None: scene = QGraphicsScene() pixmap = QPixmap('2486.jpg') pixmap_resized = pixmap.scaled(500, 370, QtCore.Qt.KeepAspectRatio) scene.addPixmap(pixmap_resized) self.graphicsView.setScene(scene) n = controlador.consultaPais(self.sesion, int(pasajero[0][11])) p = controlador.consultaProvincia(self.sesion, int(pasajero[0][12])) lc = controlador.consultaLocalidad(self.sesion, int(pasajero[0][13])) self.lbl01.setText(str(pasajero[0][3])) self.lbl02.setText(str(pasajero[0][0] + " " + pasajero[0][1])) self.lbl03.setText(str(pasajero[0][6])) self.lbl04.setText(str(pasajero[0][9])) self.lbl05.setText(n) self.lbl06.setText(p) self.lbl07.setText(lc) self.lbl08.setText(dicECivil[pasajero[0][4]]) self.lbl09.setText(str(pasajero[0][7])) self.lbl10.setText(str(pasajero[0][5])) self.lbl11.setText(str(pasajero[0][8])) self.lbl12.setText(str(pasajero[0][10]))
def set_image(self, image): qim = ImageQt(image) pix = QtGui.QPixmap.fromImage(qim) self.qr_image = pix.scaled(400, 400, QtCore.Qt.KeepAspectRatio) screen = QGraphicsScene() screen.addPixmap(self.qr_image) self.ui.graphicsView.setScene(screen)
def showDetail(self, signal): row = signal.row() detailData = self.modelManager.getTechByIndex(row) self.detailUI.labelTechName.setText(str(detailData["구조명"])) self.detailUI.labelCategoryValue.setText( str(detailData["분류"]) + "(" + str(detailData["기타"]) + ")") self.detailUI.labelLightLevelValue.setText( str(detailData["경량충격음 차단성능 (등급)"])) self.detailUI.labelHeavyLevelValue.setText( str(detailData["중량충격음 차단성능 (등급)"])) self.detailUI.labelBufferCostValue.setText( str(detailData["완충재 추산가격 (원)"])) self.detailUI.labelBufferLabelCostValue.setText( str(detailData["완충재 노무비 (원)"])) self.detailUI.labelMortarThicknessValue.setText( str(detailData["마감 모르타르 두께 (mm)"])) self.detailUI.labelConcereteThicknessValue.setText( str(detailData["경량기포 콘크리트 두께 (mm)"])) self.detailUI.labelTotalThicknessValue.setText( str(detailData["전체 두께 (mm)"])) self.detailUI.labelTotalCostValue.setText(str(detailData["전체 가격 (원)"])) imgName = "thumbnails/" + str(detailData["구조명"]) + " 1.png" size = self.detailUI.graphicsViewThumnail.size() pixmap = QPixmap(imgName).scaled(size, Qt.KeepAspectRatio) scene = QGraphicsScene() scene.addPixmap(pixmap) self.detailUI.graphicsViewThumnail.setScene(scene) self.detailUI.graphicsViewThumnail.show() self.detailDialog.show()
class MainWidget(QGraphicsView): def __init__(self, parent): super().__init__() self.parent = parent self.scene = QGraphicsScene(self) self.setScene(self.scene) def _cv2_image_to_pixmap(self): if self.cv2_out_image == COLOR_IMAGE: cv2_image = cv2.cvtColor(self.cv2_image, cv2.COLOR_BGR2RGB) elif self.cv2_out_image == GRAY_IMAGE: cv2_image = cv2.cvtColor(self.cv2_image, cv2.COLOR_GRAY2RGB) elif self.cv2_out_image == BIN_IMAGE: cv2_image = cv2.cvtColor(self.cv2_image, cv2.COLOR_GRAY2RGB) height, width, chanels = cv2_image.shape return QPixmap.fromImage( QImage(cv2_image, width, height, width * chanels, QImage.Format_RGB888)) def setImage(self, images): self.cv2_out_image = images[OUT_IMAGE] self.cv2_image = images[self.cv2_out_image] self.update_view() def update_view(self): self.scene.clear() self.scene.setSceneRect(0, 0, self.cv2_image.shape[1], self.cv2_image.shape[0]) self.scene.addPixmap(self._cv2_image_to_pixmap()) self.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio) def resizeEvent(self, event): self.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio)
class mywindow(QtWidgets.QMainWindow): def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.NameImage.setFocus() self.ui.Load.clicked.connect(self.akcja) self.ui.Remove.clicked.connect(self.akcja) self.ui.NameImage.setText( "C:/Users/Oliwia Drozdek/Pictures/MOJE NAJLEPSZE ZDJĘCIA/") self.scene = QGraphicsScene() def akcja(self): try: nadawca = self.sender() if nadawca.text() == 'Załaduj': nazwa = self.ui.NameImage.text() pixmap = QPixmap() pixmap.load(nazwa) h = self.ui.View.height() w = self.ui.View.width() self.scene.addPixmap(pixmap.scaled(w, h)) self.ui.View.setScene(self.scene) elif nadawca.text() == 'Usuń': self.ui.NameImage.clear() except ValueError: QMessageBox.warning(self, "Błąd", "Nie udało się wczytać zdjęcia.", QMessageBox.Ok)
def Morph(self): for index, val in enumerate(self.lColors): if val == 'og': with open(self.leftPts, 'a') as f: f.write( str(self.lPoints[index][0]) + ' ' + str(self.lPoints[index][1]) + '\n') self.lColors[index] = 'ob' for index, val in enumerate(self.rColors): if val == 'og': with open(self.rightPts, 'a') as f: f.write( str(self.rPoints[index][0]) + ' ' + str(self.rPoints[index][1]) + '\n') self.rColors[index] = 'ob' i1, i2 = np.array(imageio.imread(self.leftImg)), np.array( imageio.imread(self.rightImg)) t1, t2 = Morphing.loadTriangles(self.leftPts, self.rightPts) if type(i1[0][0]) == np.dtype('uint8'): m = Morphing.Morpher(i1, t1, i2, t2) else: m = Morphing.ColorMorpher(i1, t1, i2, t2) imageio.imwrite( 'mix.png', m.getImageAtAlpha(float(self.sliderText.toPlainText()))) self.morphed = 'mix.png' scene = QGraphicsScene() scene.addPixmap(QPixmap(self.morphed).scaled(216, 162)) self.imgMorph.setScene(scene)
def update(self): img = Image.open(self.map_api.get_image()) img.save(join(split(getcwd())[0], f"results/{self.name}")) scene = QGraphicsScene() scene.addPixmap( QPixmap(join(split(getcwd())[0], f"results/{self.name}"))) self.display.setScene(scene)
def loadDataFromFile(self, filePath, num): """ Handles the loading of the data from the given file name. This method will be invoked by the 'loadData' method. *** YOU MUST USE THIS METHOD TO LOAD DATA FILES. *** *** This method is required for unit tests! *** """ ##points self.de = False self.doub = False self.trick = False self.finish = False self.path1 = '' self.path2 = '' self.leftcount = 0 self.rightcount = 0 self.new_left = list() self.new_right = list() txt_path = filePath + '.txt' if os.path.exists(txt_path) is True: data = np.loadtxt(txt_path, dtype=np.float64) x = data[:, 1] y = data[:, 0] ## # hratio = width / 240 # wratio = height / 192 # pix = QPixmap(filePath).scaled(240,192, QtCore.Qt.KeepAspectRatio) pix = QPixmap(filePath) img1 = QGraphicsScene() painter = QPainter(pix) painter.setBrush(QBrush(Qt.red, Qt.SolidPattern)) for i in range(0, len(x)): painter.drawEllipse(y[i] - 12, x[i] - 12, 24, 24) painter.end() img1.addPixmap(pix) if num == 1: self.path1 = txt_path else: self.path2 = txt_path else: pix = QPixmap(filePath) img1 = QGraphicsScene() # pix_new = pix.scaled(self.Img1.width(),self.Img1.height(),Qt.KeepAspectRatio) img1.addPixmap(pix) if num == 1: self.imagepathl = filePath self.Img1.setScene(img1) self.Img1.fitInView(img1.sceneRect()) else: self.imagepathr = filePath self.Img2.setScene(img1) self.Img2.fitInView(img1.sceneRect()) if self.Img1.scene() and self.Img2.scene(): self.pushButton.setEnabled(True) self.Slider.setEnabled(True) self.checkBox.setEnabled(True) self.lineEdit.setEnabled(True)
class MainView(QGraphicsView): min_scale = 1 max_scale = 5 def __init__(self, window=None): QGraphicsView.__init__(self) self.window = window self.scene = QGraphicsScene(self) self.setScene(self.scene) self.setMouseTracking(True) self.image = None self.screen_scale = 1 def create_image(self, image_map, palette_frame): colors = [QColor(c).rgb() for c in palette_frame.get_colors()] width, height = image_map.width, image_map.height image = QImage(width, height, QImage.Format_ARGB32) for x in range(width): for y in range(height): idx = image_map.get(x, y) image.setPixel(x, y, colors[idx]) return QImage(image) def set_image(self, image_map, palette_frame): self.image = self.create_image(image_map, palette_frame) # self.image = self.image.convertToFormat(QImage.Format_ARGB32) self.setSceneRect(0, 0, self.image.width(), self.image.height()) def clear_scene(self): self.scene.clear() def show_image(self): if self.image: self.clear_scene() self.scene.addPixmap(QPixmap.fromImage(self.image)) def mousePressEvent(self, event): scene_pos = self.mapToScene(event.pos()) pixmap = self.scene.itemAt(scene_pos) if not pixmap: return image = pixmap.pixmap().toImage() pos = int(scene_pos.x()), int(scene_pos.y()) if event.button() == Qt.LeftButton: dlg = QColorDialog() dlg.setCurrentColor(QColor(image.pixel(pos[0], pos[1]))) if dlg.exec_(): self.window.change_current_palette(pos, dlg.currentColor()) def wheelEvent(self, event): if event.delta() > 0 and self.screen_scale < self.max_scale: self.screen_scale += 1 self.scale(2, 2) elif event.delta() < 0 and self.screen_scale > self.min_scale: self.screen_scale -= 1 self.scale(0.5, 0.5)
def cvt_numpy_to_qscene(img): height, width, channels = img.shape bytesPerLine = channels * width q_img = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888) scene = QGraphicsScene() scene.addPixmap(QPixmap(q_img)) return scene
class ImageDocument(DocumentInterface): def __init__(self, associated_view): super().__init__() self._selection = tuple() self._assoc_view = associated_view self._scene = QGraphicsScene(associated_view) self._pixmap = QPixmap() @property def contents(self): return self._scene @property def raw(self): raw_contents = RawContents(image=self._pixmap.toImage()) return raw_contents('image') @property def selection(self): return self._selection @selection.setter def selection(self, value): self._selection = tuple(value) @property def has_selection(self): # the same as an `if not ...` / etc. return bool(self._selection) @property def associated_view(self): return self._assoc_view def load_document(self, load_callback): load_callback(self._pixmap) if self._pixmap.isNull(): return False self._scene.addPixmap(self._pixmap) self._scene.setSceneRect(0, 0, self._pixmap.width(), self._pixmap.height()) return True def reset_document(self): self._scene.clear() def save_document(self, file_obj, format): raise NotImplementedError def get_selection_as_image(self): if not self.has_selection: raise ValueError("No Selection.") return self._pixmap.toImage().copy(*self._selection)
class MyApp(QMainWindow, Ui_MainWindow): def __init__(self): QMainWindow.__init__(self) super().__init__() self.initUI() print("self.statusbar.currentMessage():", self.statusbar.currentMessage()) def initUI(self): self.setupUi(self) self.actionOpen_File.triggered.connect(self.openMsg) self.pushButton.clicked.connect(self.oncle) self.show() # 显示 def openMsg(self): self.file, ok = QFileDialog.getOpenFileName(self, "打开", "F:\\", "Images (*.*)") self.scene = QGraphicsScene() self.pixmap = QPixmap(self.file) self.scene.addPixmap(self.pixmap) self.graphicsView.setScene(self.scene) self.statusbar.showMessage(self.file) def oncle(self): if self.statusbar.currentMessage() != '': if self.comboBox.currentText() == "YOLO": parser = argparse.ArgumentParser() parser.add_argument('--weights', default="YOLO_small.ckpt", type=str) parser.add_argument('--weight_dir', default='weights', type=str) parser.add_argument('--data_dir', default="data", type=str) parser.add_argument('--gpu', default='', type=str) args = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu yolo = YOLONet(False) weight_file = os.path.join(args.data_dir, args.weight_dir, args.weights) detector = Detector(yolo, weight_file) # detect from camera # cap = cv2.VideoCapture(-1) # detector.camera_detector(cap) # detect from image file imname = self.file detector.image_detector(imname) scene = QGraphicsScene() pixmap = QPixmap("D:\\result.jpg") scene.addPixmap(pixmap) self.graphicsView_2.setScene(scene) elif self.comboBox.currentText() == "MaskRCNN": self.maskRCNN = demo.MaskRCNN() self.maskRCNN.detect(self.file) scene = QGraphicsScene() pixmap = QPixmap("D:\\result3.jpg") scene.addPixmap(pixmap) self.graphicsView_2.setScene(scene)
def showImageFile(self, imageFile, _QGraphicsView_obj): # 显示图片 # input: image path, QGraphicsView object pixmap = QPixmap(imageFile) scene = QGraphicsScene() pixmap = pixmap.scaled(_QGraphicsView_obj.size(), Qt.KeepAspectRatio) scene.clear() scene.addPixmap(pixmap) _QGraphicsView_obj.setScene(scene)
def resizeBackgroundImage(self): scene = QGraphicsScene() pixmap = QtGui.QPixmap(self.settings.background_frame) scene.addPixmap(pixmap) scale_factor = self.background_preview.width()/scene.width() self.background_preview.scale(scale_factor, scale_factor) self.background_preview.fitInView( scene.sceneRect(), mode=QtCore.Qt.KeepAspectRatio) self.background_preview.setScene(scene)
def imageSelect(self): filename = QFileDialog.getOpenFileName(self, "OpenFile", ".", "Image Files(*.jpg *.jpeg *.png *.bmp)")[0] if len(filename): image = QImage(filename) scene = QGraphicsScene() scene.addPixmap(QPixmap.fromImage(image)) self.graphicsView.setScene(scene) # self.graphicsView.resize(image.width(), image.height()) self.graphicsView.show()
class ExampleApp(QMainWindow, design.Ui_MainWindow,QtCore.QThread):# this is class for administrator window def __init__(self): # Explaining super is out of the scope of this article # So please google it if you're not familar with it # Simple reason why we use it here is that it allows us to # access variables, methods etc in the design.py file super(self.__class__, self).__init__() self.setupUi(self) # This is defined in design.py file automatically self.thread1 = QWorker("thread1") self.thread2 = QWorker2("thread2") # It sets up layout and widgets that are defined self.toolButton.clicked.connect(self.browse_port) self.toolButton_2.clicked.connect(self.recognize) self.horizontalSlider.setMinimum(1) self.horizontalSlider.setMaximum(100) self.horizontalSlider.setSingleStep(10) self.horizontalSlider.setValue(10) self.horizontalSlider.valueChanged.connect(self.getValueHorizontal) self.toolButton_3.clicked.connect(self.showDialog) def showDialog(self): global filename filename = QFileDialog.getOpenFileName(self, 'Open File', '*.jpg')[0] if filename=='': filename = 'D:\q.jpg' self.scence = QGraphicsScene() self.scence.addPixmap(QPixmap.scaled(QPixmap(filename),300, 180)) self.graphicsView.setScene(self.scence) def getValueHorizontal(self): value = self.horizontalSlider.value() self.label.setText(str(value/1000)) val=value/1000 def recognize(self): r = recognize(filename) my_keys = r.keys() self.textEdit.setText(str('–езультат:')) for i in my_keys: if i=='pansy': self.textEdit.append('‘иалка = %.1f%%' % ( (r.get(i) * 100))) if i == 'lilyvalley': self.textEdit.append('Ћандыш = %.1f%%' % ( (r.get(i) * 100))) def browse_port(self): global p subprocess.Popen(["retrain.py", '--image_dir', 'images', '--learning_rate', val ], shell=True)
def __init__(self, parent, bank_name, required_input): DialogContainer.__init__(self, parent) self.required_input = required_input uic.loadUi(get_ui_file_path('iom_input_dialog.ui'), self.dialog_widget) self.dialog_widget.cancel_button.clicked.connect( lambda: self.button_clicked.emit(0)) self.dialog_widget.confirm_button.clicked.connect( lambda: self.button_clicked.emit(1)) if 'error_text' in required_input: self.dialog_widget.error_text_label.setText( required_input['error_text']) else: self.dialog_widget.error_text_label.hide() if 'image' in required_input['additional_data']: qimg = QImage() qimg.loadFromData( b64decode(required_input['additional_data']['image'])) image = QPixmap.fromImage(qimg) scene = QGraphicsScene(self.dialog_widget.img_graphics_view) scene.addPixmap(image) self.dialog_widget.img_graphics_view.setScene(scene) else: self.dialog_widget.img_graphics_view.hide() self.dialog_widget.iom_input_title_label.setText(bank_name) vlayout = QVBoxLayout() self.dialog_widget.user_input_container.setLayout(vlayout) self.input_widgets = {} for specific_input in self.required_input['required_fields']: label_widget = QLabel(self.dialog_widget.user_input_container) label_widget.setText(specific_input['text'] + ":") label_widget.show() vlayout.addWidget(label_widget) input_widget = QLineEdit(self.dialog_widget.user_input_container) input_widget.setPlaceholderText(specific_input['placeholder']) if specific_input['type'] == 'password': input_widget.setEchoMode(QLineEdit.Password) input_widget.show() vlayout.addWidget(input_widget) self.input_widgets[specific_input['name']] = input_widget self.dialog_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.dialog_widget.adjustSize() self.on_main_window_resize()
def img_view(self, lst): raw_image = cv2.imread(lst[0][0]) height, width, channel = raw_image.shape bytes_per_line = width * 3 image = QtGui.QImage(raw_image.data, width, height, bytes_per_line, QtGui.QImage.Format_RGB888) scene = QGraphicsScene() scene.addPixmap(QPixmap=QtGui.QPixmap.fromImage(logic.path)) self.graphic.setScene( scene) # здесь метод отображения картинки в виджете
def clear(self): clear_img = 255 * np.ones(shape=[600, 800, 3], dtype=np.uint8) scene = QGraphicsScene() pixmap1 = QPixmap.fromImage( QImage(clear_img, clear_img.shape[1], clear_img.shape[0], clear_img.strides[0], QImage.Format_RGB888)) scene.addPixmap(pixmap1) self.graphicsView.setScene(scene) self.graphicsView.viewport().update() self.lastPoint = QPoint() self.listPoint = []
def __init__(self, parent, bank_name, required_input): DialogContainer.__init__(self, parent) self.required_input = required_input uic.loadUi(get_ui_file_path('iom_input_dialog.ui'), self.dialog_widget) self.dialog_widget.cancel_button.clicked.connect(lambda: self.button_clicked.emit(0)) self.dialog_widget.confirm_button.clicked.connect(lambda: self.button_clicked.emit(1)) if 'error_text' in required_input: self.dialog_widget.error_text_label.setText(required_input['error_text']) else: self.dialog_widget.error_text_label.hide() if 'image' in required_input['additional_data']: qimg = QImage() qimg.loadFromData(b64decode(required_input['additional_data']['image'])) image = QPixmap.fromImage(qimg) scene = QGraphicsScene(self.dialog_widget.img_graphics_view) scene.addPixmap(image) self.dialog_widget.img_graphics_view.setScene(scene) else: self.dialog_widget.img_graphics_view.hide() self.dialog_widget.iom_input_title_label.setText(bank_name) vlayout = QVBoxLayout() self.dialog_widget.user_input_container.setLayout(vlayout) self.input_widgets = {} for specific_input in self.required_input['required_fields']: label_widget = QLabel(self.dialog_widget.user_input_container) label_widget.setText(specific_input['text'] + ":") label_widget.show() vlayout.addWidget(label_widget) input_widget = QLineEdit(self.dialog_widget.user_input_container) input_widget.setPlaceholderText(specific_input['placeholder']) if specific_input['type'] == 'password': input_widget.setEchoMode(QLineEdit.Password) input_widget.show() vlayout.addWidget(input_widget) self.input_widgets[specific_input['name']] = input_widget self.dialog_widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) self.dialog_widget.adjustSize() self.on_main_window_resize()
def go(): global graphic_view, status_label data_parent, data_child = Pipe(duplex=False) receiver = Process(target=generate_data, args=(data_child,)) receiver.daemon = True receiver.start() scene = QGraphicsScene() graphic_view.setScene(scene) scene.setSceneRect(0, 0, 1024, 1024) x_pos = 0 y_pos = 0 t = time.time() while True: speed = time.time() data = data_parent.recv() spectrogram = Spectrogram(data) pixmap = QPixmap.fromImage(spectrogram.create_spectrogram_image(transpose=True)) scene.setSceneRect(scene.sceneRect().adjusted(0, 0, 0, pixmap.height())) item = scene.addPixmap(pixmap) item.setPos(x_pos, y_pos) y_pos += pixmap.height() graphic_view.fitInView(scene.sceneRect()) status_label.setText("Height: {0:.0f} // Speed: {1:.2f} // Total Time: {2:.2f}".format(scene.sceneRect().height(), 1/(time.time()-speed), time.time()-t)) QApplication.instance().processEvents()
def main(): app = QApplication(sys.argv) grview = QGraphicsView() scene = QGraphicsScene() scene.setSceneRect(0, 0, 680, 459) scene.addPixmap(QPixmap('../images/phototest.tif')) grview.setScene(scene) item = AreaItem(0, 0, 300, 150) item.areaColor = QColor(155, 155, 0, 75) scene.addItem(item) grview.fitInView(scene.sceneRect(), Qt.KeepAspectRatio) grview.show() sys.exit(app.exec_())
def start_beep(self): drawbars = str(self.verticalSlider_1.value()) + \ str(self.verticalSlider_2.value()) + \ str(self.verticalSlider_3.value()) + \ str(self.verticalSlider_4.value()) + \ str(self.verticalSlider_5.value()) + \ str(self.verticalSlider_6.value()) + \ str(self.verticalSlider_7.value()) + \ str(self.verticalSlider_8.value()) + \ str(self.verticalSlider_9.value()) duration = self.doubleSpinBox_1.value() tonic_number = (12 * self.spinBox.value() + self.tonic_combo) tonic_frequency = 2 ** (( tonic_number - 57) / 12) * self.doubleSpinBox_2.value() self.statusbar.showMessage( 'Fundamental frequency: {0:.2f} Hz. Press Enter to synthesize next sound.'.format(tonic_frequency)) if self.radioButton_2.isChecked(): frequencies = [tonic_frequency * 2 ** (x / 12) for x in range(len(self.pushButtons))] else: frequencies = [tonic_frequency * x for x in [1, 256 / 243, 9 / 8, 32 / 27, 81 / 64, 4 / 3, 1024 / 729, 729 / 512, 3 / 2, 128 / 81, 27 / 16, 16 / 9, 243 / 128]] for i in range(len(self.pushButtons)): if not self.pushButtons[i].isChecked(): frequencies[i] = 0 t, x = self.synth.make_chord(frequencies, drawbars, duration, self.checkBox.isChecked()) self.synth.play(x) xbar, inst_ph = self.synth.make_analytical(x) filename = 'synth.png' self.synth.plot_hilbert(xbar, filename) scene = QGraphicsScene() scene.addPixmap(QPixmap(filename)) self.graphicsView.setScene(scene)
def getAll(self,filter={}): self.tableWidget.clear() try: data = self.parent.db.get(filter) self.tableWidget.setRowCount(len(data)) self.tableWidget.setColumnCount(5) self.tableWidget.setHorizontalHeaderLabels(["Resim","Ad","Soyad","No"]) iz = 0 for i in data: ad = QTableWidgetItem(i[1]) soyad = QTableWidgetItem(i[2]) no = QTableWidgetItem(i[3]) gp = QGraphicsScene(self) resim = QGraphicsView(gp) resim.setFixedHeight(100) resim.setFixedWidth(100) if i[8] is not None: gp.addPixmap(QPixmap("db/%s" % i[8])) resim.show() self.tableWidget.setCellWidget(iz,0,resim) btn = QPushButton(self) btn.setText("Göster") btn.data = i btn.clicked.connect(self.showogrenci) self.tableWidget.setItem(iz,1,ad) self.tableWidget.setItem(iz,2,soyad) self.tableWidget.setItem(iz,3,no) self.tableWidget.setCellWidget(iz,4,btn) self.tableWidget.setRowHeight(iz,100) iz +=1 except Exception as e: print(e)
def visualize_data(window, data_manager, search_results): # Scene where everything will be drawn scene = QGraphicsScene() reference_radiograph = data_manager.left_out_radiograph reference_image = reference_radiograph.image reference_teeth = data_manager.get_all_teeth_from_radiograph(reference_radiograph) # Draw reference image first qimg = toQImage(reference_image.astype(np.uint8)) scene.addPixmap(QPixmap.fromImage(qimg)) for tooth in reference_teeth: assert isinstance(tooth, Tooth) tooth.outline_pen = QPen(QColor.fromRgb(0, 0, 255)) tooth.draw(scene) if search_results is not None: for tooth in search_results: assert isinstance(tooth, Tooth) tooth.draw(scene) window.set_scene(scene)
class Image_View(QGraphicsView): def __init__(self, centralwidget): super(Image_View, self).__init__(centralwidget) self.scene = QGraphicsScene() self.pixmap = QPixmap() self.painter = Painter() self.setup_ui() def setup_ui(self): # GraphicsItem self.scene.addPixmap(self.pixmap) self.scene.addItem(self.painter) self.setScene(self.scene) self.setCacheMode(QGraphicsView.CacheBackground) # defs from super class def keyPressEvent(self, event): key = event.key() if key == Qt.Key_R: self.painter.reset()
def init(self): self.window = loadUi(os.path.join(get_ui_path(),"splash.ui")) self.window.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint) self.center() self.window.li.setText(notice()+"\n"+version()) self.window.setModal(Qt.WindowModal) self.window.image.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.window.image.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) window_h=self.window.height() window_w=self.window.width() r=random.randint(2, 3) image=QPixmap(os.path.join(get_image_file_path(),"splash"+str(r)+".png")) image.scaledToHeight(window_h) w=image.width() h=image.height() x_max=w-window_h-window_w/2 hour=float(time.strftime("%H"))*60 m=float(time.strftime("%m")) tot=hour+m my_max=float(24*60) value=tot/my_max xpos=int(x_max*value)+window_w/2 print("xpos=",xpos) scene=QGraphicsScene(); scene.setSceneRect(xpos, 0, 0, h) self.window.image.setScene(scene) self.window.show() scene.addPixmap(image); QTimer.singleShot(1500, self.callback_destroy)
class InitialPoseDialog(QDialog, Ui_PoseDialog): data_manager = None image = None y_line = 0 y_top_line = 0 y_lower_line = 0 landmark_size = 2 lines = None middle_idx = 0 pose_model = None def __init__(self, data_manager): super(InitialPoseDialog, self).__init__() self.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) assert isinstance(data_manager, DataManager) self.data_manager = data_manager self.pose_model = InitialPoseModel(data_manager) self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) self.image = Filter.crop_image(self.data_manager.radiographs[0].image) self.findButton.clicked.connect(self.find_jaw_divider) self.openButton.clicked.connect(self._open_radiograph) self._redraw() def find_jaw_divider(self): self.y_top_line, self.y_lower_line = self.pose_model._find_jaw_separation_line(self.pose_model._crop_image_sides(self.image)) upper_jaw_image = self.pose_model.crop_upper_jaw(self.image, self.y_top_line) lower_jaw_image = self.pose_model.crop_lower_jaw(self.image, self.y_lower_line) # Filter the image upper_jaw_image = Filter.process_image(upper_jaw_image, median_kernel=5, bilateral_kernel=17, bilateral_color=6) lower_jaw_image = Filter.process_image(lower_jaw_image, median_kernel=5, bilateral_kernel=17, bilateral_color=6) upper_jaw_image = self.pose_model._convert_to_binary_image(upper_jaw_image) lower_jaw_image = self.pose_model._convert_to_binary_image(lower_jaw_image) upper_lines = self.pose_model._find_hough_lines(upper_jaw_image, threshold=15) lower_lines = self.pose_model._find_hough_lines(lower_jaw_image, threshold=15) # Filter out lines upper_lines = self.pose_model._filter_lines(upper_lines, upper_jaw_image.shape, line_offset=6, max_line_gap=90) lower_lines = self.pose_model._filter_lines(lower_lines, lower_jaw_image.shape, line_offset=2, max_line_gap=60) self.image = lower_jaw_image self.lines = lower_lines self._redraw() def _open_radiograph(self): file_dialog = QFileDialog(self) file_dialog.setDirectory("./data/Radiographs") file_dialog.setFileMode(QFileDialog.ExistingFile) file_dialog.setNameFilter("Radiograph (*.tif)") if file_dialog.exec_() and len(file_dialog.selectedFiles()) == 1: radiograph = Radiograph() radiograph.path_to_img = file_dialog.selectedFiles()[0] #self.image = radiograph.image #crop_translation = -Filter.get_cropping_region(radiograph.image).left_top self.image = Filter.crop_image(radiograph.image) self.lines = None self._redraw() def _redraw(self, normalize=False): self.scene.clear() img = self.image.copy() if normalize: img = (img / img.max()) * 255 # Draw image qimg = toQImage(img.astype(np.uint8)) self.scene.addPixmap(QPixmap.fromImage(qimg)) # Add jaws divider self.scene.addLine(QLineF(0, self.y_line, self.image.shape[1], self.y_line), pen=QPen(QColor.fromRgb(255, 0, 0))) self.scene.addLine(QLineF(0, self.y_top_line, self.image.shape[1], self.y_top_line), pen=QPen(QColor.fromRgb(255, 0, 0))) self.scene.addLine(QLineF(0, self.y_lower_line, self.image.shape[1], self.y_lower_line), pen=QPen(QColor.fromRgb(255, 0, 0))) # Add image center self.scene.addEllipse(self.image.shape[0]/2 - self.landmark_size, self.image.shape[1]/2 - self.landmark_size, self.landmark_size * 2, self.landmark_size * 2, pen=QPen(QColor.fromRgb(255, 0, 0)), brush=QBrush(QColor.fromRgb(255, 0, 0))) # Draw Hough lines if self.lines is not None: #for x1,y1,x2,y2 in self.lines[0]: for i, line_param in enumerate(self.lines): rho,theta = line_param a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 200*(-b)) y1 = int(y0 + 200*(a)) x2 = int(x0 - 200*(-b)) y2 = int(y0 - 200*(a)) self.scene.addLine(QLineF(x1, y1, x2, y2), pen=QPen(QColor.fromRgb(0, 255, 0)))
class Lighting(QGraphicsView): def __init__(self, parent=None): super(Lighting, self).__init__(parent) self.angle = 0.0 self.m_scene = QGraphicsScene() self.m_lightSource = None self.m_items = [] self.setScene(self.m_scene) self.setupScene() self.timer = QTimer(self) self.timer.timeout.connect(self.animate) self.timer.setInterval(30) self.timer.start() self.setRenderHint(QPainter.Antialiasing) self.setFrameStyle(QFrame.NoFrame) def setupScene(self): self.m_scene.setSceneRect(-300, -200, 600, 460) linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100)) linearGrad.setColorAt(0, Qt.darkGreen)#QColor(255, 255, 255)) linearGrad.setColorAt(1, Qt.green)#QQColor(192, 192, 255)) self.setBackgroundBrush(linearGrad) radialGrad = QRadialGradient(30, 30, 30) radialGrad.setColorAt(0, Qt.yellow) radialGrad.setColorAt(0.2, Qt.yellow) radialGrad.setColorAt(1, Qt.transparent) pixmap = QPixmap(60, 60) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.setBrush(radialGrad) painter.drawEllipse(0, 0, 60, 60) painter.end() self.m_lightSource = self.m_scene.addPixmap(pixmap) self.m_lightSource.setZValue(2) self.proto = ProtoObj(0, 0, 50, 50, self) self.proto.initObj() #self.m_items.append(self.proto.getObj()[0]) self.m_scene.addItem(self.proto.getObj()[0]) #self.m_scene.addItem(self.proto.getObj()[1]) def animate(self): self.angle += (math.pi / 30) xs = 200 * math.sin(self.angle) - 40 + 25 ys = 200 * math.cos(self.angle) - 40 + 25 self.m_lightSource.setPos(xs, ys) item = self.proto.getObj()[0] effect = item.graphicsEffect() delta = QPointF(item.x() - xs, item.y() - ys) effect.setOffset(QPointF(delta.toPoint() / 30)) dd = math.hypot(delta.x(), delta.y()) color = effect.color() color.setAlphaF(max(0.4, min(1 - dd / 200.0, 0.7))) effect.setColor(color) item.setPos(self.proto.posX, self.proto.posY) #self.proto.animate(0) #self.proto.pix.setPos(self.proto.posX, self.proto.posY) self.m_scene.update() def keyPressEvent(self, event): key = event.key() if key == Qt.Key_Up or key == Qt.Key_W: #print('Pressed Up or W?') self.proto.moveObj(0, -10) #self.player.move(0, -10) if key == Qt.Key_Down or key == Qt.Key_S: #print('Pressed Down or S?') self.proto.moveObj(0, 10) #self.player.move(0, 10) if key == Qt.Key_Left or key == Qt.Key_A: #print('Pressed Left or A?') self.proto.moveObj(-10, 0) #self.player.move(-10, 0) if key == Qt.Key_Right or key == Qt.Key_D: #print('Pressed Right or D?') self.proto.moveObj(10, 0) #self.player.move(10, 0) if key == Qt.Key_Escape: exit() super(Lighting, self).keyPressEvent(event)
class ImageViewerQt(QGraphicsView): """ PyQt image viewer widget for a QPixmap in a QGraphicsView scene with mouse zooming and panning. Displays a QImage or QPixmap (QImage is internally converted to a QPixmap). To display any other image format, you must first convert it to a QImage or QPixmap. Some useful image format conversion utilities: qimage2ndarray: NumPy ndarray <==> QImage (https://github.com/hmeine/qimage2ndarray) ImageQt: PIL Image <==> QImage (https://github.com/python-pillow/Pillow/blob/master/PIL/ImageQt.py) Mouse interaction: Left mouse button drag: Pan image. Right mouse button drag: Zoom box. Right mouse button doubleclick: Zoom to show entire image. """ # Mouse button signals emit image scene (x, y) coordinates. # !!! For image (row, column) matrix indexing, row = y and column = x. leftMouseButtonPressed = pyqtSignal(float, float) rightMouseButtonPressed = pyqtSignal(float, float) leftMouseButtonReleased = pyqtSignal(float, float) rightMouseButtonReleased = pyqtSignal(float, float) leftMouseButtonDoubleClicked = pyqtSignal(float, float) rightMouseButtonDoubleClicked = pyqtSignal(float, float) def __init__(self): QGraphicsView.__init__(self) # Image is displayed as a QPixmap in a QGraphicsScene attached to this QGraphicsView. self.scene = QGraphicsScene() self.setScene(self.scene) # Store a local handle to the scene's current image pixmap. self._pixmapHandle = None # Image aspect ratio mode. # !!! ONLY applies to full image. Aspect ratio is always ignored when zooming. # Qt.IgnoreAspectRatio: Scale image to fit viewport. # Qt.KeepAspectRatio: Scale image to fit inside viewport, preserving aspect ratio. # Qt.KeepAspectRatioByExpanding: Scale image to fill the viewport, preserving aspect ratio. self.aspectRatioMode = Qt.KeepAspectRatio # Scroll bar behaviour. # Qt.ScrollBarAlwaysOff: Never shows a scroll bar. # Qt.ScrollBarAlwaysOn: Always shows a scroll bar. # Qt.ScrollBarAsNeeded: Shows a scroll bar only when zoomed. self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Stack of QRectF zoom boxes in scene coordinates. self.zoomStack = [] # Flags for enabling/disabling mouse interaction. self.canZoom = True self.canPan = True def hasImage(self): """ Returns whether or not the scene contains an image pixmap. """ return self._pixmapHandle is not None def clearImage(self): """ Removes the current image pixmap from the scene if it exists. """ if self.hasImage(): self.scene.removeItem(self._pixmapHandle) self._pixmapHandle = None def pixmap(self): """ Returns the scene's current image pixmap as a QPixmap, or else None if no image exists. :rtype: QPixmap | None """ if self.hasImage(): return self._pixmapHandle.pixmap() return None def image(self): """ Returns the scene's current image pixmap as a QImage, or else None if no image exists. :rtype: QImage | None """ if self.hasImage(): return self._pixmapHandle.pixmap().toImage() return None def setImage(self, image): """ Set the scene's current image pixmap to the input QImage or QPixmap. Raises a RuntimeError if the input image has type other than QImage or QPixmap. :type image: QImage | QPixmap """ if type(image) is QPixmap: pixmap = image elif type(image) is QImage: pixmap = QPixmap.fromImage(image) else: raise RuntimeError("ImageViewer.setImage: Argument must be a QImage or QPixmap.") if self.hasImage(): self._pixmapHandle.setPixmap(pixmap) else: self._pixmapHandle = self.scene.addPixmap(pixmap) self.setSceneRect(QRectF(pixmap.rect())) # Set scene size to image size. self.updateViewer() def loadImageFromFile(self, fileName=""): """ Load an image from file. Without any arguments, loadImageFromFile() will popup a file dialog to choose the image file. With a fileName argument, loadImageFromFile(fileName) will attempt to load the specified image file directly. """ if len(fileName) == 0: if QT_VERSION_STR[0] == '4': fileName = QFileDialog.getOpenFileName(self, "Open image file.") elif QT_VERSION_STR[0] == '5': fileName, dummy = QFileDialog.getOpenFileName(self, "Open image file.") if len(fileName) and os.path.isfile(fileName): image = QImage(fileName) self.setImage(image) def updateViewer(self): """ Show current zoom (if showing entire image, apply current aspect ratio mode). """ if not self.hasImage(): return if len(self.zoomStack) and self.sceneRect().contains(self.zoomStack[-1]): self.fitInView(self.zoomStack[-1], Qt.IgnoreAspectRatio) # Show zoomed rect (ignore aspect ratio). else: self.zoomStack = [] # Clear the zoom stack (in case we got here because of an invalid zoom). self.fitInView(self.sceneRect(), self.aspectRatioMode) # Show entire image (use current aspect ratio mode). def resizeEvent(self, event): """ Maintain current zoom on resize. """ self.updateViewer() def mousePressEvent(self, event): """ Start mouse pan or zoom mode. """ scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: if self.canPan: self.setDragMode(QGraphicsView.ScrollHandDrag) self.leftMouseButtonPressed.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: self.setDragMode(QGraphicsView.RubberBandDrag) self.rightMouseButtonPressed.emit(scenePos.x(), scenePos.y()) QGraphicsView.mousePressEvent(self, event) def mouseReleaseEvent(self, event): """ Stop mouse pan or zoom mode (apply zoom if valid). """ QGraphicsView.mouseReleaseEvent(self, event) scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: self.setDragMode(QGraphicsView.NoDrag) self.leftMouseButtonReleased.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: viewBBox = self.zoomStack[-1] if len(self.zoomStack) else self.sceneRect() selectionBBox = self.scene.selectionArea().boundingRect().intersected(viewBBox) self.scene.setSelectionArea(QPainterPath()) # Clear current selection area. if selectionBBox.isValid() and (selectionBBox != viewBBox): self.zoomStack.append(selectionBBox) self.updateViewer() self.setDragMode(QGraphicsView.NoDrag) self.rightMouseButtonReleased.emit(scenePos.x(), scenePos.y()) def mouseDoubleClickEvent(self, event): """ Show entire image. """ scenePos = self.mapToScene(event.pos()) if event.button() == Qt.LeftButton: self.leftMouseButtonDoubleClicked.emit(scenePos.x(), scenePos.y()) elif event.button() == Qt.RightButton: if self.canZoom: self.zoomStack = [] # Clear zoom stack. self.updateViewer() self.rightMouseButtonDoubleClicked.emit(scenePos.x(), scenePos.y()) QGraphicsView.mouseDoubleClickEvent(self, event)
class FilteringDialog(QDialog, Ui_Dialog): scene = None base_image = None image = None current_sampling_level = 0 sliders = None labels = None fit_allowed = False def __init__(self, data_manager): super(FilteringDialog, self).__init__() self.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) assert isinstance(data_manager, DataManager) self.base_image = data_manager.radiographs[0].image h, w = self.base_image.shape ch, cw = h / 2, w / 2 self.base_image = self.base_image[ch - 100:ch + 500, cw - 150:cw + 150].copy() self.image = self.base_image self.scene = QGraphicsScene() self.graphicsView.setScene(self.scene) self.levelSlider.setRange(1, MultiResolutionFramework.levels_count) self.levelSlider.setValue(self.current_sampling_level + 1) self.levelSlider.valueChanged.connect(self._sampling_level_changed) ranges = [(0, 20), (0, 20), (0, 20), (0, 200), (0, 200)] values = [2, 8, 9, 0, 5] self.sliders = list() self.labels = list() for i in range(0, len(ranges)): slider = QSlider(Qt.Horizontal, self.scrollAreaWidgetContents) label = QLabel() slider.setRange(ranges[i][0], ranges[i][1]) slider.setValue(values[i]) slider.valueChanged.connect(self._slider_moved) layout = QHBoxLayout() layout.addWidget(slider) layout.addWidget(label) self.scrollAreaWidgetContents.layout().addLayout(layout) self.sliders.append(slider) self.labels.append(label) self._set_labels() self._redraw() def _sampling_level_changed(self, value): self.current_sampling_level = value - 1 self.image = self.base_image scale = 1.0 for i in range(0, self.current_sampling_level): self.image = MultiResolutionFramework.downsample_image(self.image) scale *= 2 self.graphicsView.resetTransform() self.graphicsView.scale(scale, scale) self._redraw() def _slider_moved(self, value): self._set_labels() self._redraw() def _set_labels(self): for i, label in enumerate(self.labels): value = self.sliders[i].value() if i < 2: value = value * 2 + 1 if value >= 1 else 0 label.setText(str(value)) def _scharr_filter(self, img): grad_x = cv2.Scharr(img, cv2.CV_64F, 1, 0) / 16 grad_y = cv2.Scharr(img, cv2.CV_64F, 0, 1) / 16 grad = np.sqrt(grad_x ** 2 + grad_y ** 2) return grad def _perform_fft(self, img): f = np.fft.fft2(img) fshift = np.fft.fftshift(f) return fshift def _focus_view(self, size): if not self.fit_allowed: self.fit_allowed = True return rect = QRectF(0, 0, size[0], size[1]) self.scene.setSceneRect(rect) def _redraw(self): self.scene.clear() img = self.image.copy() med_kernel = self.sliders[0].value() * 2 + 1 bi_kernel = self.sliders[1].value() * 2 + 1 bi_color = self.sliders[2].value() med = cv2.medianBlur(img, med_kernel) if med_kernel > 1 else img med_bi = cv2.bilateralFilter(med, bi_kernel, bi_color, 200) if bi_kernel > 1 else med fshift = self._perform_fft(med_bi) # scharr = np.array([[ -1/16-1/16j, 1/2-1/8j, +1/16 -1/16j], # [-1/8+0j, 1/2+0j, +1/8 +0j], # [ -1/16+1/16j, 0+1/8j, +1/16 +1/16j]]) # Gx + j*Gy # fshift = signal.convolve2d(fshift, scharr, boundary='symm', mode='same') if self.sliders[3].value() != 0: rows, cols = img.shape crow, ccol = rows / 2, cols / 2 mask = np.zeros(fshift.shape) cv2.circle(mask, (ccol, crow), self.sliders[3].value(), 1, -1) cv2.circle(mask, (ccol, crow), self.sliders[4].value(), 0, -1) fshift *= mask f_ishift = np.fft.ifftshift(fshift) img_back = np.fft.ifft2(f_ishift) img_back = np.abs(img_back) grad_med_bi = self._scharr_filter(img_back) # img = (img / img.max()) * 255 mag = 20 * np.log(np.abs(fshift)) mag = (mag / mag.max()) * 255 img_back = (img_back / img_back.max()) * 255 grad_med_bi = (grad_med_bi / grad_med_bi.max()) * 255 together = np.hstack( (img.astype(np.uint8), mag.astype(np.uint8), img_back.astype(np.uint8), grad_med_bi.astype(np.uint8))) cv2.imwrite("together.png", together) qimg = toQImage(together) self.scene.addPixmap(QPixmap.fromImage(qimg)) self._focus_view((qimg.width(), qimg.height()))
class Lighting(QGraphicsView): def __init__(self, parent=None): super(Lighting, self).__init__(parent) self.angle = 0.0 self.m_scene = QGraphicsScene() self.m_lightSource = None self.m_items = [] self.setScene(self.m_scene) self.setupScene() timer = QTimer(self) timer.timeout.connect(self.animate) timer.setInterval(30) timer.start() self.setRenderHint(QPainter.Antialiasing) self.setFrameStyle(QFrame.NoFrame) def setupScene(self): self.m_scene.setSceneRect(-300, -200, 600, 460) linearGrad = QLinearGradient(QPointF(-100, -100), QPointF(100, 100)) linearGrad.setColorAt(0, QColor(255, 255, 255)) linearGrad.setColorAt(1, QColor(192, 192, 255)) self.setBackgroundBrush(linearGrad) radialGrad = QRadialGradient(30, 30, 30) radialGrad.setColorAt(0, Qt.yellow) radialGrad.setColorAt(0.2, Qt.yellow) radialGrad.setColorAt(1, Qt.transparent) pixmap = QPixmap(60, 60) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) painter.setPen(Qt.NoPen) painter.setBrush(radialGrad) painter.drawEllipse(0, 0, 60, 60) painter.end() self.m_lightSource = self.m_scene.addPixmap(pixmap) self.m_lightSource.setZValue(2) for i in range(-2, 3): for j in range(-2, 3): if (i + j) & 1: item = QGraphicsEllipseItem(0, 0, 50, 50) else: item = QGraphicsRectItem(0, 0, 50, 50) item.setPen(QPen(Qt.black, 1)) item.setBrush(QBrush(Qt.white)) effect = QGraphicsDropShadowEffect(self) effect.setBlurRadius(8) item.setGraphicsEffect(effect) item.setZValue(1) item.setPos(i * 80, j * 80) self.m_scene.addItem(item) self.m_items.append(item) def animate(self): self.angle += (math.pi / 30) xs = 200 * math.sin(self.angle) - 40 + 25 ys = 200 * math.cos(self.angle) - 40 + 25 self.m_lightSource.setPos(xs, ys) for item in self.m_items: effect = item.graphicsEffect() delta = QPointF(item.x() - xs, item.y() - ys) effect.setOffset(QPointF(delta.toPoint() / 30)) dd = math.hypot(delta.x(), delta.y()) color = effect.color() color.setAlphaF(max(0.4, min(1 - dd / 200.0, 0.7))) effect.setColor(color) self.m_scene.update()
class historywindow(QWidget): def __init__(self): super(historywindow,self).__init__() self.UI=Ui_History() self.UI.setupUi(self) self.show() self.SQL = gdal_sqlite() self.MapId = 'LT51190381991204BJC00' # TODO:修改为从用户列表处选择的返回值 self.get_imagepath() self.show_riverlist() self.show_maplist() self.show_image() self.UI.treeWidget.clicked.connect(self.getCurrentIndex) def getCurrentIndex(self): text = self.UI.treeWidget.currentItem().text(1) if text != None: print (text) QMessageBox.warning(None, "treeview select", str(text)) '''TODO:self.model''' def updata_mapid(self,MapId): self.MapId = MapId def updata_riverid(self): """用户点击选择河流,返回河流ID""" self.riverid = "TH" def get_imagepath(self): self.image_path = self.SQL.Read_River_Map(self.MapId) def get_riverlist(self): self.updata_riverid() self.riverlist = self.SQL.Read_riverlist() def get_maplist(self): self.maplist = self.SQL.Read_maplist(self.riverid) print (self.maplist) def show_riverlist(self): self.get_riverlist() for i in range(len(self.riverlist.index)): self.UI.comboBox.addItem("") self.UI.comboBox.setItemText(i, self.riverlist.RiverName[i]) def show_maplist(self): self.riverid = 'TH' DT = Gis_DrawTree() self.get_maplist() self.UI.treeWidget = DT.draw_tree(self.maplist,self.UI.treeWidget) pass def show_image(self): print (self.image_path) self.Image = QImage() self.Image.load(self.image_path) if self.Image == None: print ("图像读取错误") sys.exit() else: from PIL import Image from PIL.ImageQt import ImageQt #img = Image.open(self.image_path) img = Image.open('/Users/chensiye/zhizi.jpg') w, h = img.size print (w,h) imgQ = ImageQt(img) pixMap = QPixmap.fromImage(imgQ) self.scene = QGraphicsScene() self.scene.addPixmap(pixMap) #self.scene.setSceneRect(0, 0, 1, 1) view = self.UI.graphicsView view.setScene(self.scene) view.setSceneRect(0,0,w,h) #view.resize(1000,1000) #print (view.size()) view.fitInView(QtCore.QRectF(0, 0, w, h), QtCore.Qt.KeepAspectRatio) """
class Shufti(ShuftiWindow): def __init__(self): super(Shufti,self).__init__() try: self.key = sys.argv[1] except IndexError: print('\nshufti 2.2\n\nTo use shufti from the terminal, you must specify the full path to an image as a parameter.\n') sys.exit(1) self.dbSanitise() self.formats = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.pbm', '.pgm', '.ppm', '.xbm', '.xpm', '.dds', '.icns', '.jp2', '.mng', '.tga', '.tiff', '.wbmp', '.webp') try: open(self.key, 'r') except IOError: print('There was an error opening the file') sys.exit(1) if self.key.lower().endswith(self.formats): # If inshuft = 0, the image is not in shufti's image database self.inshuft = 0 self.rotval = 0 self.rotvals = (0,-90,-180,-270) self.dbfile = expanduser("~/.config/shufti/shufti.db") self.dbdir = os.path.dirname(self.dbfile) if not os.path.isfile(self.dbfile): self.createDB() self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName(self.dbfile) self.db.open() self.query = QtSql.QSqlQuery() self.dbSearch(self.dbkey) # Set common window attributes self.path, self.title = os.path.split(self.key) self.setWindowTitle(str(self.title)) self.img = QPixmap(self.key) self.scene = QGraphicsScene() self.scene.addPixmap(self.img) self.view = ShuftiView(self.scene, self) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # Create array of images in current image dir self.imgfiles = [] for filename in glob.glob(str(self.path) + '/*'): base, ext = os.path.splitext(filename) if ext.lower() in self.formats: self.imgfiles.append(filename) # Find location of current image in imgfiles array self.dirpos = 0 while self.dirpos < len(self.imgfiles) and self.imgfiles[self.dirpos] != self.key: self.dirpos += 1 # If we have no inshuftery, we use the defaults if self.inshuft == 0: self.newImage() else: self.oldImage() else: print("Unsupported file format") sys.exit(1) def newImage(self): self.zoom = 1 self.rotate = 0 self.resize(self.img.size()) self.view.resize(self.img.width() + 2, self.img.height() + 2) self.show() self.view.verticalScrollBar().setValue(0) self.view.horizontalScrollBar().setValue(0) def oldImage(self): if self.rotate == -90: self.rotval = 1 elif self.rotate == -180: self.rotval = 2 elif self.rotate == -270: self.rotval = 3 self.resize(self.img.size()) self.updateView() self.show() self.setGeometry(self.winposx, self.winposy, self.winsizex, self.winsizey) self.view.verticalScrollBar().setValue(self.vscroll) self.view.horizontalScrollBar().setValue(self.hscroll) def toggleFullscreen(self): if self.isFullScreen(): self.showNormal() else: self.showFullScreen() def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_F11: self.toggleFullscreen() elif event.key() == QtCore.Qt.Key_Equal or event.key() == QtCore.Qt.Key_E: self.zoomIn() elif event.key() == QtCore.Qt.Key_Minus or event.key() == QtCore.Qt.Key_D: self.zoomOut() elif event.key() == QtCore.Qt.Key_1: self.zoomReset() elif event.key() == QtCore.Qt.Key_S: self.rotateImg(-1) elif event.key() == QtCore.Qt.Key_R: self.rotateImg(1) elif event.key() == QtCore.Qt.Key_F: self.fitView() elif event.key() == QtCore.Qt.Key_Space: self.dirBrowse(1) elif event.key() == QtCore.Qt.Key_Backspace: self.dirBrowse(-1) elif event.key() == QtCore.Qt.Key_V: self.vertMax() elif event.key() == QtCore.Qt.Key_Z: self.horizMax() elif event.key() == QtCore.Qt.Key_Q: self.close() def mouseDoubleClickEvent(self, event): self.toggleFullscreen() def createDB(self): if not os.path.exists(self.dbdir): os.makedirs(self.dbdir) self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE') self.db.setDatabaseName(self.dbfile) self.query = QtSql.QSqlQuery() self.db.open() self.query.exec_("create table shuftery(filename text primary key, " "zoom real, winposx int, winposy int, winsizex int, winsizey int, " "hscroll int, vscroll int, rotate int)") return True def zoomIn(self): self.zoom *= 1.05 self.updateView() def zoomOut(self): self.zoom /= 1.05 self.updateView() def zoomReset(self): self.zoom = 1 self.updateView() def rotateImg(self, clock): self.rotval += clock if self.rotval == 4: self.rotval = 0 elif self.rotval < 0: self.rotval = 3 self.rotate = self.rotvals[self.rotval] self.updateView() def fitView(self): self.view.fitInView(self.scene.sceneRect(), QtCore.Qt.KeepAspectRatio) if self.rotate == 0: self.zoom = self.view.transform().m11() elif self.rotate == -90: self.zoom = (self.view.transform().m12()) * -1 elif self.rotate == -180: self.zoom = (self.view.transform().m11()) * -1 else: self.zoom = self.view.transform().m12() def updateView(self): self.view.setTransform(QTransform().scale(self.zoom, self.zoom).rotate(self.rotate)) def winState(self): self.winsizex = self.geometry().width() self.winsizey = self.geometry().height() self.vscroll = self.view.verticalScrollBar().value() self.hscroll = self.view.horizontalScrollBar().value() self.winposx = self.pos().x() self.winposy = self.pos().y() def dbInsert(self): self.query.exec_("insert into shuftery values('%s" % self.dbkey + "', " + str(self.zoom) + ", " + str(self.winposx) + ", " + str(self.winposy) + ", " + str(self.winsizex) + ", " + str(self.winsizey) + ", " + str(self.hscroll) + ", " + str(self.vscroll) + ", " + str(self.rotate) + ")") def dbUpdate(self): self.query.exec_("update shuftery set zoom=" + str(self.zoom) + ", winposx=" + str(self.winposx) + ", winposy=" + str(self.winposy) + ", winsizex=" + str(self.winsizex) + ", winsizey=" + str(self.winsizey) + ", hscroll=" + str(self.hscroll) + ", vscroll=" + str(self.vscroll) + ", rotate=" + str(self.rotate) + " where filename='%s'" % self.dbkey) def dbSearch(self, field): self.query.exec_("SELECT * FROM shuftery WHERE filename='%s'" % field) # If the image is found in shufti.db, load the previous view settings while self.query.next() and self.inshuft == 0: self.zoom = self.query.value(1) self.winposx = self.query.value(2) self.winposy = self.query.value(3) self.winsizex = self.query.value(4) self.winsizey = self.query.value(5) self.hscroll = self.query.value(6) self.vscroll = self.query.value(7) self.rotate = self.query.value(8) self.inshuft = 1 def dbSanitise(self): self.dbkey = self.key.replace("\"", "\"\"") self.dbkey = self.dbkey.replace("\'", "\'\'") self.dbkey = self.dbkey.replace("\\", "\\\\") def dirBrowse(self, direc): if len(self.imgfiles) > 1: self.dirpos += direc if self.dirpos > (len(self.imgfiles) - 1): self.dirpos = 0 elif self.dirpos < 0: self.dirpos = (len(self.imgfiles) - 1) shufti.winState() if self.inshuft == 0: shufti.dbInsert() else: shufti.dbUpdate() self.key = self.imgfiles[self.dirpos] self.dbSanitise() self.path, self.title = os.path.split(self.key) self.setWindowTitle(str(self.title) + " - shufti") self.inshuft = 0 self.dbSearch(self.dbkey) self.scene.clear() self.view.resetTransform() self.img = QPixmap(self.key) self.scene.addPixmap(self.img) if self.inshuft == 0: self.newImage() else: self.oldImage() def vertMax(self): self.screen_res = app.desktop().availableGeometry(shufti) self.screenh = self.screen_res.height() self.winsizex = self.geometry().width() self.winposx = self.pos().x() self.setGeometry(self.winposx, 0, self.winsizex, self.screenh) def horizMax(self): self.screen_res = app.desktop().availableGeometry(shufti) self.screenw = self.screen_res.width() self.winsizey = self.geometry().height() self.winposy = self.pos().y() self.setGeometry(0, self.winposy, self.screenw, self.winsizey) def about(self): self.pop = AboutShufti() self.pop.resize(450, 200) self.pop.setWindowTitle("About shufti") self.pop.show()
class GUI(Ui_MainWindow): def __init__(self): super().setupUi(MainWindow) self.initUI() #connect widgets with functions def initUI(self): self.scene1=QGraphicsScene() self.scene2=QGraphicsScene() self.scene3=QGraphicsScene() self.scene4=QGraphicsScene() self.actionOpen.triggered.connect(self.imageOpen) self.histogram.clicked.connect(self.imageHistogram) self.GrayvalueScrollBar.valueChanged.connect(self.sliderval) self.OTSU.clicked.connect(self.OTSUThreshold) self.MedianFilter.clicked.connect(self.medianfilter) self.MeanFilter.clicked.connect(self.meanfilter) self.GaussianFilter.clicked.connect(self.gaussianfilter) self.CoustomizedFilter.clicked.connect(self.coustomizefilter) self.BinaryErosion.clicked.connect(self.binaryerosion) self.BinaryDilation.clicked.connect(self.binarydilation) self.actionClear_All.triggered.connect(self.clearall) self.DistanceTransform.clicked.connect(self.distancetransform) self.Skeleton.clicked.connect(self.skeleton) self.SkeletonRestoration.clicked.connect(self.skeletonrestoration) self.GrayErosion.clicked.connect(self.grayerosion) self.GrayDilation.clicked.connect(self.graydilation) self.EdgeDetection.clicked.connect(self.edgedetection) self.Gradient.clicked.connect(self.gradient) self.Reconstraction_Binary.clicked.connect(self.reconstruction_binary) self.Reconstraction_Gray.clicked.connect(self.reconstruction_gray) #function menubar-file-open: Open image and show it in view1 def imageOpen(self): # filename,_ = QFileDialog.getOpenFileName(MainWindow,'Open a image',os.getenv('HOME')) filename,_ = QFileDialog.getOpenFileName(MainWindow,'Open a image','.',"Image Files(*.bmp *jpg *png *jpeg)") # filename="/home/lab105/git-sen/python_gui/lena512.bmp" # print(filename) pix=QtGui.QPixmap(filename) pix=pix.scaledToHeight(256) self.image=plt.imread(filename) Size=self.image.shape if (len(Size)==3): if (type(self.image[1,1,1]) is np.float32): self.image=misc.imread(filename) self.image=self.image[:,:,1] self.image_temp=self.image self.scene1.addPixmap(QPixmap(pix)) self.View1.setScene(self.scene1) self.clearall() #function mainwindow tab histogram-greylevel histogram: compute and show the greyvalue histogram in view 2 def imageHistogram(self): greyimage=self.image #greyimage.dtype Height, Width=greyimage.shape x=np.zeros(Height*Width) for h in range(Height): for w in range(Width): x[h*Height+w]=greyimage[h,w] num_bins=255 plt.figure(figsize=(256,256),dpi=1) n,self.bins,patches=plt.hist(x,num_bins,normed=1,facecolor='green',alpha=0.5) plt.axis("off") plt.gca().set_position([0,0,1,1]) self.figure=plt.gcf() canvas2=FigureCanvas(self.figure) self.scene2.addWidget(canvas2) self.View2.setScene(self.scene2) def sliderval(self): Threshold=self.GrayvalueScrollBar.value() self.Binarization(Threshold) # self.label.setText(str(Threshold)) #threshlod function def Binarization(self,Threshold): #filename="/home/lab105/git-sen/python_gui/lena512.bmp" #img=misc.imread(filename) img=self.image BinaryArray= img >Threshold plt.close(3) plt.figure(num=3,figsize=(256,256),dpi=1) plt.axis("off") plt.gca().set_position([0,0,1,1]) plt.imshow(BinaryArray,cmap='binary_r') figure3=plt.gcf() canvas3=FigureCanvas(figure3) self.scene3.clear() self.scene3.addWidget(canvas3) self.View3.setScene(self.scene3) self.label.setText(str(Threshold)) def OTSUThreshold(self): img=self.image thresh=threshold_otsu(img) binary=img > thresh self.showView4(binary) def showView4(self,image): plt.close(4) plt.figure(num=4,figsize=(256,256),dpi=1) if (image.max()>1): plt.imshow(image,cmap='gray') else: plt.imshow(image,cmap='binary_r') plt.gca().set_position([0,0,1,1]) plt.axis("off") figure4=plt.gcf() canvas4=FigureCanvas(figure4) self.scene4.clear() self.scene4.addWidget(canvas4) self.View4.setScene(self.scene4) def getmatrixsize(self): matrixsize=3 if (self.radioButton_1.isChecked()): matrixsize=3 if (self.radioButton_2.isChecked()): matrixsize=5 return matrixsize def medianfilter(self): self.image_temp=ndimage.median_filter(self.image_temp,size=int(self.plainTextEdit.toPlainText())) self.showView4(self.image_temp) def meanfilter(self): self.image_temp=ndimage.uniform_filter(self.image_temp,size=int(self.plainTextEdit.toPlainText())) self.showView4(self.image_temp) def gaussianfilter(self): self.image_temp=ndimage.gaussian_filter(self.image_temp,sigma=float(self.plainTextEdit_2.toPlainText())) self.showView4(self.image_temp) def getmatrix(self): self.Matrix=[] if (self.getmatrixsize()==3): matrix=np.zeros((3,3)) matrix[0,0]=float(self.plainTextEdit1_1.toPlainText()) matrix[0,1]=float(self.plainTextEdit1_2.toPlainText()) matrix[0,2]=float(self.plainTextEdit1_3.toPlainText()) matrix[1,0]=float(self.plainTextEdit2_1.toPlainText()) matrix[1,1]=float(self.plainTextEdit2_2.toPlainText()) matrix[1,2]=float(self.plainTextEdit2_3.toPlainText()) matrix[2,0]=float(self.plainTextEdit3_1.toPlainText()) matrix[2,1]=float(self.plainTextEdit3_2.toPlainText()) matrix[2,2]=float(self.plainTextEdit3_3.toPlainText()) if (matrix.max()==0): matrix[:,:]=1 if (self.getmatrixsize()==5): matrix=np.zeros((5,5)) matrix[0,0]=float(self.plainTextEdit1_1.toPlainText()) matrix[0,1]=float(self.plainTextEdit1_2.toPlainText()) matrix[0,2]=float(self.plainTextEdit1_3.toPlainText()) matrix[0,3]=float(self.plainTextEdit1_4.toPlainText()) matrix[0,4]=float(self.plainTextEdit1_5.toPlainText()) matrix[1,0]=float(self.plainTextEdit2_1.toPlainText()) matrix[1,1]=float(self.plainTextEdit2_2.toPlainText()) matrix[1,2]=float(self.plainTextEdit2_3.toPlainText()) matrix[1,3]=float(self.plainTextEdit2_4.toPlainText()) matrix[1,4]=float(self.plainTextEdit2_5.toPlainText()) matrix[2,0]=float(self.plainTextEdit3_1.toPlainText()) matrix[2,1]=float(self.plainTextEdit3_2.toPlainText()) matrix[2,2]=float(self.plainTextEdit3_3.toPlainText()) matrix[2,3]=float(self.plainTextEdit3_4.toPlainText()) matrix[2,4]=float(self.plainTextEdit3_5.toPlainText()) matrix[3,0]=float(self.plainTextEdit4_1.toPlainText()) matrix[3,1]=float(self.plainTextEdit4_2.toPlainText()) matrix[3,2]=float(self.plainTextEdit4_3.toPlainText()) matrix[3,3]=float(self.plainTextEdit4_4.toPlainText()) matrix[3,4]=float(self.plainTextEdit4_5.toPlainText()) matrix[4,0]=float(self.plainTextEdit5_1.toPlainText()) matrix[4,1]=float(self.plainTextEdit5_2.toPlainText()) matrix[4,2]=float(self.plainTextEdit5_3.toPlainText()) matrix[4,3]=float(self.plainTextEdit5_4.toPlainText()) matrix[4,4]=float(self.plainTextEdit5_5.toPlainText()) if (matrix.max()==0): matrix[:,:]=1 self.Matrix=matrix def coustomizefilter(self): self.getmatrix() self.image_temp=ndimage.correlate(self.image_temp,self.Matrix) self.showView4(self.image_temp) def binaryerosion(self): self.getmatrix() self.image_temp=ndimage.binary_erosion(self.image_temp,self.Matrix) self.showView4(self.image_temp) def binarydilation(self): self.getmatrix() self.image_temp=ndimage.binary_dilation(self.image_temp,self.Matrix) self.showView4(self.image_temp) def distancetransform(self): Size=self.image_temp.shape distance=np.zeros(Size) distance=distance+self.image_temp self.getmatrix() while (self.image_temp.max()!=0): self.image_temp=ndimage.binary_erosion(self.image_temp,self.Matrix) distance=distance+self.image_temp self.image_temp=self.image self.showView4(distance) def clearall(self): self.scene2.clear() self.scene3.clear() self.scene4.clear() self.image_temp=self.image def skeleton(self): Size=self.image_temp.shape skeleton=np.zeros(Size) self.store=np.zeros(Size) skeleton_remain=self.image_temp i=1 while (skeleton_remain.max()!=0): skeleton_remain=ndimage.binary_erosion(self.image_temp,np.ones([2*i-1,2*i-1])) subset=skeleton_remain-ndimage.binary_opening(skeleton_remain,np.ones([3,3])) skeleton=np.logical_or(skeleton,subset) self.store=self.store+subset*i i=i+1 self.showView4(skeleton) def skeletonrestoration(self): i=self.store.max() Size=self.image_temp.shape result=mid_result=np.zeros(Size) while (i!=0): index= self.store == i mid_result=ndimage.binary_dilation(index,np.ones([2*i-1,2*i-1])) result=np.logical_or(result,mid_result) i=i-1 self.showView4(result) def grayerosion(self): self.getmatrix() self.image_temp=ndimage.grey_erosion(self.image_temp,footprint=self.Matrix) self.showView4(self.image_temp) def graydilation(self): self.getmatrix() self.image_temp=ndimage.grey_dilation(self.image_temp,footprint=self.Matrix) self.showView4(self.image_temp) def getEdgeType(self): Type='S' if (self.S.isChecked()): Type='S' if (self.I.isChecked()): Type='I' if (self.E.isChecked()): Type='E' return Type def edgedetection(self): Type=self.getEdgeType() Size=self.image_temp.shape EdgeImage=np.zeros(Size) if (Type=='S'): EdgeImage=ndimage.grey_dilation(self.image_temp,footprint=np.ones([3,3]))-ndimage.grey_erosion(self.image_temp,footprint=np.ones([3,3])) if (Type=='I'): EdgeImage=self.image_temp-ndimage.grey_erosion(self.image_temp,footprint=np.ones([3,3])) if (Type=='E'): EdgeImage=ndimage.grey_dilation(self.image_temp,footprint=np.ones([3,3]))-self.image_temp self.showView4(EdgeImage) def gradient(self): Type=self.getEdgeType() Size=self.image_temp.shape EdgeImage=np.zeros(Size) if (Type=='S'): EdgeImage=(ndimage.grey_dilation(self.image_temp,footprint=np.ones([3,3]))-ndimage.grey_erosion(self.image_temp,footprint=np.ones([3,3])))/2 if (Type=='I'): EdgeImage=(self.image_temp-ndimage.grey_erosion(self.image_temp,footprint=np.ones([3,3])))/2 if (Type=='E'): EdgeImage=(ndimage.grey_dilation(self.image_temp,footprint=np.ones([3,3]))-self.image_temp)/2 self.showView4(EdgeImage) def reconstruction_binary(self): Size=self.image_temp.shape Mark_temp=np.zeros(Size) Mark=np.zeros(Size) Mark[:,112]=1 while ((not np.array_equal(Mark,Mark_temp))): Mark_temp=Mark Mark=ndimage.binary_dilation(Mark,np.ones([3,3])) Mark=np.logical_and(Mark,self.image_temp) self.showView4(Mark) def reconstruction_gray(self): Size=self.image_temp.shape Mark_temp=np.zeros(Size) Mark=np.zeros(Size) Mark[:,112]=self.image_temp[:,112] while ((not np.array_equal(Mark,Mark_temp))): Mark_temp=Mark Mark=ndimage.grey_dilation(Mark,footprint=np.ones([3,3])) logical=Mark >= self.image_temp Mark=Mark-Mark*logical+self.image_temp*logical self.showView4(Mark)
class MainWindow(QMainWindow): def __init__(self, parent): QMainWindow.__init__(self) self.printer = QPrinter() self.load_img = self.load_img_fit self.reload_img = self.reload_auto self.open_new = parent.open_win self.exit = parent.closeAllWindows self.scene = QGraphicsScene() self.img_view = ImageView(self) self.img_view.setScene(self.scene) self.setCentralWidget(self.img_view) self.create_actions() self.create_menu() self.create_dict() self.slides_next = True self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.showMenu) self.read_prefs() self.read_list = parent.read_list self.write_list = parent.write_list self.pics_dir = os.path.expanduser('~/Pictures') or QDir.currentPath() self.resize(700, 500) def create_actions(self): self.open_act = QAction('&Open', self, shortcut='Ctrl+O') self.open_act.triggered.connect(self.open) self.open_new_act = QAction('Open new window', self, shortcut='Ctrl+Shift+O') self.open_new_act.triggered.connect(partial(self.open, True)) self.reload_act = QAction('&Reload image', self, shortcut='Ctrl+R') self.reload_act.triggered.connect(self.reload_img) self.print_act = QAction('&Print', self, shortcut='Ctrl+P') self.print_act.triggered.connect(self.print_img) self.save_act = QAction('&Save image', self, shortcut='Ctrl+S') self.save_act.triggered.connect(self.save_img) self.close_act = QAction('Close window', self, shortcut='Ctrl+W') self.close_act.triggered.connect(self.close) self.exit_act = QAction('E&xit', self, shortcut='Ctrl+Q') self.exit_act.triggered.connect(self.exit) self.fulls_act = QAction('Fullscreen', self, shortcut='F11', checkable=True) self.fulls_act.triggered.connect(self.toggle_fs) self.ss_act = QAction('Slideshow', self, shortcut='F5', checkable=True) self.ss_act.triggered.connect(self.toggle_slideshow) self.ss_next_act = QAction('Next / Random image', self, checkable=True) self.ss_next_act.triggered.connect(self.set_slide_type) self.ss_next_act.setChecked(True) self.next_act = QAction('Next image', self, shortcut='Right') self.next_act.triggered.connect(self.go_next_img) self.prev_act = QAction('Previous image', self, shortcut='Left') self.prev_act.triggered.connect(self.go_prev_img) self.rotleft_act = QAction('Rotate left', self, shortcut='Ctrl+Left') self.rotleft_act.triggered.connect(partial(self.img_rotate, 270)) self.rotright_act = QAction('Rotate right', self, shortcut='Ctrl+Right') self.rotright_act.triggered.connect(partial(self.img_rotate, 90)) self.fliph_act = QAction('Flip image horizontally', self, shortcut='Ctrl+H') self.fliph_act.triggered.connect(partial(self.img_flip, -1, 1)) self.flipv_act = QAction('Flip image vertically', self, shortcut='Ctrl+V') self.flipv_act.triggered.connect(partial(self.img_flip, 1, -1)) self.resize_act = QAction('Resize image', self, triggered=self.resize_img) self.crop_act = QAction('Crop image', self, triggered=self.crop_img) self.zin_act = QAction('Zoom &In', self, shortcut='Up') self.zin_act.triggered.connect(partial(self.img_view.zoom, 1.1)) self.zout_act = QAction('Zoom &Out', self, shortcut='Down') self.zout_act.triggered.connect(partial(self.img_view.zoom, 1 / 1.1)) self.fit_win_act = QAction('Best &fit', self, checkable=True, shortcut='F', triggered=self.zoom_default) self.fit_win_act.setChecked(True) self.prefs_act = QAction('Preferences', self, triggered=self.set_prefs) self.props_act = QAction('Properties', self, triggered=self.get_props) self.help_act = QAction('&Help', self, shortcut='F1', triggered=self.help_page) self.about_act = QAction('&About', self, triggered=self.about_cm) self.aboutQt_act = QAction('About &Qt', self, triggered=qApp.aboutQt) def create_menu(self): self.popup = QMenu(self) main_acts = [self.open_act, self.open_new_act, self.reload_act, self.print_act, self.save_act] edit_acts1 = [self.rotleft_act, self.rotright_act, self.fliph_act, self.flipv_act] edit_acts2 = [self.resize_act, self.crop_act] view_acts = [self.next_act, self.prev_act, self.zin_act, self.zout_act, self.fit_win_act, self.fulls_act, self.ss_act, self.ss_next_act] help_acts = [self.help_act, self.about_act, self.aboutQt_act] end_acts = [self.prefs_act, self.props_act, self.close_act, self.exit_act] for act in main_acts: self.popup.addAction(act) edit_menu = QMenu(self.popup) edit_menu.setTitle('&Edit') for act in edit_acts1: edit_menu.addAction(act) edit_menu.addSeparator() for act in edit_acts2: edit_menu.addAction(act) self.popup.addMenu(edit_menu) view_menu = QMenu(self.popup) view_menu.setTitle('&View') for act in view_acts: view_menu.addAction(act) self.popup.addMenu(view_menu) help_menu = QMenu(self.popup) help_menu.setTitle('&Help') for act in help_acts: help_menu.addAction(act) self.popup.addMenu(help_menu) for act in end_acts: self.popup.addAction(act) self.action_list = main_acts + edit_acts1 + edit_acts2 + view_acts + help_acts + end_acts for act in self.action_list: self.addAction(act) def showMenu(self, pos): self.popup.popup(self.mapToGlobal(pos)) def create_dict(self): """Create a dictionary to handle auto-orientation.""" self.orient_dict = {None: self.load_img, '1': self.load_img, '2': partial(self.img_flip, -1, 1), '3': partial(self.img_rotate, 180), '4': partial(self.img_flip, -1, 1), '5': self.img_rotate_fliph, '6': partial(self.img_rotate, 90), '7': self.img_rotate_flipv, '8': partial(self.img_rotate, 270)} def read_prefs(self): """Parse the preferences from the config file, or set default values.""" try: conf = preferences.Config() values = conf.read_config() self.auto_orient = values[0] self.slide_delay = values[1] self.quality = values[2] except: self.auto_orient = True self.slide_delay = 5 self.quality = 90 self.reload_img = self.reload_auto if self.auto_orient else self.reload_nonauto def set_prefs(self): """Write preferences to the config file.""" dialog = preferences.PrefsDialog(self) if dialog.exec_() == QDialog.Accepted: self.auto_orient = dialog.auto_orient self.slide_delay = dialog.delay_spinb.value() self.quality = dialog.qual_spinb.value() conf = preferences.Config() conf.write_config(self.auto_orient, self.slide_delay, self.quality) self.reload_img = self.reload_auto if self.auto_orient else self.reload_nonauto def open(self, new_win=False): fname = QFileDialog.getOpenFileName(self, 'Open File', self.pics_dir)[0] if fname: if fname.lower().endswith(self.read_list): if new_win: self.open_new(fname) else: self.open_img(fname) else: QMessageBox.information(self, 'Error', 'Cannot load {} images.'.format(fname.rsplit('.', 1)[1])) def open_img(self, fname): self.fname = fname self.reload_img() dirname = os.path.dirname(self.fname) self.set_img_list(dirname) self.img_index = self.filelist.index(self.fname) def set_img_list(self, dirname): """Create a list of readable images from the current directory.""" filelist = os.listdir(dirname) self.filelist = [os.path.join(dirname, fname) for fname in filelist if fname.lower().endswith(self.read_list)] self.filelist.sort() self.last_file = len(self.filelist) - 1 def get_img(self): """Get image from fname and create pixmap.""" image = QImage(self.fname) self.pixmap = QPixmap.fromImage(image) self.setWindowTitle(self.fname.rsplit('/', 1)[1]) def reload_auto(self): """Load a new image with auto-orientation.""" self.get_img() try: orient = GExiv2.Metadata(self.fname)['Exif.Image.Orientation'] self.orient_dict[orient]() except: self.load_img() def reload_nonauto(self): """Load a new image without auto-orientation.""" self.get_img() self.load_img() def load_img_fit(self): """Load the image to fit the window.""" self.scene.clear() self.scene.addPixmap(self.pixmap) self.scene.setSceneRect(0, 0, self.pixmap.width(), self.pixmap.height()) self.img_view.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio) def load_img_1to1(self): """Load the image at its original size.""" self.scene.clear() self.img_view.resetTransform() self.scene.addPixmap(self.pixmap) self.scene.setSceneRect(0, 0, self.pixmap.width(), self.pixmap.height()) pixitem = QGraphicsPixmapItem(self.pixmap) self.img_view.centerOn(pixitem) def go_next_img(self): self.img_index = self.img_index + 1 if self.img_index < self.last_file else 0 self.fname = self.filelist[self.img_index] self.reload_img() def go_prev_img(self): self.img_index = self.img_index - 1 if self.img_index else self.last_file self.fname = self.filelist[self.img_index] self.reload_img() def zoom_default(self): """Toggle best fit / original size loading.""" if self.fit_win_act.isChecked(): self.load_img = self.load_img_fit self.create_dict() self.load_img() else: self.load_img = self.load_img_1to1 self.create_dict() self.load_img() def img_rotate(self, angle): self.pixmap = self.pixmap.transformed(QTransform().rotate(angle)) self.load_img() def img_flip(self, x, y): self.pixmap = self.pixmap.transformed(QTransform().scale(x, y)) self.load_img() def img_rotate_fliph(self): self.img_rotate(90) self.img_flip(-1, 1) def img_rotate_flipv(self): self.img_rotate(90) self.img_flip(1, -1) def resize_img(self): dialog = editimage.ResizeDialog(self, self.pixmap.width(), self.pixmap.height()) if dialog.exec_() == QDialog.Accepted: width = dialog.get_width.value() height = dialog.get_height.value() self.pixmap = self.pixmap.scaled(width, height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.save_img() def crop_img(self): self.img_view.setup_crop(self.pixmap.width(), self.pixmap.height()) dialog = editimage.CropDialog(self, self.pixmap.width(), self.pixmap.height()) if dialog.exec_() == QDialog.Accepted: coords = self.img_view.get_coords() self.pixmap = self.pixmap.copy(*coords) self.load_img() self.img_view.rband.hide() def toggle_fs(self): if self.fulls_act.isChecked(): self.showFullScreen() else: self.showNormal() def toggle_slideshow(self): if self.ss_act.isChecked(): self.showFullScreen() self.start_ss() else: self.toggle_fs() self.timer.stop() self.ss_timer.stop() def start_ss(self): self.timer = QTimer() self.timer.timeout.connect(self.update_img) self.timer.start(self.slide_delay * 1000) self.ss_timer = QTimer() self.ss_timer.timeout.connect(self.update_img) self.ss_timer.start(60000) def update_img(self): if self.slides_next: self.go_next_img() else: self.fname = random.choice(self.filelist) self.reload_img() def set_slide_type(self): self.slides_next = self.ss_next_act.isChecked() def save_img(self): fname = QFileDialog.getSaveFileName(self, 'Save your image', self.fname)[0] if fname: if fname.lower().endswith(self.write_list): keep_exif = QMessageBox.question(self, 'Save exif data', 'Do you want to save the picture metadata?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if keep_exif == QMessageBox.Yes: self.pixmap.save(fname, None, self.quality) exif = GExiv2.Metadata(self.fname) if exif: saved_exif = GExiv2.Metadata(fname) for tag in exif.get_exif_tags(): saved_exif[tag] = exif[tag] saved_exif.set_orientation(GExiv2.Orientation.NORMAL) saved_exif.save_file() else: QMessageBox.information(self, 'Error', 'Cannot save {} images.'.format(fname.rsplit('.', 1)[1])) def print_img(self): dialog = QPrintDialog(self.printer, self) if dialog.exec_(): painter = QPainter(self.printer) rect = painter.viewport() if self.pixmap.width() > self.pixmap.height(): self.pixmap = self.pixmap.transformed(QTransform().rotate(90)) size = self.pixmap.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.pixmap.rect()) painter.drawPixmap(0, 0, self.pixmap) def resizeEvent(self, event=None): if self.fit_win_act.isChecked(): try: self.load_img() except: pass def get_props(self): """Get the properties of the current image.""" image = QImage(self.fname) preferences.PropsDialog(self, self.fname.rsplit('/', 1)[1], image.width(), image.height()) def help_page(self): preferences.HelpDialog(self) def about_cm(self): about_message = 'Version: 0.3.9\nAuthor: David Whitlock\nLicense: GPLv3' QMessageBox.about(self, 'About Cheesemaker', about_message)
class CircuitDiagramView(QGraphicsView): mousePress = pyqtSignal(tuple, tuple, name='mousePress') mouseMove = pyqtSignal(tuple, tuple, name='mouseMove') mouseRelease = pyqtSignal(tuple, tuple, name='mouseRelease') def __init__(self, parent=None): QGraphicsView.__init__(self, parent) self._model = None self.controller = None self.setAcceptDrops(True) # setup & render circuit diagram grid self.scene = QGraphicsScene() self.setScene(self.scene) self._shouldShowSelection = False self._selection = None self._dragging = False self.mousePosition = None self.draggingStart = None self.render() @property def shouldShowSelection(self): return self._shouldShowSelection @shouldShowSelection.setter def shouldShowSelection(self, value): if self.shouldShowSelection is not value and value is not None: self._shouldShowSelection = value self.render() @property def model(self): return self._model @model.setter def model(self, value): self._model = value self.model.modelChanged.connect(self.render) @property def selection(self): return self._selection @selection.setter def selection(self, value): if self.selection is not value: self._selection = value self.render() @property def dragging(self): return self._dragging @dragging.setter def dragging(self, value): self._dragging = value self.render() def componentTypeToImageName(self, componentType): dictionary = { ComponentType.Battery: "assets/battery.png", ComponentType.Resistor: "assets/resistor.png", ComponentType.Voltmeter: "assets/voltmeter.png", ComponentType.Ammeter: "assets/ammeter.png", ComponentType.Switch: "assets/switch-off.png", ComponentType.Bulb: "assets/bulb-off.png", ComponentType.Button: "assets/button-off.png", } return dictionary[componentType] def componentToImage(self, component): if component.type == ComponentType.Wire: image = QPixmap("assets/icon.png").scaled(self.blockSideLength, self.blockSideLength) if component.numberOfConnections() == 1: image = QPixmap("assets/wire-top.png").scaled(self.blockSideLength, self.blockSideLength) if component.connections[Direction.Right] is not None: image = image.transformed(QtGui.QTransform().rotate(90)) elif component.connections[Direction.Bottom] is not None: image = image.transformed(QtGui.QTransform().rotate(180)) elif component.connections[Direction.Left] is not None: image = image.transformed(QtGui.QTransform().rotate(270)) elif component.numberOfConnections() == 2: if component.connections[Direction.Left] is not None and component.connections[Direction.Right] is not None: image = QPixmap("assets/wire-left-right.png").scaled(self.blockSideLength, self.blockSideLength) elif component.connections[Direction.Top] is not None and component.connections[Direction.Bottom] is not None: image = QPixmap("assets/wire-left-right.png").scaled(self.blockSideLength, self.blockSideLength).transformed(QtGui.QTransform().rotate(90)) elif component.connections[Direction.Top] is not None and component.connections[Direction.Right] is not None: image = QPixmap("assets/wire-top-right.png").scaled(self.blockSideLength, self.blockSideLength) elif component.connections[Direction.Top] is not None and component.connections[Direction.Left] is not None: image = QPixmap("assets/wire-top-right.png").scaled(self.blockSideLength, self.blockSideLength).transformed(QtGui.QTransform().rotate(270)) elif component.connections[Direction.Bottom] is not None and component.connections[Direction.Right] is not None: image = QPixmap("assets/wire-top-right.png").scaled(self.blockSideLength, self.blockSideLength).transformed(QtGui.QTransform().rotate(90)) elif component.connections[Direction.Bottom] is not None and component.connections[Direction.Left] is not None: image = QPixmap("assets/wire-top-right.png").scaled(self.blockSideLength, self.blockSideLength).transformed(QtGui.QTransform().rotate(180)) elif component.numberOfConnections() == 3: image = QPixmap("assets/wire-left-top-right.png").scaled(self.blockSideLength, self.blockSideLength) if component.connections[Direction.Left] is None: image = image.transformed(QtGui.QTransform().rotate(90)) elif component.connections[Direction.Top] is None: image = image.transformed(QtGui.QTransform().rotate(180)) elif component.connections[Direction.Right] is None: image = image.transformed(QtGui.QTransform().rotate(270)) return image else: imageName = "assets/wire-right.png" if component.type == ComponentType.Bulb: if component.isOn(): imageName = "assets/bulb-on.png" else: imageName = "assets/bulb-off.png" elif component.type == ComponentType.Switch: if component.closed: imageName = "assets/switch-on.png" else: imageName = "assets/switch-off.png" elif component.type == ComponentType.Button: if component.closed: imageName = "assets/button-on.png" else: imageName = "assets/button-off.png" else: imageName = self.componentTypeToImageName(component.type) return QPixmap(imageName).scaled(self.blockSideLength, self.blockSideLength) def mouseCoordinatesToBlockIndex(self, x, y): if self.model is None or x < self.startingX or y < self.startingY or x > self.startingX + self.model.gridSize * self.blockSideLength or y > self.startingY + self.model.gridSize * self.blockSideLength: return (-1, -1) else: return (int((x - self.startingX) / self.blockSideLength), int((y - self.startingY) / self.blockSideLength)) def blockIndexToCoordinate(self, x, y): return (self.startingX + self.blockSideLength * x, self.startingY + self.blockSideLength * y) def mousePressEvent(self, event): index = self.mouseCoordinatesToBlockIndex(event.x(), event.y()) self.mousePress.emit(index, (event.x(), event.y())) def dragEnterEvent(self, event): event.acceptProposedAction() def dragMoveEvent(self, event): index = self.mouseCoordinatesToBlockIndex(event.pos().x(), event.pos().y()) self.mouseMove.emit(index, (event.pos().x(), event.pos().y())) def dropEvent(self, event): event.acceptProposedAction() index = self.mouseCoordinatesToBlockIndex(event.pos().x(), event.pos().y()) self.mouseRelease.emit(index, (event.pos().x(), event.pos().y())) def mouseMoveEvent(self, event): self.mousePosition = (event.x(), event.y()) if self.dragging: self.render() index = self.mouseCoordinatesToBlockIndex(event.x(), event.y()) self.mouseMove.emit(index, (event.pos().x(), event.pos().y())) def mouseReleaseEvent(self, event): index = self.mouseCoordinatesToBlockIndex(event.x(), event.y()) self.mouseRelease.emit(index, (event.pos().x(), event.pos().y())) def resizeEvent(self, event): self.render() def render(self): if self.model is not None: self.scene.clear() self.renderCircuitDiagramGrid() self.renderComponents() def renderComponents(self): if self.model is not None: for component in self.model.components: pixmap = self.componentToImage(component) pixmapItem = self.scene.addPixmap(pixmap) offset = self.blockIndexToCoordinate(component.position[0],component.position[1]) pixmapItem.setOffset(offset[0],offset[1]) pixmapItem.setTransformationMode(Qt.SmoothTransformation) if component is self.selection: if self.dragging: renderPosition = (self.startingX + self.selection.position[0] * self.blockSideLength + self.mousePosition[0] - self.draggingStart[0], self.startingY + self.selection.position[1] * self.blockSideLength + self.mousePosition[1] - self.draggingStart[1]) pixmapItem.setOffset(renderPosition[0], renderPosition[1]) elif self.shouldShowSelection: pen = QPen(QBrush(QColor(0,0,255,100)), 2, Qt.DashLine) self.scene.addRect(self.startingX + component.position[0] * self.blockSideLength, self.startingY + component.position[1] * self.blockSideLength, self.blockSideLength, self.blockSideLength, pen) if component.type is ComponentType.Ammeter: font = QFont("Arial", self.blockSideLength/3.5) reading = self.scene.addText(str("%.2f" % component.current) + "A", font) offset = self.blockIndexToCoordinate(component.position[0],component.position[1]) reading.setPos(offset[0]+self.blockSideLength/20,offset[1]+self.blockSideLength/4) elif component.type is ComponentType.Voltmeter: font = QFont("Arial", self.blockSideLength/3.5) reading = self.scene.addText(str("%.2f" % component.voltage) + "V", font) offset = self.blockIndexToCoordinate(component.position[0],component.position[1]) reading.setPos(offset[0]+self.blockSideLength/20,offset[1]+self.blockSideLength/4) def renderCircuitDiagramGrid(self): pen = QPen(QBrush(QColor(200,200,200,255)), 1) pen2 = QPen(QBrush(QColor(100,100,100,255)), 3) width = self.width() height = self.height() self.blockSideLength = width / (self.model.gridSize + 2) if width < height else height / (self.model.gridSize + 2) # draw vertical lines currentX = width / 2 self.startingX = currentX - (self.model.gridSize / 2) * self.blockSideLength while currentX - self.blockSideLength >= 0: currentX -= self.blockSideLength while currentX < width: self.scene.addLine(currentX, 1, currentX, height - 1, pen) currentX += self.blockSideLength # draw horizontal lines currentY = height / 2 self.startingY = currentY - (self.model.gridSize / 2) * self.blockSideLength while currentY - self.blockSideLength >= 0: currentY -= self.blockSideLength while currentY < height: self.scene.addLine(1, currentY, width - 1, currentY, pen) currentY += self.blockSideLength self.scene.addLine(self.startingX, self.startingY, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY, pen2) self.scene.addLine(self.startingX, self.startingY + self.model.gridSize * self.blockSideLength, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY + 10 * self.blockSideLength, pen2) self.scene.addLine(self.startingX, self.startingY, self.startingX, self.startingY + self.model.gridSize * self.blockSideLength, pen2) self.scene.addLine(self.startingX + self.model.gridSize * self.blockSideLength, self.startingY, self.startingX + self.model.gridSize * self.blockSideLength, self.startingY + 10 * self.blockSideLength, pen2)
class PreView(QGraphicsView): def __init__(self): QGraphicsView.__init__(self) self.zoom = 2 self.scale(self.zoom, self.zoom) self.lastSize = 0 self.setDragMode(QGraphicsView.ScrollHandDrag) # self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.installEventFilter(self) self.hudLayout = QVBoxLayout(self) self.hudLayout.setContentsMargins(0,0,0,0) self.ellipseLabel = QLabel() self.ellipseLabel.setMinimumWidth(self.width()) self.hudLayout.addWidget(self.ellipseLabel) self.ellipseLabel.setAttribute(Qt.WA_TransparentForMouseEvents, True) def setPreviewImage(self, previewImage): self.grscene = QGraphicsScene() pixmapImage = QPixmap(previewImage) self.grscene.addPixmap(pixmapImage) self.setScene(self.grscene) def eventFilter(self, obj, event): if(event.type()==QEvent.Resize): self.ellipseLabel.setMinimumWidth(self.width()) self.updateFilledCircle(self.lastSize) return False def sizeHint(self): return QSize(200, 200) def updateFilledCircle(self, s): size = s * self.zoom pixmap = QPixmap(self.width(), self.height()) pixmap.fill(Qt.transparent) #painter filled ellipse p = QPalette() painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) brush = QBrush(p.link().color()) painter.setBrush(brush) painter.setOpacity(0.4) painter.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size)) painter.end() #painter ellipse 2 painter2 = QPainter() painter2.begin(pixmap) painter2.setRenderHint(QPainter.Antialiasing) pen2 = QPen(Qt.green) pen2.setWidth(1) painter2.setPen(pen2) painter2.drawEllipse(QRect(old_div(self.width(),2) - old_div(size,2), old_div(self.height(),2) - old_div(size,2), size, size)) painter2.end() self.ellipseLabel.setPixmap(QPixmap(pixmap)) self.lastSize = s
class Widget(QMainWindow, client_form): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setupUi(self) self.refreshLabel.setVisible(False) self.client = Client(50000, 3000) self.refreshButton.clicked.connect(self.refresh) self.connectButton.clicked.connect(self.connect) self._graphics_scene = QGraphicsScene(self) self.graphicsView.setScene(self._graphics_scene) self._graphics_scene.mousePressEvent = self.mouse_pressed self.exit_action.triggered.connect(self.exit) self.help_action.triggered.connect(self.show_help) self.bullshit_action.triggered.connect(self.send_incorrect_message) self.viewlog_action.triggered.connect(self.open_log) self.connected = False def open_log(self): if os.uname().sysname == "Darwin": webbrowser.open("file:///" + os.path.abspath("./client.log")) else: webbrowser.open("./client.log") def exit(self): if self.connected: self.revert() self.client.disconnect() self.close() def show_help(self): mb = QMessageBox.information( self, "О программе", "Программа удаленного управления рабочим столом.\n\n" "Создатели:\n" "Алексей Абакумкин, ИУ7-72\n" "Роман Инфлянскас, ИУ7-71\n" "(c) 2014, Москва, МГТУ им. Н. Э. Баумана") def critical(self, msg, log=True): self.revert() QMessageBox.critical(self, "Ошибка", msg) if log: logging.error("{ip}\t{msg}\tОшибка".format(ip=self.client.ip, msg=msg)) def send_incorrect_message(self): if self.connected: try: self.client.send_incorrect_message() except: # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") self.critical("Сервер перестал отвечать") def refresh(self): self.serverList.clear() self.refreshLabel.setVisible(True) self.repaint() for x in self.client.refresh_server_list(): self.serverList.addItem("{0}:{1}".format(x[0], x[1])) self.refreshLabel.setVisible(False) def connect(self): if self.connected: self.revert() self.client.disconnect() return try: login, login_ok = QInputDialog.getText(self, 'Логин', 'Введите логин:') if login_ok: passwd, password_ok = QInputDialog.getText(self, 'Пароль', 'Введите пароль:', 2) if password_ok: server_item = self.serverList.currentItem() try: address = server_item.text().split(":") except: # server_item = self.serverList.findItems('', 0)[0] self.serverList.setCurrentRow(0) server_item = self.serverList.currentItem() address = server_item.text().split(":") if self.client.connect_to_server(address, login, passwd): self.connectButton.setText("Отключиться") self.connected = True else: self.critical("Неверный логин или пароль!", log=False) # mb = QMessageBox.critical(self, "Ошибка", "Неверный логин или пароль!") except TimeoutError: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") def revert(self): self._graphics_scene.clear() self.connectButton.setText("Присоединиться") self.connected = False def paintEvent(self, QPaintEvent): if self.connected: try: self.image_base_64 = self.client.recieve_screenshot() except TimeoutError: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") return self.data = QByteArray.fromBase64(self.image_base_64) self.pm = QPixmap() self.pm.loadFromData(self.data, "PNG") self._graphics_scene.clear() self._graphics_scene.addPixmap(self.pm) self.update() def mouse_pressed(self, event): if self.connected: x = int(event.scenePos().x()) y = int(event.scenePos().y()) button = event.button() if button == 4: button = 3 try: self.client.send_mouse_event(x, y, button) except: self.critical("Сервер перестал отвечать") # mb = QMessageBox.critical(self, "Ошибка", "Сервер перестал отвечать") self.revert()
def finished(self): #绘制闪电密度图 ##清除上一次的QGraphicsView对象,防止其记录上一次图片结果,影响显示效果 self.density_view.setAttribute(Qt.WA_DeleteOnClose) self.verticalLayout_2.removeWidget(self.density_view) size = self.density_view.size() self.density_view.close() self.density_view = QGraphicsView(self.density_tab) self.density_view.setObjectName("density_view") self.density_view.resize(size) self.verticalLayout_2.addWidget(self.density_view) densityPic = ''.join([cwd,u'/bulletinTemp/', self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'闪电密度空间分布.tif']) scene = QGraphicsScene() pixmap_density = QPixmap(densityPic) scene.addPixmap(pixmap_density) self.density_view.setScene(scene) scale = float(self.density_view.width()) / pixmap_density.width() self.density_view.scale(scale, scale) #绘制雷暴日图 self.day_view.setAttribute(Qt.WA_DeleteOnClose) self.verticalLayout.removeWidget(self.day_view) size = self.day_view.size() self.day_view.close() self.day_view = QGraphicsView(self.day_tab) self.day_view.setObjectName("day_view") self.day_view.resize(size) self.verticalLayout.addWidget(self.day_view) dayPic = ''.join([cwd,u'/bulletinTemp/', self.in_parameters[u'datetime'],u'/',self.in_parameters[u'datetime'], self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif']) pixmap_day = QPixmap(dayPic) scene = QGraphicsScene() scene.addPixmap(pixmap_day) self.day_view.resize(self.density_view.width(),self.density_view.height()) self.day_view.setScene(scene) scale = float(self.day_view.width()) / pixmap_day.width() self.day_view.scale(scale, scale) #处理进度条和执行按钮状态 self.progressBar.setMinimum(0) self.progressBar.setMaximum(100) self.progressBar.setValue(100) self.progressBar.setFormat(u'完成!') self.execute_button.setDisabled(False) self.execute_button.setText(u'执行') #改变一些控件的状态 self.action_add_data.setDisabled(False) self.target_area.setDisabled(False) self.datetime.setDisabled(False) self.density_cell.setDisabled(False) self.density_class.setDisabled(False) self.day_cell.setDisabled(False) self.day_class.setDisabled(False) self.density_mxd.setDisabled(False) self.day_mxd.setDisabled(False) self.action_save_pic.setDisabled(False)
class Ui_MainWindow(QMainWindow, Ui_MainWindowBase): def __init__(self): super(Ui_MainWindow, self).__init__() self.setupUi(self) self.videoPlaybackInit() self.blocklyInit() self.imgInit() self.menuInit() def videoPlaybackInit(self): self.videoPlaybackWidget.hide() self.videoPlaybackWidget.frameChanged.connect(self.setFrame, type=Qt.QueuedConnection) self.filePath = None def blocklyInit(self): self.blocklyWebView.setUrl(QtCore.QUrl(blocklyURL)) self.blocklyEvaluationTimer = QtCore.QTimer(parent=self.blocklyWebView) self.blocklyEvaluationTimer.setInterval(1*100) self.blocklyEvaluationTimer.timeout.connect(self.evaluateSelectedBlock) self.blocklyEvaluationTimer.start() self.filterClassHash = None self.filter = None self.selectedBlockID = None self.fgbg = None def imgInit(self): self.cv_img = cv2.imread(os.path.join(sampleDataPath,"color_filter_test.png")) self.im_output = None self.inputScene = QGraphicsScene() self.inputGraphicsView.setScene(self.inputScene) self.inputGraphicsView.resizeEvent = self.inputGraphicsViewResized self.outputPixmap = None self.outputScene = QGraphicsScene() self.outputGraphicsView.setScene(self.outputScene) self.outputGraphicsView.resizeEvent = self.outputGraphicsViewResized qimg = misc.cvMatToQImage(self.cv_img) self.inputPixmap = QPixmap.fromImage(qimg) self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap) self.inputPixmapItem.mousePressEvent = self.getPixmapItemClickedPos self.inputScene.addItem(self.inputPixmapItem) def menuInit(self): self.actionOpenVideo.triggered.connect(self.openVideoFile) self.actionOpenImage.triggered.connect(self.openImageFile) self.actionSaveVideo.triggered.connect(self.saveVideoFile) self.actionSaveFilterData.triggered.connect(self.saveFilterFile) self.actionOpenFilterData.triggered.connect(self.openFilterFile) self.actionCreateBackground.triggered.connect(self.createBackground) def dragEnterEvent(self,event): event.acceptProposedAction() def dropEvent(self,event): mime = event.mimeData() if mime.hasUrls(): urls = mime.urls() if len(urls) > 0: self.processDropedFile(urls[0].toLocalFile()) event.acceptProposedAction() def closeEvent(self,event): pass def processDropedFile(self,filePath): root,ext = os.path.splitext(filePath) if ext == ".filter": # Read Filter self.openFilterFile(filePath=filePath) return elif self.openImageFile(filePath=filePath): return elif self.openVideoFile(filePath=filePath): return def setFrame(self, frame): if frame is not None: self.cv_img = frame self.updateInputGraphicsView() self.evaluateSelectedBlock() def setRectangleParameterToBlock(self, topLeft, bottomRight): height, width, dim = self.cv_img.shape array = [ [topLeft.x()/width, topLeft.y()/height], [bottomRight.x()/width, bottomRight.y()/height] ] parameters = {'array': '{0}'.format(array)} string = json.dumps({k: str(v) for k, v in parameters.items()}) webFrame = self.blocklyWebView.page().mainFrame() webFrame.evaluateJavaScript("Apps.setValueToSelectedBlock({0});".format(string)) def setArrayParameterToBlock(self, array): height, width, dim = self.cv_img.shape array = [[x[0]/width, x[1]/height] for x in array] parameters = {'array': '{0}'.format(array)} string = json.dumps({k: str(v) for k, v in parameters.items()}) webFrame = self.blocklyWebView.page().mainFrame() webFrame.evaluateJavaScript("Apps.setValueToSelectedBlock({0});".format(string)) def createBackground(self, activated=False): if self.videoPlaybackWidget.isOpened(): self.videoPlaybackWidget.stop() bg_dialog = BackgroundGeneratorDialog(self) bg_dialog.setWindowModality(Qt.WindowModal) bg_dialog.videoPlaybackWidget.copySource(self.videoPlaybackWidget) res = bg_dialog.exec() if res == QDialog.Accepted: if bg_dialog.fgbg is not None: self.fgbg = bg_dialog.fgbg.getBackgroundImage() def openVideoFile(self, activated=False, filePath = None): if filePath is None: filePath, _ = QFileDialog.getOpenFileName(None, 'Open Video File', userDir) if len(filePath) is not 0: self.filePath = filePath self.fgbg = None ret = self.videoPlaybackWidget.openVideo(filePath) if ret == False: return False self.videoPlaybackWidget.show() self.filterClassHash = None return True def openImageFile(self, activated=False, filePath = None): if filePath == None: filePath, _ = QFileDialog.getOpenFileName(None, 'Open Image File', userDir) if len(filePath) is not 0: self.filePath = filePath img = cv2.imread(filePath) if img is None: return False self.cv_img = img self.fgbg = None self.videoPlaybackWidget.hide() self.updateInputGraphicsView() # Initialize Filter when opening new file. self.filterClassHash = None return True else: return False def updateInputGraphicsView(self): self.inputScene.removeItem(self.inputPixmapItem) qimg = misc.cvMatToQImage(self.cv_img) self.inputPixmap = QPixmap.fromImage(qimg) rect = QtCore.QRectF(self.inputPixmap.rect()) self.inputScene.setSceneRect(rect) self.inputPixmapItem = QGraphicsPixmapItem(self.inputPixmap) self.inputScene.addItem(self.inputPixmapItem) self.inputGraphicsView.viewport().update() self.inputGraphicsViewResized() def getPixmapItemClickedPos(self, event): pos = event.scenePos().toPoint() print(pos) def inputPixmapItemClicked(self, event): pos = event.scenePos().toPoint() img = self.inputPixmap.toImage() pix = img.pixel(pos) rgb = QColor(pix).name() logger.debug("Selected pixel color: {0}".format(rgb)) parameters = { 'Color': rgb, } string = json.dumps(parameters) webFrame = self.blocklyWebView.page().mainFrame() webFrame.evaluateJavaScript("Apps.setValueToSelectedBlock({0});".format(string)) def openFilterFile(self, activated=False, filePath = None): if filePath is None: filePath, _ = QFileDialog.getOpenFileName(None, 'Open Block File', userDir, "Block files (*.filter)") if len(filePath) is not 0: logger.debug("Open Filter file: {0}".format(filePath)) filterIO = FilterIO(filePath) self.fgbg = filterIO.getBackgroundImg() exec(filterIO.getFilterCode(), globals()) blockXML = re.sub(r"[\n\r]",'', filterIO.getBlockXMLData()) frame = self.blocklyWebView.page().mainFrame() frame.evaluateJavaScript("Apps.setBlockData('{0}');".format(blockXML)) def saveFilterFile(self): self.blocklyEvaluationTimer.stop() if self.filePath is not None: candidateFilePath = os.path.splitext(self.filePath)[0] + '.filter' else: candidateFilePath = userDir filePath, _ = QFileDialog.getSaveFileName(None, 'Save Filter File', candidateFilePath, "Filter files (*.filter)") if len(filePath) is not 0: logger.debug("Saving Filter file: {0}".format(filePath)) frame = self.blocklyWebView.page().mainFrame() filterIO = FilterIO() filterIO.setBlockXMLData(frame.evaluateJavaScript("Apps.getBlockData();")) filterClassText = self.parseToClass(frame.evaluateJavaScript("Apps.getCodeFromWorkspace();")) filterIO.setFilterCode(filterClassText) filterIO.setBackgroundImg(self.fgbg) filterIO.save(filePath) self.blocklyEvaluationTimer.start() def inputGraphicsViewResized(self, event=None): self.inputGraphicsView.fitInView(QtCore.QRectF(self.inputPixmap.rect()), QtCore.Qt.KeepAspectRatio) def outputGraphicsViewResized(self, event=None): if self.outputPixmap is None: self.outputGraphicsView.fitInView(self.outputScene.sceneRect(), QtCore.Qt.KeepAspectRatio) else: self.outputGraphicsView.fitInView(QtCore.QRectF(self.outputPixmap.rect()), QtCore.Qt.KeepAspectRatio) def parseToClass(self, text): additionalText = """#self.fgbg = None #self.resize_flag = {resize_flag} #if self.resize_flag: # im_input = cv2.pyrDown(im_input) if self.resize_flag: {input} = cv2.pyrDown({input}) if self.fgbg is not None: {input} = cv2.absdiff({input}, self.fgbg) """.format(resize_flag=self.actionResize.isChecked(), input="{input}") text = additionalText + text lines = text.split("\n") classMemberPattern = r"^#" classMembers = [] filterOperations = [] for line in lines: if re.match(classMemberPattern, line): classMembers.append(line.lstrip("#")) else: filterOperations.append(line) generator = ClassTextGenerator('filterOperation') generator.functions['__init__']['lines'] = classMembers generator.functions['__init__']['args'] = ['im_input'] filterOperations.append('return {output}') generator.addFunction('filterFunc', filterOperations, args=['im_input'], returnVal=True) return generator.generate().format(input="im_input", output="im_output") def reflectSelectedBlockStateIntoUI(self): webFrame = self.blocklyWebView.page().mainFrame() data = webFrame.evaluateJavaScript("Apps.getBlockTypeFromSelectedBlock();") if data is None: self.resetSceneAction(self.selectedBlockID) self.selectedBlockID = None return blockType = data['type'] blockID = data['id'] blockAttributes = data['attributes'] if self.selectedBlockID != blockID: self.resetSceneAction(self.selectedBlockID) self.selectedBlockID = blockID if 'regionSelector' in blockAttributes: parameters = webFrame.evaluateJavaScript("Apps.getValueFromSelectedBlock();") graphicsItem = self.getGrphicsItemFromInputScene(blockID) if graphicsItem is not None: if graphicsItem.isVisible() is False: graphicsItem.show() else: height, width, dim = self.cv_img.shape array = [[x[0]*width, x[1]*height] for x in eval(parameters['array'])] if blockType == "rectRegionSelector": graphicsItem = ResizableRect() elif blockType == "ellipseRegionSelector": graphicsItem = ResizableEllipse() elif blockType == "polyRegionSelector": graphicsItem = MovablePolygon() self.inputScene.addItem(graphicsItem) graphicsItem.setPoints(array) graphicsItem.setObjectName(blockID) graphicsItem.geometryChange.connect(self.setArrayParameterToBlock) self.updateInputGraphicsView() elif 'colorSelector' in blockAttributes: self.inputPixmapItem.mousePressEvent = self.inputPixmapItemClicked else: self.inputPixmapItem.mousePressEvent = self.getPixmapItemClickedPos def resetSceneAction(self, blockID): graphicsItem = self.getGrphicsItemFromInputScene(blockID) if graphicsItem is not None: graphicsItem.hide() self.inputPixmapItem.mousePressEvent = QGraphicsPixmapItem(self.inputPixmapItem).mousePressEvent def getGrphicsItemFromInputScene(self, blockID): try: int(blockID) except: return None for item in self.inputScene.items(): # QGraphicsObjectをSceneから取り出そうとすると, # 親クラスであるQGraphicsItem(QPixmapGraphicsItem)にダウンキャスト # されて返ってくるためtryが必要. try: if blockID == item.objectName(): return item except: pass return None def evaluateSelectedBlock(self, update=True): self.im_output = None frame = self.blocklyWebView.page().mainFrame() text = frame.evaluateJavaScript("Apps.getCodeFromSelectedBlock();") self.reflectSelectedBlockStateIntoUI() if text == "" or text is None: text = frame.evaluateJavaScript("Apps.getCodeFromWorkspace();") if text is None: return False xmlText = frame.evaluateJavaScript("Apps.getBlockData();") text = self.parseToClass(text) logger.debug("Generated Code: {0}".format(text)) textHash = hashlib.md5(text.encode()) if self.filterClassHash != textHash: self.filterClassHash = textHash try: exec(text, globals()) self.filter = filterOperation(self.cv_img) self.filter.fgbg = self.fgbg except Exception as e: logger.debug("Block Evaluation Error: {0}".format(e)) return False try: self.im_output = self.filter.filterFunc(self.cv_img) except Exception as e: logger.debug("Filter execution Error: {0}".format(e)) return False if update: self.outputScene.clear() try: qimg = misc.cvMatToQImage(self.im_output) self.outputPixmap = QPixmap.fromImage(qimg) except: pass rect = QtCore.QRectF(self.outputPixmap.rect()) self.outputScene.setSceneRect(rect) self.outputScene.addPixmap(self.outputPixmap) self.outputGraphicsView.viewport().update() self.outputGraphicsViewResized() return True def saveVideoFile(self, activated=False): self.blocklyEvaluationTimer.stop() if self.evaluateSelectedBlock(False): if self.filePath is not None: candidateFilePath = os.path.splitext(self.filePath)[0] + '_processed.avi' else: candidateFilePath = userDir + '_processed.avi' filePath, _ = QFileDialog.getSaveFileName(None, 'Save Video', candidateFilePath, "AVI files (*.avi)") if len(filePath) is not 0: logger.debug("Saving Video: {0}".format(filePath)) self.videoPlaybackWidget.stop() fourcc = cv2.VideoWriter_fourcc(*'X264') out = cv2.VideoWriter(filePath, fourcc, self.videoPlaybackWidget.getFPS(), self.im_output.shape[1::-1]) numFrames = self.videoPlaybackWidget.getMaxFramePos()+1 progress = QProgressDialog("Running...\nOpenH264 Video Codec provided by Cisco Systems, Inc.", "Abort", 0, numFrames, self) progress.setWindowModality(Qt.WindowModal) currentFrameNo = self.videoPlaybackWidget.getFramePos() for i in range(numFrames): progress.setValue(i) if progress.wasCanceled(): break ret, input_frame = self.videoPlaybackWidget.readFrame(i) output_frame = self.filter.filterFunc(input_frame) if len(output_frame.shape)==2: output_frame = cv2.cvtColor(output_frame, cv2.COLOR_GRAY2BGR) out.write(output_frame) out.release() self.videoPlaybackWidget.moveToFrame(currentFrameNo) progress.setValue(numFrames) self.blocklyEvaluationTimer.start()
class StaticPhotos(QGraphicsView): def __init__(self, photoBaseDir, validPhotoFileExts, photoDeltas, picChangeMs, parent=None): QGraphicsView.__init__(self, parent) self.setAlignment(Qt.AlignLeft | Qt.AlignTop) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Vars self.picChangeMs = picChangeMs self.photoBaseDir = photoBaseDir # Widget self.scene = QGraphicsScene() self.setScene(self.scene) self.setBackgroundBrush(QColor("black")) self.setLineWidth(0) self.setFrameShape(QtWidgets.QFrame.NoFrame) # Class vars self.picChgTimer = None self.photoFileManager = PhotoFileManager(validPhotoFileExts, self.photoBaseDir, 7200.00, photoDeltas) self.photoFileManager.startPhotoListUpdate() self.userMovedBack = False # def sizeHint(self): # return QSize(600, 400) def resizeEvent(self, evt=None): xWindowSize = self.width() yWindowSize = self.height() pass def start(self): self.picChgTimer = QTimer() self.picChgTimer.setInterval(self.picChangeMs) self.picChgTimer.setSingleShot(True) self.picChgTimer.timeout.connect(self.picChangeFn) self.picChgTimer.start() # self.picChangeFn() print("Static Photos - starting") def stop(self): if self.picChgTimer is not None: self.picChgTimer.stop() print("Static Photos - stopping") # self.picChgTimer.disconnect(self.picChangeFn) self.photoFileManager.stop() def moveNext(self): self.nextPicItem() def movePrev(self): self.prevPicItem() self.userMovedBack = True def reshow(self): self.showImage() def getCurPhotoFilename(self): return self.photoFileManager.getCurPhotoFilename() def picChangeFn(self): # pass if self.userMovedBack: # Skip this update self.userMovedBack = False else: self.nextPicItem() self.picChgTimer.setInterval(self.picChangeMs) self.picChgTimer.start() def loadImage(self): self.newImg = QImage() self.newImg.load(self.photoFileManager.getCurPhotoFilename()) self.newImgInfo = self.photoFileManager.getCurPhotoInfo() transform = QTransform() transform.rotate(self.newImgInfo.rotationAngle) self.interImg = self.newImg.transformed(transform, Qt.SmoothTransformation) # xReqdSize = self.cellSize.width() * xFactor + self.xBetweenPics * (xFactor-1) # yReqdSize = self.cellSize.height() * yFactor + self.yBetweenPics * (yFactor-1) self.inter2Img = self.interImg.scaled(QSize(self.width(),self.height()), Qt.KeepAspectRatio, Qt.SmoothTransformation) # finalImg = interImg.copy(0,0,xReqdSize,yReqdSize) # print("XY Size", xFactor, yFactor, xReqdSize,yReqdSize) return self.inter2Img, self.newImgInfo def showImage(self): (newImg, newImgInfo) = self.loadImage() # return PicItem(Pixmap(QPixmap(newImg)), -1, -1, xFactor, yFactor, newImgInfo) self.scene.clear() imgSz = newImgInfo.imgSize self.setSceneRect(QRectF(0,0,imgSz.width(), imgSz.height())) pixMap = QPixmap.fromImage(newImg) # # pixMap.setWidth(self.width()) pixMapItem = self.scene.addPixmap(pixMap) # pixMapItem.setPos(50,50) # self.fitInView(QRectF(0, 0, self.width(), self.height()), Qt.KeepAspectRatio) # Add caption caption = QGraphicsTextItem() caption.setDefaultTextColor(QColor(255,255,255)) caption.setPos(0, self.height()*0.94) caption.setFont(QFont("Segoe UI", 30)) caption.setTextWidth(self.width()) # caption.setPos(100, 100) # caption.setTextWidth(1500) # if newImgInfo.createDate is not None: # caption.setPlainText(newImgInfo.createDate.format()); # else: # caption.setPlainText("Image is called bananas"); # print("Tags", newImgInfo.tags) # tagStr = "" # for tag in newImgInfo.tags: # if tag != "Duplicate": # tagStr += (", " if len(tagStr) != 0 else "") + tag # if tagStr == "": # tagStr = "NO TAGS" # captionStr = '<h1 style="text-align:center;width:100%">' + tagStr + '</h1>' # if newImgInfo.createDate is not None: # print(newImgInfo.createDate.format()) # captionStr += '<BR><h2>' + newImgInfo.createDate.format() + '</h2>' captionStr = "" try: if newImgInfo.rating is not None: for i in range(newImgInfo.rating): captionStr += "★" for i in range(5-newImgInfo.rating): captionStr += "☆" if newImgInfo.mainDate is not None: if len(captionStr) != 0: captionStr += " " captionStr += newImgInfo.mainDate.strftime("%d %b %Y") except Exception as excp: print("StaticPhotos: Cannot set caption") captionStr = '<div style="background-color:#000000;text-align: right;padding-right:10dp;">' + captionStr + "</div>" print(captionStr) caption.setHtml(captionStr) self.scene.addItem(caption) self.scene.update() def prevPicItem(self): if self.photoFileManager.getNumPhotos() == 0: return None self.photoFileManager.movePrev() # print ("Loaded photo", self.sourcePhotoList[self.curPhotoIdx], " w", finalImg.width(), " h", finalImg.height(), " facs", xFactor, yFactor) self.showImage() def nextPicItem(self): if self.photoFileManager.getNumPhotos() == 0: return None # print ("Loaded photo", self.sourcePhotoList[self.curPhotoIdx], " w", finalImg.width(), " h", finalImg.height(), " facs", xFactor, yFactor) self.photoFileManager.moveNext() self.showImage() def keyPressEvent(self, event): #QKeyEvent event.ignore()
class Minimap(QGraphicsView): ''' Minimap ''' def __init__(self, parent=0): ''' Constructor ''' super(Minimap, self).__init__(parent) self._scene = QGraphicsScene() self.setAutoFillBackground(True) self.setViewport(QGLWidget()) self.setScene(self._scene) self.setAlignment(Qt.AlignTop) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.nav_cursor = Cursor() self.nav_cursor.graphics_view = self self._scene.addItem(self.nav_cursor) self._graphic_item_list = [] self._pixmap = None self._text_edit = None self._abstract_doc_layout = None self._is_cursor_moved = False self._img_generator = ImageGenerator() self._img_generator.image_generated.connect(self._update_with) # self.setBackgroundRole(QPalette.Dark) @property def text_edit(self): return self._text_edit @text_edit.setter def text_edit(self, text_edit): if not isinstance(text_edit, QTextEdit): pass self._text_edit = text_edit self._text_edit.textChanged.connect(self.update) self._scrollbar = self._text_edit.verticalScrollBar() self._scrollbar.valueChanged.connect(self._change_cursor_pos) @pyqtSlot() def update(self): if self._is_cursor_moved: pass self._generate_image(self.text_edit) def _change_scrollbar_value(self, value): self._scrollbar.setValue(value) def resizeEvent(self, event): # self._image_label.setFixedHeight(self.height()) # self._image_label.setFixedWidth(self.width()) return QGraphicsView.resizeEvent(self, event) #-------------------------------------------------------------------------- def _generate_image(self, text_edit): doc = text_edit.document() item_list = [] for i in range(0, doc.blockCount()): block = doc.findBlockByNumber(i) item = DocItem() item.block_text = block.text() item.text_format = block.blockFormat() item.width = text_edit.viewport().width() layout = block.layout() item.lines = [] if layout: for i in range(0, layout.lineCount()): item.lines.append(layout.lineAt(i)) item_list.append(item) self._img_generator.set_items(item_list) self._img_generator.start() @pyqtSlot('QPixmap') def _update_with(self, pixmap): for g_item in self._graphic_item_list: if g_item.name == "map": self._scene.removeItem(g_item) self._graphic_item_list.remove(g_item) del g_item item = self._scene.addPixmap(pixmap) item.name = "map" item.setPos(0, 0) self._pixmap = pixmap self._graphic_item_list.append(item) self.setFixedWidth(pixmap.width()) # cursor : self.nav_cursor.setZValue(1) # width : self.nav_cursor.set_width(pixmap.width()) # height : text_edit_height = self.text_edit.height() doc_height = self.text_edit.document().size().height() minimap_height = self._pixmap.height() self.nav_cursor.set_minimap_height(minimap_height) ratio = doc_height / text_edit_height cursor_height = minimap_height / ratio self.nav_cursor.set_height(cursor_height) # position : self._change_cursor_pos() def _change_cursor_pos(self): if self._is_cursor_moved == True: return scroll_value = self._scrollbar.value() scroll_max = self._scrollbar.maximum() available_height_for_cursor = self._pixmap.height( ) - self.nav_cursor.height() if scroll_max != 0: pos_ratio = scroll_value / scroll_max self.nav_cursor.pos_ratio = pos_ratio self.nav_cursor.setPos(0, available_height_for_cursor * pos_ratio) else: self.nav_cursor.setPos(0, 0)
class OgrenciEkleWindow(QDialog): def __init__(self,parent=None): QDialog.__init__(self,parent) loadUi("ui/Ogrenci.ui",self) try: self.parent = parent self.not_ekle.clicked.connect(self.NotEkle) self.nots.setHorizontalHeaderLabels(["Not"]) self.kaydet.clicked.connect(self.OgrenciKaydet) self.fotograf_ekle.clicked.connect(self.FotografEkle) self.filename = None self.gscene = QGraphicsScene(self) self.graphicsView.setScene(self.gscene) except Exception as e: print(e) def FotografEkle(self): try: fname = QFileDialog.getOpenFileName(self, 'Dosya Seç',".",filter="Resim Dosyası (*.jpg *.jpeg *.png *.bmp)") self.filename = fname[0] px = QPixmap(self.filename) self.gscene.addPixmap(px) self.graphicsView.show() except Exception as e: print(e) def controlForm(self,elems): for elem in elems: if len(elem.text().replace(" ","")) == 0: return False return True def OgrenciKaydet(self): try: if self.controlForm([self.ad,self.soyad,self.anne,self.baba,self.dyeri,self.no]): nots = [] for i in range(self.nots.rowCount()): nots.append(self.nots.item(i,0).text()) durum = self.parent.db.create_student(self.ad.text(),self.soyad.text(),self.no.text(),self.anne.text(),self.baba.text(),self.dyeri.text(),self.dtarihi.text(),nots,self.filename ) if durum is False: QMessageBox.critical(self,"Hata","Öğrenci eklenemedi . Yazılım Hatası : %s" % self.parent.db.error) self.close() #print(self.dtarihi.text()) #print(dir(self.dtarihi)) else: QMessageBox.critical(self,"Hata","Tüm alanları doldurmalısınız.") except Exception as e: print(e) def NotEkle(self): if len(self.nottext.text().replace(" ","")) > 0: self.nots.setRowCount(self.nots.rowCount()+1) item = QTableWidgetItem(self.nottext.text()) self.nots.setItem(self.nots.rowCount()-1,0,item) self.nottext.setText("") else: QMessageBox.critical(self,"Hata","Not boş bırakılamaz.")