如何在 Python 程序中正确使用 gdaladdo?

How to correctly use gdaladdo in a Python program?

我的问题是关于名为 gdaladdo 的 GDAL(地理空间数据抽象库)工具。该工具应该从 .tif 文件构建概览图像。从我找到的文档中,我可以看到它通常是在命令提示符下输入的。我一直在尝试通过我的 Python 程序找到一种方法来获得它 运行,因为我有几千张 .tif 图像需要外部概览。我对这个程序的最终目标是能够将 .tif 图像传递给它并为其创建一个 .rrd 金字塔。到目前为止,这是我的代码:

import gdal
import os
from subprocess import call

#Define gdaladdo
gdaladdoFile = 'C:\Program Files (x86)\GDAL\gdaladdo.exe'

#--------------------------------------------------------

os.chdir("Images")

openfile = open('imagenames.txt', 'r')

if {openfile.closed == False}:
    count = 0
    while count < 5:
        #Grab the image to work with
        filename = openfile.readline()

        #Strip off the newline
        filename.rstrip('\n')

        #Create pyramid
        call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16'])
        count += 1
    openfile.close()

else:
    print "No file to open!"

我收到与 call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16']) 行有关的错误。通常在命令提示符中键入此命令时,它应该如下所示:'gdaladdo -ro --config COMPRESS_OVERVIEW DEFLATE erdas.img 2 4 8 16' 但是Python 表示选项(如 --config USE_RRD YES)是不正确的语法。所以我遵循了一个将参数传递给子进程的示例(我在此处找到)并将选项放在单引号内并在每个选项后添加逗号。语法错误消失了,但是当我 运行 测试它的程序时,新的错误又出现了。它在命令提示符 window 中显示“FAILURE: Unknown option name '--config USE_RRD YES'”。 我应该如何更改此特定行以使其执行我想要的操作?

我是Whosebug的新手,还在大学里学习编程所以请原谅我的无知并温柔对待我。在此先感谢您对这个问题的帮助。

gdaladdo reference link,以备不时之需。

从这里更改代码行:

call([gdaladdoFile, '-ro', '--config USE_RRD YES', 'filename', '2 4 8 16'])

为此:

call([gdaladdoFile, '-ro', '--config', 'USE_RRD', 'YES', filename, '2 4 8 16'])

解决了我的问题!

为避免使用 Python 子流程模块,您可以将 BuildOverviews 函数与 Python API:

from osgeo import gdal
Image = gdal.Open('ImageName.tif', 0)  # 0 = read-only, 1 = read-write.
gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
Image.BuildOverviews('NEAREST', [4, 8, 16, 32, 64, 128], gdal.TermProgress_nocb)
del Image  # close the dataset (Python object and pointers)

当您以只读模式阅读 .tiff 图像时,它将在“.ovr”文件中构建外部概览。反之,如果以读写模式打开图像,则会生成内部概览。