【问题标题】:Using gdal in python to produce tiff files from csv files在 python 中使用 gdal 从 csv 文件生成 tiff 文件
【发布时间】:2016-08-15 18:13:06
【问题描述】:

我有很多这种格式的 csv 文件:

Latitude,Longitude,Concentration
53.833399,-122.825257,0.021957
53.837893,-122.825238,0.022642
....

我的目标是根据这些文件中的信息(每个 csv 文件一个 tiff 文件)生成 GeoTiff 文件,最好使用 python。这是几年前在我正在从事的项目中完成的,但是他们之前是如何做到的已经丢失了。我只知道他们最有可能使用 GDAL。

我试图通过研究如何使用 GDAL 来做到这一点,但这对我没有任何帮助,因为资源有限而且我不知道如何使用它。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python csv tiff gdal geotiff


    【解决方案1】:

    这是我为您的情况改编的一小段代码。您需要将包含所有 *.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)
    

    【讨论】:

    • 只要在代码中的'gdal_cmd'字符串中加上参数-a_srs "EPSG:32610",就可以设置输出文件的投影了。
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多