如何配置gdal_polygonize为每个ASCII网格单元生成独立多边形
Hey Ben, great question! The default behavior of gdal_polygonize.py is to merge adjacent cells with identical values into a single polygon—exactly the behavior you're trying to avoid. To get a separate polygon for every grid cell (regardless of its original value), you just need to first create a raster where every cell has a unique identifier, then run polygonize on that modified raster. Here's a step-by-step breakdown:
Step 1: Create a Unique ID Raster
Use gdal_calc.py to generate a new raster where each cell gets a unique numerical ID based on its row and column position. This ensures no two cells share the same value, so gdal_polygonize.py won't merge them.
Run this command (replace your_input_ascii.asc with your actual file name):
gdal_calc.py -i your_input_ascii.asc --outfile unique_ids.tif --calc "((row() * (xsize() + 1)) + col())" --NoDataValue -9999
row()andcol(): GDAL's built-in functions that return the current cell's row and column indexxsize(): Returns the total number of columns in the input raster, ensuring row-based IDs don't overlap across columns--NoDataValue: Sets a consistent no-data value to match your original ASCII file (adjust if your input uses a different value)
Step 2: Polygonize the Unique ID Raster
Now run gdal_polygonize.py on the new unique ID raster to generate individual polygons for every cell:
gdal_polygonize.py unique_ids.tif -f "MapInfo File" output.tab unique_ids id
-f "MapInfo File": Specifies the output format as MapInfo TABoutput.tab: Your final output fileunique_ids: The name of the attribute column for the unique IDsid: The field name for the polygon IDs (you can change this to something more descriptive if needed)
Step 3 (Optional): Reattach Original Values
If you need to keep the original values from your ASCII file associated with each polygon, you can join the original raster's data to the new polygon layer. You can do this using:
- MapInfo's built-in table join tools (match by the unique ID or spatial position)
- GDAL's
gdallocationinfotool to extract original values for each cell, then useogr2ogrto join the extracted data to the polygon attribute table
Why This Works
gdal_polygonize.py only merges cells when they have the same value. By assigning a unique ID to every cell, we eliminate any duplicate values, forcing the tool to create a separate polygon for each grid unit.
内容的提问来源于stack exchange,提问作者user7925487

