首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在嵌套函数中调用父变量

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

Stack Overflow用户
提问于 2021-05-04 19:07:47
回答 1查看 69关注 0票数 0

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

目前的职能如下:

代码语言:javascript
复制
def denoise_single_image(img_path):
    nonlocal data
    img = cv2.imread(f'../data/jpeg/{data}/{img_path}')
    dst = cv2.fastNlMeansDenoising(img, 10,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))

必要时,datatraintestimg_list是该目录中所有图像名称的列表。

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

nonlocal不能工作,因为它假定data已经在这个环境中定义了。有什么办法让这件事起作用吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-04 19:46:49

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

代码语言:javascript
复制
executor.map(denoise_single_image, ((img_path, data) for img_path in img_list))

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

但是在您的例子中,我只需要修改单独的图像路径,如下所示

代码语言:javascript
复制
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,10,7,21)
    cv2.imwrite(f'../processed_data/{img_path}', dst)
    print(f'{img_path.split('/')[-1]} denoised.')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67390731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档