简体   繁体   English

如何在 opencv 中使用 cv::VideoCapture::waitAny()

[英]how to use cv::VideoCapture::waitAny() in opencv

I've been trying to find a way to asynchronously check to see if the next frame of the camera that I get using videocapture is ready.我一直在尝试找到一种方法来异步检查我使用 videocapture 获得的相机的下一帧是否准备好。

I came across waitAny() which is described to "Wait for ready frames from VideoCapture.".我遇到了 waitAny() ,它被描述为“等待来自 VideoCapture 的就绪帧。”。

in the OpenCV documentation, I didn't find any useful info on how to use this or what are the use cases.在 OpenCV 文档中,我没有找到任何有关如何使用它或用例是什么的有用信息。

I've been searching the net for two days now and the only thing I found is how to define the parameters this function needs(I'm new to c++) and I don't know how to fill them and what are their use cases.我已经在网上搜索了两天,我唯一发现的是如何定义这个 function 需要的参数(我是 c++ 新手),我不知道如何填充它们以及它们的用例是什么. here is the documentation: https://docs.opencv.org/master/d8/dfe/classcv_1_1VideoCapture.html#ade1c7b8d276fea4d000bc0af0f1017b3这是文档: https://docs.opencv.org/master/d8/dfe/classcv_1_1VideoCapture.html#ade1c7b8d276fea4d000bc0af0f1017b3

An approach that IMO is fairly common is to have a pair of threads -- one that "produces" frames from VideoCapture (calls VideoCapture::read() in a loop), and another that actually uses these frames (a "consumer"). IMO 相当常见的一种方法是拥有一对线程——一个从VideoCapture “生成”帧(在循环中调用VideoCapture::read() ),另一个实际使用这些帧(一个“消费者”) . The producer pushes images onto a queue (that's shared across two threads), while the consumer pops them.生产者将图像推送到队列(在两个线程之间共享),而消费者弹出它们。 In this situation, checking whether a camera has produced an image amounts to checking whether the queue is empty.在这种情况下,检查相机是否产生图像相当于检查队列是否为空。

By itself, VideoCapture does not provide such an async API. VideoCapture本身不提供这样的异步 API。

That said, if you want to use waitAny , and if you have a single camera, you could do something like this:也就是说,如果你想使用waitAny ,并且如果你有一个摄像头,你可以这样做:

VideoCapture cap = /* get the VideoCapture object from somewhere */


constexpr int64 kTimeoutNs = 1000;
std::vector<int> ready_index;
cv::Mat image;
if (VideoCapture::waitAny({cap}, ready_index, kTimeoutNs)) {
  // Camera was ready; get image.
  cap.retrieve(image);
} else {
  // Camera was not ready; do something else. 
}

Above, VideoCapture::waitAny will wait for the specified timeout (1 microsecond) for the camera to produce a frame, and will return after this period.上面, VideoCapture::waitAny将等待指定的超时时间(1 微秒)让相机产生一帧,并在此时间段后返回。 If the camera is ready, it will return true (and will also populate ready_index with the index of the ready camera. Since you only have a single camera, the vector will be either empty or non-empty).如果相机准备好,它将返回 true (并且还将使用准备好的相机的索引填充ready_index 。由于您只有一个相机,因此向量将为空或非空)。

That said, waitAny seems to only be supported by VideoCapture sources that use V4L in the backend.也就是说, waitAny似乎只有在后端使用 V4L 的VideoCapture源支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM