如何在嵌套函数中调用父变量

问题描述

我用 cv2concurrent.futures 编写了一个去噪函数,用于我的训练和测试图像数据。

功能(目前)如下:

def denoise_single_image(img_path):
    nonlocal data
    img = cv2.imread(f'../data/jpeg/{data}/{img_path}')
    dst = cv2.fastNlMeansDenoising(img,10,7,21)
    cv2.imwrite(f'../processed_data/jpeg/{data}/{img_path}',dst)
    print(f'{img_path} denoised.')
 
def denoise(data):
    img_list = os.listdir(f'../data/jpeg/{data}')
    with concurrent.futures.ProcesspoolExecutor() as executor:
        tqdm.tqdm(executor.map(denoise_single_image,img_list))

datatraintest,视需要而定; img_list 是该目录中所有图像名称的列表。

我需要在denoise_single_image()之前创建denoise()函数,否则denoise()不会识别它;但我需要在创建 data 之前定义 denoise_single_image()。这似乎是第 22 条规则,除非我能弄清楚如何告诉 denoise_single_image() 引用存在于上一级的变量。

nonlocal 不起作用,因为它假定 data 已在此环境中定义。有什么办法可以让它发挥作用吗?

解决方法

您可以将 executor.map 中的 iterable 更改为参数元组,然后可以在您的其他函数中拆分。

executor.map(denoise_single_image,((img_path,data) for img_path in img_list))

def denoise_single_image(inputs):
    img_path,data = inputs
    # etc

但在你的情况下,我只会像这样修改单个图像路径

executor.map(denoise_single_image,(f'jpeg/{data}/{img_path}' for img_path in img_list))

def denoise_single_image(img_path):
    img = cv2.imread(f'../data/{img_path}')
    dst = cv2.fastNlMeansDenoising(img,10,7,21)
    cv2.imwrite(f'../processed_data/{img_path}',dst)
    print(f'{img_path.split('/')[-1]} denoised.')