先看一段代码,这段代码是有问题的,问题在于:因为电脑开启摄像头需要一定的时间,所以frame = cvQueryFrame(capture);第一次执行完后没法获取到第一帧。
#include "cv.h"
#include "highgui.h"
int main( int argc, char** argv ) {
cvNamedWindow( "Example2_9", CV_WINDOW_AUTOSIZE );
CvCapture* capture;
if (argc==1) {
capture = cvCreateCameraCapture( 0 );
} else {
capture = cvCreateFileCapture( argv[1] );
}
assert( capture != NULL );
IplImage* frame;
while(1) {
frame = cvQueryFrame( capture );
if( !frame ) break;//问题在这里
cvShowImage( "Example2_9", frame );
char c = cvWaitKey(10);
if( c == 27 ) break;
}
cvReleaseCapture( &capture );
cvDestroyWindow( "Example2_9" );
}
解决方法是判断摄像头是否打开,最简单的方法是直接删掉if( !frame ) break;这一句
其他方法:
#include <iostream>
using namespace std;
using namespace cv;
void main()
{
Mat input_image;
VideoCapture cam(0);
if(!cam.isOpened()) exit(0);
namedWindow("input image");
while(true) {
cam >> input_image;
imshow("input image", input_image);
if(27 == waitKey(30))
break;
}
}
里面有cam.isOpened(),会执行开启摄像头的操作,判断摄像头是否已经打开,然后再执行读取,自然不会出现问题
文章引用:888哈喽888
http://tieba.baidu.com/p/3360152308