2014-05-07 57 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)