前提
感謝網絡上相頭的博客和資料,由於版本的原因有些api的更改使得源代碼不能直接使用,所以這裏放上自己基於opencv3.4做的測試。
流程
- 打開攝像頭
- 保存自己的頭像
- 整理自己頭像模型訓練
- 識別
淺出
打開攝像頭識別自己的頭像並保存
- 新建一個win32工程然後添加相關庫的引用可以參考opencv編譯後面的內容
- 打開攝像頭的代碼如下。原理是打開攝像頭識別人臉子如果有保存下來
int main()
{
VideoCapture cap(0); //打開默認攝像頭
if(!cap.isOpened())
{
return -1;
}
Mat frame;
Mat edges;
CascadeClassifier cascade, nestedCascade;
bool stop = false;
//訓練好的文件名稱,放置在可執行文件同目錄下
cascade.load("haarcascade_frontalface_default.xml");
nestedCascade.load("haarcascade_eye.xml");
frame = imread("2.jpg");
detectAndDraw(frame, cascade, nestedCascade, 2, 0);
while(!stop)
{
cap>>frame;
detectAndDraw( frame, cascade, nestedCascade,2,0 );
if(waitKey(30) >=0)
stop = true;
}
waitKey();
return 0;
}
void detectAndDraw(Mat& img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip)
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor(img, frame_gray, COLOR_BGR2GRAY);
//檢測人臉
//detectMultiScale函數中smallImg表示的是要檢測的輸入圖像爲smallImg,faces表示檢測到的人臉目標序列,1.1表示
//每次圖像尺寸減小的比例爲1.1,2表示每一個目標至少要被檢測到3次纔算是真的目標(因爲周圍的像素和不同的窗口大
//小都可以檢測到人臉),CV_HAAR_SCALE_IMAGE表示不是縮放分類器來檢測,而是縮放圖像,Size(30, 30)爲目標的
//最小最大尺寸
cascade.detectMultiScale(frame_gray, faces,
1.1, 2, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
//|CV_HAAR_DO_ROUGH_SEARCH
| CV_HAAR_SCALE_IMAGE
, Size(30, 30));
for (size_t i = 0; i < faces.size(); i++)
{
rectangle(img, faces[i], Scalar(255, 0, 0), 2, 8, 0);
}
if (faces.size() == 1)
{
Mat faceROI = img(faces[0]);
Mat myFace;
resize(faceROI, myFace, Size(92, 112));
putText(img, to_string(1), faces[0].tl(), 3, 1.2, (0, 0, 255), 2, LINE_AA);
string filename = format("C:\\Users\\lyy\\Desktop\\att_faces\\s41\\%d.jpg", pic_num);
imwrite(filename, myFace);
imshow(filename, myFace);
waitKey(500);
destroyWindow(filename);
pic_num++;
}
imshow("識別結果", img);
}
- 整理數據
- 下載opencv教程給出的數據集AT&T這裏面有40個人的臉我們在裏面添加一個s41文件夾並把上一步保存的照片放進去測了了jpg的也可以,pgm的更好
- 然後整理出圖片信息文件 可以用命令
dir /b /s *.pgm *.jpg >at.txt
- 然後生成如下格式的文件,生成的辦法可以自己手動更改上面的文件,也可以編程來實現語言不限了,官方給出了python腳本文件所以我們這裏用python,其實我更熟悉c#,安裝python 然後執行python命令 ,格式爲python 腳本文件路徑
#!/usr/bin/env python
import sys
import os.path
if __name__ == "__main__":
#if len(sys.argv) != 2:
# print "usage: create_csv <base_path>"
# sys.exit(1)
#BASE_PATH=sys.argv[1]
BASE_PATH="C:\\Users\\lyy\\Desktop\\att_faces"
SEPARATOR=";"
fh = open("at.txt",'w')
for dirname, dirnames, filenames in os.walk(BASE_PATH):
for subdirname in dirnames:
subject_path = os.path.join(dirname, subdirname)
for filename in os.listdir(subject_path):
subdirname2 = subdirname[::-1]
subdirname3 = subdirname2[:-1]
subdirname4 = subdirname3[::-1]
#print subdirname2[:-1]
label = int(subdirname4)
abs_path = "%s/%s" % (subject_path, filename)
print "%s%s%d" % (abs_path, SEPARATOR, label)
fh.write(abs_path)
fh.write(SEPARATOR)
fh.write(str(label))
fh.write("\n")
label = label + 1
fh.close()
4. 訓練自己
``` c++
int main()
{
//讀取你的CSV文件路徑.
//string fn_csv = string(argv[1]);
string fn_csv = "at.txt";
// 2個容器來存放圖像數據和對應的標籤
vector<Mat> images;
vector<int> labels;
// 讀取數據. 如果文件不合法就會出錯
// 輸入的文件名已經有了.
try
{
read_csv(fn_csv, images, labels);
}
catch (cv::Exception& e)
{
cerr << "Error opening file \"" << fn_csv << "\". Reason: " << e.msg << endl;
// 文件有問題,我們啥也做不了了,退出了
exit(1);
}
// 如果沒有讀取到足夠圖片,也退出.
if (images.size() <= 1) {
string error_message = "This demo needs at least 2 images to work. Please add more images to your data set!";
CV_Error(CV_StsError, error_message);
}
// 下面的幾行代碼僅僅是從你的數據集中移除最後一張圖片
//[gm:自然這裏需要根據自己的需要修改,他這裏簡化了很多問題]
Mat testSample = images[images.size() - 1];
int testLabel = labels[labels.size() - 1];
images.pop_back();
labels.pop_back();
// 下面幾行創建了一個特徵臉模型用於人臉識別,
// 通過CSV文件讀取的圖像和標籤訓練它。
// T這裏是一個完整的PCA變換
//如果你只想保留10個主成分,使用如下代碼
// cv::createEigenFaceRecognizer(10);
//
// 如果你還希望使用置信度閾值來初始化,使用以下語句:
// cv::createEigenFaceRecognizer(10, 123.0);
//
// 如果你使用所有特徵並且使用一個閾值,使用以下語句:
// cv::createEigenFaceRecognizer(0, 123.0);
Ptr<BasicFaceRecognizer> model = EigenFaceRecognizer::create();
model->train(images, labels);
model->save("MyFacePCAModel.xml");
Ptr<BasicFaceRecognizer> model1 = FisherFaceRecognizer::create();
model1->train(images, labels);
model1->save("MyFaceFisherModel.xml");
Ptr<LBPHFaceRecognizer> model2 = LBPHFaceRecognizer::create();
model2->train(images, labels);
model2->save("MyFaceLBPHModel.xml");
// 下面對測試圖像進行預測,predictedLabel是預測標籤結果
int predictedLabel = model->predict(testSample);
int predictedLabel1 = model1->predict(testSample);
int predictedLabel2 = model2->predict(testSample);
// 還有一種調用方式,可以獲取結果同時得到閾值:
// int predictedLabel = -1;
// double confidence = 0.0;
// model->predict(testSample, predictedLabel, confidence);
string result_message = format("Predicted class = %d / Actual class = %d.", predictedLabel, testLabel);
string result_message1 = format("Predicted class = %d / Actual class = %d.", predictedLabel1, testLabel);
string result_message2 = format("Predicted class = %d / Actual class = %d.", predictedLabel2, testLabel);
cout << result_message << endl;
cout << result_message1 << endl;
cout << result_message2 << endl;
getchar();
//waitKey(0);
return 0;
}
static Mat norm_0_255(InputArray _src) {
Mat src = _src.getMat();
// 創建和返回一個歸一化後的圖像矩陣:
Mat dst;
switch (src.channels()) {
case 1:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);
break;
case 3:
cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);
break;
default:
src.copyTo(dst);
break;
}
return dst;
}
//使用CSV文件去讀圖像和標籤,主要使用stringstream和getline方法
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {
std::ifstream file(filename.c_str(), ifstream::in);
if (!file) {
string error_message = "No valid input file was given, please check the given filename.";
CV_Error(CV_StsBadArg, error_message);
}
string line, path, classlabel;
while (getline(file, line)) {
stringstream liness(line);
getline(liness, path, separator);
getline(liness, classlabel);
if (!path.empty() && !classlabel.empty()) {
images.push_back(imread(path, 0));
labels.push_back(atoi(classlabel.c_str()));
}
}
tips :createEigenFaceRecognizer更改爲了EigenFaceRecognizer::create()
** FisherFaceRecognizer::create()與LBPHFaceRecognizer::create()同樣具體細節可以參看源碼**
- 識別自己
- 加載自己的xml文件然後執行與第一步差不多的代碼
int main3()
{
VideoCapture cap(0); //打開默認攝像頭
if (!cap.isOpened())
{
return -1;
}
Mat frame;
Mat edges;
Mat gray;
CascadeClassifier cascade;
bool stop = false;
//訓練好的文件名稱,放置在可執行文件同目錄下
cascade.load("haarcascade_frontalface_alt.xml");
Ptr<FaceRecognizer> modelPCA = EigenFaceRecognizer::create();
modelPCA->read("MyFacePCAModel.xml");
//3.4取消了load所以這裏用的read
frame = imread("3.jpg");
detectMyFace(frame, cascade, modelPCA);
while (!stop)
{
cap >> frame;
detectMyFace(frame, cascade, modelPCA);
if (waitKey(30) >= 0)
stop = true;
}
waitKey(0);
return 0;
}
void detectMyFace(Mat& img, CascadeClassifier& cascade, Ptr<FaceRecognizer> modelPCA)
{
std::vector<Rect> faces;
Mat frame_gray;
cvtColor(img, frame_gray, COLOR_BGR2GRAY);
//改變圖像大小,使用雙線性差值
//resize(gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR);
//變換後的圖像進行直方圖均值化處理
//equalizeHist(gray, gray);
cascade.detectMultiScale(frame_gray, faces,
1.1, 2, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
//|CV_HAAR_DO_ROUGH_SEARCH
| CV_HAAR_SCALE_IMAGE,
Size(30, 30));
Mat face;
Point text_lb;
for (size_t i = 0; i < faces.size(); i++)
{
if (faces[i].height > 0 && faces[i].width > 0)
{
face = frame_gray(faces[i]);
text_lb = Point(faces[i].x, faces[i].y);
rectangle(img, faces[i], Scalar(255, 0, 0), 1, 8, 0);
}
}
Mat face_test;
int predictPCA = 0;
if (face.rows >= 120)
{
resize(face, face_test, Size(92, 112));
}
//Mat face_test_gray;
//cvtColor(face_test, face_test_gray, CV_BGR2GRAY);
if (!face_test.empty())
{
//測試圖像應該是灰度圖
predictPCA = modelPCA->predict(face_test);
}
cout << predictPCA << endl;
if (predictPCA == 41)
{
string name = "liyangyang";
putText(img, name, text_lb, FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255));
}
else
{
string name = "noliyangyang";
putText(img, name, text_lb, FONT_HERSHEY_COMPLEX, 1, Scalar(0, 0, 255));
}
imshow("face", img);
}
3.4取消了load所以這裏用的read
最後附上結果圖
源碼都附上去了,其中很多都是參考網絡上的文檔,只有具體的細節和版本不同的函數做了更改。謝謝偉大的互聯網。