Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

if you have stored your images in a folder per person, like:

+- persons
    +- john
       +- img1.png
       +- img2.png
    +- mary
       +- z42341.png
       +- dsc10.png

you can try similar to this:

int train(Ptr<face::FaceRecognizer> classifier, const String &imgdir, const Size &siz)
{
    string last_n("");
    int label(-1);

    Mat images;
    Mat labels;

    vector<String> vec;
    glob(imgdir,vec,true);
    if ( vec.empty())
        return 0;

    for (size_t i=0; i<vec.size(); i++)
    {
        // extract name from filepath:
        String v = vec[i];
        int r1 = v.find_last_of(SEP);
        String v2 = v.substr(0,r1);
        int r2 = v2.find_last_of(SEP);
        String n = v2.substr(r2+1);
        if (n!=last_n)
        {
            last_n=n;
            label++;
        }
        persons[label] = n;

        // process img & add to trainset:
        Mat img=imread(vec[i],0);
        if (img.empty())
        {
               cerr << "bad image " << vec[i] << endl;
               continue;
        }
        resize(img,img,siz);
        images.push_back(img);
        labels.push_back(label);
    }
    return classifier->train(images, labels);
}

////
Ptr<face::FaceRecognizer> facerec = face::createLBPHFaceRecognizer();
train(facerec, "persons", Size(100,100));

please also have a look at http://docs.opencv.org/ref/master/tutorial_face_main.html