gdal 压缩tif,使用GDAL从tif文件创建shapefile

I am using library gdal to load a tiff file and create a shapefile.

When I load my shapefile with QGIS GUI, There are no informations on the elevation.

I would like to keep the elevation while the transformation.

import os

from osgeo import gdal,ogr,osr,gdalnumeric

import numpy as np

# this allows GDAL to throw Python Exceptions

gdal.UseExceptions()

print "reading tif file..."

try:

ds = gdal.Open( "file.tif" )

except RuntimeError, e:

print 'Unable to open file'

print e

sys.exit(1)

try:

srcband = ds.GetRasterBand(1)

except RuntimeError, e:

# for example, try GetRasterBand(10)

print 'Band ( %i ) not found' % band_num

print e

sys.exit(1)

band = ds.GetRasterBand(1)

# elevation 2D numpy array

elevation = band.ReadAsArray()

# create shapefile datasource from geotiff file

#

print "creating shapefile..."

dst_layername = "Shape"

drv = ogr.GetDriverByName("ESRI Shapefile")

dst_ds = drv.CreateDataSource( dst_layername + ".shp" )

dst_layer = dst_ds.CreateLayer(dst_layername, srs = None )

gdal.Polygonize( srcband, None, dst_layer, -1, [], callback=None

regards,

解决方案

Here is your script which is updated to create a field called "elevation" and extract the raster value in band 1 into that field.

import os

from osgeo import gdal,ogr

import sys

# mapping between gdal type and ogr field type

type_mapping = { gdal.GDT_Byte: ogr.OFTInteger,

gdal.GDT_UInt16: ogr.OFTInteger,

gdal.GDT_Int16: ogr.OFTInteger,

gdal.GDT_UInt32: ogr.OFTInteger,

gdal.GDT_Int32: ogr.OFTInteger,

gdal.GDT_Float32: ogr.OFTReal,

gdal.GDT_Float64: ogr.OFTReal,

gdal.GDT_CInt16: ogr.OFTInteger,

gdal.GDT_CInt32: ogr.OFTInteger,

gdal.GDT_CFloat32: ogr.OFTReal,

gdal.GDT_CFloat64: ogr.OFTReal}

# this allows GDAL to throw Python Exceptions

gdal.UseExceptions()

print "reading tif file..."

try:

ds = gdal.Open(sys.argv[1])

except RuntimeError, e:

print 'Unable to open file'

print e

sys.exit(1)

try:

srcband = ds.GetRasterBand(1)

except RuntimeError, e:

# for example, try GetRasterBand(10)

print 'Band ( %i ) not found' % 1

print e

sys.exit(1)

# create shapefile datasource from geotiff file

print "creating shapefile..."

dst_layername = "Shape"

drv = ogr.GetDriverByName("ESRI Shapefile")

dst_ds = drv.CreateDataSource( "poly_out.shp" )

dst_layer = dst_ds.CreateLayer(dst_layername, srs = None )

raster_field = ogr.FieldDefn('elevation', type_mapping[srcband.DataType])

dst_layer.CreateField(raster_field)

gdal.Polygonize( srcband, None, dst_layer, 0, [], callback=None)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值