python使用gdal将shp文件转为TIF

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)


版权声明:本文为weixin_42045968原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。