Exemplo n.º 1
0
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue):
    print perpAxisLabel, perpAxisValue
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(0)

    p = QPainter(img)
    p.setPen(QColor(255, 255, 255))
    p.setBrush(QBrush(QColor(255, 255, 255)))

    def arrow(p, From, To, label):
        p.drawLine(From, To)
        p.drawText(To, label)

    offset = 10
    arrow(p, QPoint(offset, offset), QPoint(offset, height - offset),
          axisLabels[1])
    arrow(p, QPoint(offset, offset), QPoint(width - offset, offset),
          axisLabels[0])
    p.drawText(2 * offset, 2 * offset,
               "%s=%d" % (perpAxisLabel, perpAxisValue))
    fm = p.fontMetrics()
    size = fm.size(Qt.TextSingleLine, "updown")

    p.drawText(numpy.random.randint(offset, width - offset - size.width()),
               numpy.random.randint(offset, height - offset - size.height()),
               "updown")

    dots = []
    numPixels = 0
    while numPixels < 30:
        r = numpy.random.randint(1, 255)
        rx, ry = numpy.random.randint(offset,
                                      width - offset), numpy.random.randint(
                                          offset, height - offset)
        if img.pixel(rx, ry) != 0:
            continue
        p.setPen(QPen(QColor(r, r, r)))
        p.drawPoint(rx, ry)
        dots.append(((rx, ry), r))
        numPixels += 1

    p.end()

    img.save('test.png')

    a = qimage2ndarray.rgb_view(img)
    a = a[:, :, 0].squeeze().swapaxes(0, 1)

    for (rx, ry), r in dots:
        assert QColor.fromRgba(img.pixel(rx, ry)).red(
        ) == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % (
            QColor.fromRgba(img.pixel(rx, ry)).red(), r)
        assert (a[rx,
                  ry] == r), "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r)
    return (a, dots)
Exemplo n.º 2
0
def sliceImg(width, height, axisLabels, perpAxisLabel, perpAxisValue):
    print perpAxisLabel, perpAxisValue
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(0)

    p = QPainter(img)
    p.setPen(QColor(255, 255, 255))
    p.setBrush(QBrush(QColor(255, 255, 255)))

    def arrow(p, From, To, label):
        p.drawLine(From, To)
        p.drawText(To, label)

    offset = 10
    arrow(p, QPoint(offset, offset), QPoint(offset, height - offset), axisLabels[1])
    arrow(p, QPoint(offset, offset), QPoint(width - offset, offset), axisLabels[0])
    p.drawText(2 * offset, 2 * offset, "%s=%d" % (perpAxisLabel, perpAxisValue))
    fm = p.fontMetrics()
    size = fm.size(Qt.TextSingleLine, "updown")

    p.drawText(
        numpy.random.randint(offset, width - offset - size.width()),
        numpy.random.randint(offset, height - offset - size.height()),
        "updown",
    )

    dots = []
    numPixels = 0
    while numPixels < 30:
        r = numpy.random.randint(1, 255)
        rx, ry = numpy.random.randint(offset, width - offset), numpy.random.randint(offset, height - offset)
        if img.pixel(rx, ry) != 0:
            continue
        p.setPen(QPen(QColor(r, r, r)))
        p.drawPoint(rx, ry)
        dots.append(((rx, ry), r))
        numPixels += 1

    p.end()

    img.save("test.png")

    a = qimage2ndarray.rgb_view(img)
    a = a[:, :, 0].squeeze().swapaxes(0, 1)

    for (rx, ry), r in dots:
        assert QColor.fromRgba(img.pixel(rx, ry)).red() == r, "QColor.fromRgba(img.pixel(rx,ry)).red() == %d != %d" % (
            QColor.fromRgba(img.pixel(rx, ry)).red(),
            r,
        )
        assert a[rx, ry] == r, "a[%d,%d] == %d != %d)" % (rx, ry, a[rx, ry], r)
    return (a, dots)
