Tuesday 11 April 2017

qgis - How to set transparency to multiple raster values with Python


With the following code I can set 100% transparency to raster value 0:



map=None

for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
if lyr.name() == "some_layer":
map= lyr

tr=None

tr=QgsRasterTransparency()
tr.initializeTransparentPixelList(0)

map.renderer().setRasterTransparency(tr)
map.triggerRepaint()

How can I define two values (0 and 8) to be 100% transparent?


When I repeat the commands of the last block with raster value 8, the first value (0) is removed from the layer transparency.



Answer



I found this other thread which was helpful How do I set layer transparency in QGIS 2.0 with Python? It seems like there should be a shorter and more efficient way, but I tested this and it works:


print 'Start'
active_layer = qgis.utils.iface.mapCanvas().currentLayer()
raster_transparency = active_layer.renderer().rasterTransparency()

ltr = QgsRasterTransparency.TransparentSingleValuePixel()
ltr2 = QgsRasterTransparency.TransparentSingleValuePixel()
tr_list = []
ltr.min = 0 # Or another value
ltr.max = 0 # Or another value
ltr.percentTransparent = 100 # Or another value
ltr2.min = 8 # Or another value
ltr2.max = 8 # Or another value
ltr2.percentTransparent = 100
tr_list.append(ltr)

tr_list.append(ltr2)

raster_transparency.setTransparentSingleValuePixelList(tr_list)

active_layer.triggerRepaint() # Tried with iface.mapCanvas().refresh(), but it didn't work
print 'Finish'

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...