永发信息网

vs2008+opencv2.4.9 打开摄像头程序异常退出

答案:2  悬赏:10  手机版
解决时间 2021-12-25 12:24
  • 提问者网友:了了无期
  • 2021-12-25 05:37
vs2008+opencv2.4.9 打开摄像头程序异常退出,这程序是借鉴来的,编译没错,运行就自动退出
线程 'Win32 线程' (0xad4) 已退出,返回值为 -1 (0xffffffff)。
线程 'Win32 线程' (0x1250) 已退出,返回值为 -1 (0xffffffff)。
线程 'Win32 线程' (0xbd0) 已退出,返回值为 -1 (0xffffffff)。
程序“[168] CameraTest.exe: 本机”已退出,返回值为 -1 (0xffffffff)。
代码如下
#include
#include

int main()
{
char title[128];
IplImage *img = 0;
int key = 0;

CvCapture* capture = cvCaptureFromCAM(-1);
// If no compatible camera detected, print message and exit.
if (capture == NULL) {
printf("No camera detected!\n");
exit(-1);
}

// query frame and generate window title
img = cvQueryFrame(capture);
if (img == NULL) {
printf("Camera detected, but grab image error!\n");
exit(-1);
}
sprintf(title, "Camera Testing (%dx%d)", img->width, img->height);

// create a window at the top-left corner
cvNamedWindow(title, CV_WINDOW_AUTOSIZE);
cvMoveWindow(title, 0, 0);

while(1)
{
img = cvQueryFrame(capture);
// show the frame in the window created
cvShowImage(title, img);

key = cvWaitKey(20); // wait 20 ms
if ( key == 's' || key == 'S')
{
cvSaveImage("test.jpg", img);
continue;
}
if ( key > 0)
break;
}
// destroy the window and release the capture
cvDestroyWindow(title);
cvReleaseCapture( &capture );
return 0;
}
最佳答案
  • 五星知识达人网友:深街酒徒
  • 2021-12-25 06:19
程序应该是在这两个地方出了问题:
1. if (capture == NULL) {
        printf("No camera detected!\n");
        exit(-1);
    }
2. if (img == NULL) {
        printf("Camera detected, but grab image error!\n");
        exit(-1);
    } 
第一段的作用是判断摄像头有没有启动成功,第二段的作用是在判断有没有从摄像头读到图像。
“CvCapture* capture = cvCaptureFromCAM(-1);”这件话的作用是打开摄像头。
因为摄像头启动和图像读取都需要一定的时间,所以程序运行到这两个判断步时,摄像头可能还没有启动或者启动后获取的图像还未能传输到相应位置,进而会触发相应判断条件而执行“exit(-1)”,引起程序异常退出。
你可以在调试程序时分别在这两个判断语句中设置断点来验证是不是该处出现了问题。
如果问题是出现在这里,解决方法如下:
把两个判断条件段改为
while(1)
{
      if (capture !=NULL)
          break;
}

while(1)
{
     if (img!=NULL)
         break;
}
如果问题不是出现在这里,欢迎继续交流。(我也是刚接触opencv,遇到过类似的问题。回答若有不准确的地方请包涵并指出。)
全部回答
  • 1楼网友:像个废品
  • 2021-12-25 07:38
百度一下 资源很多
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