Python 如何在嵌套函数中调用父变量
我已经用and编写了一个去噪函数,用于我的训练和测试图像数据 功能(当前)如下所示:Python 如何在嵌套函数中调用父变量,python,function,scope,nested,python-nonlocal,Python,Function,Scope,Nested,Python Nonlocal,我已经用and编写了一个去噪函数,用于我的训练和测试图像数据 功能(当前)如下所示: 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/{dat
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))
必要时,数据
为列车
或测试
img_list
是该目录中所有图像名称的列表
我需要在denoise()
之前创建denoise\u single\u image()
函数,否则denoise()
将无法识别它;但是我需要定义数据
,然后才能创建去噪单个图像()。这似乎是第二十二条军规,除非我能想出如何告诉去噪\u single\u image()
非本地
不起作用,因为它假定已在此环境中定义了数据
。有什么方法可以让它工作吗?您可以将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,10,7,21)
cv2.imwrite(f'../processed_data/{img_path}', dst)
print(f'{img_path.split('/')[-1]} denoised.')
为什么数据不能全局范围化?您似乎不需要在任何地方修改它,因此这是一个不错的用例。@m.oulmakki我已经尝试了全局
和非局部
。虽然它(技术上)与global
一起运行,但它似乎并不承认任何东西的存在。在全局数据
之后添加打印(数据)
不会返回任何内容。在定义去噪
之前,仅在调用去噪
之前,您无需定义去噪
。此外,非局部
适用于词法范围,而不是可以调用去噪单个图像
的范围。参数data
不是去噪单图像
引用的非局部变量data
。您有两个选择:使数据
全局,以便去噪
可以在调用去噪单图像
之前设置其值,或者将data
作为denoise_single_image
的一个参数,并使用类似lambda x:denoise_single_image(“train”,x)
作为map
@chepner的第一个参数,我认为这是可行的,但是tqdm.tqdm(executor.map(lambda x:denoise_single_image(data,x),img_list))
似乎会暂停该功能。几分钟后,我在输出目录中什么也看不到,而且我没有得到任何{img\u path}去噪的
响应,即使在定义去噪单个图像(数据,img\u路径)
之后。