我正在尝试将我的程序之一转换为使用多处理,最好是多处理池,因为这些似乎更容易做到。概括地说,该过程是根据图像创建补丁数组,然后将它们传递到 GPU 进行对象检测。 CPU和GPU部分各耗时约4秒,但CPU有8核,不需要等待GPU,因为数据经过GPU后不再进行任何操作。
Here is a diagram of how I imagine this should work:
为了帮助整个过程,我想要一个我的实现的高级版本的演示。假设我们正在循环访问包含 10 个图像的文件夹中的图像列表。我们一次调整 4 个图像的大小。然后我们一次将它们转换为黑白两个,我们可以将转换视为此处过程的 GPU 部分。代码如下:
def im_resize(im, num1, num2):
return im.resize((num1, num2), Image.ANTIALIAS)
def convert_bw(im):
return im.convert('L')
def read_images(path):
imlist = []
for pathAndFileName in glob.iglob(os.path.join(path, "*")):
if pathAndFileName.endswith(tuple([".jpg", ".JPG"])):
imlist.append(Image.open(pathAndFileName))
return imlist
img_list = read_images("path/to/images/")
final_img_list = []
for image in img_list:
# Resize needs to run concurrently on 4 processes so that the next img_tmp is always ready to go for convert
img_tmp = im_resize(image, 100, 100)
# Convert is limited, need to run on 2 processes
img_tmp = convert_bw(img_tmp)
final_img_list.append(img_tmp)
特定进程数量等的原因是由于系统性能指标,这会减少运行时间。我只是想确保 GPU 不必等待 CPU 完成图像处理,并且我希望有一个常量队列,其中填充了准备好 GPU 运行的预处理图像。我最好将队列的最大大小保留为大约 4-10 个预处理图像。如果你们能帮我说明如何通过这个简化的示例来实现这一目标,我相信我可以弄清楚如何将其转化为我需要的内容。
Thanks!
这是实现您想要的内容的尝试:
...
# Mapping functions can only take one arg, we provide tuple
def img_resize_splat(a):
img_resize(*a)
if __name__=="__main__":
# Make a CPU pool and a GPU pool
cpu = Pool(4)
gpu = Pool(2)
# Hopefully this returns an iterable, and not a list with all images read into memory
img_list = read_images("path/to/images/")
# I'm assuming you want images to be processed as soon as ready, order doesn't matter
resized = cpu.imap_unordered(img_resize_splat, ((img, 100, 100) for img in img_list))
converted = gpu.imap_unordered(convert_bw, resized)
# This is an iterable with your results, slurp them up one at a time
for bw_img in converted:
# do something
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)