python使用gdal将shp文件转为TIF
方法一
def vector2raster(inputfilePath, outputfile, resp):
sf = shapefile.Reader(inputfilePath)
min_x, min_y, max_x, max_y = sf.bbox
resp = 100
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)
band = targetDataset.GetRasterBand(1)
NoData_value = -999
band.SetNoDataValue(NoData_value)
band.FlushCache()
gdal.RasterizeLayer(targetDataset, [1], layer, )
inputfilePath = "input_shp.shp"
outputfile = 'ouput_tif.tif'
resp = 100
vector2raster(inputfilePath, outputfile, 100)
方法二
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())
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)