編輯光柵化GDAL層
這裏是做正確的方式,和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適合渲染地理數據(我想要否抗鋸齒和一個非常強大的渲染器,能夠正確繪製非常大和非常小的特徵,可能來自「髒數據」(退化多邊形等),有時指定在大座標中)?
比如我想從這個去:
http://i.imagehost.org/0232/from.png http://i.imagehost.org/0232/from.png
要這樣:
http://f.imagehost.org/0012/to_4.png http://f.imagehost.org/0012/to_4.png
這裏,多邊形由一個屬性值差異(顏色並不重要,我只想爲屬性的每個值有不同的值)。
謝謝Luper,這對我今天非常有幫助! gdal的文檔很難找到正確的信息... – yosukesabai 2011-11-27 18:44:01
嗨@Luper,太棒了!我正在尋找這個!考慮到我正確地指定了您的名字並鏈接到了這個問題,您是否允許將示例代碼中的(部分)代碼包含在GPLv3許可的開源項目中? – 2013-06-04 07:48:10
@ andreas-h確定沒有問題。 – 2013-06-04 09:39:13