def multibandRasterLayer(self) -> QgsRasterLayer:

        try:
            from utilities import unitTestDataPath
            path = pathlib.Path(unitTestDataPath()) / 'landsat_4326.tif'
        except ModuleNotFoundError:
            path = pathlib.Path(__file__).parent / 'landsat_4326.tif'

        assert isinstance(path, pathlib.Path) and path.is_file()
        lyr = QgsRasterLayer(path.as_posix())
        lyr.setName(path.name)
        self.assertIsInstance(lyr, QgsRasterLayer)
        self.assertTrue(lyr.isValid())
        self.assertTrue(lyr.bandCount() > 1)

        return lyr
    def add_raster_layer(self, path, id):
        """Add a downloaded raster layer to the workspace."""

        # create a new rasterlayer from the supplied TIF file
        layer = QgsRasterLayer(path, id)

        # load layer style based on number of bands
        bands = layer.bandCount()
        if bands == 1:
            path = os.path.join(self.plugin_dir, 'styles', 'singleband.qml')
        else:
            path = os.path.join(self.plugin_dir, 'styles', 'multiband.qml')

        layer.loadNamedStyle(path)

        # add the layer to the workspace
        QgsMapLayerRegistry.instance().addMapLayer(layer)
Example #3
0
def set_band_based_on_range(layer: QgsRasterLayer, t_range: QgsDateTimeRange) -> int:
    """
    Set raster layer band based on temporal range
    :param layer: Raster layer
    :param t_range: temporal range
    :return: band number
    """
    band_num = 1
    tprops: QgsRasterLayerTemporalProperties = layer.temporalProperties()
    if (
        tprops.isVisibleInTemporalRange(t_range)
        and t_range.begin().isValid()
        and t_range.end().isValid()
    ):
        if tprops.mode() == QgsRasterLayerTemporalProperties.ModeFixedTemporalRange:
            layer_t_range: QgsDateTimeRange = tprops.fixedTemporalRange()
            start: datetime.datetime = layer_t_range.begin().toPyDateTime()
            end: datetime.datetime = layer_t_range.end().toPyDateTime()
            delta = (end - start) / layer.bandCount()
            band_num = int((t_range.begin().toPyDateTime() - start) / delta) + 1
            set_raster_renderer_to_singleband(layer, band_num)
    return band_num
Example #4
0
def readRasterLayer(i, allBandData):
    # pylint: disable=too-many-locals

    fileInfo = QFileInfo(shared.rasterFileName[i])
    fileBaseName = fileInfo.baseName()

    layer = QgsRasterLayer(shared.rasterFileName[i], fileBaseName)
    if not layer.isValid():
        shared.fpOut.write("Raster layer '" + shared.rasterFileName[i] +
                           "'failed to load")
        return -1

    # Store the title as the first list item
    allBandData.append(shared.rasterFileTitle[i])

    # Get more info
    xSize = layer.width()
    ySize = layer.height()

    cellWidth = layer.rasterUnitsPerPixelX()
    cellHeight = layer.rasterUnitsPerPixelY()

    provider = layer.dataProvider()
    extnt = provider.extent()
    dpi = provider.dpi()

    shared.fpOut.write("Raster layer '" + shared.rasterFileTitle[i] +
                       "' loaded with X, Y resolution = " + str(cellWidth) +
                       ", " + str(cellHeight) + " m\n")
    #shared.fpOut.write(layer.metadata())
    #shared.fpOut.write(layer.rasterType())

    # Store the above as the second list item
    allBandData.append(
        [provider, xSize, ySize, cellWidth, cellHeight, extnt, dpi])

    # Now store the data for each band as a QgsRasterBlock
    nBands = layer.bandCount()
    for band in range(nBands):
        #shared.fpOut.write(layer.bandName(i))

        bandData = provider.block(band, extnt, xSize, ySize)

        # Store as a further list item
        allBandData.append(bandData)

    # Sort out style
    #shared.fpOut.write("Style file " + str(i) + " is " + shared.rasterFileStyle[i])
    if not shared.rasterFileStyle[i]:
        # No style file specified, so try the default style for this layer
        shared.rasterFileStyle[i] = layer.styleURI()
        #shared.fpOut.write("Trying default style file " + shared.rasterFileStyle[i])

        if not layer.loadDefaultStyle():
            shared.fpOut.write("Could not load default style '" +
                               shared.rasterFileStyle[i] +
                               "' for raster layer '" +
                               shared.rasterFileTitle[i] + "'")

    else:
        # A style file was specified, so try to load it
        #shared.fpOut.write("Trying style file " + shared.rasterFileStyle[i])
        if not layer.loadNamedStyle(shared.rasterFileStyle[i]):
            shared.fpOut.write("Could not load style '" +
                               shared.rasterFileStyle[i] +
                               "' for raster layer '" +
                               shared.rasterFileTitle[i] + "'")

    # Set opacity
    layer.renderer().setOpacity(shared.rasterFileOpacity[i])

    # Add this layer to the app's registry
    QgsProject.instance().addMapLayer(layer)

    return layer
Example #5
0
projInfo=dem .GetProjection()
print projInfo

demLayer  = QgsRasterLayer(os.path.join(input_Dir,dem_filename), "dem")
if not demLayer.isValid(): print "DEM Layer failed to load!"

# Load raster layer into canvas
QgsMapLayerRegistry.instance().addMapLayer(demLayer)
 
# Print Extent of the DEM layer (for use with raster calculator)
print demLayer.extent().xMinimum(), demLayer.extent().xMaximum()
print demLayer.extent().yMinimum(), demLayer.extent().yMaximum()
print demLayer.width(), demLayer.height()
name = demLayer.name()
print name
bands = demLayer.bandCount()
print bands

# Slope layer
degslopeLayer = QgsRasterLayer(os.path.join(input_Dir,'slope_dec.tif'), "Degrees_Slope")
if not degslopeLayer.isValid(): print "Slope (decimal degrees) Layer failed to load!"
# Load raster layer into canvas
QgsMapLayerRegistry.instance().addMapLayer(degslopeLayer)

# Aspect layer
degaspectLayer = QgsRasterLayer(os.path.join(input_Dir,'aspect_dec.tif'), "Degrees_Aspect")
if not degaspectLayer.isValid(): print "Aspect (decimal degrees) Layer failed to load!"
# Load raster layer into canvas
QgsMapLayerRegistry.instance().addMapLayer(degaspectLayer)

# Importing collar GPS data