在学习用OpenCV获取摄像头视频时,运行过程中出现中断异常:
在终端中提示:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file ..\..\..\..\opencv\modules\highgui\src\window.cpp, line 261
源程序的主要代码如下:
// 读取摄像头的程序
VideoCapture capture(0);
if (!capture.isOpened())
{
return -1;
}
bool stop(false);
Mat frame;
namedWindow("Camera");
while (!stop)
{
capture >> frame;
imshow("Camera", frame);
if (waitKey(30) >= 0)
stop = true;
}
capture.release();
这个错误的原因在于imshow要显示的Mat为空的,解决方法是 在第一次调用摄像头的imshow前面加一条判断不为空的语句,具体代码如下:
// 读取摄像头的程序
VideoCapture capture(0);
if (!capture.isOpened())
{
return -1;
}
bool stop(false);
Mat frame;
namedWindow("Camera");
while (!stop)
{
capture >> frame;
if (!frame.empty()) // 先判断frame是否为空
imshow("Camera", frame);
if (waitKey(30) >= 0)
stop = true;
}
capture.release();