Ask Your Question
0

How to crop a single face out of several faces detected?

asked 2015-03-09 09:50:18 -0500

Hello,

I am a beginner to openCV and I have to detect a face in a video stream. I know how to detect face using inbuilt face but I don't know how to crop face of a particular person and store it to hard disk. I am using crop function to do so in matlab but it results to an error.

Any suggestion will be highly appreciated...

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-03-09 10:53:18 -0500

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

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2015-03-09 09:50:18 -0500

Seen: 1,202 times

Last updated: Mar 09 '15