OpenCV C++程序使用C API cvClearMemStorage空指针错误

OpenCV C++ program using C API cvClearMemStorage null pointer error

我正在开始使用OpenCV,它是C API,我写了这个人脸检测程序,但它无法执行,我使用的是OpenCV 2.4.9,这是我的代码:

#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace cv;
using namespace std;
String faceCascade_name = "haarcascade_frontalface_default.xml";
char* name = "res";
CvHaarClassifierCascade* faceCascade;
CvMemStorage* storage = 0;

int detectAndDisplay( IplImage* frame );

int main(int argc, char** argv){
  CvCapture* capture;
  capture = cvCaptureFromCAM(CV_CAP_ANY);
  faceCascade = (CvHaarClassifierCascade*)cvLoad( faceCascade_name.c_str() );
  IplImage* frame;
  cvNamedWindow(name, 1);
  if( !faceCascade){
    printf("--(!)Error loading face cascade\n"); 
    return -1; 
  }
  if ( !capture ) {
    printf("--(!)Error opening video capture\n");
    return -1;
  }

  while( true ){
    frame = cvQueryFrame(capture);
    detectAndDisplay(frame);
    if(cvWaitKey(30) == 27){
      break;
    }
  }
  return 0;
}

int detectAndDisplay( IplImage* frame ){
    int scale = 1;
    int i;
    CvPoint pt1, pt2;
    cvClearMemStorage(storage);
    CvSeq* faces = cvHaarDetectObjects( &frame, faceCascade, storage, 1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/, cvSize(24, 24) );
    for( i = 0; i < (faces ? faces->total : 0); i++ ){
        // Create a new rectangle for drawing the face
        CvRect* r = (CvRect*)cvGetSeqElem( faces, i );

        // Find the dimensions of the face,and scale it if necessary
        pt1.x = r->x*scale;
        pt2.x = (r->x+r->width)*scale;
        pt1.y = r->y*scale;
        pt2.y = (r->y+r->height)*scale;

        // Draw the rectangle in the input image
        cvRectangle( &frame, pt1, pt2, CV_RGB(255,0,0), 3 );
        }
  cvShowImage(name, &frame);
  return 0;
}

但是,我在执行编译后的程序时出现如下错误:

OpenCV Error: Null pointer () in cvClearMemStorage, file C:\builds_4_PackSlave-win32-vc12-shared\opencv\modules\core\src\datastructs.cpp

请告诉我如何修复它,如果您有更多时间,请为我完成程序!

使用新的API。来自 CvMemStorage 上的 OpenCV 2.4 文档:

The section describes OpenCV 1.x API for creating growable sequences and other dynamic data structures allocated in CvMemStorage. If you use the new C++, Python, Java etc interface, you will unlikely need this functionality. Use std::vector or other high-level data structures

也就是说,如果你想继续使用CvMemStorage,你需要先给结构体分配内存。根据文档:

A new memory buffer that may be allocated explicitly by MemStorageAlloc() function or implicitly by higher-level functions, such as SeqPush(), GraphAddEdge() etc

有关详细信息,请参阅 http://docs.opencv.org/2.4/modules/core/doc/dynamic_structures.html

另外,在创建结构的时候,需要给cvCreateMemStorage传入一个整数。同样,文档:

CvMemStorage* cvCreateMemStorage(int block_size=0 ) Parameters: block_size – Size of the storage blocks in bytes. If it is 0, the block size is set to a default value - currently it is about 64K.

不这样做可能会导致您的参数错误