Example #1
0
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
Example #2
0
    def toImage(self, *args):
        """
        .. py:method:: toImage()
            :noindex:
        
            Convert the graphic to a `QImage`

            All pixels of the image get initialized by 0 ( transparent )
            before the graphic is scaled and rendered on it.

            The format of the image is `QImage.Format_ARGB32_Premultiplied`.
            
            The size of the image is the default size ( ceiled to integers )
            of the graphic.

            :return: The graphic as image in default size

        .. py:method:: toImage(size, [aspectRatioMode=Qt.IgnoreAspectRatio])
            :noindex:
        
            Convert the graphic to a `QImage`

            All pixels of the image get initialized by 0 ( transparent )
            before the graphic is scaled and rendered on it.

            The format of the image is `QImage.Format_ARGB32_Premultiplied`.
            
            :param QSize size: Size of the image
            :param `Qt.AspectRatioMode` aspectRatioMode: Aspect ratio how to scale the graphic
            :return: The graphic as image

        .. seealso::
        
            :py:meth:`toPixmap()`, :py:meth:`render()`
        """
        if len(args) == 0:
            if self.isNull():
                return QImage()
            sz = self.defaultSize()
            w = np.ceil(sz.width())
            h = np.ceil(sz.height())
            image = QImage(w, h, QImage.Format_ARGB32)
            image.fill(0)
            r = QRect(0, 0, sz.width(), sz.height())
            painter = QPainter(image)
            self.render(painter, r, Qt.KeepAspectRatio)
            painter.end()
            return image
        elif len(args) in (1, 2):
            size = args[0]
            aspectRatioMode = Qt.IgnoreAspectRatio
            if len(args) == 2:
                aspectRatioMode = args[-1]
            image = QImage(size, QImage.Format_ARGB32_Premultiplied)
            image.fill(0)
            r = QRect(0, 0, size.width(), size.height())
            painter = QPainter(image)
            self.render(painter, r, aspectRatioMode)
            return image
Example #3
0
    def paintEvent(self, event):
        super(DetailedProgress, self).paintEvent(event)
        if not self._current_progress:
            return

        painter = QPainter(self)
        width = self.width()
        height = self.height()
        aspect_ratio = float(width) / height
        nr_realizations = max([iens for iens, _, _ in self._current_progress]) + 1
        fm_size = max([len(progress) for _, progress, _ in self._current_progress])
        self.grid_height = math.ceil(math.sqrt(nr_realizations / aspect_ratio))
        self.grid_width = math.ceil(self.grid_height * aspect_ratio)
        sub_grid_size = math.ceil(math.sqrt(fm_size))
        cell_height = height / self.grid_height
        cell_width = width / self.grid_width

        foreground_image = QImage(self.grid_width * sub_grid_size, self.grid_height * sub_grid_size,
                                  QImage.Format_ARGB32)
        foreground_image.fill(QColor(0, 0, 0, 0))

        for index, (iens, progress, _) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))
            self.draw_window(x * sub_grid_size, y * sub_grid_size, progress, foreground_image)
            painter.drawImage(self.contentsRect(), foreground_image)

        for index, (iens, progress, state) in enumerate(self._current_progress):
            y = int(iens / self.grid_width)
            x = int(iens - (y * self.grid_width))

            painter.setPen(QColor(80, 80, 80))
            painter.drawText(x * cell_width, y * cell_height, cell_width, cell_height,
                             Qt.AlignHCenter | Qt.AlignVCenter, str(iens))

            if iens == self.selected_realization:
                pen = QPen(QColor(240, 240, 240))
            elif (self.has_realization_failed(progress)):
                pen = QPen(QColor(*self.state_colors['Failure']))
            elif (state == JobStatusType.JOB_QUEUE_RUNNING):
                pen = QPen(QColor(*self.state_colors['Running']))
            else:
                pen = QPen(QColor(80, 80, 80))

            thickness = 4
            pen.setWidth(thickness)
            painter.setPen(pen)
            painter.drawRect((x * cell_width) + (thickness / 2),
                             (y * cell_height) + (thickness / 2),
                             cell_width - (thickness - 1),
                             cell_height - (thickness - 1))
