Ejemplo n.º 1
0
def display_one_band(layer, keyword, iface):
    index_group = TerreImageConstant().index_group
    logger.debug("keyword {}".format(keyword))
    corres = {
        'red': "_bande_rouge",
        'green': "_bande_verte",
        'blue': "_bande_bleue",
        'pir': "_bande_pir",
        'mir': "_bande_mir",
        "nat": "_couleurs_naturelles"
    }

    raster_layer = QgsRasterLayer(layer.get_source(),
                                  layer.name() + corres[keyword])

    if keyword == 'nat':
        logger.debug("display on natural colors")
        band_red = layer.bands['red']
        band_green = layer.bands['green']
        band_blue = layer.bands['blue']
        renderer = raster_layer.renderer()
        # raster_layer.setDrawingStyle("MultiBandColor")
        renderer.setRedBand(band_red)
        renderer.setGreenBand(band_green)
        renderer.setBlueBand(band_blue)
        # raster_layer.setRenderer( renderer )
        # contrastForRasters( raster_layer, 0, 0, [pir, red, green] )
        histogram_stretching(raster_layer, iface.mapCanvas())
        QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
        TerreImageConstant().legendInterface.moveLayer(raster_layer,
                                                       index_group)
        return raster_layer
    else:

        band = layer.bands[keyword]
        if band:
            logger.debug("band num: {}".format(band))
            raster_layer.setDrawingStyle("MultiBandSingleBandGray")
            renderer = raster_layer.renderer()
            logger.debug(renderer)
            renderer.setGrayBand(band)

            # contrastForRasters( raster_layer, 0, 0 )
            histogram_stretching(raster_layer, iface.mapCanvas())
            QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
            TerreImageConstant().legendInterface.moveLayer(
                raster_layer, index_group)
            return raster_layer
Ejemplo n.º 2
0
    def loadLabelImage(imagepath, labeldescriptor = None):
        """
        Load a labeled single band raster in the canvas

        Keyword arguments:
        imagepath -- the path to the image
        labeldescriptor -- a dictionnary for label (int) to tuple (QColor, QString) conversion
        """
        if imagepath is None:
            return

        name = os.path.splitext( os.path.basename(imagepath) )[0]
        qgslayer = QgsRasterLayer(imagepath, name)
        if not qgslayer.isValid():
            QtGui.QMessageBox.critical(None,
                                       u"Erreur",
                                       u"Impossible de charger la couche %s" % unicode(imagepath))

        QgsMapLayerRegistry.instance().addMapLayer(qgslayer)

        qgslayer.setDrawingStyle('SingleBandPseudoColor')

        colorlist = []
        max_label = 0
        for label in sorted(labeldescriptor.keys()):
            color = labeldescriptor[label][0]
            labeltxt = labeldescriptor[label][1]
            colorlist.append(QgsColorRampShader.ColorRampItem(label, color, labeltxt))
            if labeltxt > max_label:
                max_label = labeltxt

        s = QgsRasterShader()
        c = QgsColorRampShader()
        c.setColorRampType(QgsColorRampShader.INTERPOLATED)
        c.setColorRampItemList(colorlist)
        s.setRasterShaderFunction(c)
        ps = QgsSingleBandPseudoColorRenderer(qgslayer.dataProvider(), 1, s)
        qgslayer.setRenderer(ps)

        for bandNo in range(1,qgslayer.dataProvider().bandCount()+1):
            qgslayer.dataProvider().setUseSrcNoDataValue( bandNo, False )

        QGisLayers.iface.legendInterface().refreshLayerSymbology(qgslayer)
        if hasattr(qgslayer, "setCacheImage"):
            qgslayer.setCacheImage(None)
        qgslayer.triggerRepaint()
    def on_pushButton_clicked(self):
        """Wow - an autoconnected slot!"""
	print 'Click!'
        myPath = os.path.join(
            os.path.dirname(__file__),
            'landsat.tif')
        print myPath
        layer = QgsRasterLayer(myPath, 'A Layer')
        QgsMapLayerRegistry.instance().addMapLayers([layer])
        layer.setGrayBandName(layer.bandName(1))
        layer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor)
        layer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader)
        layer.saveDefaultStyle() 
        self.widget.zoomToFullExtent()
        print self.widget.extent().toString()
        print layer.extent().toString()
	self.widget.refresh()
