Ask Your Question

Revision history [back]

You should crop the detected face from the image like this:

std::vector<Rect> faces;
//detect and store faces in faces:
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

//save all detected faces to disk (or the face you like):
for (size_t i = 0; i < faces.size(); i++)
{
    Mat face_roi;
    frame(faces[i]).copyTo(face_roi);

    char name[20];
    sprintf_s(name,"face_%d.png", i);

    imwrite(string(name), face_roi);
}

Complete code here:

 CascadeClassifier face_cascade;

 int main(int argc, const char** argv)
 {  
  CvCapture* capture;
  string face_cascade_name = "haarcascade_frontalface_alt.xml";
  string image_name = "The_Faces_(1970).png";
  Mat frame;

  //-- 1. Load the cascades
  if (!face_cascade.load(face_cascade_name)){ printf("--(!)Error loading\n"); return -1; };

  frame = imread(image_name);

  detectAndSave(frame);
  return 0;
 }

void detectAndSave(Mat frame)
{
 std::vector<Rect> faces;
 Mat frame_gray;

 cvtColor(frame, frame_gray, CV_BGR2GRAY);
 equalizeHist(frame_gray, frame_gray);

 //-- Detect faces
 face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));

 for (size_t i = 0; i < faces.size(); i++)
 {
    Mat face_roi;
    frame(faces[i]).copyTo(face_roi);

    char name[20];
    sprintf_s(name,"face_%d.png", i);

    imwrite(string(name), face_roi);
 }
}

image description

image description