简体   繁体   English

Python:如何将 geotiff 转换为 geopandas?

[英]Python: how to convert geotiff to geopandas?

I have a geotiff file.我有一个 geotiff 文件。

import xarray as xr
urbanData = xr.open_rasterio('myGeotiff.tif')
plt.imshow(urbanData)

Here the link to the file.这里是文件的链接

I can convert the file as a dataframe with coordinates as points我可以将文件转换为 dataframe 坐标为点

ur  = xr.DataArray(urbanData, name='myData')
ur  = ur.to_dataframe().reset_index() 
gdfur  = gpd.GeoDataFrame(ur, geometry=gpd.points_from_xy(ur.x, ur.y))

However I would like to get a dataframe that contains the geometry of the pixels as polygons and not as points.但是,我想获得一个 dataframe ,其中包含像素的几何形状作为多边形而不是点。 Is it possible?可能吗?

Somewhat to my surprise, I haven't really found a package which wrap rasterio.features to take DataArrays and produce GeoDataFrames.令我惊讶的是,我还没有真正找到一个 package 包装rasterio.features以获取 DataArrays 并生成 GeoDataFrames。

These might be very useful though:这些可能非常有用:

https://corteva.github.io/geocube/stable/ https://corteva.github.io/geocube/stable/

https://corteva.github.io/rioxarray/stable/ https://corteva.github.io/rioxarray/stable/

I generally use something like this:我通常使用这样的东西:

import affine
import geopandas as gpd
import rasterio.features
import xarray as xr
import shapely.geometry as sg


def polygonize(da: xr.DataArray) -> gpd.GeoDataFrame:
    """
    Polygonize a 2D-DataArray into a GeoDataFrame of polygons.

    Parameters
    ----------
    da : xr.DataArray

    Returns
    -------
    polygonized : geopandas.GeoDataFrame
    """
    if da.dims != ("y", "x"):
        raise ValueError('Dimensions must be ("y", "x")')

    values = da.values
    transform = da.attrs.get("transform", None)
    if transform is None:
        raise ValueError("transform is required in da.attrs")
    transform = affine.Affine(*transform)
    shapes = rasterio.features.shapes(values, transform=transform)

    geometries = []
    colvalues = []
    for (geom, colval) in shapes:
        geometries.append(sg.Polygon(geom["coordinates"][0]))
        colvalues.append(colval)

    gdf = gpd.GeoDataFrame({"value": colvalues, "geometry": geometries})
    gdf.crs = da.attrs.get("crs")
    return gdf

Note that you should squeeze the band dimensions from your xarray first to make it 2D, after reading it with xr.open_rasterio :请注意,在使用xr.open_rasterio阅读后,您应该首先从 xarray 中压缩波段尺寸以使其成为 2D:

urbanData = xr.open_rasterio('myGeotiff.tif').squeeze('band', drop=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM