Пример #1
0
 def toImage(self, *args):
     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
Пример #2
0
def array_to_qimage(arr, copy=False):
    """Convert NumPy array to QImage object"""
    # https://gist.githubusercontent.com/smex/5287589/raw/toQImage.py
    if arr is None:
        return QImage()
    if len(arr.shape) not in (2, 3):
        raise NotImplementedError("Unsupported array shape %r" % arr.shape)
    data = arr.data
    ny, nx = arr.shape[:2]
    stride = arr.strides[0]  # bytes per line
    color_dim = None
    if len(arr.shape) == 3:
        color_dim = arr.shape[2]
    if arr.dtype == np.uint8:
        if color_dim is None:
            qimage = QImage(data, nx, ny, stride, QImage.Format_Indexed8)
#            qimage.setColorTable([qRgb(i, i, i) for i in range(256)])
            qimage.setColorCount(256)
        elif color_dim == 3:
            qimage = QImage(data, nx, ny, stride, QImage.Format_RGB888)
        elif color_dim == 4:
            qimage = QImage(data, nx, ny, stride, QImage.Format_ARGB32)
        else:
            raise TypeError("Invalid third axis dimension (%r)" % color_dim)
    elif arr.dtype == np.uint32:
        qimage = QImage(data, nx, ny, stride, QImage.Format_ARGB32)
    else:
        raise NotImplementedError("Unsupported array data type %r" % arr.dtype)
    if copy:
        return qimage.copy()
    return qimage
