I am new to GDAL and geom shapefiles.
I have a 3-band .img file (with other associated files) as raster images.
And also a shapefile which includes 10000+ features (multi-polygons), the properties of each includes 'shape_leng', and 'BM' (corresponding to the geographic class of this area, e.g. water/forest).
I want to rasterize the shapefile with property 'BM' as labeled pixel value (single/three channels) to put it together with my raster image so that I can visualize the segmentation or further train an image segmentation network using this as a training dataset.
How to implement it using Python? Or is there any tutorial/notebook that I can learn from?
-
It's quite simple to do in pure GDAL. This answer has a function for it using just GDAL.Jose– Jose2020年12月15日 19:00:05 +00:00Commented Dec 15, 2020 at 19:00
1 Answer 1
Rasterizing with GDAL is possible, but rather verbose in Python. The documentation is not very explanatory. There is this thread and this one on how to do this in GDAL. However, I recommend using GeoCube thread, which makes it easy as Py:
from geocube.api.core import make_geocube
import rioxarray
import geopandas as gpd
raster_path = 'your path'
vector_path = 'other path'
source_ds = gpd.read_file(vector_path)
raster = rioxarray.open_rasterio(raster_path,masked=True)
Cube = make_geocube(vector_data=source_ds['BM'],like=raster)
Cube.BM.plot()
good luck!