我正在尝试将值附加到列表中。但是,由于它是多处理的,列表最终只有一个值。有没有办法将所有图像的大小附加到列表中,而不仅仅是一个?
import cv2
import concurrent.futures
import os
length = []
def multi_proc(image):
name = image[0:-4]
im = cv2.imread(image)
final_im = cv2.resize(im, (100,100))
cv2.imwrite(name+"rs"+".png", final_im)
l = im.shape
print(l)
length.append(l)
with concurrent.futures.ProcessPoolExecutor() as executor:
sound_files = [f for f in os.listdir('.') if f.endswith('.png')]
executor.map(multi_proc, sound_files)
import cv2
import concurrent.futures
import os
length = []
def multi_proc(image):
name = image[0:-4]
im = cv2.imread(image)
final_im = cv2.resize(im, (100,100))
cv2.imwrite(name+"rs"+".png", final_im)
l = im.shape
print(l)
return l
def app_img(l):
length.append(l)
def start_processing():
with concurrent.futures.ProcessPoolExecutor() as executor:
sound_files = [f for f in os.listdir('.') if f.endswith('.png')]
breakpoint()
future_proc = {executor.submit(multi_proc, f): f for f in sound_files}
for future in concurrent.futures.as_completed(future_proc):
app_img(future.result())
if __name__ == "__main__":
start_processing()
print(len(length))
输入:2个PNG文件 输出:
(225, 225, 3)
(313, 161, 3)
2
用ThreadPoolExecutor
替换ProcessPoolExecutor
帮助我解决了这个问题。
您可以只使用嵌套列表。不要使用 length.append(l(,而是尝试 length.append([im, final_im, l](。