Пример #3
0
    def toImage(self, *args):
        """
        .. py:method:: toImage()
        
            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])
        
            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
Пример #4
0
 def renderDocument(self,
                    plot,
                    filename,
                    sizeMM=(300, 200),
                    resolution=85,
                    format_=None):
     if isinstance(sizeMM, tuple):
         sizeMM = QSizeF(*sizeMM)
     if format_ is None:
         ext = osp.splitext(filename)[1]
         if not ext:
             raise TypeError(
                 "Unable to determine target format from filename")
         format_ = ext[1:]
     if plot is None or sizeMM.isEmpty() or resolution <= 0:
         return
     title = plot.title().text()
     if not title:
         title = "Plot Document"
     mmToInch = 1. / 25.4
     size = sizeMM * mmToInch * resolution
     documentRect = QRectF(0.0, 0.0, size.width(), size.height())
     fmt = format_.lower()
     if fmt in ("pdf", "ps"):
         printer = QPrinter()
         if fmt == "pdf":
             printer.setOutputFormat(QPrinter.PdfFormat)
         else:
             printer.setOutputFormat(QPrinter.PostScriptFormat)
         printer.setColorMode(QPrinter.Color)
         printer.setFullPage(True)
         printer.setPaperSize(sizeMM, QPrinter.Millimeter)
         printer.setDocName(title)
         printer.setOutputFileName(filename)
         printer.setResolution(resolution)
         painter = QPainter(printer)
         self.render(plot, painter, documentRect)
         painter.end()
     elif fmt == "svg":
         generator = QSvgGenerator()
         generator.setTitle(title)
         generator.setFileName(filename)
         generator.setResolution(resolution)
         generator.setViewBox(documentRect)
         painter = QPainter(generator)
         self.render(plot, painter, documentRect)
         painter.end()
     elif fmt in QImageWriter.supportedImageFormats():
         imageRect = documentRect.toRect()
         dotsPerMeter = int(round(resolution * mmToInch * 1000.))
         image = QImage(imageRect.size(), QImage.Format_ARGB32)
         image.setDotsPerMeterX(dotsPerMeter)
         image.setDotsPerMeterY(dotsPerMeter)
         image.fill(QColor(Qt.white).rgb())
         painter = QPainter(image)
         self.render(plot, painter, imageRect)
         painter.end()
         image.save(filename, fmt)
     else:
         raise TypeError("Unsupported file format '%s'" % fmt)
Пример #5
0
    def setBrentjensImage(self, image):
      absmin = abs(image.min())
      MaxAbs = abs(image.max())
      if (absmin > MaxAbs):
        MaxAbs = absmin
      self.ValueAxis.calcTransferFunction(-MaxAbs, MaxAbs, 0, self.ComplexColorMap.getNumberOfColors()-1)

      if image.min() != image.max():
# get real and imaginary arrays
        real_image = image.real
        imag_image = image.imag
        shape = image.shape
        Ncol = self.ComplexColorMap.getNumberOfColors()
        bits_per_pixel = 32
        self.Qimage = QImage(shape[0], shape[1], bits_per_pixel, Ncol)
        for i in range(shape[0]):
          for j in range(shape[1]):
            colre = int(self.ValueAxis.worldToAxis(real_image[i,j]))
            colim = int(self.ValueAxis.worldToAxis(imag_image[i,j]))
            if(colre < Ncol and colim < Ncol): 
              value = self.ComplexColorMap.get_color_value(colre,colim)
              self.Qimage.setPixel(i,j,value)
            else:
              if HAS_TIMBA:
               _dprint(2, "*************************************");
               _dprint(2, "colre: ", colre);
               _dprint(2, "colim: ", colim);
               _dprint(2, "real : ", real_image[i,j]);
               _dprint(2, "imag : ", imag_image[i,j]);
               _dprint(2, "Ncol: ", Ncol);
               _dprint(2, "*************************************");
        self.Qimage.mirror(0,1)
Пример #6
0
 def toImage(self, xMap, yMap, series, from_, to, pen, antialiased,
             numThreads):
     if USE_THREADS:
         if numThreads == 0:
             numThreads = QThread.idealThreadCount()
         if numThreads <= 0:
             numThreads = 1
     rect = self.__data.boundingRect.toAlignedRect()
     image = QImage(rect.size(), QImage.Format_ARGB32)
     image.fill(Qt.transparent)
     if pen.width() <= 1 and pen.color().alpha() == 255:
         command = QwtDotsCommand()
         command.series = series
         command.rgb = pen.color().rgba()
         if USE_THREADS:
             numPoints = int((to - from_ + 1) / numThreads)
             futures = []
             for i in range(numThreads):
                 pos = rect.topLeft()
                 index0 = from_ + i * numPoints
                 if i == numThreads - 1:
                     command.from_ = index0
                     command.to = to
                     qwtRenderDots(xMap, yMap, command, pos, image)
                 else:
                     command.from_ = index0
                     command.to = index0 + numPoints - 1
                     futures += [
                         QtConcurrent.run(qwtRenderDots, xMap, yMap,
                                          command, pos, image)
                     ]
             for future in futures:
                 future.waitForFinished()
         else:
             command.from_ = from_
             command.to = to
             qwtRenderDots(xMap, yMap, command, rect.topLeft(), image)
     else:
         painter = QPainter(image)
         painter.setPen(pen)
         painter.setRenderHint(QPainter.Antialiasing, antialiased)
         chunkSize = 1000
         for i in range(chunkSize):
             indexTo = min([i + chunkSize - 1, to])
             points = self.toPoints(xMap, yMap, series, i, indexTo)
             painter.drawPoints(points)
     return image
Пример #7
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())
Пример #8
0
def qwtDrawBackground(painter, canvas):
    painter.save()
    borderClip = canvas.borderPath(canvas.rect())
    if not borderClip.isEmpty():
        painter.setClipPath(borderClip, Qt.IntersectClip)
    brush = canvas.palette().brush(canvas.backgroundRole())
    if brush.style() == Qt.TexturePattern:
        pm = QPixmap(canvas.size())
        QwtPainter.fillPixmap(canvas, pm)
        painter.drawPixmap(0, 0, pm)
    elif brush.gradient():
        rects = []
        if brush.gradient().coordinateMode() == QGradient.ObjectBoundingMode:
            rects += [canvas.rect()]
        else:
            rects += [painter.clipRegion().rects()]
        useRaster = False
        if painter.paintEngine().type() == QPaintEngine.X11:
            useRaster = True
        if useRaster:
            format_ = QImage.Format_RGB32
            stops = brush.gradient().stops()
            for stop in stops:
                if stop.second.alpha() != 255:
                    format_ = QImage.Format_ARGB32
                    break
            image = QImage(canvas.size(), format_)
            p = QPainter(image)
            p.setPen(Qt.NoPen)
            p.setBrush(brush)
            p.drawRects(_rects_conv_PyQt5(rects))
            p.end()
            painter.drawImage(0, 0, image)
        else:
            painter.setPen(Qt.NoPen)
            painter.setBrush(brush)
            painter.drawRects(_rects_conv_PyQt5(rects))
    else:
        painter.setPen(Qt.NoPen)
        painter.setBrush(brush)
        painter.drawRects(_rects_conv_PyQt5(painter.clipRegion().rects()))

    painter.restore()
Пример #9
0
 def toImage(self, xMap, yMap, series, from_, to, pen, antialiased):
     """
     Translate a series into a QImage
     
     :param qwt.scale_map.QwtScaleMap xMap: x map
     :param qwt.scale_map.QwtScaleMap yMap: y map
     :param series: Series of points to be mapped
     :param int from_: Index of the first point to be painted
     :param int to: Index of the last point to be painted
     :param QPen pen: Pen used for drawing a point of the image, where a point is mapped to
     :param bool antialiased: True, when the dots should be displayed antialiased
     :return: Image displaying the series
     """
     #TODO: rewrite this method to fix performance issue (litteral translation from C++!)
     rect = self.__data.boundingRect.toAlignedRect()
     image = QImage(rect.size(), QImage.Format_ARGB32)
     image.fill(Qt.transparent)
     if pen.width() <= 1 and pen.color().alpha() == 255:
         bits = image.bits()
         w = image.width()
         h = image.height()
         x0 = rect.topLeft().x()
         y0 = rect.topLeft().y()
         for i in range(from_, to + 1):
             sample = series.sample(i)
             x = int(xMap.transform(sample.x()) + 0.5) - x0
             y = int(yMap.transform(sample.y()) + 0.5) - y0
             if x >= 0 and x < w and y >= 0 and y < h:
                 bits[y * w + x] = pen.color().rgba()
     else:
         painter = QPainter(image)
         painter.setPen(pen)
         painter.setRenderHint(QPainter.Antialiasing, antialiased)
         chunkSize = 1000
         for i in range(chunkSize):
             indexTo = min([i + chunkSize - 1, to])
             points = self.toPoints(xMap, yMap, series, i, indexTo)
             painter.drawPoints(points)
     return image
Пример #10
0
def oldToQImage(array):
    """Converts a numpy array to a QImage 
    A Python version of PyQt4.Qwt5.toQImage(array) in PyQwt < 5.2.
    Function written by Gerard Vermeulen 
    """
    if array.ndim != 2:
        raise RuntimeError('array must be 2-D')
    nx, ny = array.shape # width, height
    xstride, ystride = array.strides
    if array.dtype == numpy.uint8:
        image = QImage(nx, ny, QImage.Format_Indexed8)
        f_array = numpy.reshape(array,(nx*ny,),order='F')
        for j in range(ny):
            pointer = image.scanLine(j)
            pointer.setsize(nx*array.itemsize)
            memory = numpy.frombuffer(pointer, numpy.uint8)
            first_value = j*nx
            last_value = (j+1)*nx 
            memory[:] = f_array[first_value:last_value]
        image.setColorCount(256)
        for i in range(256):
            image.setColor(i, qRgb(i, i, i))
        return image
    elif array.dtype == numpy.uint32:
        image = Qt.QImage(
            array.tostring(), width, height, Qt.QImage.Format_ARGB32)
        f_array = numpy.reshape(array,(nx*ny,),order='F')
        for j in xrange(ny):
            pointer = image.scanLine(j)
            pointer.setsize(nx*array.itemsize)
            memory = numpy.frombuffer(pointer, numpy.uint32)
            first_value = j*nx
            last_value = (j+1)*nx 
            memory[:] = f_array[first_value:last_value]
        return image
    else:
        raise RuntimeError('array.dtype must be uint8 or uint32')