Exemplo n.º 3
0
    def basefinished(self):
        if self.basereply.error() != QNetworkReply.NoError:
            return
        self.basepixmap = QPixmap()
        self.basepixmap.loadFromData(self.basereply.readAll())
        if self.basepixmap.size() != self.rect.size():
            self.basepixmap = self.basepixmap.scaled(self.rect.size(),
                                                     Qt.KeepAspectRatio,
                                                     Qt.SmoothTransformation)
        self.setPixmap(self.basepixmap)

        # make marker pixmap
        self.mkpixmap = QPixmap(self.basepixmap.size())
        self.mkpixmap.fill(Qt.transparent)
        br = QBrush(QColor(Config.dimcolor))
        painter = QPainter()
        painter.begin(self.mkpixmap)
        painter.fillRect(0, 0, self.mkpixmap.width(), self.mkpixmap.height(),
                         br)
        for marker in self.radar['markers']:
            if 'visible' not in marker or marker['visible'] == 1:
                pt = getPoint(marker["location"], self.point, self.zoom,
                              self.rect.width(), self.rect.height())
                mk2 = QImage()
                mkfile = 'teardrop'
                if 'image' in marker:
                    mkfile = marker['image']
                if os.path.dirname(mkfile) == '':
                    mkfile = os.path.join('markers', mkfile)
                if os.path.splitext(mkfile)[1] == '':
                    mkfile += '.png'
                mk2.load(mkfile)
                if mk2.format != QImage.Format_ARGB32:
                    mk2 = mk2.convertToFormat(QImage.Format_ARGB32)
                mkh = 80  # self.rect.height() / 5
                if 'size' in marker:
                    if marker['size'] == 'small':
                        mkh = 64
                    if marker['size'] == 'mid':
                        mkh = 70
                    if marker['size'] == 'tiny':
                        mkh = 40
                if 'color' in marker:
                    c = QColor(marker['color'])
                    (cr, cg, cb, ca) = c.getRgbF()
                    for x in range(0, mk2.width()):
                        for y in range(0, mk2.height()):
                            (r, g, b,
                             a) = QColor.fromRgba(mk2.pixel(x, y)).getRgbF()
                            r = r * cr
                            g = g * cg
                            b = b * cb
                            mk2.setPixel(x, y,
                                         QColor.fromRgbF(r, g, b, a).rgba())
                mk2 = mk2.scaledToHeight(mkh, 1)
                painter.drawImage(pt.x - mkh / 2, pt.y - mkh / 2, mk2)

        painter.end()

        self.wmk.setPixmap(self.mkpixmap)
Exemplo n.º 4
0
    def _initPredictionLayers(self, predictionSlot):
        layers = []
        opLane = self.topLevelOperatorView

        # Use a slicer to provide a separate slot for each channel layer
        opSlicer = OpMultiArraySlicer2(parent=opLane.viewed_operator().parent)
        opSlicer.Input.connect(predictionSlot)
        opSlicer.AxisFlag.setValue('c')

        for channel, channelSlot in enumerate(opSlicer.Slices):
            if channelSlot.ready():
                drange = channelSlot.meta.drange or (0.0, 1.0)
                predictsrc = LazyflowSource(channelSlot)
                predictLayer = AlphaModulatedLayer(
                    predictsrc,
                    tintColor=QColor.fromRgba(self._colorTable16[channel + 1]),
                    # FIXME: This is weird.  Why are range and normalize both set to the same thing?
                    range=drange,
                    normalize=drange)
                predictLayer.opacity = 1.0
                predictLayer.visible = True
                predictLayer.name = "Probability Channel #{}".format(channel +
                                                                     1)
                layers.append(predictLayer)

        return layers
Exemplo n.º 5
0
    def paintEvent(self, event):
        self.painter = QPainter()
        self.painter.begin(self)
        if self.zoom >= 3:
            self.painter.setPen(QPalette().foreground().color())

            # draw horizontal lines
            for i in range(self.image.width() + 1):
                self.painter.drawLine(self.zoom * i,
                                      0,
                                      self.zoom * i,
                                      self.zoom * self.image.height())

            # draw vertical lines
            for j in range(self.image.height() + 1):
                self.painter.drawLine(0,
                                      self.zoom * j,
                                      self.zoom * self.image.width(),
                                      self.zoom * j)

            for i in range(self.image.width()):
                for j in range(self.image.height()):
                    rect = self.pixelRect(i, j)
                    if not event.region().intersected(rect).isEmpty():
                        color = QColor.fromRgba(self.image.pixel(QPoint(i, j)))
                        if color.red() < 255:
                            self.painter.fillRect(rect, self.QT_WHITE)
                        self.painter.fillRect(rect, color)
        self.painter.end()
