1

Let say we have a georaster file with a given resolution. Is is possible to create a grid where each cell of the grid correspond to each pixel? Is it possible to store this grid as a GeoPandas dataframe?

This is a example of the image that I have.

fname = 'myFile.tif'
f = rasterio.open(fname)
show(f)

enter image description here

This is what I tried to do but I am not able to convert the meshgrid as a geopandas dataframe.

from affine import Affine
import xarray as xr
da = xr.open_rasterio(fname)
transform = Affine.from_gdal(*da.attrs['transform'])
nx, ny = da.sizes['x'], da.sizes['y']
x, y = np.meshgrid(np.arange(nx)+0.5, np.arange(ny)+0.5) * transform

The goal is to have a GeoPandas dataframe in which each rows correspond to a pixel with the value of the georaster because I want to make spatial join with other GeoPandas dataframes.

0
1

I solved the problem as following:

def geopandasFromRaster(geofile):
    mask = None
    with rasterio.Env():
        with rasterio.open(geofile) as src:
            image = src.read(1) # first band
            results = (
            {'properties': {'raster_val': v}, 'geometry': s}
            for i, (s, v) 
            in enumerate(
                shapes(image, mask=mask, transform=src.transform)))
    geoms = list(results)
    return gpd.GeoDataFrame.from_features(geoms)


gdf = geopandasFromRaster(fname)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.