1.准备训练数据
网络上下载(训练数据量大时,通过爬虫获取)目标的图片:
运用以下代码将原图中的
人脸头像识别、提取、调整大小(这里是150*200),并分别保存。
运行环境:win7 64+VS2013+openCV3.1。
(PS:抱怨下vs和opencv的版本密切相关,注意安装配置)
#include <opencv2\opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/videoio/videoio_c.h>
#include <opencv2/highgui/highgui_c.h>
using namespace std;
using namespace cv;
/** Function Headers */
void detectAndDisplay(Mat frame);
/** Global variables */
String face_cascade_name = "F:\\Downloads\\opencv_build\\install\\etc\\haarcascades\\haarcascade_frontalface_default.xml";
String eyes_cascade_name = "F:\\Downloads\\opencv_build\\install\\etc\\haarcascades\\haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade; //定义人脸分类器
CascadeClassifier eyes_cascade; //定义人眼分类器
String window_name = "Capture - Face detection";
/** @function main */
int main(void)
{
//-- 1. Load the cascades
if (!face_cascade.load(face_cascade_name)){ printf("--(!)Error loading face cascade\n"); return -1; };
if (!eyes_cascade.load(eyes_cascade_name)){ printf("--(!)Error loading eyes cascade\n"); return -1; };
//-- 2. 遍历原图像文件夹
vector<String> files;
glob("D:\\training\\liudh_before\\*.jpg", files, true);
//-- 3. 识别、提取,并保存头像至新文件夹。图片均调整为150x200像素
for (int i = 0; i < files.size(); i++)
{
//Image processing
Mat img = imread(files[i]); //读取文件
cout << files[i] << '\n';
detectAndDisplay(img); //提取头像
waitKey(1000);
}
}
/** @function detectAndDisplay */
void detectAndDisplay(Mat frame)
{
static int count = 0;
std::vector<Rect> faces;
Mat frame_gray;
Mat MyFace;
cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
//equalizeHist(frame_gray, frame_gray);
//imshow(