opencv 和多处理 [英] opencv and multiprocessing

查看:43
本文介绍了opencv 和多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 python 的多处理模块来创建一个进程,该进程通过 opencv 的 python 接口不断轮询网络摄像头,将任何结果图像发送到其他进程可以访问它们的队列.但是,每当我尝试对队列中其他进程检索到的图像执行任何操作时,都会遇到挂起(Ubuntu 12.04 上的 python 2.7).这是一个最小的例子:

I'm looking to use the multiprocessing module for python to create one process that continually polls a webcam via opencv's python interface, sending any resulting images to a queue from which other processes can access them. However, I'm encountering a hang (python 2.7 on Ubuntu 12.04) whenever I try to do anything with the images retrieved by other processes from the queue. Here's a minimal example:

import multiprocessing
import cv

queue_from_cam = multiprocessing.Queue()

def cam_loop(queue_from_cam):
    print 'initializing cam'
    cam = cv.CaptureFromCAM(-1)
    print 'querying frame'
    img = cv.QueryFrame(cam)
    print 'queueing image'
    queue_from_cam.put(img)
    print 'cam_loop done'


cam_process = multiprocessing.Process(target=cam_loop,args=(queue_from_cam,))
cam_process.start()

while queue_from_cam.empty():
    pass

print 'getting image'
from_queue = queue_from_cam.get()
print 'saving image'
cv.SaveImage('temp.png',from_queue)
print 'image saved'

此代码应该一直运行到保存图像"的打印输出.但随后挂起.有什么想法可以解决这个问题吗?

This code should run up to the print out of "saving image" but then hang. Any ideas how I can go about fixing this?

推荐答案

最简单的方法是使用基于 NumPy 数组的较新的 cv2 模块.这样你就不必搞乱手动酸洗.这是修复程序(我只是更改了 4 行代码):

The simplest approach is to use the newer cv2 module that's based on NumPy arrays. That way you don't have to mess with manual pickling. Here's the fix (I just changed 4 lines of code):

import multiprocessing
import cv2

queue_from_cam = multiprocessing.Queue()

def cam_loop(queue_from_cam):
    print 'initializing cam'
    cap = cv2.VideoCapture(0)
    print 'querying frame'
    hello, img = cap.read()
    print 'queueing image'
    queue_from_cam.put(img)
    print 'cam_loop done'

cam_process = multiprocessing.Process(target=cam_loop,args=(queue_from_cam,))
cam_process.start()

while queue_from_cam.empty():
    pass

print 'getting image'
from_queue = queue_from_cam.get()
print 'saving image'
cv2.imwrite('temp.png', from_queue)
print 'image saved'

这篇关于opencv 和多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