gpt4 book ai didi

python - 如何并行化此 Python for 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:04 24 4
gpt4 key购买 nike

我正在处理一个需要并行处理的图像处理问题。我看过几个展示在 Python 中使用并行处理的示例,但所有这些示例的输入都是一维数组。因此,我正在寻找一种方法来并行化对图像执行两个过程的函数。以下代码是我需要并行化的代码:

for i in arange(0, shape(img)[0] - window_size[0], 10):
for j in arange(0, shape(img)[1] - window_size[1], 10):
Process1 = Do_something(img[i: i + winSize[0], j: j + winSize[1]])
Process2 = Do_something(Process1)

如何并行化这个嵌套循环?

最佳答案

我不完全确定变量的含义或 Do_something() 函数的作用,但这是使其并行的一般方法:

import concurrent.futures
import functools

def process_stuff(i, j, img, winSize):
Process1 = Do_something(img[i: i + winSize[0], j: j + winSize[1]])
Process2 = Do_something(Process1)

with concurrent.futures.ProcessPoolExecutor() as executor:
for i in arange(0, shape(img)[0] - window_size[0], 10):
for j in arange(0, shape(img)[1] - window_size[1], 10):
executor.submit(process_stuff, i, j, img, winSize)

此解决方案适用于 Python 3.2 及更高版本。旧版本可能使用 multiprocessing模块。

如果您希望有一种更有效的方式来获取返回值,这是另一种方式:

import concurrent.futures
import functools
import itertools
import operator

def process_stuff(i, j, img, winSize):
Process1 = Do_something(img[i: i + winSize[0], j: j + winSize[1]])
Process2 = Do_something(Process1)

with concurrent.futures.ProcessPoolExecutor() as executor:
i_iterator = arange(0, shape(img)[0] - window_size[0], 10)
j_iterator = arange(0, shape(img)[1] - window_size[1], 10)
product = itertools.product(i_iterator, j_iterator)
iter1, iter2 = itertools.tee(product)
i_iterator = map(operator.itemgetter(0), iter1)
j_iterator = map(operator.itemgetter(1), iter2)

do_process = functools.partial(process_stuff, img=img, winSize=winSize)
executor.map(do_process, i_iterator, j_iterator)

它有点复杂,但我在这里所做的是获取 ij 的所有组合的 product(),拆分 ij 为两个迭代器,map() 以迭代器为变量。

更新:

我最好的选择是,阻碍您的是将图像转移到不同的过程。这只会传输图像的适当部分:

import concurrent.futures
import itertools

def process_stuff(img_part):
Process1 = Do_something(img_part)
Process2 = Do_something(Process1)

with concurrent.futures.ProcessPoolExecutor() as executor:
i_iterator = arange(0, shape(img)[0] - window_size[0], 10)
j_iterator = arange(0, shape(img)[1] - window_size[1], 10)
product = itertools.product(i_iterator, j_iterator)
parts_generator = (img[i: i + winSize[0], j: j + winSize[1]]
for i, j in product)

executor.map(process_stuff, parts_generator)

关于python - 如何并行化此 Python for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36235648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com