OpenCV从缓冲区写入和读取 [英] Opencv writing and reading from a buffer
问题描述
我有两个任务(线程),每个任务运行在不同的处理器(核心)上,第一个任务使用OpenCV videocapture()
重复捕获图像.
I have two tasks (Threads) each task runs on a different processor(core), the first capture an image repeatedly using OpenCV videocapture()
.
我仅将这两行用于捕获:
I only used these two lines for the capture :
cv::Mat frame;
capture.read(frame);
现在,我想使用第二个任务显示捕获的图像.在第二个任务的代码中执行imshow
函数后:
Now I want to display the captured image using the second task. After executing the imshow
function within the second task's code :
cv::imshow("Display window", frame);
我收到以下输出错误:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /build/opencv-L2vuMj/opencv-3.2.0+dfsg/modules/highgui/src/window.cpp, line 304
terminate called after throwing an instance of 'cv::Exception'
what(): /build/opencv-L2vuMj/opencv-3.2.0+dfsg/modules/highgui/src/window.cpp:304: error: (-215) size.width>0 && size.height>0 in function imshow
那么,如何避免此错误?
So, how can I avoid this error?
完整的代码位于 Github
推荐答案
您的代码存在的问题是存在数据争用.尝试在读取之前显示它,以便您可以看到问题 如果需要同步解决方案,则可以使用pthread条件&等到读取图像以指示您的显示功能,否则您将一直处于等待状态!
The problem with your code is that there is a data race.. Imagine the display thread goes first lock the frame & try to display it before it is read so as you can see the problem If you want a synchronized solution you can use the pthread condition & wait till an image is read to signal your display function otherwise you are gonna have an active wait!!
// in the declaration part
// Declaration of thread condition variable
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
//in the display function
ptask DisplyingImageTask()
{
int task_job = 0;
while (1)
{
std::cout << "The job " << task_job << " of Task T" << ptask_get_index()
<< " is running on core " << sched_getcpu() << " at time : "
<< ptask_gettime(MILLI) << std::endl;
cv::namedWindow("Display window", cv::WINDOW_AUTOSIZE);
pthread_mutex_lock(&frame_rw);
//wait for the read function to send a signal
pthread_cond_wait(&cond1, &frame_rw);
cv::imshow("Display window", frame);
cv::waitKey(1);
pthread_mutex_unlock(&frame_rw);
ptask_wait_for_period();
task_job++;
}
}
// in the Read function
ptask CapturingImageTask()
{
int task_job = 0;
while (1)
{
std::cout << "The job " << task_job << " of Task T" << ptask_get_index()
<< " is running on core " << sched_getcpu() << " at time : "
<< ptask_gettime(MILLI) << std::endl;
pthread_mutex_lock(&frame_rw);
capture.read(frame);
//after capturing the frame signal the display function & everything should be synchronize as you want
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&frame_rw);
ptask_wait_for_period();
task_job++;
}
}
这篇关于OpenCV从缓冲区写入和读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!