编程语言
首页 > 编程语言> > Python:将多个LANDSAT图像导入Grass GIS的脚本

Python:将多个LANDSAT图像导入Grass GIS的脚本

作者:互联网

我正在尝试编写Python代码,以通过修改以下代码将LANDSAT卫星图像导入Grass GIS:

LANDSAT切片作为文件夹下载,每个切片包含7张tiff图像(波段1-7).因此,我有一个包含几个子目录的目录(每个LANDSAT磁贴一个).

我目前的代码如下:

#!/usr/bin/python

import os
import sys
import glob
import grass.script as grass

def import_tifs(dirpath):

    for dirpath, dirname, filenames in os.walk(dirpath):
        for dirname in dirpath:

        dirname = os.path.join(dirpath,dirname)

            for file in os.listdir(dirname):
                if os.path.splitext(file)[-1] != '.TIF':
                    continue
                ffile = os.path.join(dirname, file)
                name = os.path.splitext(file)[0].split(dirname)[-1]

                grass.message('Importing %s -> %s@%s...' % (file, name, dirpath))

                grass.run_command('r.in.gdal',
                                  flags = 'o',
                                  input = ffile,
                                  output = name,
                                  quiet = True,
                                  overwrite = True)

def main():                                 
    if len(sys.argv) == 1:
        for directory in filter(os.path.isdir, os.listdir(os.getcwd())):
            import_tifs(directory)
    else:
        import_tifs(sys.argv[1])

if __name__ == "__main__":
    main()

我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/Simon/Documents/import_landsat2.py", line
40, in <module>
    main()
  File "C:/Users/Simon/Documents/import_landsat2.py", line
37, in main
    import_tifs(sys.argv[1])
  File "C:/Users/Simon/Documents/import_landsat2.py", line
17, in import_tifs
    for file in os.listdir(dirname):
WindowsError: [Error 3] The system cannot find the path
specified: 'dirpath\\C/*.*'

谁能解释正在发生的事情以及我需要做什么来解决它,或者提出替代方案?谢谢.

解决方法:

我相信您的主要问题是os.walk()中的目录名返回一个列表(不是字符串),因此您的后续字符串(即目录名= os.path.join(dirpath,dirname))有点格式错误.这是一种可能的选择-为了测试这一点,我使用了目录的完整路径作为sys.argv [1],但是可以根据需要调整其动态范围.另外,避免使用诸如文件之类的变量名,因为它们是Python关键字.我无法测试您的grass.*函数,但希望这将是一个足够清楚的示例,以便您可以调整所需的方法. os.walk()本机处理许多标准解析,因此您可以删除一些目录操作函数:

def import_tifs(dirpath):
  for dirpath, dirname, filenames in os.walk(dirpath):
    # Iterate through the files in the current dir returned by walk()
    for tif_file in filenames:
      # If the suffix is '.TIF', process
      if tif_file.upper().endswith('.tif'):
        # This will contain the full path to your file
        full_path = os.path.join(dirpath, tif_file)

        # tif_file will already contain the name, so you can call from here
        grass.message('Importing %s -> %s@%s...' % (full_path, tif_file, dirpath))

        grass.run_command('r.in.gdal',
                          flags = 'o',
                          input = full_path,
                          output = tif_file,
                          quiet = True,
                          overwrite = True)

标签:gis,python,grass,landsat
来源: https://codeday.me/bug/20191031/1977946.html