首页 > 解决方案 > Argparse - 制作输入和输出列表

问题描述

蟒蛇新手,

我的教授给了我一段代码来帮助处理一些图像,但是由于每次都需要规定输入和输出,它一次只能处理一个图像。通常我会输入 import os 或 glob 但 argparse 对我来说是新事物,我常用的方法不起作用。

我需要编辑它以创建“.hdf”文件列表,其输出与输入相同,只是名称更改为“_Processed.hdf”

下面的代码:

# Import the numpy library
import numpy
# Import the GDAL library
from osgeo import gdal
# Import the GDAL/OGR spatial reference library
from osgeo import osr
# Import the HDF4 reader.
import pyhdf.SD
# Import the system library
import sys
# Import the python Argument parser
import argparse
import pprint
import rsgislib    

def creatGCPs(lat_arr, lon_arr):

    y_size = lat_arr.shape[0]
    x_size = lat_arr.shape[1]
    print(x_size)
    print(y_size)

    gcps = []
    for y in range(y_size):
        for x in range(x_size):
            gcps.append([x, y, lon_arr[y,x], lat_arr[y,x]])
    return gcps


def run(inputFile, outputFile):   
    hdfImg = pyhdf.SD.SD(inputFile)
    #print("Available Datasets")
    pprint.pprint(hdfImg.datasets())
    #print("Get Header Attributes")
    #attr = hdfImg.attributes(full=1)
    #pprint.pprint(attr)
    rsgisUtils = rsgislib.RSGISPyUtils()
    wktStr = rsgisUtils.getWKTFromEPSGCode(4326)
    #print(wktStr)

    lat_arr = hdfImg.select('Latitude')[:]
    long_arr = hdfImg.select('Longitude')[:]    
    sel_dataset_arr = hdfImg.select('Optical_Depth_Land_And_Ocean')[:]

    gcplst = creatGCPs(lat_arr, long_arr)


    y_size = lat_arr.shape[0]
    x_size = lat_arr.shape[1]

    min_lat = numpy.min(lat_arr)
    max_lat = numpy.max(lat_arr)
    min_lon = numpy.min(long_arr)
    max_lon = numpy.max(long_arr)

    lat_res = (max_lat-min_lat)/float(y_size)
    lon_res = (max_lon-min_lon)/float(x_size)

    driver = gdal.GetDriverByName( "KEA" )
    metadata = driver.GetMetadata()
    dst_ds = driver.Create( outputFile, x_size, y_size, 1, gdal.GDT_Float32 )
    dst_ds.GetRasterBand(1).WriteArray(sel_dataset_arr)

    gcp_list = []
    for gcp_arr in gcplst:
        gcp = gdal.GCP(int(gcp_arr[2]), int(gcp_arr[3]), int(0), gcp_arr[0], gcp_arr[1])
        gcp_list.append(gcp)

    dst_ds.SetGCPs(gcp_list, wktStr)

    dst_ds = None



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Define the argument for specifying the input file.
    parser.add_argument("-i", "--input", type=str, required=True,  help="Specify the input image file.")
    # Define the argument for specifying the output file.
    parser.add_argument("-o", "--output", type=str, required=True, help="Specify the output image file.")
    args = parser.parse_args()


    run(args.input, args.output)

标签: pythonargparse

解决方案


此处的 argparse 文档中,您可以简单地将 a 添加nargs='*'到参数定义中。但是,一定要以相同的顺序给出输入和输出文件...

此外,您可以使用现在Python >=3.4 中的标准pathlib.Path对象来处理文件名。

因此,from pathlib import Path在顶部添加一个,代码的最后一部分变为:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    # Define the argument for specifying the input file.
    parser.add_argument("-i", "--input", nargs='*', type=str, required=True,  help="Specify the input image file.")

    args = parser.parse_args()

    for input in args.input:
        output = Path(input).stem + '_Processed.hdf'
        run(input, output)

这里,args.input现在是一个字符串列表,所以我们对其进行迭代。该.stem属性返回没有任何扩展名的文件名,我发现它比类似的更干净input[:-4],它只适用于特定的扩展长度......

这适用于标准 linux shell 中的 glob 模式(我不知道其他情况)。

前任。调用python this_script.py -i Image_*,处理文件名以“Image_”开头的每个文件。


推荐阅读