Ejemplo n.º 4
0
    def accept(self):
        """Handler for when OK is clicked.
        """
        input_path = str(self.leInputPath.text())
        output_path = str(self.leOutputPath.text())
        if not output_path.endswith('.tif'):
            # noinspection PyArgumentList
            QMessageBox.warning(
                self.parent, self.tr('InaSAFE'),
                (self.tr('Output file name must be tif file')))
        if not os.path.exists(input_path):
            # noinspection PyArgumentList
            QMessageBox.warning(
                self.parent, self.tr('InaSAFE'),
                (self.tr('Input file is not exist')))
            return
        if self.radNearest.isChecked():
            my_algorithm = 'nearest'
        else:
            my_algorithm = 'invdist'

        QtGui.qApp.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))

        fileName = convert_mmi_data(
            input_path, output_path,
            algorithm=my_algorithm,
            algorithm_filename_flag=False)

        QtGui.qApp.restoreOverrideCursor()

        if self.cBLoadLayer.isChecked():
            fileInfo = QFileInfo(fileName)
            baseName = fileInfo.baseName()
            layer = QgsRasterLayer(fileName, baseName)
            layer.setGrayBandName(layer.bandName(1))
            layer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor)
            layer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader)
            layer.saveDefaultStyle()
            if not layer.isValid():
                LOGGER.debug("Failed to load")
            else:
                # noinspection PyArgumentList
                QgsMapLayerRegistry.instance().addMapLayer(layer)
        self.done(self.Accepted)
Ejemplo n.º 5
0
def display_one_band(layer, keyword, iface):
    index_group = TerreImageConstant().index_group
    logger.debug("keyword " + str(keyword))
    corres = {'red': "_bande_rouge", 'green': "_bande_verte", 'blue': "_bande_bleue",
              'pir': "_bande_pir", 'mir': "_bande_mir", "nat": "_couleurs_naturelles"}

    raster_layer = QgsRasterLayer(layer.get_source(), layer.name() + corres[keyword])

    if keyword == 'nat':
        logger.debug("display on natural colors")
        band_red = layer.bands['red']
        band_green = layer.bands['green']
        band_blue = layer.bands['blue']
        renderer = raster_layer.renderer()
        # raster_layer.setDrawingStyle("MultiBandColor")
        renderer.setRedBand(band_red)
        renderer.setGreenBand(band_green)
        renderer.setBlueBand(band_blue)
        # raster_layer.setRenderer( renderer )
        # contrastForRasters( raster_layer, 0, 0, [pir, red, green] )
        histogram_stretching(raster_layer, iface.mapCanvas())
        QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
        TerreImageConstant().legendInterface.moveLayer(raster_layer, index_group)
        return raster_layer
    else:

        band = layer.bands[keyword]
        if band:
            logger.debug("band num: " + str(band))
            raster_layer.setDrawingStyle("MultiBandSingleBandGray")
            renderer = raster_layer.renderer()
            logger.debug(renderer)
            renderer.setGrayBand(band)

            # contrastForRasters( raster_layer, 0, 0 )
            histogram_stretching(raster_layer, iface.mapCanvas())
            QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
            TerreImageConstant().legendInterface.moveLayer(raster_layer, index_group)
            return raster_layer