Example #4
0
    def __init__(self, parent=None):
        super().__init__(parent)

        global colorIndexId
        colorIndexId += 1
        self.m_backgroundColorIndex = colorIndexId

        self.m_text = ""
        self.m_image = QImage()
        self.m_lastPos = QPoint()
        self.m_backingStore = None
        self.m_renderTimer = 0

        self.initialize()
Example #5
0
 def add_thumb_bytes(self, result):
     bytes_, wrapper = result
     img = QImage()
     img.loadFromData(bytes_)
     icon = QIcon(QPixmap.fromImage(img))
     name = wrapper.getName()
     if len(name) > 18:
         name = name[:15] + "..."
     item = QListWidgetItem(icon, name)
     item.setTextAlignment(Qt.AlignHCenter | Qt.AlignBottom)
     item.wrapper = wrapper
     self._item_map[wrapper.getId()] = item
     self.addItem(item)
     if self._current_item.isImage():
         self.select_image()
Example #6
0
    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:
            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))
Example #7
0
    def load_icon(self, project_path, project=None, as_pixmap=False):
        """
        Load project icon for project located at `project_path`.
        """
        logger.debug(str((project_path, project['name'], as_pixmap)))
        from PIL.ImageQt import ImageQt
        from PIL import Image

        if project is None:
            project = self.load_project(project_path)

        icon_path = os.sep.join([project_path, project.icon])

        if os.path.isfile(icon_path):
            try:
                icon = qta.icon('fa.gear')
                image = Image.open(icon_path)
                image = ImageQt(image)
                qt_image = QImage(image)
                pixmap = QPixmap.fromImage(qt_image)
                icon = QIcon(pixmap)
            except Exception:
                icon = qta.icon('fa.gear')
        else:
            icon = qta.icon('fa.gear')

        if as_pixmap:
            try:
                icon = icon.pixmap(icon.availableSizes()[0])
            except Exception:
                icon = QPixmap(*IMAGE_ICON_SIZE)
        return icon
