[GIS] Python – Extract raster values at point locations

pythonraster

I'm a beginner with python. I would like to extract raster (.tif) values from a set of specific points that I have in a shapefile.
I would like to have the same result as the QGIS Point Sampling Tool plugin.
I can't install on Python libraries like qgis.core arcpy pygrass, but I have available GeoPandas GDAL Fiona Shapely rasterio and others.

How can I do this?

Best Answer

I use rasterio and geopandas. My example uses UTM coordinates. Obviously these fields will depend on your particular shapefile. In my experience this produces indentical results to the QGIS Point Sampling Tool. I like this method because the resulting DataFrame of point and corresponding raster values is easy to analyze (e.g. compute the difference between the point and raster values) and then plot or export to some other tabular format (e.g. CSV).

import rasterio
import geopandas as gpd

# Read points from shapefile
pts = gpd.read_file('your_point_shapefile.shp')
pts = pts[['UTM_E', 'UTM_N', 'Value', 'geometry']]
pts.index = range(len(pts))
coords = [(x,y) for x, y in zip(pts.UTM_E, pts.UTM_N)]

# Open the raster and store metadata
src = rasterio.open('your_raster.tif')

# Sample the raster at every point location and store values in DataFrame
pts['Raster Value'] = [x for x in src.sample(coords)]
pts['Raster Value'] = probes.apply(lambda x: x['Raster Value'][0], axis=1)
Related Question