Ejemplo n.º 6
0
    def accept(self):
        """Handler for when OK is clicked.
        """
        input_path = str(self.leInputPath.text())
        output_path = str(self.leOutputPath.text())
        if not output_path.endswith('.tif'):
            # noinspection PyArgumentList
            QMessageBox.warning(self.parent, self.tr('InaSAFE'),
                                (self.tr('Output file name must be tif file')))
        if not os.path.exists(input_path):
            # noinspection PyArgumentList
            QMessageBox.warning(self.parent, self.tr('InaSAFE'),
                                (self.tr('Input file is not exist')))
            return
        if self.radNearest.isChecked():
            my_algorithm = 'nearest'
        else:
            my_algorithm = 'invdist'

        fileName = convert_mmi_data(input_path,
                                    output_path,
                                    the_algorithm=my_algorithm,
                                    algorithm_name=False)
        if self.cBLoadLayer.isChecked():
            fileInfo = QFileInfo(fileName)
            baseName = fileInfo.baseName()
            layer = QgsRasterLayer(fileName, baseName)
            layer.setGrayBandName(layer.bandName(1))
            layer.setDrawingStyle(QgsRasterLayer.SingleBandPseudoColor)
            layer.setColorShadingAlgorithm(QgsRasterLayer.PseudoColorShader)
            layer.saveDefaultStyle()
            if not layer.isValid():
                LOGGER.debug("Failed to load")
            else:
                # noinspection PyArgumentList
                QgsMapLayerRegistry.instance().addMapLayer(layer)
        self.done(self.Accepted)
Ejemplo n.º 7
0
def create_raster_layer(matrix):
    driver = gdal.GetDriverByName("GTiff")

    filename = tempfile.mktemp(prefix="hmtk", suffix=".tif")

    # sort the data by lon, lat
    gridded_data = numpy.array(
        sorted(matrix, key=lambda row: (90 + row[1]) * 180 + (180 + row[0])))

    # extract it into separate vars
    lons, lats, vals = (
        gridded_data[:, 0], gridded_data[:, 1], gridded_data[:, 3])

    ncols = lons[lons == lons[0]].size
    nrows = lats[lats == lats[0]].size

    # put values in a grid
    gridded_vals = vals.reshape((ncols, nrows)).T

    dataset = driver.Create(filename, ncols, nrows, 1, gdal.GDT_Float32)

    dataset.SetGeoTransform((
        min(lons),
        (max(lons) - min(lons)) / ncols,
        0,
        max(lats),
        0,
        -(max(lats) - min(lats)) / nrows))

    out_srs = osr.SpatialReference()
    out_srs.ImportFromEPSG(4326)
    dataset.SetProjection(out_srs.ExportToWkt())

    out_band = dataset.GetRasterBand(1)
    out_band.WriteArray(gridded_vals)
    out_band.SetNoDataValue(0)
    out_band.FlushCache()
    out_band = None
    dataset = None

    fileInfo = QFileInfo(filename)
    baseName = fileInfo.baseName()
    layer = QgsRasterLayer(filename, baseName)

    stat = layer.dataProvider().bandStatistics(1)

    minVal = stat.minimumValue
    maxVal = stat.maximumValue
    entries_nr = 20

    colorRamp = QgsStyleV2().defaultStyle().colorRamp("Spectral")
    currentValue = float(minVal)
    intervalDiff = float(maxVal - minVal) / float(entries_nr - 1)

    colorRampItems = []
    for i in reversed(xrange(entries_nr)):
        item = QgsColorRampShader.ColorRampItem()
        item.value = currentValue
        item.label = unicode(currentValue)
        currentValue += intervalDiff
        item.color = colorRamp.color(float(i) / float(entries_nr))
        item.color.setAlphaF(0.75)
        colorRampItems.append(item)

    rasterShader = QgsRasterShader()
    colorRampShader = QgsColorRampShader()

    colorRampShader.setColorRampItemList(colorRampItems)
    colorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
    rasterShader.setRasterShaderFunction(colorRampShader)

    layer.setDrawingStyle('SingleBandPseudoColor')
    layer.renderer().setShader(rasterShader)

    QgsMapLayerRegistry.instance().addMapLayer(layer)

    return layer