opencv 人脸识别 (二)训练和识别

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

∙转为灰度和对齐是后面做训练时EigenFaceRecognizer的要求;

∙归一化是防止光照带来的影响

在上一篇的 2.2 Prehelper.cpp文件中加入函数

void resizeandtogray(char* dir,int k, vector &images, vector &labels, vector &testimages, vector &testlabels);

[cpp]view plaincopyprint?

1.void resizeandtogray(char* dir,int K, vector &images, vector &l

abels,

2. vector &testimages, vector &testlabels)

3.{

4. IplImage* standard = cvLoadImage("D:\\privacy\\picture\\photo\\2.jpg"

,CV_LOAD_IMAGE_GRAYSCALE);

5. string cur_dir;

6.char id[5];

7.int i,j;

8. for(int i=1; i<=K; i++)

9. {

10. cur_dir = dir;

11. cur_dir.append("gray\\");

12. _itoa(i,id,10);

13. cur_dir.append(id);

14. const char* dd = cur_dir.c_str();

15. CStatDir statdir;

16. if (!statdir.SetInitDir(dd))

17. {

18. puts("Dir not exist");

19. return;

20. }

21. cout<<"Processing samples in Class "<

22. vectorfile_vec = statdir.BeginBrowseFilenames("*.*");

23. for (j=0;j

24. {

25. IplImage* cur_img = cvLoadImage(file_vec[j],CV_LOAD_IMAGE_GRA

YSCALE);

26. cvResize(cur_img,standard,CV_INTER_AREA);

27. Mat cur_mat = cvarrToMat(standard,true),des_mat;

28. cv::normalize(cur_mat,des_mat,0, 255, NORM_MINMAX, CV_8UC1);

29. cvSaveImage(file_vec[j],cvCloneImage(&(IplImage) des_mat));

30. if(j!=file_vec.size())

31. {

32. images.push_back(des_mat);

33. labels.push_back(i);

34. }

35. else

36. {

37. testimages.push_back(des_mat);

38. testlabels.push_back(i);

39. }

40. }

41. cout<

42. }

43.}

并在main中调用:

[cpp]view plaincopyprint?

1.int main( )

2.{

3. CvCapture* capture = 0;

4. Mat frame, frameCopy, image;

5. string inputName;

6.int mode;

7.

8.char dir[256] = "D:\\Courses\\CV\\Face_recognition\\pic\\";

9. //preprocess_trainingdata(dir,K); //face_detection and extract to fil

e

10. vector images,testimages;

11. vector labels,testlabels;

12. resizeandtogray(dir,K,images,labels,testimages,testlabels); //togray,

normalize and resize

13.

14. system("pause");

15. return 0;

16.}

2. 训练

有了vector images,testimages; vector labels,testlabels; 可以开始训练了,我们采用EigenFaceRecognizer建模。

在Prehelper.cpp中加入函数

Ptr Recognition(vector images, vector

labels,vector testimages, vector testlabels);

[cpp]view plaincopyprint?

1.Ptr Recognition(vector images, vector labels,

2. vector testimages, vector testlabels)

3.{

4. Ptr model = createEigenFaceRecognizer(10);//10 Princi

pal components

5. cout<<"train"<

6. model->train(images,labels);

7.int i,acc=0,predict_l;

8. for (i=0;i

9. {

10. predict_l = model->predict(testimages[i]);

11. if(predict_l != testlabels[i])

12. {

13. cout<<"An error in recognition: sample "<

14. predict_l<<", groundtruth "<

15. imshow("error 1",testimages[i]);

16. waitKey();

相关文档
最新文档