python使用gdal将shp文件转为TIF

该文介绍了两种方法将Shapefile(shp)文件通过GDAL库转换为TIFF(TIF)图像。方法一涉及计算shp文件的边界和栅格大小,而方法二则利用模板文件来设定坐标系和分辨率。转换过程中包括设置栅格大小、创建目标TIFF文件、设置地理变换和投影信息。
摘要由CSDN通过智能技术生成

python使用gdal将shp文件转为TIF

方法一

# 缺少获取shp文件坐标系的步骤
def vector2raster(inputfilePath, outputfile, resp):
    sf = shapefile.Reader(inputfilePath)
    # 读取shp四至
    min_x, min_y, max_x, max_y = sf.bbox
    resp = 100  # 设置每个cell的大小
    tifrow = int((max_x - min_x) / resp)
    tifcol = int((max_y - min_y) / resp)

    vector = ogr.Open(inputfilePath)
    layer = vector.GetLayer()

    targetDataset = gdal.GetDriverByName('GTiff').Create(outputfile, tifrow, tifcol, 1, gdal.GDT_Byte)
    transform = (min_x, resp, 0, min_y, 0, resp)

    targetDataset.SetGeoTransform(transform)
    # targetDataset.SetProjection(data.GetProjection())
    band = targetDataset.GetRasterBand(1)
    NoData_value = -999
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(targetDataset, [1], layer, )


inputfilePath = "input_shp.shp"  # 输入的待转换为tif的shp文件
outputfile = 'ouput_tif.tif'  # 转为TIF后的存储地址
resp = 100  # 栅格中每个cell的大小

vector2raster(inputfilePath, outputfile, 100)

方法二

# 003 通过模板设置坐标系
import gdal
from osgeo.gdal import gdalconst
from osgeo import gdal, ogr
import numpy as np
import os
import glob
import shapefile

def vector2raster(inputfilePath, outputfile, tempaltefile):
    inputfilePath = inputfilePath
    outputfile = outputfile
    tempaltefile = tempaltefile
    data = gdal.Open(tempaltefile, gdalconst.GA_ReadOnly)
    x_res = data.RasterXSize
    y_res = data.RasterYSize
    vector = ogr.Open(inputfilePath)
    layer = vector.GetLayer()
    targetDataset = gdal.GetDriverByName('GTiff').Create(outputfile, x_res, y_res, 1, gdal.GDT_Byte)
    targetDataset.SetGeoTransform(data.GetGeoTransform())
    # targetDataset.SetProjection(data.GetProjection())
    band = targetDataset.GetRasterBand(1)
    NoData_value = -999
    band.SetNoDataValue(NoData_value)
    band.FlushCache()
    gdal.RasterizeLayer(targetDataset, [1], layer, )


inputfilePath = "input_shp.shp"
outputfile = 'output_tif.tif'
tempaltefile = 'tempaltefile .tif'
vector2raster(inputfilePath, outputfile, tempaltefile)

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值