opencv3/C++ 从视频中获取人脸数据

在利用opencv_traincascaded训练样本数据中需要人脸图片作为正样本数据,人脸图片可以通过下载公开数据集或自己采集获得。此处通过提取视频中的人脸来获得需要的人脸图片。

#include
//#include
using namespace cv;

int main()  
{  
    CascadeClassifier faceCascader, eyeCascader;
    String filename1 = "D:/opencv3.1.0/opencv/tools/opencv_contrib/install/etc/haarcascades/haarcascade_frontalface_alt.xml";
    if (!faceCascader.load(filename1))
    {
        printf("can not load the face feature data \n");
        return -1;
    }
    namedWindow("input", WINDOW_AUTOSIZE);
    namedWindow("output", WINDOW_AUTOSIZE);
    VideoCapture capture;
    char filename[100];
    //读取视频文件
    capture.open("E:/image/broke_girls.mkv");
    if (!capture.isOpened())
    {
        printf("can not load the video \n");
        return -1;
    }
    Mat frame, gray, faceROI, src;
    std::vector faces, eyes;
    int k = 0;
    while (capture.read(frame))
    {
        src = frame;
        cvtColor(frame, gray, COLOR_BGR2GRAY);
        equalizeHist(gray, gray);
        faceCascader.detectMultiScale(gray, faces,1.2, 3, 0, Size(100, 100));
        for (int i = 0; i < faces.size(); i++)
        {
            Rect roi;
            roi.x = faces[static_cast<int>(i)].x + 2;
            roi.y = faces[static_cast<int>(i)].y + 2;
            roi.width = faces[static_cast<int>(i)].width - 2;
            roi.height = faces[static_cast<int>(i)].height - 2;
            //人脸所在的感兴趣区域
            faceROI = frame(roi);
            rectangle(frame, faces[static_cast<int>(i)], Scalar(0,255,0), 1, 8, 0);
            k++;
            //将人脸图像的大小统一调整为150*150
            resize(faceROI,faceROI,Size(150,150));
            //输出文件路径
            sprintf(filename,"E:/img/%d.jpg",k);
            imwrite(filename, faceROI);
        }
        char q = waitKey(1);
        if (q == 27)
        {
            break;
        }
        imshow("input", frame);
        imshow("output", faceROI);

    }
    waitKey(0);
    capture.release();
    return 0;  
} 

opencv3/C++ 从视频中获取人脸数据_第1张图片

之后可以在输出路径下看到采集到的人脸图片:

opencv3/C++ 从视频中获取人脸数据_第2张图片

你可能感兴趣的:(OpenCV)