我有一个OpenCV程序,它是这样工作的:
VideoCapture cap(0);
Mat frame;
while(true) {
cap >> frame;
myprocess(frame);
}问题是,如果myprocess花费的时间长于摄像机的IO间隔,捕获的帧将被延迟,无法获得与实时同步的帧。
因此,我认为要解决这个问题,应该让摄像头流媒体和myprocess并行运行。一个线程做IO操作,另一个线程做CPU计算。当摄像头完成捕获后,发送到工作线程进行处理。
这个想法对吗?有没有更好的策略来解决这个问题?
演示:
int main(int argc, char *argv[])
{
cv::Mat buffer;
cv::VideoCapture cap;
std::mutex mutex;
cap.open(0);
std::thread product([](cv::Mat& buffer, cv::VideoCapture cap, std::mutex& mutex){
while (true) { // keep product the new image
cv::Mat tmp;
cap >> tmp;
mutex.lock();
buffer = tmp.clone(); // copy the value
mutex.unlock();
}
}, std::ref(buffer), cap, std::ref(mutex));
product.detach();
while (cv::waitKey(20)) { // process in the main thread
mutex.lock();
cv::Mat tmp = buffer.clone(); // copy the value
mutex.unlock();
if(!tmp.data)
std::cout<<"null"<<std::endl;
else {
std::cout<<"not null"<<std::endl;
cv::imshow("test", tmp);
}
}
return 0;
}或者使用线程继续清除缓冲区。
int main(int argc, char *argv[])
{
cv::Mat buffer;
cv::VideoCapture cap;
std::mutex mutex;
cap.open(0);
std::thread product([](cv::Mat& buffer, cv::VideoCapture cap, std::mutex& mutex){
while (true) { // keep product the new image
cap.grab();
}
}, std::ref(buffer), cap, std::ref(mutex));
product.detach();
int i;
while (true) { // process in the main thread
cv::Mat tmp;
cap.retrieve(tmp);
if(!tmp.data)
std::cout<<"null"<<i++<<std::endl;
else {
cv::imshow("test", tmp);
}
if(cv::waitKey(30) >= 0) break;
}
return 0;
}第二个演示我认为应该是基于https://docs.opencv.org/3.0-beta/modules/videoio/doc/reading_and_writing_video.html#videocapture-grab的工作,但它不是…
发布于 2019-03-26 04:28:46
在多目标跟踪项目中,我使用了两个帧缓冲区(cv::Mat frames2)和两个线程:
用于捕获下一帧的
我使用index = 0,1进行缓冲区交换,这个索引是由互斥保护的。关于工作结束的信号使用了2个条件变量。
First与framescapture_ind buffer一起使用捕获,而Tracking则与前一帧1- CatureAndDetect _ind buffer一起使用。下一步-切换缓冲区: capture_ind =1- capture_ind。
你可以在这里做这个项目吗:Multitarget-tracker。
https://stackoverflow.com/questions/55273689
复制相似问题