2013-02-08 78 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