opencv 读取摄像头失败

最近在做opencv读取摄像头的实验,用的网上的实例代码如下:

#include 
#include 
#include 
using namespace cv;
int main()
{
	VideoCapture cap(0);
	if(!cap.isOpened())
	{
		return -1;
	}
	Mat frame;
	Mat edges;


	bool stop = false;
	while(!stop)
	{
		cap>>frame;
		cvtColor(frame, edges, CV_BGR2GRAY);
		GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
		Canny(edges, edges, 0, 30, 3);
		imshow("当前视频",edges);
		if(waitKey(30) >=0)
			stop = true;
	}
	return 0;
}
但是出现了如下错误:

opencv 读取摄像头失败_第1张图片

分析是在cap>>frame这里,获取出现frame为空,但也有可以正常运行的。

加入了waitKey函数,重新修改代码,

int main()
{
int cameraNumber = 0;
 
     VideoCapture camera;
    camera.open(cameraNumber);
    if ( !camera.isOpened() ) {
         cerr << "ERROR: Could not access the camera or video!" << endl;
         exit(1);
    }
 
     int CAMERA_CHECK_ITERATIONS = 10;
     while (true) {
         Mat cameraFrame;
         camera >> cameraFrame;   
         if ( !cameraFrame.empty() ) {
             imshow("Video", cameraFrame);
           cvtColor(cameraFrame, edges, CV_BGR2GRAY); 
             GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);  
	     Canny(edges, edges, 0, 30, 3); 
            int key = waitKey(1);
             if ( key == 27 )    break;
        } else {
             cout << "::: Accessing camera :::" << endl;
            if ( CAMERA_CHECK_ITERATIONS > 0 ) CAMERA_CHECK_ITERATIONS--;
             else  break;
          }
     }
 
}

openv中对cvWaitkey函数的定义如下:

int cvWaitKey( int delay=0 )

返回值为int型,函数的参数为int型,当delay小于等于0的时候,如果没有键盘触发,则一直等待,此时的返回值为-1,否则返回值为键盘按下的码字;当delay大于0时,如果没有键盘的的触发,则等待delay的时间,此时的返回值是-1,否则返回值为键盘按下的码字。

参考:

http://www.tuicool.com/articles/jYjEj2Y

http://stackoverflow.com/questions/3940780/opencv-c-video-capture-does-not-seem-to-work

你可能感兴趣的:(opencv学习)