Example #8
0
    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.
        """
        # Needs to come after qtpy imports
        path = output
        if path in self.pixmaps:
            return

        if path:
            if os.path.isfile(path):
                try:
                    if sys.platform == 'darwin':
                        from PIL.ImageQt import ImageQt
                        from PIL import Image

                        image = Image.open(path)
                        image = ImageQt(image)
                        qt_image = QImage(image)
                        pixmap = QPixmap.fromImage(qt_image)
                    else:
                        extension = path.split('.')[-1].upper()

                        if extension in ['PNG', 'JPEG', 'JPG']:
                            pixmap = QPixmap(path, format=extension)
                        else:
                            pixmap = QPixmap(path)

                    self.pixmaps[path] = pixmap
                except (IOError, OSError) as error:
                    logger.error(str(error))
Example #9
0
    def loadServos(self):
        model = QStandardItemModel()

        devs = il.devices(il.NET_PROT.EUSB)
        for dev in devs:
            try:
                net = il.Network(il.NET_PROT.EUSB, dev)
            except il.exceptions.ILCreationError:
                continue

            found = net.servos()
            for servo_id in found:
                try:
                    servo = il.Servo(net, servo_id)
                except il.exceptions.ILCreationError:
                    continue

                item = QStandardItem('0x{:02x} ({})'.format(servo_id, dev))
                item.setData(servo, Qt.UserRole)

                image = QImage(join(_RESOURCES, 'images', 'triton-core.png'))
                item.setData(QPixmap.fromImage(image), Qt.DecorationRole)

                model.appendRow([item])

        self.cboxServos.setModel(model)
Example #10
0
def qt_image(image):
    assert image.ndim in [
        2, 3
    ], f"qt_image: unsupported image dimensions {image.ndim}"
    assert image.dtype == np.uint8, f"qt_image: expected np.uint8 got {image.dtype}"

    if image.ndim == 3:
        height, width, _ = image.shape
        bytesPerLine = 3 * width
        return QImage(image.data, width, height, bytesPerLine,
                      QImage.Format.Format_BGR888)
    elif image.ndim == 2:
        height, width = image.shape
        bytesPerLine = width
        return QImage(image.data, width, height, bytesPerLine,
                      QImage.Format.Format_Grayscale8)
Example #11
0
 def data(self, index: QModelIndex, role: Qt.ItemDataRole):
     """Return data stored under ``role`` for the item at ``index``."""
     layer = self.getItem(index)
     if role == Qt.DisplayRole:  # used for item text
         return layer.name
     if role == Qt.TextAlignmentRole:  # alignment of the text
         return Qt.AlignCenter
     if role == Qt.EditRole:  # used to populate line edit when editing
         return layer.name
     if role == Qt.ToolTipRole:  # for tooltip
         return layer.name
     if role == Qt.CheckStateRole:  # the "checked" state of this item
         return Qt.Checked if layer.visible else Qt.Unchecked
     if role == Qt.SizeHintRole:  # determines size of item
         return QSize(200, 34)
     if role == ThumbnailRole:  # return the thumbnail
         thumbnail = layer.thumbnail
         return QImage(
             thumbnail,
             thumbnail.shape[1],
             thumbnail.shape[0],
             QImage.Format_RGBA8888,
         )
     # normally you'd put the icon in DecorationRole, but we do that in the
     # # LayerDelegate which is aware of the theme.
     # if role == Qt.DecorationRole:  # icon to show
     #     pass
     return super().data(index, role)
Example #12
0
    def paint(
        self,
        painter: QPainter,
        style: QStyleOptionViewItem,
        model: QModelIndex,
    ):
        style2 = QStyleOptionViewItem(style)

        cbar_rect = QRect(
            style.rect.x(),
            style.rect.y() + PADDING,
            style.rect.width() - TEXT_WIDTH,
            style.rect.height() - 2 * PADDING,
        )
        text_rect = QRect(
            style.rect.width() - TEXT_WIDTH,
            style.rect.y() + PADDING,
            style.rect.width(),
            style.rect.height() - 2 * PADDING,
        )
        style2.rect = text_rect
        super().paint(painter, style2, model)
        cbar = make_colorbar(ensure_colormap(model.data()), (18, 100))
        image = QImage(
            cbar,
            cbar.shape[1],
            cbar.shape[0],
            QImage.Format_RGBA8888,
        )
        painter.drawImage(cbar_rect, image)
Example #13
0
    def __init__(self):
        QWidget.__init__(self)

        self.styles = load_styles()
        self.image = StyledCapture(QImage(256, 256, QImage.Format_RGB888),
                                   '')  # placeholder
        self.freeze = None
        if isinstance(settings.CAPTURE_HANDLER, string_types):
            self.capture_handler = locate(settings.CAPTURE_HANDLER)
        else:
            self.capture_handler = settings.CAPTURE_HANDLER
        self.setup_ui()

        self.frame_grabber = FrameGrabber(settings.SIZES[0])
        self.frame_thread = QThread()
        # self.frame_grabber.image_signal.connect(self.display_frame)
        self.frame_grabber.last_frame_signal.connect(self.last_frame)
        self.frame_grabber.moveToThread(self.frame_thread)
        self.frame_thread.started.connect(self.frame_grabber.grab)
        self.stop_signal.connect(self.frame_grabber.stop_work)
        self.quality_changed.connect(self.frame_grabber.change_size)
        self.frame_thread.start()

        self.image_processor = ImageProcessor(self.styles[0])
        self.image_thread = QThread()
        self.image_processor.image_signal.connect(self.display_frame)
        self.image_processor.moveToThread(self.image_thread)
        self.image_thread.started.connect(self.image_processor.monitor_images)
        self.stop_signal.connect(self.image_processor.stop_work)
        self.style_changed.connect(self.image_processor.change_style)
        self.last_frame_changed.connect(self.image_processor.change_last_frame)
        self.image_thread.start()
Example #14
0
    def run(self):
        try:
            import cv2
        except ImportError as e:
            self.errored.emit(str(e))
            self.stopped.emit()
            return
        try:
            ueye = UEye(self._cam_id, self._image_width, self._image_height)
        except CameraException as e:
            self.errored.emit(str(e))
            self.stopped.emit()
            return
        self._ueye.start_video_capture()

        while True:
            try:
                self._update_mutex.lock()
                if self._stopped:
                    ueye.close()
                    del ueye
                    self.stopped.emit()
                    return
            finally:
                self._update_mutex.unlock()

            frame = ueye.get_video_frame()
            if frame is None:
                ueye.close()
                del ueye
                self.stopped.emit()
                return

            rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            h, w, ch = rgb_image.shape
            bytes_per_line = ch * w
            convert_to_qt_format = QImage(
                rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888
            )
            try:
                self._update_mutex.lock()
                p = convert_to_qt_format.scaled(
                    self._width, self._height, Qt.KeepAspectRatio
                )
            finally:
                self._update_mutex.unlock()
            self.pixmapReady.emit(p)
Example #15
0
 def array2pixmap(array: np.ndarray, rescale: bool = True) -> QPixmap:
     # https://github.com/sjara/brainmix/blob/master/brainmix/gui/numpy2qimage.py
     if rescale:
         array = VGraphicsScene.rescale_array(array)
     array = np.require(array, np.uint8, 'C')
     w, h = array.shape
     qimage = QImage(array.data, w, h, QImage.Format_Grayscale8)
     return QPixmap.fromImage(qimage)
Example #16
0
def qwtBackgroundWidget(w):
    if w.parentWidget() is None:
        return w
    if w.autoFillBackground():
        brush = w.palette().brush(w.backgroundRole())
        if brush.color().alpha() > 0:
            return w
    if w.testAttribute(Qt.WA_StyledBackground):
        image = QImage(1, 1, QImage.Format_ARGB32)
        image.fill(Qt.transparent)
        painter = QPainter(image)
        painter.translate(-w.rect().center())
        qwtDrawStyledBackground(w, painter)
        painter.end()
        if qAlpha(image.pixel(0, 0)) != 0:
            return w
    return qwtBackgroundWidget(w.parentWidget())
Example #17
0
 def mouse_on_map(self, val):
     if val != self.current_color:
         self.current_color = val
         img = color_image_fun(
             np.arange(0, 256).reshape((1, 256, 1)), [val], [(0, 256)])
         self.image = QImage(img.data, 256, 1, img.dtype.itemsize * 256 * 3,
                             QImage.Format_RGB888)
         self.preview.repaint()
Example #18
0
    def monitor_images(self):
        while self.active:
            if self.last_frame:
                image_array = self.style.stylize(self.last_frame)
                image = QImage(image_array.data, image_array.shape[1],
                               image_array.shape[0], image_array.strides[0],
                               QImage.Format_RGB888)

                rotating = QTransform()
                rotating.scale(-1, 1)  # mirror
                rotating.rotate(settings.ROTATE_IMAGE)
                image = image.transformed(rotating)

                self.image_signal.emit(StyledCapture(image, self.style.name))

            # check for stop/changes
            QApplication.processEvents()
Example #19
0
	def init_image(self, resolution):
		self.resolution = resolution
		# apparently, using numpy values in QImage causes it to crash
		self.image_qt = QImage(int(resolution[0]), int(resolution[1]), self.QT_IMAGE_FORMAT)
		self.image_view = qimage2ndarray.byte_view(self.image_qt, 'little')
		# self.image_view = np.zeros((resolution[1], resolution[0], 4), np.uint8)
		#print(f'byte view {self.image_view.shape} {self.image_view.dtype}')

		self.image_view[:] = 0
Example #20
0
def get_thumbnail(project_dir_path):
    thumb_path = os.path.join(project_dir_path, '.thumbnail')
    if os.path.isfile(thumb_path):
        pix = QPixmap()
        pix.convertFromImage(QImage(thumb_path, 'PNG'))
        icon = QIcon(pix)
    else:
        icon = get_icon('missing_thumbnail.png')
    return icon
Example #21
0
 def _icon_from_key_frame(self, key_frame):
     """Generate QIcon from a key frame"""
     thumbnail = QImage(
         key_frame.thumbnail,
         key_frame.thumbnail.shape[1],
         key_frame.thumbnail.shape[0],
         QImage.Format_RGBA8888,
     )
     return QIcon(QPixmap.fromImage(thumbnail))
Example #22
0
    def show_image(self, img):
        self.resize(200, 200)

        try:
            rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        except cv2.error:
            return

        h, w, ch = rgb_image.shape
        bytes_per_line = ch * w
        qt_image = QImage(rgb_image.data, w, h, bytes_per_line, QImage.Format_RGB888)
        img_w = qt_image.width()
        img_h = qt_image.height()
        proportion = img_w / img_h
        self.resize(self.width() * proportion, self.height())
        qt_image = qt_image.scaled(self.width(), self.height())
        self.setPixmap(QPixmap(qt_image))
        self.node.update_shape()
Example #23
0
def get_font_array(sz, chars=DEFAULT_CHARS):
    from qtpy.QtGui import QFont, QPainter, QColor

    font = QFont()
    font.setFixedPitch(True)
    font.setPixelSize(int(sz))
    font.setStyleStrategy(QFont.NoAntialias)
    dummy = QImage(10, 10, QImage.Format_ARGB32)
    pnt = QPainter(dummy)
    pnt.setFont(font)
    metric = pnt.fontMetrics()
    rct = metric.boundingRect(chars)
    pnt.end()
    h = rct.height()
    w = rct.width()
    img = QImage(w, h, QImage.Format_ARGB32)
    paint = QPainter()
    paint.begin(img)
    paint.setFont(font)
    paint.setBrush(QColor(255, 255, 255))
    paint.setPen(QColor(255, 255, 255))
    paint.drawRect(0, 0, w + 1, h + 1)
    paint.setPen(QColor(0, 0, 0))
    paint.setBrush(QColor(0, 0, 0))
    paint.drawText(0, paint.fontMetrics().ascent(), chars)
    paint.end()
    try:
        try:
            # PyQt4 (at least until Qt 4.8)
            data = img.bits().asstring(img.numBytes())
        except AttributeError:
            if PYSIDE2:
                # PySide2
                data = bytes(img.bits())
            else:
                # PyQt5
                data = img.bits().asstring(img.byteCount())
    except SystemError:
        # PyQt4 (4.11.3) and PyQt5 (5.3.2) on Python 3
        return
    npy = np.frombuffer(data, np.uint8)
    npy.shape = img.height(), int(img.bytesPerLine() / 4), 4
    return npy[:, :, 0]
Example #24
0
 def update_image(self, img: np.ndarray):
     rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
     h, w, ch = rgb_image.shape
     bytes_per_line = ch * w
     qimg = QImage(rgb_image.data, w, h, bytes_per_line,
                   QImage.Format_RGB888)
     pixmap = QPixmap.fromImage(qimg)
     self.current_image.setPixmap(pixmap)
     self._scene.setSceneRect(0, 0, w, h)
     self.fitInView(self._scene.sceneRect(), Qt.KeepAspectRatio)
Example #25
0
 def _on_thumbnail_change(self, event=None):
     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))
Example #26
0
 def copy_to_clipboard(self):
     """Copy the current figure image to clipboard"""
     # store the image in a buffer using savefig(), this has the
     # advantage of applying all the default savefig parameters
     # such as background color; those would be ignored if you simply
     # grab the canvas using Qt
     buf = io.BytesIO()
     self.canvas.figure.savefig(buf)
     QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
     buf.close()
 def get_qimage(self) -> QImage:
     """To QImage."""
     height, width, color = self._img.shape
     return QImage(
         self._img.data,
         width,
         height,
         color * height,
         QImage.Format_RGB888
     )
 def paintEvent(self, event: QPaintEvent):
     outerRadius = min(self.width(), self.height())
     baseRect = QRectF(1, 1, outerRadius - 2, outerRadius - 2)
     buffer = QImage(outerRadius, outerRadius, QImage.Format_ARGB32_Premultiplied)
     p = QPainter(buffer)
     p.setRenderHint(QPainter.Antialiasing)
     self.rebuildDataBrushIfNeeded()
     self.drawBackground(p, buffer.rect())
     self.drawBase(p, baseRect)
     if self.m_value > 0:
         delta = (self.m_max - self.m_min) / (self.m_value - self.m_min)
     else:
         delta = 0
     self.drawValue(p, baseRect, self.m_value, delta)
     innerRect, innerRadius = self.calculateInnerRect(outerRadius)
     self.drawInnerBackground(p, innerRect)
     self.drawText(p, innerRect, innerRadius, self.m_value)
     p.end()
     painter = QPainter(self)
     painter.fillRect(baseRect, self.palette().window())
     painter.drawImage(0, 0, buffer)
Example #29
0
    def _draw_map(self, intersection: OctreeIntersection) -> None:
        """Draw the minimap showing the latest intersection.

        Parameters
        ----------
        intersection : OctreeIntersection
            The intersection we are drawing on the map.
        """
        data = self._create_map_data(intersection)
        height, width = data.shape[:2]
        image = QImage(data, width, height, QImage.Format_RGBA8888)
        self.setPixmap(QPixmap.fromImage(image))
Example #30
0
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
Example #31
0
def imsave(filename, img, format_str=None):
    # we can add support for other than 3D uint8 here...
    img = prepare_for_display(img)
    qimg = QImage(img.data, img.shape[1], img.shape[0], img.strides[0],
                  QImage.Format_RGB888)
    if _is_filelike(filename):
        byte_array = QtCore.QByteArray()
        qbuffer = QtCore.QBuffer(byte_array)
        qbuffer.open(QtCore.QIODevice.ReadWrite)
        saved = qimg.save(qbuffer, format_str.upper())
        qbuffer.seek(0)
        filename.write(qbuffer.readAll().data())
        qbuffer.close()
    else:
        saved = qimg.save(filename)
    if not saved:
        from textwrap import dedent
        msg = dedent('''The image was not saved. Allowable file formats
            for the QT imsave plugin are:
            BMP, JPG, JPEG, PNG, PPM, TIFF, XBM, XPM''')
        raise RuntimeError(msg)
Example #32
0
def imsave(filename, img, format_str=None):
    # we can add support for other than 3D uint8 here...
    img = prepare_for_display(img)
    qimg = QImage(img.data, img.shape[1], img.shape[0],
                  img.strides[0], QImage.Format_RGB888)
    if _is_filelike(filename):
        byte_array = QtCore.QByteArray()
        qbuffer = QtCore.QBuffer(byte_array)
        qbuffer.open(QtCore.QIODevice.ReadWrite)
        saved = qimg.save(qbuffer, format_str.upper())
        qbuffer.seek(0)
        filename.write(qbuffer.readAll().data())
        qbuffer.close()
    else:
        saved = qimg.save(filename)
    if not saved:
        from textwrap import dedent
        msg = dedent(
            '''The image was not saved. Allowable file formats
            for the QT imsave plugin are:
            BMP, JPG, JPEG, PNG, PPM, TIFF, XBM, XPM''')
        raise RuntimeError(msg)
Example #33
0
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
Example #34
0
def imread(filename):
    """
    Read an image using QT's QImage.load
    """
    qtimg = QImage()
    if not qtimg.load(filename):
        # QImage.load() returns false on failure, so raise an exception
        raise IOError('Unable to load file %s' % filename)
    if qtimg.depth() == 1:
        raise IOError('1-bit images currently not supported')
    # TODO: Warn about other odd formats we don't currently handle properly,
    # such as the odd 16-bit packed formats QT supports
    arrayptr = qtimg.bits()
    # QT may pad the image, so we need to use bytesPerLine, not width for
    # the conversion to a numpy array
    bytes_per_pixel = qtimg.depth() // 8
    pixels_per_line = qtimg.bytesPerLine() // bytes_per_pixel
    img_size = pixels_per_line * qtimg.height() * bytes_per_pixel
    arrayptr.setsize(img_size)
    img = np.array(arrayptr)
    # Reshape and trim down to correct dimensions
    if bytes_per_pixel > 1:
        img = img.reshape((qtimg.height(), pixels_per_line, bytes_per_pixel))
        img = img[:, :qtimg.width(), :]
    else:
        img = img.reshape((qtimg.height(), pixels_per_line))
        img = img[:, :qtimg.width()]
    # Strip qt's false alpha channel if needed
    # and reorder color axes as required
    if bytes_per_pixel == 4 and not qtimg.hasAlphaChannel():
        img = img[:, :, 2::-1]
    elif bytes_per_pixel == 4:
        img[:, :, 0:3] = img[:, :, 2::-1]
    return img