How to start camera in OpenCV and draw a rectangle on a detection? Nullpointer exception.
I want to start my Webcam and draw a Rectangle based on the regions returned by face detection. The compiler of Code::Blocks says no error while compiling. If i want to "Run" the Code the webcam started and in a few second after stoped it and i get this Error in Terminal:
http://imageshack.us/photo/my-images/835/20130423173054486x346sc.png/
So i have the following code:
#include "/usr/local/include/opencv/cv.h"
#include "/usr/local/include/opencv/highgui.h"
#include <iostream>
#include <cstdio>
using namespace std;
using namespace cv;
CvRect *r;
const string haarcascade_face = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml";
const string haarcascade_eye = "/usr/local/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml";
////String window_name = "Capture - Face detection";
CvHaarClassifierCascade* cascade;
CvMemStorage* storage;
void detectAndDisplay( IplImage* img);
int main()
{
CascadeClassifier cascade_face, cascade_eye;
char c;
cascade = (CvHaarClassifierCascade*)cvLoad("/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml");
CvCapture *capture = 0;
IplImage *frame;
if(!cascade_face.load(haarcascade_face))
{
cout << "[ERROR]: Could not load classifier cascade Face" <<endl;
return -1;
}
if(!cascade_eye.load(haarcascade_eye))
{
cout << "[ERROR]: Could not load classifier cascade Eye" <<endl;
return -1;
}
capture = cvCaptureFromCAM(0); // select camera
if(capture == NULL)
{
cout << "[ERROR] No camera found!" << endl;
return -1;
}
// loop forever till ESC
for(;;)
{
// capture a frame from the camera
frame = cvQueryFrame(capture);
// display it
if(!frame) break;
detectAndDisplay(frame);
// test for ESC
c = cvWaitKey(33);
if(c == 27 /* ESC */)
break;
}
return 0;
}
void detectAndDisplay(IplImage* img)
{
int i;
CvSeq* faces = cvHaarDetectObjects(img, cascade, storage, 1.1, 3, CV_HAAR_DO_CANNY_PRUNING, cvSize (100, 100));
for(i = 0; i<(faces ? faces->total:0); i++)
{
r=(CvRect*)cvGetSeqElem(faces,i);
cvRectangle(img,
cvPoint(r->x, r->y),
cvPoint(r->x + r->width, r->y + r->height),
CV_RGB(255,0,0), 1, 8, 0);
}
cvShowImage("Capture - Face Detection", img);
}
I dont know what the problem is, can someone help me solve this problem?
Thank you for helping me!!!
I tried your program and the null pointer exception was resolved just giving memory to the storage in the loop: storage = cvCreateMemStorage(0);
Hope will help you!