2016-08-15 57 views
0

我有这种格式许多CSV文件:使用python中@中从CSV文件生成TIFF文件

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

我的目标是产生基于这些文件中的信息(支持GeoTiff文件每CSV一个TIFF文件文件),最好使用python。这是几年前在我正在进行的项目上完成的,但是他们之前的做法是如何失败的。我所知道的是他们最有可能使用GDAL。

我试图通过研究如何使用GDAL来做到这一点,但由于资源有限并且我不知道如何使用它,所以这并没有给我带来任何帮助。

有人可以帮助我吗?

回答

2

这里有一个我适应你的情况的代码。您需要将GDAL目录中的所有* .exe添加到您的路径中才能正常工作(在大多数情况下,它是C:\Program Files (x86)\GDAL)。

它使用gdal_grid.exe UTIL(见DOC这里: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) 
+0

只需将参数-a_srs“EPSG:32610”添加到代码中的'gdal_cmd'字符串中,它将设置输出文件的投影。 – kaycee