[GIS] How to extract X Y coordinates and RGB from pixels using python in QGIS

coordinatespythonqgisrasterrgb

I'm trying to white a Python plugin in QGIS (2.2) to get, for each pixel of a raster image, its X Y coordinates, as well as, its RGB (3 bands) values.

At first I opened the raster file using: rlayer = QgsRasterLayer(rfileName, rbaseName)

Now I don't know how to get, for example, for pixel (1,1) its coordinates (X,Y) and its RGB color values.

Anybody could help me?

I know that I'll need to implement a DO WHILE, but I don't know the commands to extract this information of each pixel.

Thanks in advance,
Mateus

Best Answer

As a geologist, I make geological cross section using the elevations values from a DEM and the colors from a geological map, look at the pure Python solution with osgeo.gdal in Python Script for getting elevation difference between two points

But now, since PyQGIS 2.x, it is easier with PyQGIS and the QgsRaster.IdentifyFormatValuefunction

  • example with a DEM (one band):

    myDEM = qgis.utils.iface.activeLayer()  
    print myDEM.bandCount()  
    1   
    print myDEM.dataProvider().identify(QgsPoint(229774,111171), QgsRaster.IdentifyFormatValue)  
    {1: 221.0}
    
  • example with a classic raster (three bands -> R,G,B values):

     print myraster.dataProvider().identify(QgsPoint(229774,111171), QgsRaster.IdentifyFormatValue).results()
     {1: 180.0, 2: 142.0, 3: 125.0}
    

The result is a dictionary (key= band number) and you can create a simple function that returns the values:

def val_raster(point,raster):
    return raster.dataProvider().identify(point, QgsRaster.IdentifyFormatValue).results().values()

elevation = val_raster(QgsPoint(229774,111171),myDEM)
print elevation
221.0
R,G,B = val_raster(QgsPoint(229774,111171),myraster)
print R,G,B
180.0, 142.0, 125.0

I presented a complete solution with PyQGIS in French PyQGIS (QGIS 2): geological cross-sections (colorization of a topographic profile build from a DEM with the colors of a raster and placement of the intersection points of the geological layers boundaries )

enter image description here

Related Question