【问题标题】:Running python multiprocess for Image processing运行 python 多进程进行图像处理
【发布时间】:2013-02-13 00:24:42
【问题描述】:

我有一个 python 函数,它接收图像路径并根据图像是否为黑色输出真或假。我想在同一台机器上处理多个图像,如果其中一个不是黑色的,则停止该过程。我在这里阅读了很多关于 python、celery 等的多处理,但我不知道从哪里开始。

【问题讨论】:

    标签: python multiprocessing


    【解决方案1】:

    我建议查看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.'
    

    【讨论】:

    • 我有一个用于生成我的进程的工作代码,它工作正常,但如果进程的函数返回 False,我将无法退出。
    • 如果您使用的是池,那么您可以使用终止。我添加了一个更新来向您展示如何操作。如果您要对 Process 进行子分类,请务必在开始计算之前检查“image_found”是否为 False。
    • 感谢您的代码示例,但您的示例将引发错误,因为 'p' 未被识别为函数 'processImage' 范围内的变量,并且我们无法从其中调用 p.terminate()功能。如果我错了,请纠正我。
    • 这个函数也不知道 state_info 字典。
    • 由于 p 是在函数外部定义的,因此它具有全局范围。如果尝试修改p,则需要在processImage开头添加global p,否则上面的代码应该可以。
    【解决方案2】:

    最后这对我很有效。从示例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
    

    【讨论】:

      最近更新 更多