天天看點

人臉識别之性别實作

說明一下,我的實作是将一張圖像輸入到程式中,程式給出這張圖檔的屬性值,包括:性别、是否帶帽子、是否戴眼鏡、是否帶口罩以及遮擋物的顔色。

說說思想吧,當然遮臉跳過了搜集和訓練的這一步,這實作這一步包括了搜集和訓練。我采用PCA(主成分分析算法)來實作訓練和預測,用HSV顔色空間H值分量來進行顔色比對。

這裡略去PCA算法的原理講解,也略去HSV顔色空間比對方法的介紹,如果有疑問的就在下面評論指出,當然不足之處也請指出,共同學習,共同進退:

由于整個程式代碼有700多行,下面給出部分代碼

搜集和學習代碼部分:

//性别的識别

int sex_Rec(string fn_csv, string tn_csv)

{

int returnSex;

vector<Mat> allImages, train_images;

vector<int> allLabels, train_labels;

vector<Mat> testImages, test_images;

vector<int> testLabels, test_labels;

//-------------------------訓練集---------------------//

try {

read_csv(fn_csv, allImages, allLabels);

}

catch (cv::Exception& e) {

cerr << "Error opening file " << fn_csv << ". Reason: " << e.msg << endl;

exit(1);

}

for (int i = 0; i < allImages.size(); i++)

equalizeHist(allImages[i], allImages[i]);

int photoTrainNumber = allImages.size();

for (int i = 0; i < photoTrainNumber; i++)

{

train_images.push_back(allImages[i]);

train_labels.push_back(allLabels[i]);

}

//------------------------訓練結束---------------------//

//-------------------------測試---------------------------//

try {

read_csv(tn_csv, testImages, testLabels);

}

catch (cv::Exception& e) {

cerr << "Error opening file " << fn_csv << ". Reason: " << e.msg << endl;

exit(1);

}

for (int i = 0; i < testImages.size(); i++)

equalizeHist(testImages[i], testImages[i]);

int photoTestNum = testImages.size();

for (int i = 0; i < photoTestNum; i++)

{

test_images.push_back(testImages[i]);

test_labels.push_back(testLabels[i]);

}

//------------------------測試結束----------------------//

Ptr<FaceRecognizer> model = createEigenFaceRecognizer();//定義pca模型  

model->train(train_images, train_labels);//訓練pca模型,這裡的model包含了所有特征值和特征向量

int predictedLabel;

int testPhotoNum = test_images.size();

for (int i = 0; i < testPhotoNum; i++)

{

predictedLabel = model->predict(test_images[i]);

if (test_labels[i] == predictedLabel)

{

if (0 == predictedLabel)

{

returnSex = 0;

//cout << "性别: 女" << endl;

}

else

{

returnSex = 1;

//cout << "性别: 男" << endl;

}

}

else

{

returnSex = -1;

//cout << "ERROR : 未能預測出性别!" << endl;

}

}

return returnSex;

}

這裡我設定了傳回值來友善我自己的整個程式對性别識别部分的調用。由于太長了,就接下篇博文吧!!

繼續閱讀