opencv2.4.8 在win7下无法打开摄像头,或者摄像头灰色图像,我折腾了一晚上还没解决,其实很奇怪,这个是官方的例子,为什么会跑不出来呢?
后来看了下程序的逻辑,发现在打开摄像头的时候,程序马上会进入while循环,由于摄像头的启动要一定的时间,这时候自然没办法获取到第一帧,所以程序直接break了。我的解决方案是sleep一下。如果你的代码也是我的这个逻辑,估计都可以这样解决。代码如下:
// testOpenCvVideo.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> #include <stdlib.h> #include "cv.h" #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #pragma comment( lib, "opencv_core248d.lib" ) #pragma comment( lib, "opencv_highgui248d.lib" ) using namespace cv; int g_slider_position = 0; CvCapture* g_capture = NULL; void onTrackbarSlide(int pos) { cvSetCaptureProperty( g_capture, CV_CAP_PROP_POS_FRAMES, pos ); } int _tmain(int argc, _TCHAR* argv[]) { /* cvNamedWindow( "Example3", CV_WINDOW_AUTOSIZE ); // g_capture = cvCreateFileCapture("../test.avi"); g_capture = cvCreateCameraCapture(0); /* int frames = (int) cvGetCaptureProperty( g_capture, CV_CAP_PROP_FRAME_COUNT ); if( frames!= 0 ) { cvCreateTrackbar("Position","Example3",&g_slider_position,frames,onTrackbarSlide); } cvSetTrackbarPos("Position","Example3",10); int NewPos=g_slider_position; */ /* IplImage* frame; while(1) { frame = cvQueryFrame( g_capture ); if( !frame ) break; cvShowImage( "Example3", frame ); char c = cvWaitKey(30); if( c == 27 ) break; // cvCreateTrackbar("Position","Example3",&NewPos,frames,onTrackbarSlide); // NewPos++; } cvReleaseCapture( &g_capture ); cvDestroyWindow( "Example3" ); return 0; */ //声明IplImage指针 IplImage* pFrame = NULL; //获取摄像头 CvCapture* pCapture = cvCreateCameraCapture(0); // CvCapture* pCapture = cvCaptureFromCAM(-1); //创建窗口 cvNamedWindow("video", CV_WINDOW_AUTOSIZE); Sleep(2000); //显示视屏 while(1) { pFrame=cvQueryFrame( pCapture ); if(!pFrame)break; cvShowImage("video",pFrame); char c=cvWaitKey(33); if(c==27)break; } cvReleaseCapture(&pCapture); cvDestroyWindow("video"); return 0; }