Exemplo n.º 6
0
 def __init__( self, editor, clickFunctor, datasource , colorTable, direct=False, right=True ):
     assert isinstance(datasource, SourceABC)
     super(ClickableColortableLayer, self).__init__(datasource, editor, clickFunctor, direct=direct, right=right)
     self._colorTable = colorTable
     self.data = datasource
     
     self.colortableIsRandom = False
     self.zeroIsTransparent = (QColor.fromRgba(colorTable[0]).alpha() == 0)
 def loadconf(self,fileName=None):
     if fileName==None:
         fileName = QFileDialog.getOpenFileName(self,caption="Load Configuration",directory= "./Configuration/Parameters",filter="Config file (*.cfg)")
         #open() does not work with 'unicode' type object, conversion is needed
         fileName=fileName[0].encode('utf8')
     if fileName!="":
         file_opened=open(fileName,'r')
         self.ui.macfold.setText(file_opened.readline()[:-1])
         self.ui.measfold.setText(file_opened.readline()[:-1])
         self.ui.smtpadd.setText(file_opened.readline()[:-1])
         self.ui.login.setText(file_opened.readline()[:-1])
         self.ui.mdp.setText(file_opened.readline()[:-1])
         self.linecolor=QColor.fromRgba(int(file_opened.readline()[:-1]))
         self.pointcolor=QColor.fromRgba(int(file_opened.readline()[:-1]))
         self.ui.pointsize.setValue(int(file_opened.readline()))
         self.ui.smtpport.setValue(int(file_opened.readline()))
         file_opened.close()       
Exemplo n.º 8
0
 def loadconf(self,fileName=None):
     if fileName==None:
         fileName = QFileDialog.getOpenFileName(self,caption="Load Configuration",directory= "./Configuration/Parameters",filter="Config file (*.cfg)")
         #open() does not work with 'unicode' type object, conversion is needed
         fileName=fileName[0].encode('utf8')
     if fileName!="":
         file_opened=open(fileName,'r')
         self.ui.macfold.setText(file_opened.readline()[:-1])
         self.ui.measfold.setText(file_opened.readline()[:-1])
         self.ui.smtpadd.setText(file_opened.readline()[:-1])
         self.ui.login.setText(file_opened.readline()[:-1])
         self.ui.mdp.setText(file_opened.readline()[:-1])
         self.linecolor=QColor.fromRgba(int(file_opened.readline()[:-1]))
         self.pointcolor=QColor.fromRgba(int(file_opened.readline()[:-1]))
         self.ui.pointsize.setValue(int(file_opened.readline()))
         self.ui.smtpport.setValue(int(file_opened.readline()))
         file_opened.close()       
Exemplo n.º 9
0
 def getColorFromDialog(self):
     rgb, ok = QColorDialog.getRgba(self.lastSel.rgba(),
                                    self.parentWidget())
     if not ok:
         return
     col = QColor.fromRgba(rgb)
     self.insertColor(col, self.tr("Custom"), -1)
     self.lastSel = col
     self.emit(SIGNAL("selected(QColor)"), col)
Exemplo n.º 10
0
 def updateColorTable(self):
     layerColorTable = self._layer.colorTable
     self._colorTable = np.zeros((len(layerColorTable), 4), dtype=np.uint8)
     for i, c in enumerate(layerColorTable):
         color = QColor.fromRgba(c)
         self._colorTable[i,0] = color.red()
         self._colorTable[i,1] = color.green()
         self._colorTable[i,2] = color.blue()
         self._colorTable[i,3] = color.alpha() 
     self.isDirty.emit(QRect()) # empty rect == everything is dirty
