OpenCV:23.实时人脸检测和识别

具体代码请看:NDKPractice项目的opencv71

1. 训练人脸样本

三种训练方法:

  • eigenFace 算法 : EigenFaceRecognizer
  • FisherFace 算法:FisherFaceRecognizer
  • LBPH 算法:LBPHFaceRecognizer

网站1

网站2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Java_com_east_opencv71_FaceDetection_trainingPattern(JNIEnv *env, jobject instance) {
// 训练样本,这一步是在数据采集做的
// train it
vector<Mat> faces;
vector<int> labels;

// 样本比较少
for (int i = 1; i <= 5; ++i) {
for (int j = 1; j <= 5; ++j) {
Mat face = imread(format("/storage/emulated/0/s%d/%d.pgm", i, j), 0);
if (face.empty()) {
LOGE("face mat is empty");
continue;
}
// 确保大小一致
resize(face, face, Size(128, 128));
faces.push_back(face);
labels.push_back(i);
}
}

for (int i = 1; i <= 8; ++i) {
Mat face = imread(format("/storage/emulated/0/face_%d.png", i), 0);
if (face.empty()) {
LOGE("face mat is empty");
continue;
}
resize(face, face, Size(128, 128));
faces.push_back(face);
labels.push_back(11);
}

// 训练方法
Ptr<BasicFaceRecognizer> model = EigenFaceRecognizer::create();
// 采集了八张,同一个人 label 一样
model->train(faces, labels);
// 训练样本是 xml ,本地
model->save("/storage/emulated/0/face_darren_pattern.xml");// 存的是处理的特征数据
LOGE("樣本訓練成功");
}

2. 识别人脸

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Java_com_east_opencv71_FaceDetection_loadPattern(JNIEnv *env, jobject instance,
jstring patternPath_) {
const char *patternPath = env->GetStringUTFChars(patternPath_, 0);
// 加载样本数据,Error:(142, 12) error: no matching member function for call to 'load' 怎么搞?
// model->load(patternPath);
FileStorage fs(patternPath, FileStorage::READ);
// 报错,没有提示
// CV_Assert(fs.isOpened());
// 抛个 java 异常
FileNode fn = fs.getFirstTopLevelNode();
model->read(fn);
env->ReleaseStringUTFChars(patternPath_, patternPath);
LOGE("训练样本加载成功");
}
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%