【发布时间】:2011-01-14 07:30:28
【问题描述】:
编辑
这是正确的做法,documentation:
import random
from osgeo import gdal, ogr
RASTERIZE_COLOR_FIELD = "__color__"
def rasterize(pixel_size=25):
# Open the data source
orig_data_source = ogr.Open("test.shp")
# Make a copy of the layer's data source because we'll need to
# modify its attributes table
source_ds = ogr.GetDriverByName("Memory").CopyDataSource(
orig_data_source, "")
source_layer = source_ds.GetLayer(0)
source_srs = source_layer.GetSpatialRef()
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create a field in the source layer to hold the features colors
field_def = ogr.FieldDefn(RASTERIZE_COLOR_FIELD, ogr.OFTReal)
source_layer.CreateField(field_def)
source_layer_def = source_layer.GetLayerDefn()
field_index = source_layer_def.GetFieldIndex(RASTERIZE_COLOR_FIELD)
# Generate random values for the color field (it's here that the value
# of the attribute should be used, but you get the idea)
for feature in source_layer:
feature.SetField(field_index, random.randint(0, 255))
source_layer.SetFeature(feature)
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', x_res,
y_res, 3, gdal.GDT_Byte)
target_ds.SetGeoTransform((
x_min, pixel_size, 0,
y_max, 0, -pixel_size,
))
if source_srs:
# Make the target raster have the same projection as the source
target_ds.SetProjection(source_srs.ExportToWkt())
else:
# Source has no projection (needs GDAL >= 1.7.0 to work)
target_ds.SetProjection('LOCAL_CS["arbitrary"]')
# Rasterize
err = gdal.RasterizeLayer(target_ds, (3, 2, 1), source_layer,
burn_values=(0, 0, 0),
options=["ATTRIBUTE=%s" % RASTERIZE_COLOR_FIELD])
if err != 0:
raise Exception("error rasterizing layer: %s" % err)
原始问题
我正在寻找有关如何使用osgeo.gdal.RasterizeLayer() 的信息(文档字符串非常简洁,我在C 或C++ API 文档中找不到它。我只找到了java bindings 的文档)。
我改编了 unit test 并在由多边形组成的 .shp 上进行了尝试:
import os
import sys
from osgeo import gdal, gdalconst, ogr, osr
def rasterize():
# Create a raster to rasterize into.
target_ds = gdal.GetDriverByName('GTiff').Create('test.tif', 1280, 1024, 3,
gdal.GDT_Byte)
# Create a layer to rasterize from.
cutline_ds = ogr.Open("data.shp")
# Run the algorithm.
err = gdal.RasterizeLayer(target_ds, [3,2,1], cutline_ds.GetLayer(0),
burn_values=[200,220,240])
if err != 0:
print("error:", err)
if __name__ == '__main__':
rasterize()
它运行良好,但我得到的只是一个黑色的 .tif。
burn_values 参数是什么?可以使用RasterizeLayer() 栅格化具有不同颜色特征的图层吗?基于属性的值?
如果不能,我应该使用什么? AGG 是否适合渲染地理数据(我想要 no 抗锯齿和非常强大的渲染器,能够正确绘制非常大和非常小的特征,可能来自“脏数据”(退化多边形等) ..),有时以大坐标指定)?
这里,多边形是通过属性值来区分的(颜色无关紧要,我只想为属性的每个值设置不同的颜色)。
【问题讨论】:
-
感谢 Luper,今天这对我很有帮助! gdal 的文档很难找到正确的信息...
-
嗨@Luper,太好了!我正在寻找这个!您是否允许将您的示例代码(部分)包含在 GPLv3 许可的开源项目中,因为我正确地注明了您的姓名并链接到这个问题?
-
@andreas-h 确定没问题。
-
@andreas-h 代码的最终形式可以在here 找到。它也是 GPLv3。
-
@LuperRouch 太好了,感谢您的链接!
标签: python gis gdal rasterizing