2014-05-07 32 views
0

我正在使用Python 2.7.5和OpenCV。我有一个测试图像,我想在图像数组中找到它最相似的图像。我写了一个使用OpenCV的函数,它会给我相似点的总数。我有更相似的点,图像更相似。不幸的是,这是一个相当耗时的功能,所以我想并行化我的代码以使其更快。使用python进行多处理以找到最大值

#img is the image that I am trying to find the most number of similar pointswith 
maxSimilarPts = 0; 

#testImages is a list of testImages 
for testImage in testImages: 
    #getNumSimilarPts returns the number of similar points between two images 
    similarPts = getNumSimilarPts(img, testImage) 

    if similarPts > maxSimilarPts: 
     maxSimilarPts = similarPts 

我该如何与python并行?任何帮助将不胜感激。

+0

你可能想看看[这篇文章](http://stackoverflow.com/questions/11368486/openmp-and-python)。它与OpenCV无关。但是它有很多与python进行多线程的讨论。 –

回答

0

以下是原始代码的(未经测试的)并行版本。它并行运行5名工人。每个人从输入队列中获取图像,计算相似度,然后将值和图像放到输出队列中。当所有的工作完成后,没有更多的图像,然后父进程打印最相似图像的(相似性,图像ID)。

# adapted from Raymond Hettinger 
# http://stackoverflow.com/questions/11920490/how-do-i-run-os-walk-in-parallel-in-python/23779787#23779787 

from multiprocessing.pool import Pool 
from multiprocessing import JoinableQueue as Queue 
import os, sys 


def parallel_worker(): 
    while True: 
     testImage = imageq.get() 
     similarPts = getNumSimilarPts(img, testImage) 
     similarq.put([similarPts, testImage]) 
     imageq.task_done() 

similarq = Queue() 
imageq = Queue() 
for testImage in testImages: 
    imageq.put(testImage) 

pool = Pool(5) 
for i in range(5): 
    pool.apply_async(parallel_worker) 

imageq.join() 
print 'Done' 

print max(similarq)