我有一個程序,使用OpenCV庫(版本2.4.1)從我的筆記本電腦的攝像頭(或任何其他連接的攝像頭)捕捉視頻並將其保存到.avi文件。當我在Visual Studio 2010中進行調試時,在CvCapture或IplImage被釋放時,程序的最後會出現未處理的異常。下面是代碼:未處理的異常 - OpenCV - cvReleaseCapture和cvReleaseImage - C++
// WriteRealTimeCapturedVideo.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
int main()
{
CvCapture* capture = cvCaptureFromCAM(1); //CV_CAP_ANY
if (!capture)
{
fprintf(stderr, "ERROR: capture is NULL \n");
getchar();
return -1;
}
// Create a window in which the captured images will be presented
cvNamedWindow("mywindow", CV_WINDOW_AUTOSIZE);
double fps = cvGetCaptureProperty (capture, CV_CAP_PROP_FPS);
CvSize size = cvSize((int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH), (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT));
#ifndef NOWRITE
CvVideoWriter* writer = cvCreateVideoWriter("Capture.avi", CV_FOURCC('M','J','P','G'), fps, size); //CV_FOURCC('M','J','P','G')
#endif
int width = (int)(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH));
int height = (int)(cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT));
IplImage* frame = cvCreateImage(cvSize(width,height), IPL_DEPTH_8U, 1);
while (1)
{
// Get one frame
frame = cvQueryFrame(capture);
if (!frame)
{
fprintf(stderr, "ERROR: frame is null...\n");
getchar();
break;
}
cvShowImage("mywindow", frame);
#ifndef NOWRITE
cvWriteToAVI(writer, frame);
#endif
char c = cvWaitKey(33);
if(c == 27) break;
}
#ifndef NOWRITE
cvReleaseVideoWriter(&writer);
#endif
cvDestroyWindow("mywindow");
cvReleaseImage(&frame);
cvReleaseCapture(&capture);
return 0;
}
我發現,我必須有tbb.dll和tbb_debug.dll在同一個目錄中的源代碼(.cpp文件)的程序協同工作。這些DLL可以從英特爾下載。
視頻捕捉工作,即出現窗口並顯示視頻,但無論如何重新排列發佈語句,都會發生異常。如果我刪除發佈語句(VideoWriter除外),我沒有得到例外,但是生成的.avi文件無法打開。當用戶按下Esc鍵時程序退出while循環。
感謝另一個代碼。它現在有效。我還必須將fps更改爲一個常數值(30.0),以便從文件播放捕獲的視頻。 IplImage * frame = cvQueryFrame(capture)行是否爲每一幀分配新內存?這個內存什麼時候發佈? –
IplImage * frame = cvQueryFrame(capture);將不分配內存,這將返回一個指向捕獲緩衝區中圖像之一的指針。如果您想對從相機獲取的圖像進行任何處理,您應該創建一個「幀」的副本。如果您只想顯示或保存圖像,則不需要創建副本。 – alinoz