Exemplo n.º 11
0
    def onObjectMeshesComputed(self):
        self.dlg.accept()
        logger.debug("*** Preparing 3D view ***")

        #Clean up possible previous 3D displays
        for c in self.cutter:
            if c: self.qvtk.renderer.RemoveActor(c)
        for a in self.objects:
            self.qvtk.renderer.RemoveActor(a)

        self.polygonAppender = vtkAppendPolyData()
        for g in self.dlg.extractor.meshes.values():
            self.polygonAppender.AddInput(g)

        self.cutter[0] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[0].GetOutlineProperty().SetColor(1, 0, 0)
        self.cutter[1] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[1].GetOutlineProperty().SetColor(0, 1, 0)
        self.cutter[2] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[2].GetOutlineProperty().SetColor(0, 0, 1)
        for c in self.cutter:
            c.SetPickable(False)

        ## 1. Use a render window with alpha bits (as initial value is 0 (false)):
        #self.renderWindow.SetAlphaBitPlanes(True);
        ## 2. Force to not pick a framebuffer with a multisample buffer
        ## (as initial value is 8):
        #self.renderWindow.SetMultiSamples(0);
        ## 3. Choose to use depth peeling (if supported) (initial value is 0 (false)):
        #self.renderer.SetUseDepthPeeling(True);
        ## 4. Set depth peeling parameters
        ## - Set the maximum number of rendering passes (initial value is 4):
        #self.renderer.SetMaximumNumberOfPeels(100);
        ## - Set the occlusion ratio (initial value is 0.0, exact image):
        #self.renderer.SetOcclusionRatio(0.0);

        for i, g in self.dlg.extractor.meshes.items():
            logger.debug(" - showing object with label = {}".format(i))
            mapper = vtkPolyDataMapper()
            mapper.SetInput(g)
            actor = vtkActor()
            actor.SetMapper(mapper)
            self.qvtk.registerObject(actor)
            self.objects.append(actor)
            if self.colorTable:
                c = self.colorTable[i]
                c = QColor.fromRgba(c)
                actor.GetProperty().SetColor(c.red() / 255.0,
                                             c.green() / 255.0,
                                             c.blue() / 255.0)

            self.qvtk.renderer.AddActor(actor)

        self.qvtk.update()
Exemplo n.º 12
0
    def onObjectMeshesComputed(self):
        self.dlg.accept()
        logger.debug( "*** Preparing 3D view ***" )
        
        #Clean up possible previous 3D displays
        for c in self.cutter:
            if c: self.qvtk.renderer.RemoveActor(c)
        for a in self.objects:
            self.qvtk.renderer.RemoveActor(a) 
        
        self.polygonAppender = vtkAppendPolyData()
        for g in self.dlg.extractor.meshes.values():
            self.polygonAppender.AddInput(g)
        
        self.cutter[0] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[0].GetOutlineProperty().SetColor(1,0,0)
        self.cutter[1] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[1].GetOutlineProperty().SetColor(0,1,0)
        self.cutter[2] = Outliner(self.polygonAppender.GetOutput())
        self.cutter[2].GetOutlineProperty().SetColor(0,0,1)
        for c in self.cutter:
            c.SetPickable(False)
        
        ## 1. Use a render window with alpha bits (as initial value is 0 (false)):
        #self.renderWindow.SetAlphaBitPlanes(True);
        ## 2. Force to not pick a framebuffer with a multisample buffer
        ## (as initial value is 8):
        #self.renderWindow.SetMultiSamples(0);
        ## 3. Choose to use depth peeling (if supported) (initial value is 0 (false)):
        #self.renderer.SetUseDepthPeeling(True);
        ## 4. Set depth peeling parameters
        ## - Set the maximum number of rendering passes (initial value is 4):
        #self.renderer.SetMaximumNumberOfPeels(100);
        ## - Set the occlusion ratio (initial value is 0.0, exact image):
        #self.renderer.SetOcclusionRatio(0.0);

        for i, g in self.dlg.extractor.meshes.items():
            logger.debug( " - showing object with label = {}".format(i) )
            mapper = vtkPolyDataMapper()
            mapper.SetInput(g)
            actor = vtkActor()
            actor.SetMapper(mapper)
            self.qvtk.registerObject(actor)
            self.objects.append(actor)
            if self.colorTable:
                c = self.colorTable[i]
                c = QColor.fromRgba(c)
                actor.GetProperty().SetColor(c.red()/255.0, c.green()/255.0, c.blue()/255.0)
            
            self.qvtk.renderer.AddActor(actor)
        
        self.qvtk.update()
