[GIS] How to get pixel values of indvidual pixels falling under a poygon to shapefile attribute table or CSV

gdalpyqgisqgiszonal statistics

I want to be able to write pixel values of each pixel falling under a polygon onto a polygon attribute table or a CSV. I have about 1200 polygons and a georefernced GeoTiff file with NDVI values. While I understand there are many tools available to calculate zonal stats and I have tried zonal statistics, LecoS and rasterstats plugin (all QGIS), they all provide only summary statistics (mean, median, min, max, etc.) but not individual pixel values. So pretty much are of no use here. I also took a look at rasterstats source code but could not find a quick way to modify the zonal output parameters to suit my needs. So I'm wondering if there is a GDAL, QGIS, python based solution out there?

TL;DR: I would like to write pixel values of all the pixels falling under a poylgon onto a CSV or a shapefile attribute table (1200 polygons).

Best Answer

If you want to get all pixel values as value per row there is one way to do it easily though might be pretty high demanding on memory / data processing time if you have huge grid dataset.

The way is to convert raster to points and then select points by polygons.

  1. Save raster as xyz format and load as delimited text values as points (also can be converted from raster to points through processing toolbox - Grass / r.to.vect)
  2. use Vector / Data management Tools / Join attributes by location to assign polygon ID value into points table
  3. delete points with empty (Null) polygon ID column and save points layer as CSV or select all in points table and paste into your favorite spreadsheet editor
Related Question