Bra*_*son 2 python csv tiff gdal geotiff
我有很多这种格式的 csv 文件:
Latitude,Longitude,Concentration
53.833399,-122.825257,0.021957
53.837893,-122.825238,0.022642
....
Run Code Online (Sandbox Code Playgroud)
我的目标是根据这些文件中的信息(每个 csv 文件一个 tiff 文件)生成 GeoTiff 文件,最好使用 python。这是几年前在我正在从事的项目中完成的,但是他们之前是如何做的已经丢失了。我所知道的是他们最有可能使用 GDAL。
我试图通过研究如何使用 GDAL 来做到这一点,但这并没有让我在任何地方,因为资源有限而且我不知道如何使用它。
有人可以帮我弄这个吗?
这是我为您的情况改编的一些代码。您需要将包含所有 *.exe 的 GDAL 目录添加到您的路径中才能使其工作(在大多数情况下是C:\Program Files (x86)\GDAL
)。
它使用gdal_grid.exe
util(参见此处的文档:http : //www.gdal.org/gdal_grid.html)
您可以根据需要修改gdal_cmd
变量以满足您的需要。
import subprocess
import os
# your directory with all your csv files in it
dir_with_csvs = r"C:\my_csv_files"
# make it the active directory
os.chdir(dir_with_csvs)
# function to get the csv filenames in the directory
def find_csv_filenames(path_to_dir, suffix=".csv"):
filenames = os.listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith(suffix) ]
# get the filenames
csvfiles = find_csv_filenames(dir_with_csvs)
# loop through each CSV file
# for each CSV file, make an associated VRT file to be used with gdal_grid command
# and then run the gdal_grid util in a subprocess instance
for fn in csvfiles:
vrt_fn = fn.replace(".csv", ".vrt")
lyr_name = fn.replace('.csv', '')
out_tif = fn.replace('.csv', '.tiff')
with open(vrt_fn, 'w') as fn_vrt:
fn_vrt.write('<OGRVRTDataSource>\n')
fn_vrt.write('\t<OGRVRTLayer name="%s">\n' % lyr_name)
fn_vrt.write('\t\t<SrcDataSource>%s</SrcDataSource>\n' % fn)
fn_vrt.write('\t\t<GeometryType>wkbPoint</GeometryType>\n')
fn_vrt.write('\t\t<GeometryField encoding="PointFromColumns" x="Longitude" y="Latitude" z="Concentration"/>\n')
fn_vrt.write('\t</OGRVRTLayer>\n')
fn_vrt.write('</OGRVRTDataSource>\n')
gdal_cmd = 'gdal_grid -a invdist:power=2.0:smoothing=1.0 -zfield "Concentration" -of GTiff -ot Float64 -l %s %s %s' % (lyr_name, vrt_fn, out_tif)
subprocess.call(gdal_cmd, shell=True)
Run Code Online (Sandbox Code Playgroud)