Exemplo n.º 13
0
    def getIconData(self):
        width = self.image.width()
        height = self.image.height()

        matrix = list()
        for y in range(height):
            row = list()
            for x in range(width):
                opaque = 1 if QColor.fromRgba(
                        self.image.pixel(QPoint(x, y))).red() != 255 else 0
                row.append(opaque)
            matrix.append(row)
        return np.array(matrix)
Exemplo n.º 14
0
def QColor_from_Color(color):
    """ Convert the given Enaml Color into a QColor.

    Parameters
    ----------
    color : Color
        The Enaml Color object.

    Returns
    -------
    result : QColor
        The QColor instance for the given Enaml color.

    """
    return QColor.fromRgba(color.argb)
Exemplo n.º 15
0
def QColor_from_Color(color):
    """ Convert the given Enaml Color into a QColor.

    Parameters
    ----------
    color : Color
        The Enaml Color object.

    Returns
    -------
    result : QColor
        The QColor instance for the given Enaml color.

    """
    return QColor.fromRgba(color.argb)
Exemplo n.º 16
0
 def __init__(self, layer, parent=None):
     super(LayerColortableDialog, self).__init__(parent=parent)
     
     h = QHBoxLayout(self)
     t = QTableWidget(self)
     t.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)       
     t.setRowCount(len(layer._colorTable))
     t.setColumnCount(1)
     t.setVerticalHeaderLabels(["%d" %i for i in range(len(layer._colorTable))])
     
     for i in range(len(layer._colorTable)): 
         item = QTableWidgetItem(" ")
         t.setItem(i,0, item);
         item.setBackgroundColor(QColor.fromRgba(layer._colorTable[i]))
         item.setFlags(Qt.ItemIsSelectable)
     
     h.addWidget(t)
Exemplo n.º 17
0
    def updateColorTable(self):
        layerColorTable = self._layer.colorTable
        self._colorTable = np.zeros((len(layerColorTable), 4), dtype=np.uint8)

        for i, c in enumerate(layerColorTable):
            #note that we use qimage2ndarray.byte_view() on a QImage with Format_ARGB32 below.
            #this means that the memory layout actually is B, G, R, A

            if isinstance(c, QColor):
                color = c
            else: 
                color = QColor.fromRgba(c)
            self._colorTable[i,0] = color.blue()
            self._colorTable[i,1] = color.green()
            self._colorTable[i,2] = color.red()
            self._colorTable[i,3] = color.alpha() 
        self.isDirty.emit(QRect()) # empty rect == everything is dirty
Exemplo n.º 18
0
    def updateColorTable(self):
        layerColorTable = self._layer.colorTable
        self._colorTable = np.zeros((len(layerColorTable), 4), dtype=np.uint8)

        for i, c in enumerate(layerColorTable):
            #note that we use qimage2ndarray.byte_view() on a QImage with Format_ARGB32 below.
            #this means that the memory layout actually is B, G, R, A

            if isinstance(c, QColor):
                color = c
            else:
                color = QColor.fromRgba(c)
            self._colorTable[i, 0] = color.blue()
            self._colorTable[i, 1] = color.green()
            self._colorTable[i, 2] = color.red()
            self._colorTable[i, 3] = color.alpha()
        self.isDirty.emit(QRect())  # empty rect == everything is dirty
Exemplo n.º 19
0
 def __init__(self, layer, parent=None):
     super(LayerColortableDialog, self).__init__(parent=parent)
     
     h = QHBoxLayout(self)
     t = QTableWidget(self)
     t.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)       
     t.setRowCount(len(layer._colorTable))
     t.setColumnCount(1)
     t.setVerticalHeaderLabels(["%d" %i for i in range(len(layer._colorTable))])
     
     for i in range(len(layer._colorTable)): 
         item = QTableWidgetItem(" ")
         t.setItem(i,0, item);
         item.setBackgroundColor(QColor.fromRgba(layer._colorTable[i]))
         item.setFlags(Qt.ItemIsSelectable)
     
     h.addWidget(t)
