def __init__(self, previewImage, fileName): super(ImageView, self).__init__() self.fileName = fileName mainLayout = QVBoxLayout(self) self.imageLabel = QLabel() self.imageLabel.setPixmap(QPixmap.fromImage(previewImage)) mainLayout.addWidget(self.imageLabel) topLayout = QHBoxLayout() self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName)) self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction) topLayout.addWidget(self.fileNameLabel) topLayout.addStretch() copyButton = QPushButton("Copy") copyButton.setToolTip("Copy file name to clipboard") topLayout.addWidget(copyButton) copyButton.clicked.connect(self.copy) launchButton = QPushButton("Launch") launchButton.setToolTip("Launch image viewer") topLayout.addWidget(launchButton) launchButton.clicked.connect(self.launch) mainLayout.addLayout(topLayout)
def tick(self): self.game.tick() bitmap = self.game.visualize() image = QImage(bitmap.data, bitmap.shape[1], bitmap.shape[0], QImage.Format_Grayscale8) self.scene.removeItem(self.item) pixmap = QPixmap.fromImage(image) self.item = self.scene.addPixmap(pixmap)
def generateAndExportClicked(self): g = Generator() g.tileWidth = self.tileWidthSpinBox.value() g.tileHeight = self.tileHeightSpinBox.value() g.forcePot = self.forcePotCheckBox.isChecked() g.isTransparent = self.transparentCheckbox.isChecked() g.bgColor = self.backgroundColorEdit.getColor() g.reorder = self.reorderTilesCheckBox.isChecked() g.padding = self.paddingSpinBox.value() target = g.create(self.pixmapWidget.pixmap); # export self.lastDir = os.path.dirname(self.path) targetPath = QFileDialog.getSaveFileName(self, 'Export', self.lastDir, 'PNG (*.png)') if targetPath: target.save(targetPath[0]) showPixmap = QPixmap.fromImage(target) if self.showPixmapWidget: self.showPixmapWidget.deleteLater() del self.showPixmapWidget self.showPixmapWidget = PixmapWidget() self.showPixmapWidget.setWindowIcon(self.windowIcon()) self.showPixmapWidget.setWindowTitle(os.path.basename(targetPath[0])) self.showPixmapWidget.resize(showPixmap.width(), showPixmap.height()) self.showPixmapWidget.setPixmap(showPixmap) self.showPixmapWidget.show()
def updatePixmap(self, image, scaleFactor): if not self.lastDragPos.isNull(): return self.pixmap = QPixmap.fromImage(image) self.pixmapOffset = QPoint() self.lastDragPosition = QPoint() self.pixmapScale = scaleFactor self.update()
def render_bgr_mat(self, mat: np.ndarray): mat_rgb = cv.cvtColor(mat, cv.COLOR_BGR2RGB) height, width, _ = mat_rgb.shape bytes_per_line, *_ = mat_rgb.strides img = QImage(mat_rgb.data, width, height, bytes_per_line, QImage.Format_RGB888) pixmap = QPixmap.fromImage(img) if pixmap.width() > self.width() or pixmap.height() > self.height(): pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.FastTransformation) self.setPixmap(pixmap) self.__current_rgb_mat = mat_rgb
def load(self,fileName): image = QImage(fileName) if image.isNull(): QMessageBox.information(self,QApplication.applicationName(), "Cannot load "+fileName) self.setWindowTitle("Image viewer") self.setPixmap(QPixmap()) self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.setWindowTitle(fileName)
def cv_to_qpixmap(cvimg): qformat = QImage.Format_Indexed8 if len(cvimg.shape) == 3: if cvimg.shape[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 qimg = QImage(cvimg.data, cvimg.shape[1], cvimg.shape[0], cvimg.strides[0], qformat) qimg = qimg.rgbSwapped() return QPixmap.fromImage(qimg)
def convert_to_qimage(self, image): from PySide2.QtGui import QPixmap from PySide2.QtWidgets import QLabel from PIL.ImageQt import ImageQt qim = ImageQt(image) pix = QPixmap.fromImage(qim) result_label = QLabel('') result_label.setPixmap(pix) return result_label
def cargar_imagen_ignore(self, label): """insertar imagen elastica""" # verificamos que la ruta sea valida, si no retornamos /*/*/*/*/*/ ruta = self.obtener_ruta() if(ruta==''):return # generamos el Pixmap en base a la ruta de imagen /*/*/*/*/*/ imagen = QPixmap.fromImage(ruta) # insertar imagen /*/*/*/*/*/ label.setPixmap(imagen)
def update_limage(self, image, level): # qim = ImageQt(image) qim = QImage( image, image.shape[1], image.shape[0], image.strides[0], QImage.Format_RGB888, ) self.set_widget_size_from_img(image) self.limage_label.setPixmap(QPixmap.fromImage(qim)) self.level_label.setText('Level: {}'.format(level + 1))
def draw_qr_view(self): self.current_view = "qr_code" scene = QGraphicsScene() url = self.config.get_base_url() + self.session_service.session_uuid self._clear_all_buttons() self._rename_button(self.main_window.pushButton_4, "New Session", "") self._rename_button(self.main_window.pushButton, "Contiune Session", "") self.main_window.button_led.emit((True, False, False, True)) im = Image.open(self.config.get_qr_code_png_path()) pixmap = QPixmap.fromImage(ImageQt.ImageQt(im)) pixmap_qr_code = QPixmap.fromImage( self.qr_code_serivce.generade_qr_code("https://" + url)) self.grapics_view_service.create_qr_scene(scene, pixmap_qr_code, url, pixmap) self.grapics_view_service.show_scene(scene)
def _set_portrait_from_current_index(self): portrait_name, texture = self._portraits[self._current_index] self.portrait_name_label.setText(portrait_name) self.current_image_label.setText( "%d / %d" % (self._current_index + 1, len(self._portraits))) scene = QGraphicsScene() scene.addPixmap(QPixmap.fromImage(texture.image())) scene.setSceneRect(0.0, 0.0, 128.0, 128.0) self.display.setScene(scene) self.display.setSceneRect(0.0, 0.0, float(texture.width()), float(texture.height()))
def videostart(self): if self.step >= self.cap.get(cv2.CAP_PROP_FRAME_COUNT): return frame = self.video_array[self.step] frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = qimage2ndarray.array2qimage(frame) self.imageLabel.setPixmap(QPixmap.fromImage(image)) self.step += 1 self.positionSlider.setValue(self.step)
def drawBackground(self, qp, qrF): """ Overrides QGraphicsView.drawBackground @param qp: @type qp: QPainter @param qrF: @type qrF: QRectF """ graphicsScene = self.scene() s = graphicsScene.axeSize if graphicsScene.cubicItem.histImg is not None: qp.drawPixmap(QRect(0, -s, s, s), QPixmap.fromImage(graphicsScene.cubicItem.histImg))
def open_image(self, img): if img.shape[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 copy = img_as_ubyte(img) qimg = QImage(copy.data, copy.shape[1], copy.shape[0], copy.strides[0], qformat).rgbSwapped() pixmap = QPixmap.fromImage(qimg) self.__label.setPixmap(pixmap) self.__label.adjustSize()
def _load_from_png(x: int, y: int) -> QIcon: image = png.copy( QRect(x * Block.SIDE_LENGTH, y * Block.SIDE_LENGTH, Block.SIDE_LENGTH, Block.SIDE_LENGTH)) mask = image.createMaskFromColor( QColor(*MASK_COLOR).rgb(), Qt.MaskOutColor) image.setAlphaChannel(mask) pixmap = QPixmap.fromImage(image) icon_from_png = QIcon(pixmap) return icon_from_png
def set_image(self, image): self.last_frame = image rect = [int(i) for i in self.cur_pos_rect] # rect = [0, 0, 500, 500] new_image = image[rect[1]:rect[1] + rect[3], rect[0]:rect[0] + rect[2]].copy(order='C') h, w, ch = new_image.shape tem_pixmap = QPixmap.fromImage( QImage(new_image, w, h, ch * w, QImage.Format_RGB888)) if tem_pixmap.size().toTuple() != self.size().toTuple(): tem_pixmap = tem_pixmap.scaled(self.size()) self.setPixmap(tem_pixmap)
def assert_equal(self): __tracebackhide__ = True self.end() self.different_pixels = 0 actual_image: QImage = self.actual.device().toImage() expected_image: QImage = self.expected.device().toImage() diff_pixmap = QPixmap(actual_image.width(), actual_image.height()) diff = QPainter(diff_pixmap) try: white = QColor('white') diff.fillRect(0, 0, actual_image.width(), actual_image.height(), white) for x in range(actual_image.width()): for y in range(actual_image.height()): actual_colour = actual_image.pixelColor(x, y) expected_colour = expected_image.pixelColor(x, y) diff.setPen( self.diff_colour(actual_colour, expected_colour, x, y)) diff.drawPoint(x, y) finally: diff.end() diff_image: QImage = diff.device().toImage() display_diff(actual_image, diff_image, expected_image, self.different_pixels) if self.different_pixels == 0: return actual_image.save(str(self.work_dir / (self.name + '_actual.png'))) expected_image.save(str(self.work_dir / (self.name + '_expected.png'))) diff_path = self.work_dir / (self.name + '_diff.png') is_saved = diff_image.save(str(diff_path)) diff_width = self.diff_max_x - self.diff_min_x + 1 diff_height = self.diff_max_y - self.diff_min_y + 1 diff_section = QImage(diff_width, diff_height, QImage.Format_RGB32) diff_section_painter = QPainter(diff_section) try: diff_section_painter.drawPixmap(0, 0, diff_width, diff_height, QPixmap.fromImage(diff_image), self.diff_min_x, self.diff_min_y, diff_width, diff_height) finally: diff_section_painter.end() # To see an image dumped in the Travis CI log, copy the text from the # log, and paste it in test_pixmap_differ.test_decode_image. print(f'Encoded image of differing section ' f'({self.diff_min_x}, {self.diff_min_y}) - ' f'({self.diff_max_x}, {self.diff_max_y}):') print(encode_image(diff_section)) message = f'Found {self.different_pixels} different pixels, ' message += f'see' if is_saved else 'could not write' message += f' {diff_path.relative_to(Path(__file__).parent.parent)}.' assert self.different_pixels == 0, message
def get_pose(self): try: res = self.q.get(False) assert (type(res) == dict) img_show = res['img_show'] showImage = QImage(img_show, img_show.shape[1], img_show.shape[0], QImage.Format_BGR888) self.label.setPixmap(QPixmap.fromImage(showImage)) if self.is_running: self.recorded_data.append(res['results']) except Exception as e: pass
def requestPixmap(self, id, size, requestedSize): camId = int(id.split("/")[0]) if camId == -1: return if self.previewDevices.isEmpty(): return frame = self.previewDevices.getDevice( 0).frame # Because we only have one device qImg = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888).rgbSwapped() return QPixmap.fromImage(qImg)
def updateView(self): if self.currentMat is None: return img = QImage(self.currentMat.data, self.currentMat.shape[1], self.currentMat.shape[0], QtGui.QImage.Format_RGB888).rgbSwapped() pixmap = QPixmap.fromImage(img) self.setPixmap(pixmap) self.setMinimumHeight(self.currentMat.shape[0]) self.setMinimumWidth(self.currentMat.shape[1]) self.setMaximumHeight(self.currentMat.shape[0]) self.setMaximumWidth(self.currentMat.shape[1]) self.currentMat = self.original.copy()
def updatePixmap(self, maskOnly=False): """ Synchronize qPixmap and rPixmap with the image layer and mask. If maskOnly is True, cmImage is not updated. if maskIsEnabled is False, the mask is not shown. If maskIsEnabled is True, then - if maskIsSelected is True, the mask is drawn over the layer as a color mask. - if maskIsSelected is False, the mask is drawn as an opacity mask, setting image opacity to that of mask (mode DestinationIn). Mask color is no used. @param maskOnly: default False @type maskOnly: boolean """ currentImage = self.getCurrentImage() # apply color management to presentation layer if icc.COLOR_MANAGE and self.parentImage is not None and getattr( self, 'role', None) == 'presentation': # CAUTION : reset alpha channel img = convertQImage(currentImage, transformation=self.parentImage. colorTransformation) # time 0.66 s for 15 Mpx. # restore alpha channel # img = img.convertToFormat(currentImage.format()) # TODO 15/10/18 dome by convertQImage() buf0 = QImageBuffer(img) buf1 = QImageBuffer(currentImage) buf0[:, :, 3] = buf1[:, :, 3] else: img = currentImage qImg = img rImg = currentImage if self.maskIsEnabled: #qImg = vImage.visualizeMask(qImg, self.mask, color=self.maskIsSelected, clipping=self.isClipping) rImg = vImage.visualizeMask(rImg, self.mask, color=self.maskIsSelected, clipping=self.isClipping) self.qPixmap = QPixmap.fromImage(qImg) self.rPixmap = QPixmap.fromImage(rImg) self.setModified(True)
def __init__(self, name, baseSize, contourPath, presetFilename=None, image=None): """ @param name: @type name: str @param baseSize: @type baseSize: int @param contourPath: base shape of the brush family @type contourPath: QPainterPath @param presetFilename: preset file @type presetFilename: str """ self.name = name self.baseSize = baseSize # init the brush pixmap self.basePixmap = QPixmap(self.baseSize, self.baseSize) # to get an alpha channel, we must fill the pixmap a first time with an opacity < 255 self.basePixmap.fill(QColor(0, 0, 0, 0)) if self.name == 'eraser': self.basePixmap.fill(QColor(0, 0, 0, 255)) self.contourPath = contourPath # init brush cursor self.baseCursor = QPixmap(self.baseSize, self.baseSize) self.baseCursor.fill(QColor(0, 0, 0, 0)) qp = QPainter(self.baseCursor) pen = qp.pen() pen.setWidth(self.baseSize / 20) qp.setPen(pen) # needed!! qp.drawPath(contourPath) qp.end() self.__pxmp = None self.bOpacity = 1.0 self.bFlow = 1.0 self.bHardness = 1.0 self.preset = None if presetFilename is not None: img = QImage(presetFilename) elif image is not None: img = image else: return img = img.convertToFormat(QImage.Format_ARGB32) buf = QImageBuffer(img) b = np.sum(buf[..., :3], axis=-1, dtype=np.float) b /= 3 buf[..., 3] = b self.preset = QPixmap.fromImage(img)
def __init__(self): super(ThresholdingGui, self).__init__() self.setWindowTitle('Adaptive Thresholding') open_image_btn = QPushButton('Open Image', self) open_image_btn.clicked.connect(self.open_image) self.method_combobox = QComboBox() for title in self.titles: self.method_combobox.addItem(title) self.method_combobox.currentIndexChanged.connect(self.update_preview) self.block_size_label = QLabel(f"Block Size: {self.block_size}") self.block_size_slider = QSlider() self.block_size_slider.setOrientation(Qt.Horizontal) self.block_size_slider.setTickPosition(QSlider.TicksBelow) self.block_size_slider.setMinimum(3) self.block_size_slider.setMaximum(255) self.block_size_slider.setTickInterval(2) self.block_size_slider.setSingleStep(2) self.block_size_slider.setValue(self.block_size) self.block_size_slider.valueChanged.connect(self.set_block_size) self.c_constant_label = QLabel(f"C constant: {self.c_constant}") self.c_constant_slider = QSlider() self.c_constant_slider.setOrientation(Qt.Horizontal) self.c_constant_slider.setTickPosition(QSlider.TicksBelow) self.c_constant_slider.setMinimum(0) self.c_constant_slider.setMaximum(100) self.c_constant_slider.setValue(self.c_constant) self.c_constant_slider.valueChanged.connect(self.set_c_constant) self.image_label = QLabel() self.image = np.tile(np.arange(256, dtype=np.uint8).repeat(2), (512, 1)) q_img = QImage(self.image.data, 512, 512, 512, QImage.Format_Indexed8) self.image_label.setPixmap(QPixmap.fromImage(q_img)) # Create layout and add widgets layout = QVBoxLayout() layout.addWidget(open_image_btn) layout.addWidget(self.method_combobox) layout.addWidget(self.block_size_label) layout.addWidget(self.block_size_slider) layout.addWidget(self.c_constant_label) layout.addWidget(self.c_constant_slider) layout.addWidget(self.image_label) # Set dialog layout self.setLayout(layout)
def getCurrentMaskedImage(self): """ Blend the layer stack up to self (included), taking into account the masks. The method uses the non color managed rPixmap to build the masked image. For convenience, mainly to be able to use its color space buffers, the built image is of type bImage. It is drawn on a container image, instantiated only once. @return: masked image @rtype: bImage """ # init containers if needed. They are instantiated only # once and updated by drawing. if self.parentImage.useHald: return self.getHald() if self.maskedThumbContainer is None: self.maskedThumbContainer = bImage.fromImage( self.getThumb(), parentImage=self.parentImage) if self.maskedImageContainer is None: self.maskedImageContainer = bImage.fromImage( self, parentImage=self.parentImage) if self.parentImage.useThumb: img = self.maskedThumbContainer else: img = self.maskedImageContainer # draw lower stack qp = QPainter(img) top = self.parentImage.getStackIndex(self) bottom = 0 for i, layer in enumerate(self.parentImage.layersStack[bottom:top + 1]): if layer.visible: if i == 0: qp.setCompositionMode(QPainter.CompositionMode_Source) else: qp.setOpacity(layer.opacity) qp.setCompositionMode(layer.compositionMode) if layer.rPixmap is None: layer.rPixmap = QPixmap.fromImage(layer.getCurrentImage( )) # TODO modified 9/12/18 validate qp.drawPixmap(QRect(0, 0, img.width(), img.height()), layer.rPixmap) # clipping if layer.isClipping and layer.maskIsEnabled: # draw mask as opacity mask # mode DestinationIn (set dest opacity to source opacity) qp.setCompositionMode( QPainter.CompositionMode_DestinationIn) omask = vImage.color2OpacityMask(layer.mask) qp.drawImage(QRect(0, 0, img.width(), img.height()), omask) qp.end() return img
def setPhoto(self, qimage=None): pixmap = QPixmap.fromImage(qimage) self._zoom = 0 if pixmap and not pixmap.isNull(): self._empty = False self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag) self._photo.setPixmap(pixmap) else: self._empty = True self.setDragMode(QtWidgets.QGraphicsView.NoDrag) self._photo.setPixmap(QtGui.QPixmap()) self.fitInView()
def load_talk_windows() -> Dict: assets_service = locator.get_scoped("AssetsService") bch_talk_window_standard = assets_service.load_bch( "/ui/TalkWindow.bch.lz") bch_name_plate = assets_service.load_bch("/ui/TalkWindow2.bch.lz") bch_talk_window_w = assets_service.load_bch("/ui/TalkWindowW.bch.lz") bch_talk_window_b = assets_service.load_bch("/ui/TalkWindowB.bch.lz") return { "standard": _slice_talk_window( QPixmap.fromImage( bch_talk_window_standard["TalkWindow"].image())), "name_plate": _slice_name_plate( QPixmap.fromImage(bch_name_plate["TalkWindow2"].image())), "birthright": _slice_talk_window( QPixmap.fromImage(bch_talk_window_w["TalkWindow"].image())), "conquest": _slice_talk_window( QPixmap.fromImage(bch_talk_window_b["TalkWindow"].image())) }
def data(self, index, role): if self.video_pipeline: if role == Qt.DisplayRole: i = self.video_pipeline.filter(index.row()).index + 1 return "{:02d} - ".format(i) + self.video_pipeline.filter( index.row()).meta()["name"] if role == Qt.DecorationRole: try: icon = QIcon() icon.addPixmap( QPixmap.fromImage( QImage(":/all/icons/list_normal.png")), QIcon.Mode.Normal) icon.addPixmap( QPixmap.fromImage( QImage(":/all/icons/list_selected.png")), QIcon.Mode.Selected) return icon except Exception as exc: print(exc) pass
def grayscale(): im2 = Image.open('image_name.jpg') new_list = [((a[0] * 299 + a[1] * 587 + a[2] * 114) // 1000, ) * 3 for a in im2.getdata()] im2.putdata(new_list) #turn PIL image to Qimage so we can use it in the GUI if im2.mode == 'RGB': im2 = im2.convert('RGBA') qimage = toqimage(im2) return QPixmap.fromImage(qimage)
def set_image_on_viewer(self): # Delete existing image item if len(self.imgs_pixmap) != 0: for item in self.imgs_pixmap: self.scene.removeItem(item) self.scene.clear_contents() self.imgs_pixmap.clear() self.imgs.clear() # load original image self.org_qimg = QImage(self.org_img_file_path) self.org_pixmap = QPixmap.fromImage(self.org_qimg) org_img_size = self.org_qimg.size() self.org_img_width = org_img_size.width() self.org_img_height = org_img_size.height() # Set layer image self.layer_qimg = QImage(self.org_img_width, self.org_img_height, QImage.Format_RGBA8888) self.layer_qimg.fill(QColor(0, 0, 0, self.layer_alpha)) self.layer_pixmap = QPixmap.fromImage(self.layer_qimg) self.imgs.append(self.org_qimg) self.imgs.append(self.layer_qimg) # Set image to scene self.imgs_pixmap.append(QGraphicsPixmapItem(self.org_pixmap)) self.scene.addItem(self.imgs_pixmap[-1]) self.imgs_pixmap.append(QGraphicsPixmapItem(self.layer_pixmap)) self.scene.addItem(self.imgs_pixmap[-1]) self.scene.set_img_contents(self.imgs) # Set scene to graphics view self.graphics_view.setScene(self.scene) self.graphics_view.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.show()
def update_preview(self): method_idx = self.method_combobox.currentIndex() if method_idx == 0: ret, th = '-', self.image elif method_idx == 1: ret, th = cv2.threshold(self.image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) self.threshold_label.setText(f"Threshold calculated: {ret}") image_h, image_w = th.shape q_img = QImage(th.data, image_w, image_h, image_w, QImage.Format_Indexed8) self.image_label.setPixmap(QPixmap.fromImage(q_img))
def set_img(self, frame): def normalize(f): lmin = float(self.min) lmax = float(self.max) return np.floor((f - lmin) / (lmax - lmin) * 255.) if self.data.show_annot == True: self.canvas = normalize( imutils.resize(frame, width=512, height=512)) for coords in self.points: x, y = coords # cv2.circle(self.canvas, (int(x), int(y)), int(10), (255, 255, 255), 2) cv2.drawMarker(self.canvas, (int(x), int(y)), (255, 255, 255), markerType=cv2.MARKER_CROSS, markerSize=10, thickness=2) self.image_label.setPixmap( QPixmap.fromImage(array2qimage(self.canvas))) else: frame = normalize(imutils.resize(frame, width=512, height=512)) self.image_label.setPixmap(QPixmap.fromImage(array2qimage(frame)))
def setPhoto(self, pixmap=None): self._zoom = 0 if pixmap and not pixmap.isNull(): self.empty = False self.changed = False self._photo.setPixmap(pixmap) self.seg_image = QImage(pixmap.width(), pixmap.height(), QImage.Format_ARGB32_Premultiplied) self.seg_image.fill(QtCore.Qt.transparent) self._seglayer.setPixmap(QPixmap.fromImage(self.seg_image)) else: self._empty = True self._photo.setPixmap(QPixmap()) self.fitInView()
def _pillow_to_pixmap(self, img): if img.mode == "RGB": r, g, b = img.split() img = Image.merge("RGB", (b, g, r)) elif img.mode == "RGBA": r, g, b, a = img.split() img = Image.merge("RGBA", (b, g, r, a)) elif img.mode == "L": img = img.convert("RGBA") img2 = img.convert("RGBA") data = img2.tobytes("raw", "RGBA") qim = QImage(data, img.size[0], img.size[1], QImage.Format_ARGB32) pixmap = QPixmap.fromImage(qim) return pixmap