我用cv2和concurrent.futures编写了一个去噪函数,用于我的训练和测试图像数据。
目前的职能如下:
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))必要时,data是train或test;img_list是该目录中所有图像名称的列表。
我需要在denoise_single_image()之前创建denoise()函数,否则denoise()不会识别它;但是在创建denoise_single_image()之前我需要定义data。这似乎是一个陷阱-22,除非我能弄清楚如何告诉denoise_single_image()引用一个存在于一级以上的变量。
nonlocal不能工作,因为它假定data已经在这个环境中定义了。有什么办法让这件事起作用吗?
发布于 2021-05-04 19:46:49
您可以将executor.map中的可迭代更改为参数的元组,然后在其他函数中拆分。
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.')https://stackoverflow.com/questions/67390731
复制相似问题