Exemplo n.º 20
0
    def __init__( self, arraySource2D, colorTable ):
        """ colorTable: a list of QRgba values """

        assert isinstance(arraySource2D, SourceABC), 'wrong type: %s' % str(type(arraySource2D))
        super(ColortableImageSource, self).__init__()
        self._arraySource2D = arraySource2D
        self.id = arraySource2D.id
        
        self._arraySource2D.isDirty.connect(self.setDirty)
        self._arraySource2D.idChanged.connect(self._onIdChanged)        

        self._colorTable = np.zeros((len(colorTable), 4), dtype=np.uint8)
        for i, c in enumerate(colorTable):
            color = QColor.fromRgba(c)
            self._colorTable[i,0] = color.red()
            self._colorTable[i,1] = color.green()
            self._colorTable[i,2] = color.blue()
            self._colorTable[i,3] = color.alpha() 
Exemplo n.º 21
0
    def __init__(self,
                 editor,
                 clickFunctor,
                 datasource,
                 colorTable,
                 direct=False,
                 right=True):
        assert isinstance(datasource, SourceABC)
        super(ClickableColortableLayer, self).__init__(datasource,
                                                       editor,
                                                       clickFunctor,
                                                       direct=direct,
                                                       right=right)
        self._colorTable = colorTable
        self.data = datasource

        self.colortableIsRandom = False
        self.zeroIsTransparent = (QColor.fromRgba(colorTable[0]).alpha() == 0)
Exemplo n.º 22
0
    def __init__( self, datasource , colorTable, normalize=False, direct=False ):
        assert isinstance(datasource, SourceABC)
        
        """
        By default, no normalization is performed on ColortableLayers.  
        If the normalize parameter is set to 'auto', 
        your data will be automatically normalized to the length of your colorable.  
        If a tuple (dmin, dmax) is passed, this specifies the range of your data, 
        which is used to normalize the data before the colorable is applied.
        """


        if normalize is 'auto':
            normalize = None
        range = (0,len(colorTable)-1)
        super(ColortableLayer, self).__init__([datasource], range = range, normalize=normalize, direct=direct)
        self.data = datasource
        self._colorTable = colorTable
        
        self.colortableIsRandom = False
        self.zeroIsTransparent = (QColor.fromRgba(colorTable[0]).alpha() == 0)
Exemplo n.º 23
0
    def __init__(self, datasource, colorTable, normalize=False, direct=False):
        assert isinstance(datasource, SourceABC)
        """
        By default, no normalization is performed on ColortableLayers.  
        If the normalize parameter is set to 'auto', 
        your data will be automatically normalized to the length of your colorable.  
        If a tuple (dmin, dmax) is passed, this specifies the range of your data, 
        which is used to normalize the data before the colorable is applied.
        """

        if normalize is 'auto':
            normalize = None
        range = (0, len(colorTable) - 1)
        super(ColortableLayer, self).__init__([datasource],
                                              range=range,
                                              normalize=normalize,
                                              direct=direct)
        self.data = datasource
        self._colorTable = colorTable

        self.colortableIsRandom = False
        self.zeroIsTransparent = (QColor.fromRgba(colorTable[0]).alpha() == 0)
    def _initPredictionLayers(self, predictionSlot):
        layers = []
        opLane = self.topLevelOperatorView

        # Use a slicer to provide a separate slot for each channel layer
        opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent )
        opSlicer.Input.connect( predictionSlot )
        opSlicer.AxisFlag.setValue('c')

        for channel, channelSlot in enumerate(opSlicer.Slices):
            if channelSlot.ready():
                drange = channelSlot.meta.drange or (0.0, 1.0)
                predictsrc = LazyflowSource(channelSlot)
                predictLayer = AlphaModulatedLayer( predictsrc,
                                                    tintColor=QColor.fromRgba(self._colorTable16[channel+1]),
                                                    # FIXME: This is weird.  Why are range and normalize both set to the same thing?
                                                    range=drange,
                                                    normalize=drange )
                predictLayer.opacity = 1.0
                predictLayer.visible = True
                predictLayer.name = "Probability Channel #{}".format( channel+1 )
                layers.append(predictLayer)

        return layers
