def main(): """ """ if len(sys.argv) < 2: print("give an image file as parameter please.") sys.exit(1) if len(sys.argv) > 2: print("only one parameter please.") sys.exit(1) filename = sys.argv[1] w = PrintPreviewDialog() w.resize(400, 500) comment = "" for i in range(20): comment += "Line number %d: En un lugar de La Mancha de cuyo nombre ...\n" % i if filename[-3:] == "svg": item = qt.QSvgRenderer(filename, w.page) w.addSvgItem(item, title=filename, comment=comment, commentPosition="CENTER") else: w.addPixmap(qt.QPixmap.fromImage(qt.QImage(filename)), title=filename, comment=comment, commentPosition="CENTER") w.addImage(qt.QImage(filename), comment=comment, commentPosition="LEFT") sys.exit(w.exec_())
def testAddPixmap(self): p = qt.QPrinter() d = PrintPreviewDialog(printer=p) d.addPixmap( qt.QPixmap.fromImage( qt.QImage(resource_filename("gui/icons/clipboard.png")))) self.qapp.processEvents()
def _arrayToPixmap(vector, cmap, nColors=256): """ Creates a pixmap from an array, using the provided colormap. :param vector: a numpy array. :param cmap: a matplotlib colormap. :param nColors: number of colors to use. :return: """ assert vector.ndim <= 2 sm = cm.ScalarMappable(cmap=cmap) colors = sm.to_rgba(np.arange(nColors)) cmap = [Qt.QColor.fromRgbF(*c).rgba() for c in colors] vMin = vector.min() vMax = vector.max() image = np.round((nColors - 1.) * (vector - vMin) / (vMax - vMin)) image = image.astype(np.int8) if image.ndim == 1: height = 1 width = image.shape[0] else: height = image.shape[0] width = image.shape[1] qImage = Qt.QImage(image.data, width, height, Qt.QImage.Format_Indexed8) qImage.setColorTable(cmap) return Qt.QPixmap.fromImage(qImage)
def testConvertQImageToArray(self): """Test conversion of QImage to numpy array""" qimage = qt.QImage(3, 3, qt.QImage.Format_RGB888) qimage.fill(0x010101) image = _utils.convertQImageToArray(qimage) self.assertEqual(qimage.height(), image.shape[0]) self.assertEqual(qimage.width(), image.shape[1]) self.assertEqual(image.shape[2], 3) self.assertTrue(numpy.all(numpy.equal(image, 1)))
def rasterText(text, font, size=-1, weight=-1, italic=False): """Raster text using Qt. It supports multiple lines. :param str text: The text to raster :param font: Font name or QFont to use :type font: str or :class:`QFont` :param int size: Font size in points Used only if font is given as name. :param int weight: Font weight in [0, 99], see QFont.Weight. Used only if font is given as name. :param bool italic: True for italic font (default: False). Used only if font is given as name. :return: Corresponding image in gray scale and baseline offset from top :rtype: (HxW numpy.ndarray of uint8, int) """ if not text: _logger.info("Trying to raster empty text, replaced by white space") text = ' ' # Replace empty text by white space to produce an image if not isinstance(font, qt.QFont): font = qt.QFont(font, size, weight, italic) metrics = qt.QFontMetrics(font) size = metrics.size(qt.Qt.TextExpandTabs, text) bounds = metrics.boundingRect(qt.QRect(0, 0, size.width(), size.height()), qt.Qt.TextExpandTabs, text) width = bounds.width() + 2 # Add extra border # align line size to 32 bits to ease conversion to numpy array width = 4 * ((width + 3) // 4) image = qt.QImage(width, bounds.height(), qt.QImage.Format_RGB888) # TODO if Qt5 use Format_Grayscale8 instead image.fill(0) # Raster text painter = qt.QPainter() painter.begin(image) painter.setPen(qt.Qt.white) painter.setFont(font) painter.drawText(bounds, qt.Qt.TextExpandTabs, text) painter.end() array = convertQImageToArray(image) # RGB to R array = numpy.ascontiguousarray(array[:, :, 0]) return array, metrics.ascent()
def setSliderProfile(self, profile, colormap=None, resetSliders=None, snap=True): """ Use the profile array to create a pixmap displayed in the slider groove. See also : RangeSlider.setSliderPixmap :param profile: 1D array :param colormap: a list of QRgb values (see : QImage.setColorTable) :param resetSliders: True to reset the slider positions to their extremes. If None the values positions will be reset if there was no previous profile. :param snap: set to True to set the number of steps equal to the length of the profile (equivalent to calling setNSteps and setSnap). If false, the number of steps will be unchanged, and snap will be set to False. :return: """ if profile is None: self.setSliderPixmap(None) return if profile.ndim != 1: raise ValueError('Profile must be a 1D array.') if profile.shape[0] <= 1: raise ValueError('Profile must be have a length > 1.') if colormap is not None: nColors = len(colormap) if nColors > 255: raise ValueError('Max 256 indexed colors supported' ' at the moment') else: nColors = 255 _min = profile.min() _max = profile.max() indices = np.int8(nColors * (profile.astype(np.float64) - _min) / (_max - _min)) qimage = Qt.QImage(indices.data, indices.shape[0], 1, Qt.QImage.Format_Indexed8) if colormap is not None: qimage.setColorTable(colormap) qpixmap = Qt.QPixmap.fromImage(qimage) self.setSliderPixmap(qpixmap, resetSliders=resetSliders, snap=snap)
def convertArrayToQImage(image): """Convert an array-like RGB888 image to a QImage. The created QImage is using a copy of the array data. Limitation: Only supports RGB888 and RGBA8888 format. :param image: Array-like image data :type image: numpy.ndarray of uint8 of dimension HxWx3 :return: Corresponding Qt image :rtype: QImage """ # Possible extension: add a format argument to support more formats image = numpy.array(image, copy=False, order='C', dtype=numpy.uint8) height, width, depth = image.shape if depth == 3: qimage = qt.QImage( image.data, width, height, image.strides[0], # bytesPerLine qt.QImage.Format_RGB888) elif depth == 4: qimage = qt.QImage( image.data, width, height, image.strides[0], # bytesPerLine qt.QImage.Format_RGBA8888) else: assert(False) return qimage.copy() # Making a copy of the image and its data
def testConvertQImageToArray(self): """Test conversion of QImage to numpy array""" for format_, channels in [ ('Format_RGB888', 3), # Native support ('Format_ARGB32', 4), # Native support ('Format_RGB32', 3) ]: # Conversion to RGB with self.subTest(format_): color = numpy.arange(channels) # RGB(A) values qimage = qt.QImage(3, 3, getattr(qt.QImage, format_)) qimage.fill(qt.QColor(*color)) image = convertQImageToArray(qimage) self.assertEqual(qimage.height(), image.shape[0]) self.assertEqual(qimage.width(), image.shape[1]) self.assertEqual(image.shape[2], len(color)) self.assertTrue(numpy.all(numpy.equal(image, color)))