[QGIS-Developer] Apply transparency on pixels in an image with PyQGIS

HerbertGourout hndzondzi at gmail.com
Wed Jan 31 08:35:43 PST 2018


I'm trying to grab the pixels that intersect with my polygon shapefile and
apply transparency to them (that is, I'm trying to create a hole in my
raster)

For that, I get all the pixels that are in the footprint of the shapefile in
a list (see code below)

Then I used the QgsRasterTransparency.TransparentThreeValuePixel () class to
apply transparency, but I get an error message:

Error message: AttributeError: 'Dataset' object has no attribute 'renderer'






from PyQt4.QtCore import *
from osgeo import gdal, ogr
from osgeo.gdalconst import *
import numpy as np


iface = qgis.utils.iface

layers = iface.legendInterface().layers()
raster = gdal.Open("F:\\MASTER
GEOM\\MasterGeomatique_data\\PLEIADES\\PLEIADES_20130415_COLNAT.TIF")
print(raster)

transform = raster.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]
print xOrigin, yOrigin


shp = ogr.Open("F:\essai.shp")
lyr = shp.GetLayer()
feat = lyr.GetNextFeature()
geom = feat.GetGeometryRef()

if (geom.GetGeometryName() == 'POLYGON'):
    ring = geom.GetGeometryRef(0)
    numpoints = ring.GetPointCount()
    pointsX = []; pointsY = []
    for p in range(numpoints):
                lon, lat, z = ring.GetPoint(p)
                pointsX.append(lon)
                pointsY.append(lat)
                #print (pointsX)
xmin = min(pointsX)
xmax = max(pointsX)
ymin = min(pointsY)
ymax = max(pointsY)
print xmin, ymin
print xmax, ymax  
 # Specify offset and rows and columns to read
xoff = int((xmin - xOrigin)/pixelWidth)
yoff = int((yOrigin - ymax)/pixelWidth)
xcount = int((xmax - xmin)/pixelWidth)+1
ycount = int((ymax - ymin)/pixelWidth)+1
print xoff, yoff
print xcount, ycount

bandList = []
# retrieve pixel on region of interest
for i in range(raster.RasterCount):
    band = raster.GetRasterBand(i+1)
    data = band.ReadAsArray(xoff, yoff, xcount, ycount)
    bandList.append(data)

# Apply transparency using
QgsRasterTransparency.TransparentThreeValuePixel()
active_layer = raster
raster_transparency  = active_layer.renderer().rasterTransparency()
ltr = QgsRasterTransparency.TransparentThreeValuePixel()
tr_list = []
ltr.min = np.min(bandList)
ltr.max = np.max(bandList)
ltr.percentTransparent = 100  
tr_list.append(ltr)  
active_layer.renderer().rasterTransparency().setTransparentThreeValuePixelList(tr_list)
active_layer.triggerRepaint() 

# Refresh canvas
QgsMapLayerRegistry.instance().addMapLayer(raster)

# Message d'erreur : AttributeError: 'Dataset' object has no attribute
'renderer'



--
Sent from: http://osgeo-org.1560.x6.nabble.com/QGIS-Developer-f4099106.html


More information about the QGIS-Developer mailing list