def _set_pixmap_from_array(self, arr): bpl = arr.strides[0] is_rgb = len(arr.shape) == 3 if is_rgb and arr.dtype == np.uint8: format = QImage.Format_RGB32 image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format) elif not is_rgb and arr.dtype == np.uint8: # TODO: Somehow need to make sure data is ordered as I'm assuming format = QImage.Format_Indexed8 image = QImage(arr.data, self.camera.width, self.camera.height, bpl, format) self._saved_img = arr elif not is_rgb and arr.dtype == np.uint16: if not self._cmax: self._cmax = arr.max() # Set cmax once from first image arr = scipy.misc.bytescale(arr, self._cmin, self._cmax) format = QImage.Format_Indexed8 w, h = self.camera.width, self.camera.height image = QImage(arr.data, w, h, w, format) self._saved_img = arr # Save a reference to keep Qt from crashing else: raise Exception("Unsupported color mode") self.setPixmap(QPixmap.fromImage(image)) pixmap_size = self.pixmap().size() if pixmap_size != self.size(): self.setMinimumSize(self.pixmap().size())
def get_icon(iconpath, size=None): image = QImage(iconpath) if size is not None: qsize = QtCore.QSize(*size) image = image.scaled(qsize) pixmap = QPixmap.fromImage(image) iconw = QIcon(pixmap) return iconw
def cmap2pixmap(cmap, steps=50): """Convert a Ginga colormap into a QPixmap """ inds = numpy.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [ cmap.clst[int(x*n)] for x in inds ] rgbas = [QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups] im = QImage(steps, 1, QImage.Format_Indexed8) im.setColorTable(rgbas) for i in range(steps): im.setPixel(i, 0, i) im = im.scaled(128, 32) pm = QPixmap.fromImage(im) return pm
def __init__( self, icon: QIcon, script: str, filename: str, file_format: List[str], parent: MainWindowBase, *, compressed_script: str = "M[]" ): """Input parameters: + Script + Lexer + File name + File suffix """ super(ScriptDialog, self).__init__(parent) self.setupUi(self) self.setWindowFlags( self.windowFlags() & ~Qt.WindowContextHelpButtonHint | Qt.WindowMaximizeButtonHint ) self.setWindowIcon(icon) self.script_view = _ScriptBrowser(self) self.script_view.setText(script) self.main_layout.insertWidget(0, self.script_view) self.filename = filename self.file_format = file_format self.output_to = parent.output_to self.save_reply_box = parent.save_reply_box self.setWindowTitle(self.filename) # Compressed script self.compressed_script = compressed_script if self.compressed_script == "M[]": self.show_qrcode.setVisible(False) return line_edit = QLineEdit(self) line_edit.setText(self.compressed_script) line_edit.setReadOnly(True) self.main_layout.insertWidget(1, line_edit) # Image display image = make(self.compressed_script, image_factory=_NpImage) self.image: QPixmap = QPixmap.fromImage(image.get_qimage())
def cmap2pixmap(cmap, steps=50): """Convert a Ginga colormap into a QPixmap """ inds = numpy.linspace(0, 1, steps) n = len(cmap.clst) - 1 tups = [cmap.clst[int(x * n)] for x in inds] rgbas = [ QColor(int(r * 255), int(g * 255), int(b * 255), 255).rgba() for r, g, b in tups ] im = QImage(steps, 1, QImage.Format_Indexed8) im.setColorTable(rgbas) for i in range(steps): im.setPixel(i, 0, i) im = im.scaled(128, 32) pm = QPixmap.fromImage(im) return pm
def _on_thumbnail_change(self, event=None): """Update thumbnail image on the layer widget. Parameters ---------- event : qtpy.QtCore.QEvent, optional Event from the Qt context. """ thumbnail = self.layer.thumbnail # Note that QImage expects the image width followed by height image = QImage( thumbnail, thumbnail.shape[1], thumbnail.shape[0], QImage.Format_RGBA8888, ) self.thumbnailLabel.setPixmap(QPixmap.fromImage(image))
def _on_thumbnail_change(self, event=None): """Update thumbnail image on the layer widget. Parameters ---------- event : napari.utils.event.Event, optional The napari event that triggered this method. """ thumbnail = self.layer.thumbnail # Note that QImage expects the image width followed by height image = QImage( thumbnail, thumbnail.shape[1], thumbnail.shape[0], QImage.Format_RGBA8888, ) self.thumbnailLabel.setPixmap(QPixmap.fromImage(image))
def loadServos(self): model = QStandardItemModel() net, servo = il.lucky(il.NET_PROT.ETH, "../../resources/dictionaries/eve-net_1.7.1.xdf", address_ip='192.168.2.22', port_ip=1061, protocol=2) if net is not None and servo is not None: item = QStandardItem('0x{:02x} ({})'.format(1, "Everest")) item.setData(servo, Qt.UserRole) image = QImage(join(_RESOURCES, 'images', 'eve-xcr.png')) item.setData(QPixmap.fromImage(image), Qt.DecorationRole) model.appendRow([item]) self.cboxServos.setModel(model)
def __init__(self, parent, arr): QLabel.__init__(self) # we need to hold a reference to # arr because QImage doesn't copy the data # and the buffer must be alive as long # as the image is alive. self.arr = arr # we also need to pass in the row-stride to # the constructor, because we can't guarantee # that every row of the numpy data is # 4-byte aligned. Which Qt would require # if we didn't pass the stride. self.img = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_RGB888) self.pm = QPixmap.fromImage(self.img) self.setPixmap(self.pm) self.setAlignment(QtCore.Qt.AlignTop) self.setMinimumSize(100, 100)
def __init__(self, parent, arr): QLabel.__init__(self) # we need to hold a reference to # arr because QImage doesn't copy the data # and the buffer must be alive as long # as the image is alive. self.arr = arr # we also need to pass in the row-stride to # the constructor, because we can't guarantee # that every row of the numpy data is # 4-byte aligned. Which Qt would require # if we didn't pass the stride. self.img = QImage(arr.data, arr.shape[1], arr.shape[0], arr.strides[0], QImage.Format_RGB888) self.pm = QPixmap.fromImage(self.img) self.setPixmap(self.pm) self.setAlignment(QtCore.Qt.AlignTop) self.setMinimumSize(100, 100)
def _on_colormap_change(self, event=None): """Receive layer model colormap change event and update dropdown menu. Parameters ---------- event : napari.utils.event.Event, optional The napari event that triggered this method, by default None. """ name = self.layer.colormap.name if name not in self.colormapComboBox._allitems: self.colormapComboBox._allitems.add(name) self.colormapComboBox.addItem(name) if name != self.colormapComboBox.currentText(): self.colormapComboBox.setCurrentText(name) # Note that QImage expects the image width followed by height cbar = self.layer.colormap.colorbar image = QImage( cbar, cbar.shape[1], cbar.shape[0], QImage.Format_RGBA8888, ) self.colorbarLabel.setPixmap(QPixmap.fromImage(image))
def create_splash_screen(): """Create splash screen.""" if not running_under_pytest(): image = QImage(500, 400, QImage.Format_ARGB32_Premultiplied) image.fill(0) painter = QPainter(image) renderer = QSvgRenderer(get_image_path('splash')) renderer.render(painter) painter.end() pm = QPixmap.fromImage(image) pm = pm.copy(0, 0, 500, 400) splash = QSplashScreen(pm) splash_font = splash.font() splash_font.setPixelSize(14) splash.setFont(splash_font) else: splash = None return splash
def _on_colormap_change(self): """Receive layer model colormap change event and update dropdown menu.""" name = self.layer.colormap.name if name not in self.colormapComboBox._allitems: cm = AVAILABLE_COLORMAPS.get(name) if cm: self.colormapComboBox._allitems.add(name) self.colormapComboBox.addItem(cm._display_name, name) if name != self.colormapComboBox.currentData(): index = self.colormapComboBox.findData(name) self.colormapComboBox.setCurrentIndex(index) # Note that QImage expects the image width followed by height cbar = self.layer.colormap.colorbar image = QImage( cbar, cbar.shape[1], cbar.shape[0], QImage.Format_RGBA8888, ) self.colorbarLabel.setPixmap(QPixmap.fromImage(image))
def __init__(self, *args, **kwargs): super(OpenSpaceDataViewer, self).__init__(*args, **kwargs) self._logo = QLabel() self._image = QPixmap.fromImage(QImage(LOGO)) self._logo.setPixmap(self._image) self._logo.setAlignment(Qt.AlignCenter) self._ip = QLineEdit() self._ip.setText('ws://localhost:4682/websocket') self._button = QPushButton('Connect') self._button.clicked.connect(self.connect_to_openspace) self._layout = QVBoxLayout() self._layout.addWidget(self._logo) self._horizontal = QHBoxLayout() self._horizontal.addWidget(self._ip) self._horizontal.addWidget(self._button) self._layout.addLayout(self._horizontal) self._main = QWidget() self._main.setLayout(self._layout) self.setCentralWidget(self._main)
def __structure_list_context_menu(self, point) -> None: """Context menu for the type synthesis results.""" index = self.structure_list.currentIndex().row() self.to_collection.setEnabled(index > -1) self.copy_edges.setEnabled(index > -1) self.copy_image.setEnabled(index > -1) action = self.pop_menu_topo.exec_(self.structure_list.mapToGlobal(point)) if not action: return clipboard = QApplication.clipboard() if action == self.to_collection: self.add_collection(self.answer[index].edges) elif action == self.copy_edges: clipboard.setText(str(self.answer[index].edges)) elif action == self.copy_image: # Turn the transparent background to white image1 = self.__atlas_image() image2 = QImage(image1.size(), image1.format()) image2.fill(Qt.white) painter = QPainter(image2) painter.drawImage(QPointF(0, 0), image1) painter.end() clipboard.setPixmap(QPixmap.fromImage(image2))
def _on_colormap_change(self, event=None): """Receive layer model colormap change event and update dropdown menu. Parameters ---------- event : qtpy.QtCore.QEvent, optional. Event from the Qt context, by default None. """ name = self.layer.colormap[0] if name not in self.colormapComboBox._allitems: self.colormapComboBox._allitems.add(name) self.colormapComboBox.addItem(name) if name != self.colormapComboBox.currentText(): self.colormapComboBox.setCurrentText(name) # Note that QImage expects the image width followed by height image = QImage( self.layer._colorbar, self.layer._colorbar.shape[1], self.layer._colorbar.shape[0], QImage.Format_RGBA8888, ) self.colorbarLabel.setPixmap(QPixmap.fromImage(image))
def convert_image(self, worker, output, error): """ Load an image using PIL, and converts it to a QPixmap. This was needed as some image libraries are not found in some OS. """ path = output if path in self.pixmaps: return try: if sys.platform == 'darwin' and PYQT4: from PIL.ImageQt import ImageQt from PIL import Image if path: image = Image.open(path) image = ImageQt(image) qt_image = QImage(image) pixmap = QPixmap.fromImage(qt_image) else: pixmap = QPixmap() else: if path and os.path.isfile(path): extension = path.split('.')[-1].upper() if extension in ['PNG', 'JPEG', 'JPG']: # This might be producing an error message on windows # for some of the images pixmap = QPixmap(path, format=extension) else: pixmap = QPixmap(path) else: pixmap = QPixmap() self.pixmaps[path] = pixmap except (IOError, OSError) as error: logger.error(str(error))
def _mgui_set_value(self, val: np.ndarray) -> None: image = QImage(val, val.shape[1], val.shape[0], QImage.Format_RGBA8888) self._pixmap = QPixmap.fromImage(image) self._rescale()
def _populate_colormap_combo_box(self): for cmap_name in get_colormap_names(): qt_img = create_colormap_img(cmap_name) pixmap = QPixmap.fromImage(qt_img) self.colormap_combo_box.addItem(QIcon(pixmap), cmap_name)
def graph2icon(g: Graph, width: int, node_mode: bool, show_label: bool, monochrome: bool, *, except_node: Optional[int] = None, engine: str = "", pos: Optional[_Pos] = None) -> QIcon: """Draw a generalized chain graph.""" if engine: pos = engine_picker(g, engine, node_mode) if pos is None: raise ValueError("no engine selected") if not pos: pixmap = QPixmap(width, width) pixmap.fill(Qt.transparent) return QIcon(pixmap) width_bound = -float('inf') for x, y in pos.values(): if abs(x) > width_bound: width_bound = x if abs(y) > width_bound: width_bound = y width_bound *= 2.5 image = QImage(QSize(int(width_bound), int(width_bound)), QImage.Format_ARGB32_Premultiplied) image.fill(Qt.transparent) painter = QPainter(image) painter.translate(image.width() / 2, image.height() / 2) pen = QPen() r = int(width_bound / 50) pen.setWidth(r) painter.setPen(pen) _font.setPixelSize(r * 6) painter.setFont(_font) # Draw edges if node_mode: for l1, l2 in g.edges: if except_node in {l1, l2}: pen.setColor(Qt.gray) else: pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(QPointF(pos[l1][0], -pos[l1][1]), QPointF(pos[l2][0], -pos[l2][1])) else: color = color_qt('dark-gray') if monochrome else LINK_COLOR color.setAlpha(150) painter.setBrush(QBrush(color)) for link in g.vertices: if link == except_node: pen.setColor(Qt.gray) else: pen.setColor(Qt.black) painter.setPen(pen) painter.drawPolygon(*convex_hull([(pos[n][0], -pos[n][1]) for n, edge in edges_view(g) if link in edge], as_qpoint=True)) # Draw vertices for k, (x, y) in pos.items(): if node_mode: color = color_num(len(list(g.neighbors(k))) - 1) if k == except_node: color.setAlpha(150) else: if monochrome: color = Qt.black elif except_node in dict(edges_view(g))[k]: color = color_qt('green') else: color = color_qt('blue') pen.setColor(color) painter.setPen(pen) painter.setBrush(QBrush(color)) point = QPointF(x, -y) painter.drawEllipse(point, r, r) if show_label: pen.setColor(Qt.darkMagenta) painter.setPen(pen) painter.drawText(point, str(k)) painter.end() return QIcon(QPixmap.fromImage(image).scaledToWidth(width))
def update_image(self): width = self.width() pm = QPixmap.fromImage(self.img) pm = pm.scaledToWidth(width) self.setPixmap(pm)
def getImageFromArray(self, array, outlabel): qimg = qimage2ndarray.array2qimage(array, normalize=True) pixmap = QPixmap.fromImage(qimg) pixmap = pixmap.scaled(outlabel.width(), outlabel.height(), QtCore.Qt.KeepAspectRatio) outlabel.setPixmap(pixmap)
def resizeEvent(self, evt): width = self.width() pm = QPixmap.fromImage(self.img) self.pm = pm.scaledToWidth(width) self.setPixmap(self.pm)
def resizeEvent(self, evt): width = self.width() pm = QPixmap.fromImage(self.img) self.pm = pm.scaledToWidth(width) self.setPixmap(self.pm)
def setImage(self, img): if isinstance(img, QImage): img = QPixmap.fromImage(img) self._imageItem.setPixmap(img)
def _update_bitmap(self) -> None: """Update the bitmap with latest image data.""" height, width = BITMAP_SHAPE[:2] image = QImage(self._image, width, height, QImage.Format_RGBA8888) self.setPixmap(QPixmap.fromImage(image))
def mouseReleaseEvent(self, event): if event.button == Qt.LeftButton: # self.drawing = False self.label.setPixmap(QPixmap.fromImage(self.image))
def inspect_PngImageFile(value): label = QLabel() label.setPixmap(QPixmap.fromImage(ImageQt(value))) return label
def set_image(self, image): pixmap = QPixmap.fromImage(image) pixmap_scaled = pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.image_label.setPixmap(pixmap_scaled)
def update_image(self): width = self.width() pm = QPixmap.fromImage(self.img) pm = pm.scaledToWidth(width) self.setPixmap(pm)