OpenCV之人脸识别(训练模型-->保存模型--->使用模型)
一、概述
案例:使用OpenCV训练模型并将自己识别出来。其中包含了训练模型、保存模型、使用模型
训练模型步骤:
1.加载采集好的数据文件,并将图片和图片对一个的标签存入vector
2.准备一个测试数据,ps:从采集的文件中取
3.实例化特征脸人脸识别模型EigenFaceRecognizer model
4.训练模型model->trans
保存模型及加载模型:
1.保存模型:model->save(模型路径)
2.加载模型:Ptr
使用训练好的模型进行人脸识别步骤:
1.实例化并加载训练好的人脸数据模型
2.使用级联分类器加载人脸模型
3.实例化VideoCapture加载视频文件(或打开摄像头)
4.while循环读取frame
4.1在frame中找到人脸roi区域
4.2.对roi区域灰度化
4.3.对roi区域执行model->predict(roi)进行预测
4.4.如果预测结果为101(我自己人脸的标签值),则说明把我自己识别出来了。
4.5循环4步骤,直到视频播放结束(或关闭摄像头)
二、代码示例
Face_Recognizer_My_Face::Face_Recognizer_My_Face(QWidget *parent)
: MyGraphicsView{parent}
{
this->setWindowTitle("人脸识别小案例");
QPushButton *btn = new QPushButton(this);
btn->setText("选择视频文件");
connect(btn,&QPushButton::clicked,[=](){
chooseVideoFile();
});
}
void Face_Recognizer_My_Face::chooseVideoFile(){
QString filePath = QFileDialog::getOpenFileName(this,"选择视频文件","/Users/yangwei/Downloads/","数据文件(*.mp4)");
qDebug()< images;
vector labels;
while(getline(file,line)){
stringstream liness(line);
getline(liness,path,' ');
getline(liness,classLabel);
images.push_back(imread(path, 0));
labels.push_back(atoi(classLabel.c_str()));
}
if(images.size()<1||labels.size()<1){
qDebug()<<"准备的训练数据不对";
return;
}
int width = images[0].cols;
int height = images[0].rows;
cout << "width:"< model = EigenFaceRecognizer::create();
// //训练
// model->train(images,labels);
// model->save("/Users/yangwei/Documents/tony/opencv/myfaces/test.txt");
Ptr model =Algorithm::load("/Users/yangwei/Documents/tony/opencv/myfaces/test.txt");
//预测
int predictLabel = model->predict(testMat);
cout <<"测试标签:"< faces;
while(capture.read(frame)){
faceDetector.detectMultiScale(frame,faces,1.1,3,0,Size(100,100),Size(400,400));
for(int i=0;ipredict(testMat);
rectangle(frame,faces[i],Scalar(255,0,0),2,8,0);
putText(frame, format("i'm %s", (label == 110 ? "yw.yang" : "Unknow")), faces[i].tl(), FONT_HERSHEY_PLAIN, 1.0, Scalar(0, 0, 255), 2, 8);
}
imshow("frame",frame);
int key = waitKey(1);
if(key==27){
break;
}
}
}
三、演示图像