0
votes

I have following piece of code, detectFacialFeatures is called in loop (on frame capture from cam). This retrieves the faces properly and I can see them in the image window. However, I need to do som processing when someone clicks on any of the faces found (rectangle drawn on them in img). To do this, I am setting a mousecallback which passes the vector faces as void*. But when am casting it back to vector am not getting the original object back. The code,

cout << faces->size() << endl;;

returns garbage value. Not sure what am I doing wrong.

void FaceDetect::detectFacialFeatures(Mat img)
{
  Mat img_gray;
  cvtColor(img, img_gray, CV_BGR2GRAY);
  equalizeHist( img_gray, img_gray );
  vector<Rect> faces;

  if( !cascade.empty() )
    cascade.detectMultiScale( img_gray, faces, 1.1, 3, 0|CV_HAAR_SCALE_IMAGE, Size(40, 40) );
  else
    printf("\nFrontal face cascade not loaded\n");

  for(unsigned int i = 0 ; i < faces.size() ; i++ )
  {
    Rect face  = faces.at(i);
    rectangle(img, face, CV_RGB(255, 0, 0), 1, 8, 0);

    cout << face.size() << "or" << endl;
    Mat faceImg = img(face);
  }
  imshow(winname, img);
  setMouseCallback(winname, onMouse, (void*)&faces);
}


void FaceDetect::onMouse(int event, int x, int y, int z, void* param)
{
    if  ( event == EVENT_LBUTTONDOWN )
    {
        vector<Rect>* faces = (vector<Rect>*) param;
        Point pt(x, y);
        cout << faces->size() << endl; //This code returns garbage value
    }
}
1

1 Answers

1
votes

faces is a stack-allocated variable which will get destructed when the detectFacialFeatures function exists. You should either heap-allocate the vector, or pass an existing one in as an argument. Heap allocation:

vector<Rect>* faces = new vector<Rect>();  

Also, you should not use C-style casts in C++. In this example you should use static_cast.

vector<Rect>* faces = static_cast<vector<Rect>*>(param);