Exemplo n.º 25
0
    def renderer(self):
        qgis = QgsApplication([], False)
        qgis.setPrefixPath(self.settings.get('path'), True)
        qgis.setMaxThreads(1)
        qgis.initQgis()

        while True:
            try:
                fndata, srs, render_size, extended, \
                    target_box, result = self.queue.get()

                layer = QgsVectorLayer(fndata, 'layer', 'ogr')

                crs = QgsCoordinateReferenceSystem(srs.id)
                layer.setCrs(crs)

                settings = QgsMapSettings()
                settings.setLayers([layer.id()])
                settings.setFlag(QgsMapSettings.DrawLabeling)
                settings.setFlag(QgsMapSettings.Antialiasing)

                settings.setCrsTransformEnabled(True)
                settings.setDestinationCrs(crs)
                settings.setMapUnits(crs.mapUnits())
                settings.setOutputSize(QSize(*render_size))
                settings.setExtent(QgsRectangle(*extended))

                settings.setOutputImageFormat(QImage.Format_ARGB32)
                bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0))
                settings.setBackgroundColor(bgcolor)
                settings.setOutputDpi(96)

                QgsMapLayerRegistry.instance().addMapLayer(layer)
                settings.setLayers([layer.id()])

                # Создаем QImage руками чтобы можно было использовать
                # QgsMapRendererCustomPainterJob. Остальные не позволяют
                # обойти баг с рисованием поверх старого.
                img = QImage(settings.outputSize(), QImage.Format_ARGB32)

                # Эти костыли нужны для того, чтобы корректно рисовались
                # слои на прозрачном фоне, без этого получается каша.
                img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255)))
                img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0)))

                # DPI должно быть таким же как в settings, иначе ошибка. В QImage
                # разрешение указывается в точках на метр по каждой оси.
                dpm = settings.outputDpi() / 25.4 * 1000
                img.setDotsPerMeterX(dpm)
                img.setDotsPerMeterY(dpm)

                painter = QPainter(img)
                job = QgsMapRendererCustomPainterJob(settings, painter)
                job.renderSynchronously()
                painter.end()

                QgsMapLayerRegistry.instance().removeAllMapLayers()

                # Преобразование QImage в PIL
                ba = QByteArray()
                bf = QBuffer(ba)
                bf.open(QIODevice.WriteOnly)
                img.save(bf, 'PNG')
                bf.close()

                buf = StringIO()
                buf.write(bf.data())
                buf.seek(0)

                img = PIL.Image.open(buf)

                # Вырезаем нужный нам кусок изображения
                result.put(img.crop(target_box))

            except Exception as e:
                self.logger.error(e.message)

        qgis.exitQgis()
 def choose_color(self):
     rgba, valid = QColorDialog.getRgba(self._color.rgba(),
                                        self.parentWidget())
     if valid:
         color = QColor.fromRgba(rgba)
         self.set_color(color)
Exemplo n.º 27
0
 def choose_color(self):
     rgba, valid = QColorDialog.getRgba(self._color.rgba(),
                                        self.parentWidget())
     if valid:
         color = QColor.fromRgba(rgba)
         self.set_color(color)
