利用Numpy并行化图像处理

2024-06-01 07:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python中的并行处理来加速我的一部分代码,但是我很难让它正常工作,甚至找不到与我相关的示例。在

代码使用Delaunay三角剖分生成一个低多边形版本的图像,而减慢速度的部分是找到每个三角形的平均值。在

通过矢量化我的代码,我已经可以获得很好的速度提升,但希望通过并行化获得更多:

我遇到问题的代码是一个非常简单的for循环:

for tri in tris:
        lopo[tridex==tri,:] = np.mean(hipo[tridex==tri,:],axis=0)

引用的变量如下。在

tris-三角形所有索引的唯一python列表

lopo-图像的最终低多边形版本的Numpy数组

hipo-原始图像的Numpy数组

tridex-与图像大小相同的Numpy数组。每个元素表示一个像素,并存储该像素所在的三角形

我似乎找不到一个使用多个numpy数组作为输入并共享其中一个数组的好例子。在

我尝试过多处理(上面的代码片段包装在一个名为colorImage的函数中):

^{pr2}$

但我马上就收到了一个断管错误。在


Tags: 代码图像版本numpyfor像素数组多边形
1条回答
网友
1楼 · 发布于 2024-06-01 07:39:02

因此,Python的多处理工作方式(在大多数情况下)是必须指定要运行的各个线程。我在这里做了一个简短的介绍教程:http://will-farmer.com/parallel-python.html

在您的例子中,我建议将tris分成一组不同的部分,每个部分大小相等,每个部分代表一个“worker”。您可以使用numpy.split()拆分此列表(此处的文档:http://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html)。在

然后,对于tri中的每个列表,我们使用线程和队列模块来指定8个工人。在

import numpy as np
# split into 8 different lists
tri_lists = np.split(tris, 8)
# Queues are threadsafe
return_values = queue.Queue()
threads = []
def color_image(q, tris, hipo, tridex):
    """ This is the function we're parallelizing """
    for tri in tris:
        return_values.put(np.mean(hipo[tridex==tri,:], axis=0))
# Now we run the jobs
for i in range(8):
    threads.append(threading.Thread(
        target=color_image,
        args=(return_values, tri_lists[i], hipo, tridex)))
# Now we have to cleanup our results
# First get items from queue
results = [item for item in return_values.queue]
# Now set values in lopo
for i in range(len(results)):
    for t in tri_lists[i]:
        lopo[tridex==t, :] = results[i]

这不是最干净的方法,我不确定它是否有效,因为我无法测试它,但这是一个不错的方法。并行化部分现在是np.mean(),而设置值不是并行化的。在

如果您还想并行化这些值的设置,那么必须有一个共享变量,可以使用队列,也可以使用全局变量。在

有关共享的全局变量,请参阅本文:Python Global Variable with thread

相关问题 更多 >