[QGIS-Developer] How to create QgsRasterLayer from gdal "MEM" dataset
zhang liye
liyezn at outlook.com
Thu Sep 27 18:13:29 PDT 2018
Hi, All
I try to visualize the numpy.array matrix 'm' as a raster layer from Qgis. Because I have to show the matrix dynamically, I do not want to save the raster to *.tif file.
Is there any way to do this. I can create raster dataset using gdal library, but do not know how to create a raster layer to show on Qgis window. The code is as follows. Thank you so much!
def show_matrix_as_raster(self, m, lng_min, lat_min, pixelWidth, pixelHeight):
cols = m.shape[1]
rows = m.shape[0]
driver = gdal.GetDriverByName('MEM')
outRaster = driver.Create('', cols, rows, 1, gdal.GDT_Byte) # create dataset in memory
outRaster.SetGeoTransform((lng_min, pixelWidth, 0, lat_min, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(m)
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326)
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
layer = QgsRasterLayer( file_name_???, layer_name) # how to create QgsRsterLayer from 'outRaster', rather than file?
QgsMapLayerRegistry.instance().addMapLayer( layer )
###### render
##
myGrayRenderer = QgsSingleBandGrayRenderer(layer.dataProvider(), 1)
layer.setRenderer(myGrayRenderer)
renderer = layer.renderer()
uses_band = renderer.usesBands()
myType = renderer.dataType(uses_band[0])
myEnhancement = QgsContrastEnhancement(myType)
contrast_enhancement = QgsContrastEnhancement.StretchToMinimumMaximum
myEnhancement.setContrastEnhancementAlgorithm(contrast_enhancement, True)
myEnhancement.setMinimumValue(m.min())
myEnhancement.setMaximumValue(m.max())
layer.renderer().setContrastEnhancement(myEnhancement)
layer.renderer().setOpacity(0.5)
layer.triggerRepaint()
if layer.isValid() is False:
print "Unable to show the raster layer."
Best regards!
Liye,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20180928/7abf1956/attachment.html>
More information about the QGIS-Developer
mailing list