Exemplo n.º 28
0
    def renderer(self):
        if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ:
            os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp'

        qgis = None
        while True:
            options, result = self.queue.get()

            # Don't start QGIS until first request
            if qgis is None:
                qgis = QgsApplication([], False)
                qgis.setPrefixPath(self.settings.get('path'), True)
                qgis.setDefaultSvgPaths(qgis.svgPaths() +
                                        self.settings.get('svgpaths'))
                qgis.setMaxThreads(1)
                qgis.initQgis()

            try:
                if isinstance(options, LegendOptions):
                    style, = options

                    layer = self._qgs_memory_layer(style)
                    layer.setName(style.parent.display_name)

                    QgsMapLayerRegistry.instance().addMapLayer(layer)

                    root = QgsLayerTreeGroup()
                    root.addLayer(layer)

                    # 'Cannot create a QPixmap when no GUI is being used'
                    #  warning occurs here
                    model = QgsLayerTreeModel(root)

                    settings = QgsLegendSettings()
                    settings.setTitle('')
                    settings.setBoxSpace(1)
                    settings.setSymbolSize(QSizeF(5, 3))
                    settings.setDpi(96)

                    renderer = QgsLegendRenderer(model, settings)

                    # Dots per mm
                    dpmm = settings.dpi() / 25.4

                    min_size = renderer.minimumSize()
                    size = QSize(dpmm * min_size.width(),
                                 dpmm * min_size.height())
                    img = QImage(size, QImage.Format_ARGB32)
                    img.fill(QColor(0, 0, 0, 0))

                    painter = QPainter()
                    painter.begin(img)
                    painter.scale(dpmm, dpmm)
                    renderer.drawLegend(painter)
                    painter.end()

                    QgsMapLayerRegistry.instance().removeAllMapLayers()

                    ba = QByteArray()
                    bf = QBuffer(ba)
                    bf.open(QIODevice.WriteOnly)
                    img.save(bf, 'PNG')
                    bf.close()

                    buf = StringIO()
                    buf.write(bf.data())
                    buf.seek(0)
                    result.put(buf)

                else:
                    path = features = None
                    if isinstance(options, VectorRenderOptions):
                        style, features, render_size, \
                            extended, target_box = options
                        layer = self._qgs_memory_layer(style,
                                                       features=features)
                    elif isinstance(options, RasterRenderOptions):
                        style, path, render_size, \
                            extended, target_box = options
                        layer = QgsRasterLayer(path)
                        layer.loadNamedStyle(
                            self.env.file_storage.filename(style.qml_fileobj))

                    settings = QgsMapSettings()
                    settings.setLayers([layer.id()])
                    settings.setFlag(QgsMapSettings.DrawLabeling)
                    settings.setFlag(QgsMapSettings.Antialiasing)

                    settings.setCrsTransformEnabled(True)
                    settings.setDestinationCrs(layer.crs())
                    settings.setMapUnits(layer.crs().mapUnits())
                    settings.setOutputSize(QSize(*render_size))
                    settings.setExtent(QgsRectangle(*extended))

                    settings.setOutputImageFormat(QImage.Format_ARGB32)
                    bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0))
                    settings.setBackgroundColor(bgcolor)
                    settings.setOutputDpi(96)

                    QgsMapLayerRegistry.instance().addMapLayer(layer)
                    settings.setLayers([layer.id()])

                    # Create QImage by hand to be able to use
                    # QgsMapRendererCustomPainterJob. Others will not
                    # allow to workaround a bug with overlay rendering.
                    img = QImage(settings.outputSize(), QImage.Format_ARGB32)

                    # These cludges are needed for rendering
                    # on transparent background, otherwise it's a mess.
                    img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255)))
                    img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0)))

                    # DPI should be equal to settings, otherwise an error.
                    # In QImage the resolution is set in dots per meter
                    # for each axis.
                    dpm = settings.outputDpi() / 25.4 * 1000
                    img.setDotsPerMeterX(dpm)
                    img.setDotsPerMeterY(dpm)

                    painter = QPainter(img)
                    job = QgsMapRendererCustomPainterJob(settings, painter)
                    job.renderSynchronously()
                    painter.end()

                    QgsMapLayerRegistry.instance().removeAllMapLayers()

                    img = self._qimage_to_pil(img)

                    # Clip needed part
                    result.put(img.crop(target_box))

                    # Cleanup
                    if path is not None:
                        gdal.Unlink(path)

            except Exception as exc:
                self.logger.error(exc.message)
                result.put(exc)

        qgis.exitQgis()
Exemplo n.º 29
0
 def getColor(self, value):
     try:
         return QColor.fromRgba(int(value))
     except ValueError:
         return QColor(value)
Exemplo n.º 30
0
 def getColor(self, value):
     try:
         return QColor.fromRgba(int(value))
     except ValueError:
         return QColor(value)
Exemplo n.º 31
0
 def labelColor(self, label):
     """ return the current color for object 'label' """
     color = self.layer.colorTable[label]
     color = QColor.fromRgba(color)
     return color