【问题标题】:Is there a more efficient way of converting tif files in Python? [closed]有没有更有效的方式在 Python 中转换 tif 文件? [关闭]
【发布时间】:2021-09-02 04:29:54
【问题描述】:

在这里,我使用gdal 将 tif 文件转换为 Stata 数据集。为简单起见,我将以最低分辨率链接ones(如果重要,我使用的是 2.5m 分辨率文件)。

这是我的代码:

### Be sure to copy the file I've
### linked to your current directory

from osgeo import gdal
import pandas as pd, os, glob

for file in glob.glob("*.tif"):
    ds = gdal.Open(file) # Make TIF into a dataset

    xyz = gdal.Translate(file+".xyz", ds) # Extracts coordinates
    
    xyz = None

    df = pd.read_csv(file+".xyz", sep = " ", header = None)
    df.columns = ["_CX","_CY", "tmin"]
    df.to_stata(file+".dta", write_index=False)
    
    del ds

    files_in_dir = glob.iglob('*.xyz')

    for _file in files_in_dir:
        print(_file)
        os.remove(_file)
        
    os.remove(file)

代码完成了我需要它做的所有事情——但在更高的分辨率下,它只需要一个半小时左右,我有兴趣优化它。有什么办法可以让这个运行更快?

【问题讨论】:

  • 您可以将其移动到一个函数中并应用multiprocessing 以扇出多个内核。我不知道 gdal 是做什么的,所以不能说它是否更好。您需要更加谨慎地删除这些 .xyz 文件。
  • 如果没有正确解释代码的目的,就不可能告诉你为什么代码很慢。您应该尝试测试例如的性能一个单一的gdal.Translate 电话,并尝试阅读gdal 文档以获取任何性能提示或在任何支持论坛/问题跟踪器等上询问gdal 关于性能不佳的问题。 Stack Overflow 不是技术支持。
  • @KarlKnechtel 原帖说这段代码的唯一目标是把这些gif文件变成Stata-data文件。

标签: python optimization gis


【解决方案1】:

您可以使用multiprocessing 模块将其分布在多个内核上。这并不总能加快速度,如果您最终过度提交内存,实际上会使事情变得更糟。但值得一试。

from osgeo import gdal
import pandas as pd, os, glob
import multiprocessing as mp

def gdal_izer(file):
    ds = gdal.Open(file) # Make TIF into a dataset

    xyz = gdal.Translate(file+".xyz", ds) # Extracts coordinates
    
    xyz = None

    df = pd.read_csv(file+".xyz", sep = " ", header = None)
    df.columns = ["_CX","_CY", "tmin"]
    df.to_stata(file+".dta", write_index=False)    
    del ds

    # TODO: Fix = this will delete xyz files used by other
    # processes. Should it just be deleting the one file?
    files_in_dir = glob.iglob('*.xyz')

    for _file in files_in_dir:
        print(_file)
        os.remove(_file)

    # TODO: removing the tif seems pretty extreme. maybe
    # save it in case something goes wrong?
    os.remove(file)

    
def main():
    # note: all cores is likely too much
    files = glob.glob("*.tif")
    with mp.Pool(min(len(files), mp.cpu_count() * .6)) as pool:
        result = mp.map(gdal_izer, glob.glob("*.tif"))

if __name__ == "__main__":
    main()

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多