同步线程以同时读取不同的资源

sync threads to read different resources at exactly the same time

我有两个摄像头,这对于同时使用 OpenCV 读取帧很重要,我想到了 Lock 之类的东西,但我不知道如何实现它。

我需要一些触发器来推送并启用线程读取帧,然后等待另一个触发器命中,如下所示:

def get_frame(queue, cap):
    while running:
        if(read_frame):
            queue.put(cap.read());
        else:
            # without this sleep this function just consumes unnecessary CPU time
            time.sleep(some_time);

q = Queue.Queue()
# for every camera
for u in xrange(2):
    t = threading.Thread(target=get_frame, args = (q, caps[u]))
    t.daemon = True
    t.start()

上述实现的问题是:

  1. 我需要定义睡眠时间,因为我不知道每帧读取之间的 delay(即可能长或短,具体取决于计算)
  2. 这并不能让我在每次触发时都阅读一次。

所以这个方法行不通,有什么建议吗?

考虑从 VideoCapture 获取 FPS。另外,请注意 VideoCapture.grab 和 VideoCapture.retrieve 帧之间的区别。用于相机同步。

首先为两个摄像头调用 VideoCapture#grab,然后检索帧。参见 docs