2013-02-08 50 views
0

我有一個python函數,它接受圖像路徑並根據圖像是否黑色輸出true或false。我想在同一臺機器上處理多個圖像,並且如果其中一個圖像不是黑色的,則會停止該過程。我在這裏讀了很多python,芹菜等多處理,但我不知道從哪裏開始。運行python多進程進行圖像處理

回答

2

我會建議看看Pools輕鬆創建流程。如果你需要有一些共享狀態,在這種情況下,找到一個表示非黑色圖像的布爾值,請看Managers

更新:這裏是我的意思的例子。

import multiprocessing.Manager as Manager 
import multiprocessing.Pool as Pool 

m = Manager() 
p = Pool(processes=5) 

state_info = m.dict() 
state_info['image_found'] = False 

def processImage(img): 

    # ... Process Image ... 

    if imageIsBlack(img): 
     state_info['image_found'] = True 
     p.terminate() 

p.apply(processImage, imageList) 

if state_info['image_found']: 
    print 'There was a black image!!' 
else: 
    print 'No black images were found.' 
+0

我有一個工作代碼產卵我的進程,它工作正常,但我不能退出如果函數的過程返回False。 – alok 2013-02-11 20:09:53

+0

如果你正在使用池,那麼你可以使用終止。我添加了一個更新來向你展示如何。如果你正在對流程進行分類,那麼在開始計算之前一定要檢查'image_found'是否爲False。 – owobeid 2013-02-11 22:07:31

+0

感謝代碼示例,但您的示例會引發錯誤,因爲'p'在函數'processImage'的作用域中不被識別爲變量,我們無法從此函數內部調用p.terminate()。糾正我,如果我錯了。 – alok 2013-02-11 22:25:56

0

最後,這對我很好。從示例here複製它。爲了說明的目的,我將_isImgNonBlack函數和圖像序列替換爲0和1的列表,其中0是黑色圖像和1個非黑色圖像。

import multiprocessing 

def isImgNonBlack(result_queue, imgSeq): 
    for img in imgSeq: 
     # If a non-black is found put a result 
     if img==1: 
      result_queue.put(1) 

    # else put a zero as the result 
    result_queue.put(0) 

if __name__ == '__main__': 
    processs = [] 
    result_queue = multiprocessing.Queue() 
    nbProc = 20 

    # making a fake list of images with 
    # 10,000 0's follwed by a single 1 
    images = [0 for n in range(10000)] 
    images.append(1) 

    for n in range(nbProc): # start processes crawling for the result 
     process = multiprocessing.Process(target=isImgNonBlack, args=[result_queue, images]) 
     process.start() 
     processs.append(process) 
     print 'Starting Process : %s' % process 

    result = result_queue.get() # waits until any of the proccess have `.put()` a result 

    for process in processs: # then kill them all off 
     process.terminate() 

    # finally print the result 
    print "Seq have a non black img: %s" % result