Face recognition

From , 5 Years ago, written in Java, viewed 227 times.
URL https://pastebin.vip/view/bea5955b
  1.                
  2. import com.googlecode.javacpp.FloatPointer;
  3. import com.googlecode.javacpp.Pointer;
  4. import java.io.BufferedReader;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.logging.Logger;
  10. import static com.googlecode.javacv.cpp.opencv_highgui.cvWaitKey;
  11. import static com.googlecode.javacv.cpp.opencv_highgui.cvShowImage;
  12. import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
  13. import static com.googlecode.javacv.cpp.opencv_highgui.cvDestroyWindow;
  14. import static com.googlecode.javacv.cpp.opencv_highgui.CV_LOAD_IMAGE_GRAYSCALE;
  15. import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;
  16. import com.googlecode.javacv.FrameGrabber;
  17. import com.googlecode.javacv.FrameGrabber.Exception;
  18. import com.googlecode.javacv.OpenCVFrameGrabber;
  19. import com.googlecode.javacv.VideoInputFrameGrabber;
  20. import com.googlecode.javacv.cpp.opencv_core.CvFont;
  21. import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
  22. import com.googlecode.javacv.cpp.opencv_core.CvPoint;
  23. import com.googlecode.javacv.cpp.opencv_core.CvRect;
  24. import com.googlecode.javacv.cpp.opencv_core.CvScalar;
  25. import com.googlecode.javacv.cpp.opencv_core.CvSeq;
  26. import com.googlecode.javacv.cpp.opencv_core.IplImage;
  27. import static com.googlecode.javacv.cpp.opencv_legacy.*;
  28. import static com.googlecode.javacv.cpp.opencv_objdetect.CV_HAAR_DO_CANNY_PRUNING;
  29. import static com.googlecode.javacv.cpp.opencv_objdetect.CV_HAAR_FIND_BIGGEST_OBJECT;
  30. import static com.googlecode.javacv.cpp.opencv_objdetect.CV_HAAR_DO_ROUGH_SEARCH;
  31. import static com.googlecode.javacv.cpp.opencv_objdetect.cvHaarDetectObjects;
  32. import static com.googlecode.javacv.cpp.opencv_imgproc.CV_BGR2GRAY;
  33. import static com.googlecode.javacv.cpp.opencv_imgproc.cvEqualizeHist;
  34. import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;     
  35. import static com.googlecode.javacv.cpp.opencv_core.CvMat;
  36. import static com.googlecode.javacv.cpp.opencv_core.cvReleaseImage;
  37. import static com.googlecode.javacv.cpp.opencv_core.cvLoad;
  38. import static com.googlecode.javacv.cpp.opencv_core.CV_FONT_HERSHEY_COMPLEX_SMALL;
  39. import static com.googlecode.javacv.cpp.opencv_core.cvGetSize;
  40. import static com.googlecode.javacv.cpp.opencv_core.CV_32FC1;
  41. import static com.googlecode.javacv.cpp.opencv_core.cvCreateMat;
  42. import static com.googlecode.javacv.cpp.opencv_core.cvCloneImage;
  43. import static com.googlecode.javacv.cpp.opencv_core.IPL_DEPTH_8U;
  44. import static com.googlecode.javacv.cpp.opencv_core.cvCreateImage;
  45. import static com.googlecode.javacv.cpp.opencv_core.CvSize;
  46. import static com.googlecode.javacv.cpp.opencv_core.cvResetImageROI;
  47. import static com.googlecode.javacv.cpp.opencv_core.cvClearMemStorage;
  48. import static com.googlecode.javacv.cpp.opencv_core.cvSize;
  49. import static com.googlecode.javacv.cpp.opencv_core.cvCopy;
  50. import static com.googlecode.javacv.cpp.opencv_core.cvSetImageROI;
  51. import static com.googlecode.javacv.cpp.opencv_core.CV_AA;
  52. import static com.googlecode.javacv.cpp.opencv_core.cvPoint;
  53. import static com.googlecode.javacv.cpp.opencv_core.cvInitFont;
  54. import static com.googlecode.javacv.cpp.opencv_core.cvGetSeqElem;
  55. import static com.googlecode.javacv.cpp.opencv_core.cvRectangle;
  56. import static com.googlecode.javacv.cpp.opencv_core.cvPutText;
  57. import static com.googlecode.javacv.cpp.opencv_core.CV_32SC1;
  58. import static com.googlecode.javacv.cpp.opencv_core.CvTermCriteria;
  59. import static com.googlecode.javacv.cpp.opencv_core.IPL_DEPTH_32F;
  60. import static com.googlecode.javacv.cpp.opencv_core.CV_L1;
  61. import static com.googlecode.javacv.cpp.opencv_core.CV_TERMCRIT_ITER;
  62. import static com.googlecode.javacv.cpp.opencv_core.cvNormalize;
  63. import static com.googlecode.javacv.cpp.opencv_core.CvFileStorage;
  64. import static com.googlecode.javacv.cpp.opencv_core.cvWriteInt;
  65. import static com.googlecode.javacv.cpp.opencv_core.cvTermCriteria;
  66. import static com.googlecode.javacv.cpp.opencv_core.CV_STORAGE_WRITE;
  67. import static com.googlecode.javacv.cpp.opencv_core.cvOpenFileStorage;
  68. import static com.googlecode.javacv.cpp.opencv_core.cvWrite;
  69. import static com.googlecode.javacv.cpp.opencv_core.cvWriteString;
  70. import static com.googlecode.javacv.cpp.opencv_core.cvReleaseFileStorage;
  71. import static com.googlecode.javacv.cpp.opencv_core.CV_STORAGE_READ;
  72. import static com.googlecode.javacv.cpp.opencv_core.cvReadIntByName;
  73. import static com.googlecode.javacv.cpp.opencv_core.cvReadStringByName;
  74. import static com.googlecode.javacv.cpp.opencv_core.cvReadByName;
  75. import static com.googlecode.javacv.cpp.opencv_core.cvRect;
  76. import static com.googlecode.javacv.cpp.opencv_core.cvConvertScale;
  77. import static com.googlecode.javacv.cpp.opencv_core.cvMinMaxLoc;
  78. import static com.googlecode.javacv.cpp.opencv_imgproc.CV_INTER_LINEAR;
  79. import static com.googlecode.javacv.cpp.opencv_imgproc.CV_INTER_AREA;
  80. import static com.googlecode.javacv.cpp.opencv_imgproc.cvResize;
  81. import static com.googlecode.javacv.cpp.opencv_imgproc.cvCvtColor;
  82.  
  83.        
  84. import java.io.*;
  85.  
  86. import org.eclipse.swt.SWT;
  87. import org.eclipse.swt.widgets.FileDialog;
  88. import org.eclipse.swt.widgets.MessageBox;
  89. import org.eclipse.swt.widgets.Shell;
  90.        
  91.         public class FaceRecognizer{
  92.        
  93.           private static final Logger LOGGER = Logger.getLogger(FaceRecognizer.class.getName());
  94.           private int nTrainFaces = 0;
  95.           private int nPersons=0;
  96.           private int nEigens = 0;
  97.           private int countSavedFace=1;
  98.           private CvMat personNumTruthMat;
  99.           private  CvMat eigenValMat;
  100.           private CvMat projectedTrainFaceMat;
  101.           private CvMat trainPersonNumMat=null;
  102.           final static List<String> personNames = new ArrayList<String>();
  103.           private CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad("data\\haarcascade_frontalface_alt2.xml"));
  104.           private static final int newWidth=50;
  105.           private static final int newHeight=50;
  106.          
  107.           IplImage[] eigenVectArr;
  108.           IplImage[] trainingFaceImgArr;
  109.           IplImage[] testFaceImgArr;
  110.           IplImage pAvgTrainImg;
  111.          
  112.          
  113.           public static String personName;
  114.           private static String textName="unknow";
  115.          
  116.           public static double g_confidence=0;  
  117.          
  118.          
  119.           public FaceRecognizer() {
  120.                   trainPersonNumMat = loadTrainingData();
  121.           }
  122.          
  123.          
  124.           private void learn(final String trainingFileName) {
  125.             int i;
  126.        
  127.             // load training data
  128.             LOGGER.info("===========================================");
  129.             LOGGER.info("Loading the training images in " + trainingFileName);
  130.             trainingFaceImgArr = loadFaceImgArray(trainingFileName);
  131.             nTrainFaces = trainingFaceImgArr.length;
  132.             LOGGER.info("Got " + nTrainFaces + " training images");
  133.             if (nTrainFaces < 3) {
  134.               LOGGER.severe("Need 3 or more training faces\n"
  135.                       + "Input file contains only " + nTrainFaces);
  136.               return;
  137.             }
  138.        
  139.             // do Principal Component Analysis on the training faces
  140.             doPCA();
  141.        
  142.             LOGGER.info("projecting the training images onto the PCA subspace");
  143.             // project the training images onto the PCA subspace
  144.             projectedTrainFaceMat = cvCreateMat(
  145.                     nTrainFaces, // rows
  146.                     nEigens, // cols
  147.                     CV_32FC1); // type, 32-bit float, 1 channel
  148.        
  149.             // initialize the training face matrix - for ease of debugging
  150.             for (int i1 = 0; i1 < nTrainFaces; i1++) {
  151.               for (int j1 = 0; j1 < nEigens; j1++) {
  152.                 projectedTrainFaceMat.put(i1, j1, 0.0);
  153.               }
  154.             }
  155.        
  156.             LOGGER.info("created projectedTrainFaceMat with " + nTrainFaces + " (nTrainFaces) rows and " + nEigens + " (nEigens) columns");
  157.             if (nTrainFaces < 5) {
  158.               LOGGER.info("projectedTrainFaceMat contents:\n" + oneChannelCvMatToString(projectedTrainFaceMat));
  159.             }
  160.        
  161.             final FloatPointer floatPointer = new FloatPointer(nEigens);
  162.             for (i = 0; i < nTrainFaces; i++) {
  163.               cvEigenDecomposite(
  164.                       trainingFaceImgArr[i], // obj
  165.                       nEigens, // nEigObjs
  166.                       eigenVectArr, // eigInput (Pointer)
  167.                       0, // ioFlags
  168.                       null, // userData (Pointer)
  169.                       pAvgTrainImg, // avg
  170.                       floatPointer); // coeffs (FloatPointer)
  171.        
  172.               if (nTrainFaces < 5) {
  173.                 LOGGER.info("floatPointer: " + floatPointerToString(floatPointer));
  174.               }
  175.               for (int j1 = 0; j1 < nEigens; j1++) {
  176.                 projectedTrainFaceMat.put(i, j1, floatPointer.get(j1));
  177.               }
  178.             }
  179.             if (nTrainFaces < 5) {
  180.               LOGGER.info("projectedTrainFaceMat after cvEigenDecomposite:\n" + projectedTrainFaceMat);
  181.             }
  182.        
  183.             // store the recognition data as an xml file
  184.             storeTrainingData();
  185.        
  186.             // Save all the eigenvectors as images, so that they can be checked.
  187.             storeEigenfaceImages();
  188.           }
  189.  
  190.        
  191.         private IplImage convertImageToGreyscale(IplImage imageSrc)
  192.           {
  193.                 IplImage imageGrey;
  194.                 // Either convert the image to greyscale, or make a copy of the existing greyscale image.
  195.                 // This is to make sure that the user can always call cvReleaseImage() on the output, whether it was greyscale or not.
  196.                 if (imageSrc.nChannels()==3) {
  197.                         imageGrey = cvCreateImage( cvGetSize(imageSrc), IPL_DEPTH_8U, 1 );
  198.                         cvCvtColor( imageSrc, imageGrey, CV_BGR2GRAY );
  199.                 }
  200.                 else {
  201.                         imageGrey = cvCloneImage(imageSrc);
  202.                 }
  203.                 return imageGrey;
  204.           }
  205.          
  206.          
  207.         private IplImage resizeImage(IplImage origImg)
  208.           {
  209.                 IplImage outImg = null;
  210.                 int origWidth=0;
  211.                 int origHeight=0;
  212.                 if (origImg!=null) {
  213.                         origWidth = origImg.width();
  214.                         origHeight = origImg.height();
  215.                 }
  216.                 if (newWidth <= 0 || newHeight <= 0 || origImg == null || origWidth <= 0 || origHeight <= 0) {
  217.                         LOGGER.info("ERROR in resizeImage: Bad desired image size of");
  218.                         LOGGER.info(String.valueOf(newWidth)+","+String.valueOf(newHeight));
  219.                         System.exit(1);
  220.                 }
  221.        
  222.                 // Scale the image to the new dimensions, even if the aspect ratio will be changed.
  223.                 outImg = cvCreateImage(cvSize(newWidth, newHeight), origImg.depth(), origImg.nChannels());
  224.                 if (newWidth > origImg.width() && newHeight > origImg.height()) {
  225.                         // Make the image larger
  226.                         cvResetImageROI((IplImage)origImg);
  227.                         cvResize(origImg, outImg, CV_INTER_LINEAR);     // CV_INTER_CUBIC or CV_INTER_LINEAR is good for enlarging
  228.                 }
  229.                 else {
  230.                         // Make the image smaller
  231.                         cvResetImageROI((IplImage)origImg);
  232.                         cvResize(origImg, outImg, CV_INTER_AREA);       // CV_INTER_AREA is good for shrinking / decimation, but bad at enlarging.
  233.                 }
  234.        
  235.                 return outImg;
  236.           }
  237.        
  238.        
  239.        
  240.          private IplImage cropImage(IplImage img, CvRect region)
  241.           {
  242.                
  243.                 IplImage imageTmp;
  244.                 IplImage imageRGB;
  245.        
  246.           //    size.height()=img.height();
  247.           //    size.width() = img.width();
  248.                
  249.                 if (img.depth() != IPL_DEPTH_8U) {
  250.                         LOGGER.info("ERROR in cropImage: Unknown image depth of");
  251.                         LOGGER.info(String.valueOf(img.depth()));
  252.                         LOGGER.info(" given in cropImage() instead of 8 bits per pixel.");
  253.                         System.exit(1);
  254.                 }
  255.        
  256.                 // First create a new (color or greyscale) IPL Image and copy contents of img into it.
  257.                 imageTmp = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, img.nChannels());
  258.                 cvCopy(img, imageTmp);
  259.                
  260.                 // Create a new image of the detected region
  261.                 // Set region of interest to that surrounding the face
  262.                 cvSetImageROI(imageTmp, region);
  263.                 // Copy region of interest (i.e. face) into a new iplImage (imageRGB) and return it
  264.                 imageRGB = cvCreateImage(cvSize(region.width(),region.height()),  IPL_DEPTH_8U, img.nChannels());
  265.                 cvCopy(imageTmp, imageRGB);     // Copy just the region.
  266.        
  267.               cvReleaseImage(imageTmp);
  268.               //region.setNull();
  269.                 return imageRGB;       
  270.                 }
  271.        
  272.            
  273.          
  274.          public boolean recognizeFromCam() throws Exception
  275.           {
  276.                         OpenCVFrameGrabber  grabber = null;
  277.                         FileDialog fd;
  278.                         IplImage pFrame=null;
  279.                         int keypress = 0;
  280.                         if(LoginShell.video_flag)//如果被选,刚用视频
  281.                         {      
  282.                                 fd=new FileDialog(LoginShell.sShell,SWT.OPEN);  
  283.                                 fd.setFilterExtensions(new String[]{"*.avi","*.wmv","*.mp4","*.*"});
  284.                                 fd.setFilterNames(new String[]{".avi",".wmv",".mp4"});
  285.                                 String filename=fd.open();
  286.                                 grabber = OpenCVFrameGrabber.createDefault(filename);
  287.                         }
  288.                         else
  289.                                 grabber = OpenCVFrameGrabber.createDefault(0);
  290.                         grabber.start();
  291.                 pFrame = grabber.grab();  
  292.                 while( pFrame!=null ){
  293.                         detectAndCropAndPre( pFrame,cascade,CV_HAAR_DO_CANNY_PRUNING | CV_HAAR_DO_ROUGH_SEARCH);                               
  294.                         cvShowImage("Press 'Esc' to Stop!",pFrame);
  295.                                 pFrame = grabber.grab();
  296.                                 keypress=cvWaitKey(24);
  297.                                 System.out.println(g_confidence);
  298.                                 if( keypress== 27){    
  299.                                         grabber.release();
  300.                                         cvDestroyWindow("Press 'Esc' to Stop!");
  301.                                         break;
  302.                                 }
  303.                 }
  304.                 cvWaitKey(1000);
  305.                 cvReleaseImage(pFrame);
  306.                 //cvDestroyWindow("BP_FaceRecognizer_FaceLogin");
  307.                 grabber.release();
  308.                         return false;
  309.           }
  310.          
  311.          public void recongizeFormImage(String filePath){
  312.                         IplImage signleImage=null;
  313.                         System.out.println(filePath);
  314.                         signleImage=cvLoadImage(filePath);
  315.                         if(!signleImage.isNull());
  316.                                 detectAndCropFromImg(signleImage,cascade,CV_HAAR_DO_CANNY_PRUNING | CV_HAAR_DO_ROUGH_SEARCH);                          
  317.                 cvShowImage("Press 'Esc' to exit",signleImage);
  318.                         cvWaitKey(0);
  319.                         cvDestroyWindow("Press 'Esc' to exit");
  320.          }
  321.          
  322.          
  323.          
  324.        
  325.          public boolean register(String name)throws Exception
  326.          {       
  327.                         boolean flag=true;
  328.                         OpenCVFrameGrabber  grabber = null;
  329.                         FileDialog fd;
  330.                         IplImage pFrame=null;
  331.                         int keypress = 0;
  332.                         int countSecond=0;
  333.                        
  334.                         for(int i=0;i<personNames.size();i++){
  335.                                 if(name.equals(personNames.get(i).toString()))
  336.                                 {
  337.                                         MessageBox messageBox = new MessageBox(RegisterShell.sShell, SWT.ICON_QUESTION |SWT.YES | SWT.NO);
  338.                                         messageBox.setMessage("此用户已经被使用!!!连续按 “否” 返回");  
  339.                                         messageBox.open();
  340.                                         flag=false;
  341.                                 }
  342.                         }
  343.                          
  344.                         if(LoginShell.video_flag)//用视频文件进行注册
  345.                         {
  346.                                 fd=new FileDialog(LoginShell.sShell,SWT.OPEN);  
  347.                                 fd.setFilterExtensions(new String[]{"*.avi","*.wmv","*.mp4","*.*"});
  348.                                 fd.setFilterNames(new String[]{".avi",".wmv",".mp4"});
  349.                                 String filename=fd.open();
  350.                                 grabber = OpenCVFrameGrabber.createDefault(filename);
  351.                         }
  352.                         else
  353.                                 grabber = OpenCVFrameGrabber.createDefault(0);
  354.                         grabber.start();
  355.                 pFrame = grabber.grab();                                       
  356.                 while( pFrame!=null )
  357.                 {
  358.                         countSecond++;
  359.                         detectForRegister(pFrame,cascade,CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH,name);
  360.                         cvShowImage("Press 'Esc' to Stop",pFrame);
  361.                                 pFrame = grabber.grab();
  362.                                 keypress=cvWaitKey(24);
  363.                                 if( keypress== 27 ||countSecond==100||countSavedFace==6)//||second==60
  364.                                 {      
  365.                                         cvReleaseImage(pFrame);
  366.                                         grabber.release();
  367.                                         break;                         
  368.                                 }
  369.                 }
  370.  
  371.                 personNames.add(name);
  372.                 writeNameToTXT(name);
  373.                 learn("data\\ForTraining.txt");
  374.                 cvDestroyWindow("Press 'Esc' to Stop");
  375.                         return flag;
  376.          }
  377.          
  378.  
  379.          
  380.          
  381.          private void detectForRegister(IplImage src,CvHaarClassifierCascade cascade,int flag,String name){
  382.  
  383.                 IplImage greyImg=null;
  384.                 IplImage faceImg=null;
  385.                 IplImage sizedImg=null;
  386.                 IplImage equalizedImg=null;
  387.  
  388.                
  389.                 CvRect r ;
  390.                 CvFont font = new CvFont(CV_FONT_HERSHEY_COMPLEX_SMALL, 1, 1);
  391.                 cvInitFont(font,CV_FONT_HERSHEY_COMPLEX_SMALL, 1.0, 0.8,1,1,CV_AA);
  392.                 greyImg = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );            
  393.                 greyImg=convertImageToGreyscale(src);
  394.                 CvMemStorage storage = CvMemStorage.create();
  395.                
  396.                 CvSeq sign = cvHaarDetectObjects(
  397.                                 greyImg,
  398.                                 cascade,
  399.                                 storage,
  400.                                 1.1,
  401.                                 3,
  402.                                 flag);
  403.                 cvClearMemStorage(storage);
  404.                 if(sign.total()==1)//只会有一个脸部
  405.                 {      
  406.                         r = new CvRect(cvGetSeqElem(sign, 0));
  407.                         faceImg = cropImage(greyImg, r);               
  408.                         sizedImg = resizeImage(faceImg);
  409.                         equalizedImg = cvCreateImage(cvGetSize(sizedImg), 8, 1);       
  410.                         cvEqualizeHist(sizedImg, equalizedImg);        
  411.                         cvRectangle (
  412.                                                         src,
  413.                                                         cvPoint(r.x(), r.y()),
  414.                                                         cvPoint(r.width() + r.x(), r.height() + r.y()),
  415.                                                         CvScalar.WHITE,
  416.                                                         1,
  417.                                                         CV_AA,
  418.                                                         0);
  419.                         cvPutText(src, "This is your No."+String.valueOf(countSavedFace)+" photos. " ,cvPoint(r.x()-30, r.y() + r.height() + 30), font, CvScalar.RED);                         
  420.                         cvSaveImage("img\\"+name+countSavedFace+".jpg",equalizedImg);
  421.                         cvWaitKey(1000);
  422.                         countSavedFace++;      
  423.                         cvReleaseImage(greyImg);
  424.                         cvReleaseImage(faceImg);
  425.                         cvReleaseImage(sizedImg);
  426.                         cvReleaseImage(equalizedImg);  
  427.                 }
  428.                
  429.                        
  430.        
  431.                
  432. }
  433.                
  434.                                          
  435.          
  436.          private  void writeNameToTXT(String name){
  437.                         String text=null;
  438.                         int temp;
  439.                         temp=personNames.size();
  440.                         if(temp==0)
  441.                                 temp=temp+1;
  442.                                
  443.                         try {
  444.                              File file = new File("data\\ForTraining.txt");
  445.                              FileOutputStream fos = new FileOutputStream(file,true);
  446.                              OutputStreamWriter osw = new OutputStreamWriter(fos);
  447.                              BufferedWriter bw = new BufferedWriter(osw);
  448.                             // if(personNames.size()==0)
  449.                                  
  450.                              for(int i=1;i<6;i++){
  451.                                      text=temp+" "+name+" "+"img\\"+name+i+".jpg";
  452.                                      bw.write(text);
  453.                                      bw.newLine();
  454.                              }
  455.                              
  456.                              bw.flush();
  457.                              bw.close();
  458.                              osw.close();
  459.                              fos.close();
  460.  
  461.                         }
  462.                         catch (FileNotFoundException e1) {
  463.                              e1.printStackTrace();
  464.                             } catch (IOException e2) {
  465.                              e2.printStackTrace();
  466.                             }
  467.          }
  468.          
  469.          
  470.          private void eigenDecomImg(IplImage src){
  471.                 //CvMat trainPersonNumMat=null;
  472.                 float confidence = 0.0f;
  473.                 int  nearest=0;
  474.                 int iNearest=0;
  475.                
  476.                
  477.                 LOGGER.info("=====================================Waiting For the camera .....");
  478.           //   
  479.                 if( trainPersonNumMat==null) {
  480.                         LOGGER.info("ERROR in recognizeFromCam(): Couldn't load the training data!\n");
  481.                         System.exit(1);
  482.                 }
  483.                 float[] projectedTestFace = new float[nEigens];
  484.                         cvEigenDecomposite(
  485.                                 src,
  486.                                 nEigens,
  487.                                 eigenVectArr,
  488.                                 0,
  489.                                 null,
  490.                                 pAvgTrainImg,
  491.                                 projectedTestFace);
  492.        
  493.             final FloatPointer pConfidence = new FloatPointer(confidence);
  494.             iNearest = findNearestNeighbor(projectedTestFace, new FloatPointer(pConfidence));
  495.             confidence = pConfidence.get();
  496.             nearest = trainPersonNumMat.data_i().get(iNearest);
  497.             personName="";
  498.                 textName=personNames.get(nearest-1);
  499.                 personName=personNames.get(nearest-1);
  500.             g_confidence=confidence;
  501.                
  502.         }
  503.                    
  504.          
  505.          private void detectAndCropAndPre(IplImage src,CvHaarClassifierCascade cascade,int flag)
  506.          {
  507.                         int nearest=0;
  508.                         IplImage greyImg=null;
  509.                         IplImage faceImg=null;
  510.                         IplImage sizedImg=null;
  511.                         IplImage equalizedImg=null;
  512.                         boolean faceIsTrue=false;
  513.                         CvRect r ;
  514.                         CvFont font = new CvFont(CV_FONT_HERSHEY_COMPLEX_SMALL, 1, 1);
  515.                         cvInitFont(font,CV_FONT_HERSHEY_COMPLEX_SMALL, 1.0, 0.8,1,1,CV_AA);
  516.                         greyImg = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );            
  517.                         greyImg=convertImageToGreyscale(src);
  518.                         CvMemStorage storage = CvMemStorage.create();
  519.                        
  520.                         CvSeq sign = cvHaarDetectObjects(
  521.                                         greyImg,
  522.                                         cascade,
  523.                                         storage,
  524.                                         1.1,
  525.                                         3,
  526.                                         flag);
  527.                         cvClearMemStorage(storage);
  528.                         if(sign.total()>0)
  529.                         {
  530.                                
  531.                                 for(int i=0;i<sign.total();i++)
  532.                                 {
  533.                                         r = new CvRect(cvGetSeqElem(sign, i));
  534.                                         faceImg = cropImage(greyImg, r);       
  535.                                         sizedImg = resizeImage(faceImg);
  536.                                         if(i==0)
  537.                                                 equalizedImg = cvCreateImage(cvGetSize(sizedImg), 8, 1);       
  538.                                         cvEqualizeHist(sizedImg, equalizedImg);                        
  539.                                         cvRectangle (
  540.                                                                         src,
  541.                                                                         cvPoint(r.x(), r.y()),
  542.                                                                         cvPoint(r.width() + r.x(), r.height() + r.y()),
  543.                                                                         CvScalar.WHITE,
  544.                                                                         1,
  545.                                                                         CV_AA,
  546.                                                                         0);
  547.                                
  548.                                         eigenDecomImg(equalizedImg);
  549.                                         if(g_confidence*100>50){
  550.                                                 cvPutText(src, textName,cvPoint(r.x()-10, r.y() + r.height() + 20), font, CvScalar.WHITE);
  551.                                                 cvPutText(src, " conf="+Integer.valueOf((int) (g_confidence*100))+"%",cvPoint(r.x()-10, r.y() + r.height() + 40), font, CvScalar.GREEN);
  552.                                                 textName="unknow";
  553.                                         }
  554.                                         else {
  555.                                                 cvPutText(src, "unknow",cvPoint(r.x()-10, r.y() + r.height() + 20), font, CvScalar.WHITE);
  556.                                                 cvPutText(src, " conf="+Integer.valueOf((int) (g_confidence*100))+"%",cvPoint(r.x()-10, r.y() + r.height() + 40), font, CvScalar.GREEN);
  557.                                         }
  558.                                 }
  559.                                 cvReleaseImage(greyImg);
  560.                                 cvReleaseImage(faceImg);
  561.                                 cvReleaseImage(sizedImg);
  562.                                 cvReleaseImage(equalizedImg);
  563.                         }      
  564.                                
  565.        
  566.                 }
  567.  
  568.          private void detectAndCropFromImg(IplImage src,CvHaarClassifierCascade cascade,int flag)
  569.          {
  570.                         IplImage greyImg=null;
  571.                         IplImage faceImg=null;
  572.                         IplImage sizedImg=null;
  573.                         IplImage equalizedImg=null;
  574.                         CvRect r ;
  575.                         CvFont font = new CvFont(CV_FONT_HERSHEY_COMPLEX_SMALL, 1, 1);
  576.                         cvInitFont(font,CV_FONT_HERSHEY_COMPLEX_SMALL, 1.0, 0.8,1,1,CV_AA);
  577.                         greyImg = cvCreateImage( cvGetSize(src), IPL_DEPTH_8U, 1 );            
  578.                         greyImg=convertImageToGreyscale(src);
  579.                         CvMemStorage storage = CvMemStorage.create();
  580.                        
  581.                         CvSeq sign = cvHaarDetectObjects(
  582.                                         greyImg,
  583.                                         cascade,
  584.                                         storage,
  585.                                         1.1,
  586.                                         3,
  587.                                         flag);
  588.                         cvClearMemStorage(storage);
  589.                         if(sign.total()>0)
  590.                         {
  591.                                
  592.                                 for(int i=0;i<sign.total();i++)
  593.                                 {
  594.                                         r = new CvRect(cvGetSeqElem(sign, i));
  595.                                         faceImg = cropImage(greyImg, r);       
  596.                                         sizedImg = resizeImage(faceImg);
  597.                                         if(i==0)
  598.                                                 equalizedImg = cvCreateImage(cvGetSize(sizedImg), 8, 1);       
  599.                                         cvEqualizeHist(sizedImg, equalizedImg);                        
  600.                                         cvRectangle (
  601.                                                                         src,
  602.                                                                         cvPoint(r.x(), r.y()),
  603.                                                                         cvPoint(r.width() + r.x(), r.height() + r.y()),
  604.                                                                         CvScalar.WHITE,
  605.                                                                         1,
  606.                                                                         CV_AA,
  607.                                                                         0);
  608.                                
  609.                                         eigenDecomImg(equalizedImg);
  610.                                         if(g_confidence*100>50){
  611.                                                 cvPutText(src, textName,cvPoint(r.x()-10, r.y() + r.height() + 20), font, CvScalar.WHITE);
  612.                                                 cvPutText(src, " conf="+Integer.valueOf((int) (g_confidence*100))+"%",cvPoint(r.x()-10, r.y() + r.height() + 40), font, CvScalar.GREEN);
  613.                                                 textName="unknow";
  614.                                         }
  615.                                         else{
  616.                                                 cvPutText(src, "Unknow",cvPoint(r.x()-10, r.y() + r.height() + 20), font, CvScalar.WHITE);
  617.                                                 cvPutText(src, " conf="+Integer.valueOf((int) (g_confidence*100))+"%",cvPoint(r.x()-10, r.y() + r.height() + 40), font, CvScalar.GREEN);
  618.                                         }
  619.                                 }
  620.                         }
  621.                         else
  622.                                 cvPutText(src, "can't find any face!",cvPoint(src.width()/2, src.height()/2), font, CvScalar.GREEN);
  623.                         //cvReleaseImage(greyImg);
  624.                         //if(!faceImg.isNull())
  625.                         //      cvReleaseImage(faceImg);
  626.                         //cvReleaseImage(sizedImg);
  627.                         //cvReleaseImage(equalizedImg);
  628.                 }      
  629.  
  630.                        
  631.  
  632.          
  633.          private IplImage[] loadFaceImgArray(final String filename) {
  634.             IplImage[] faceImgArr;
  635.             BufferedReader imgListFile;
  636.             String imgFilename;
  637.             int iFace = 0;
  638.             int nFaces = 0;
  639.             int i;
  640.             try {
  641.               // open the input file
  642.               imgListFile = new BufferedReader(new FileReader(filename));
  643.        
  644.               // count the number of faces
  645.               while (true) {
  646.                 final String line = imgListFile.readLine();
  647.                 if (line == null || line.isEmpty()) {
  648.                   break;
  649.                 }
  650.                 nFaces++;
  651.               }
  652.               LOGGER.info("nFaces: " + nFaces);
  653.               imgListFile = new BufferedReader(new FileReader(filename));
  654.        
  655.               // allocate the face-image array and person number matrix
  656.               faceImgArr = new IplImage[nFaces];
  657.               personNumTruthMat = cvCreateMat(
  658.                       1, // rows
  659.                       nFaces, // cols
  660.                       CV_32SC1); // type, 32-bit unsigned, one channel
  661.        
  662.               // initialize the person number matrix - for ease of debugging
  663.               for (int j1 = 0; j1 < nFaces; j1++) {
  664.                 personNumTruthMat.put(0, j1, 0);
  665.               }
  666.        
  667.               personNames.clear();        // Make sure it starts as empty.
  668.               nPersons = 0;
  669.        
  670.               // store the face images in an array
  671.               for (iFace = 0; iFace < nFaces; iFace++) {
  672.                 String personName;
  673.                 String sPersonName;
  674.                 int personNumber;
  675.        
  676.                 // read person number (beginning with 1), their name and the image filename.
  677.                 final String line = imgListFile.readLine();
  678.                 if (line.isEmpty()) {
  679.                   break;
  680.                 }
  681.                 final String[] tokens = line.split(" ");
  682.                 personNumber = Integer.parseInt(tokens[0]);
  683.                 personName = tokens[1];
  684.                 imgFilename = tokens[2];
  685.                 sPersonName = personName;
  686.                 LOGGER.info("Got " + iFace + " " + personNumber + " " + personName + " " + imgFilename);
  687.        
  688.                 // Check if a new person is being loaded.
  689.                 if (personNumber > nPersons) {
  690.                   // Allocate memory for the extra person (or possibly multiple), using this new person's name.
  691.                   personNames.add(sPersonName);
  692.                   nPersons = personNumber;
  693.                   LOGGER.info("Got new person " + sPersonName + " -> nPersons = " + nPersons + " [" + personNames.size() + "]");
  694.                 }
  695.        
  696.                 // Keep the data
  697.                 personNumTruthMat.put(
  698.                         0, // i
  699.                         iFace, // j
  700.                         personNumber); // v
  701.        
  702.                 // load the face image
  703.                 faceImgArr[iFace] = cvLoadImage(
  704.                         imgFilename, // filename
  705.                         CV_LOAD_IMAGE_GRAYSCALE); // isColor
  706.        
  707.                 if (faceImgArr[iFace] == null) {
  708.                   throw new RuntimeException("Can't load image from " + imgFilename);
  709.                 }
  710.               }
  711.        
  712.               imgListFile.close();
  713.        
  714.             } catch (IOException ex) {
  715.               throw new RuntimeException(ex);
  716.             }
  717.        
  718.             LOGGER.info("Data loaded from '" + filename + "': (" + nFaces + " images of " + nPersons + " people).");
  719.             final StringBuilder stringBuilder = new StringBuilder();
  720.             stringBuilder.append("People: ");
  721.             if (nPersons > 0) {
  722.               stringBuilder.append("<").append(personNames.get(0)).append(">");
  723.             }
  724.             for (i = 1; i < nPersons && i < personNames.size(); i++) {
  725.               stringBuilder.append(", <").append(personNames.get(i)).append(">");
  726.             }
  727.             LOGGER.info(stringBuilder.toString());
  728.        
  729.             return faceImgArr;
  730.           }
  731.        
  732.          
  733.           private void doPCA() {
  734.             int i;
  735.             CvTermCriteria calcLimit;
  736.             CvSize faceImgSize = new CvSize();
  737.        
  738.             // set the number of eigenvalues to use
  739.             nEigens = nTrainFaces-1 ;
  740.        
  741.             LOGGER.info("allocating images for principal component analysis, using " + nEigens + (nEigens == 1 ? " eigenvalue" : " eigenvalues"));
  742.        
  743.             // allocate the eigenvector images
  744.             faceImgSize.width(trainingFaceImgArr[0].width());
  745.             faceImgSize.height(trainingFaceImgArr[0].height());
  746.             eigenVectArr = new IplImage[nEigens];
  747.             for (i = 0; i < nEigens; i++) {
  748.               eigenVectArr[i] = cvCreateImage(
  749.                       faceImgSize, // size
  750.                       IPL_DEPTH_32F, // depth
  751.                       1); // channels
  752.             }
  753.        
  754.             // allocate the eigenvalue array
  755.             eigenValMat = cvCreateMat(
  756.                     1, // rows
  757.                     nEigens, // cols
  758.                     CV_32FC1); // type, 32-bit float, 1 channel
  759.        
  760.             // allocate the averaged image
  761.             pAvgTrainImg = cvCreateImage(
  762.                     faceImgSize, // size
  763.                     IPL_DEPTH_32F, // depth
  764.                     1); // channels
  765.        
  766.             // set the PCA termination criterion
  767.             calcLimit = cvTermCriteria(
  768.                     CV_TERMCRIT_ITER, // type
  769.                     nEigens, // max_iter
  770.                     1); // epsilon
  771.        
  772.             LOGGER.info("computing average image, eigenvalues and eigenvectors");
  773.             // compute average image, eigenvalues, and eigenvectors
  774.             cvCalcEigenObjects(
  775.                     nTrainFaces, // nObjects
  776.                     trainingFaceImgArr, // input
  777.                     eigenVectArr, // output
  778.                     CV_EIGOBJ_NO_CALLBACK, // ioFlags
  779.                     0, // ioBufSize
  780.                     null, // userData
  781.                     calcLimit,
  782.                     pAvgTrainImg, // avg
  783.                     eigenValMat.data_fl()); // eigVals
  784.        
  785.             LOGGER.info("normalizing the eigenvectors");
  786.             cvNormalize(
  787.                     eigenValMat, // src (CvArr)
  788.                     eigenValMat, // dst (CvArr)
  789.                     1, // a
  790.                     0, // b
  791.                     CV_L1, // norm_type
  792.                     null); // mask
  793.           }
  794.        
  795.          
  796.           private void storeTrainingData() {
  797.             CvFileStorage fileStorage;
  798.             int i;
  799.        
  800.             LOGGER.info("writing data/facedata.xml");
  801.        
  802.             // create a file-storage interface
  803.             fileStorage = cvOpenFileStorage(
  804.                     "data\\facedata.xml", // filename
  805.                     null, // memstorage
  806.                     CV_STORAGE_WRITE, // flags
  807.                     null); // encoding
  808.        
  809.             // Store the person names. Added by Shervin.
  810.             cvWriteInt(
  811.                     fileStorage, // fs
  812.                     "nPersons", // name
  813.                     nPersons); // value
  814.        
  815.             for (i = 0; i < nPersons; i++) {
  816.               String varname = "personName_" + (i + 1);
  817.               cvWriteString(
  818.                       fileStorage, // fs
  819.                       varname, // name
  820.                       personNames.get(i), // string
  821.                       0); // quote
  822.             }
  823.        
  824.             // store all the data
  825.             cvWriteInt(
  826.                     fileStorage, // fs
  827.                     "nEigens", // name
  828.                     nEigens); // value
  829.        
  830.             cvWriteInt(
  831.                     fileStorage, // fs
  832.                     "nTrainFaces", // name
  833.                     nTrainFaces); // value
  834.        
  835.             cvWrite(
  836.                     fileStorage, // fs
  837.                     "trainPersonNumMat", // name
  838.                     personNumTruthMat); // value
  839.        
  840.             cvWrite(
  841.                     fileStorage, // fs
  842.                     "eigenValMat", // name
  843.                     eigenValMat); // value
  844.        
  845.             cvWrite(
  846.                     fileStorage, // fs
  847.                     "projectedTrainFaceMat", // name
  848.                     projectedTrainFaceMat);
  849.        
  850.             cvWrite(fileStorage, // fs
  851.                     "avgTrainImg", // name
  852.                     pAvgTrainImg); // value
  853.        
  854.             for (i = 0; i < nEigens; i++) {
  855.               String varname = "eigenVect_" + i;
  856.               cvWrite(
  857.                       fileStorage, // fs
  858.                       varname, // name
  859.                       eigenVectArr[i]); // value
  860.             }
  861.        
  862.             // release the file-storage interface
  863.             cvReleaseFileStorage(fileStorage);
  864.           }
  865.        
  866.        
  867.           private CvMat loadTrainingData() {
  868.             LOGGER.info("loading training data");
  869.             CvMat pTrainPersonNumMat = null; // the person numbers during training
  870.             CvFileStorage fileStorage;
  871.             int i;
  872.        
  873.             // create a file-storage interface
  874.             fileStorage = cvOpenFileStorage(
  875.                     "data\\facedata.xml", // filename
  876.                     null, // memstorage
  877.                     CV_STORAGE_READ, // flags
  878.                     null); // encoding
  879.             if (fileStorage == null) {
  880.               LOGGER.severe("Can't open training database file 'data/facedata.xml'.");
  881.               return null;
  882.             }
  883.        
  884.             // Load the person names.
  885.             personNames.clear();        // Make sure it starts as empty.
  886.             nPersons = cvReadIntByName(
  887.                     fileStorage, // fs
  888.                     null, // map
  889.                     "nPersons", // name
  890.                     0); // default_value
  891.             if (nPersons == 0) {
  892.               LOGGER.severe("No people found in the training database 'data/facedata.xml'.");
  893.               return null;
  894.             } else {
  895.               LOGGER.info(nPersons + " persons read from the training database");
  896.             }
  897.        
  898.             // Load each person's name.
  899.             for (i = 0; i < nPersons; i++) {
  900.               String sPersonName;
  901.               String varname = "personName_" + (i + 1);
  902.               sPersonName = cvReadStringByName(
  903.                       fileStorage, // fs
  904.                       null, // map
  905.                       varname,
  906.                       "");
  907.               personNames.add(sPersonName);
  908.             }
  909.             LOGGER.info("person names: " + personNames);
  910.        
  911.             // Load the data
  912.             nEigens = cvReadIntByName(
  913.                     fileStorage, // fs
  914.                     null, // map
  915.                     "nEigens",
  916.                     0); // default_value
  917.             nTrainFaces = cvReadIntByName(
  918.                     fileStorage,
  919.                     null, // map
  920.                     "nTrainFaces",
  921.                     0); // default_value
  922.             Pointer pointer = cvReadByName(
  923.                     fileStorage, // fs
  924.                     null, // map
  925.                     "trainPersonNumMat"); // name
  926.             pTrainPersonNumMat = new CvMat(pointer);
  927.        
  928.             pointer = cvReadByName(
  929.                     fileStorage, // fs
  930.                     null, // map
  931.                     "eigenValMat"); // name
  932.             eigenValMat = new CvMat(pointer);
  933.        
  934.             pointer = cvReadByName(
  935.                     fileStorage, // fs
  936.                     null, // map
  937.                     "projectedTrainFaceMat"); // name
  938.             projectedTrainFaceMat = new CvMat(pointer);
  939.        
  940.             pointer = cvReadByName(
  941.                     fileStorage,
  942.                     null, // map
  943.                     "avgTrainImg");
  944.             pAvgTrainImg = new IplImage(pointer);
  945.        
  946.             eigenVectArr = new IplImage[nTrainFaces];
  947.             for (i = 0; i <= nEigens; i++) {
  948.               String varname = "eigenVect_" + i;
  949.               pointer = cvReadByName(
  950.                       fileStorage,
  951.                       null, // map
  952.                       varname);
  953.               eigenVectArr[i] = new IplImage(pointer);
  954.             }
  955.        
  956.             // release the file-storage interface
  957.             cvReleaseFileStorage(fileStorage);
  958.        
  959.             LOGGER.info("Training data loaded (" + nTrainFaces + " training images of " + nPersons + " people)");
  960.             final StringBuilder stringBuilder = new StringBuilder();
  961.             stringBuilder.append("People: ");
  962.             if (nPersons > 0) {
  963.               stringBuilder.append("<").append(personNames.get(0)).append(">");
  964.             }
  965.             for (i = 1; i < nPersons; i++) {
  966.               stringBuilder.append(", <").append(personNames.get(i)).append(">");
  967.             }
  968.             LOGGER.info(stringBuilder.toString());
  969.        
  970.             return pTrainPersonNumMat;
  971.           }
  972.        
  973.  
  974.           private void storeEigenfaceImages() {
  975.             // Store the average image to a file
  976.             LOGGER.info("Saving the image of the average face as 'data/out_averageImage.bmp'");
  977.             cvSaveImage("img\\out_averageImage.jpg", pAvgTrainImg);
  978.        
  979.             // Create a large image made of many eigenface images.
  980.             // Must also convert each eigenface image to a normal 8-bit UCHAR image instead of a 32-bit float image.
  981.             LOGGER.info("Saving the " + nEigens + " eigenvector images as 'data/out_eigenfaces.bmp'");
  982.        
  983.             if (nEigens > 0) {
  984.               // Put all the eigenfaces next to each other.
  985.               int COLUMNS = 8;        // Put upto 8 images on a row.
  986.               int nCols = Math.min(nEigens, COLUMNS);
  987.               int nRows = 1 + (nEigens / COLUMNS);        // Put the rest on new rows.
  988.               int w = eigenVectArr[0].width();
  989.               int h = eigenVectArr[0].height();
  990.               CvSize size = cvSize(nCols * w, nRows * h);
  991.               final IplImage bigImg = cvCreateImage(
  992.                       size,
  993.                       IPL_DEPTH_8U, // depth, 8-bit Greyscale UCHAR image
  994.                       1);        // channels
  995.               for (int i = 0; i < nEigens; i++) {
  996.                 // Get the eigenface image.
  997.                 IplImage byteImg = convertFloatImageToUcharImage(eigenVectArr[i]);
  998.                 // Paste it into the correct position.
  999.                 int x = w * (i % COLUMNS);
  1000.                 int y = h * (i / COLUMNS);
  1001.                 CvRect ROI = cvRect(x, y, w, h);
  1002.                 cvSetImageROI(
  1003.                         bigImg, // image
  1004.                         ROI); // rect
  1005.                 cvCopy(
  1006.                         byteImg, // src
  1007.                         bigImg, // dst
  1008.                         null); // mask
  1009.                 cvResetImageROI(bigImg);
  1010.                 cvReleaseImage(byteImg);
  1011.               }
  1012.               cvSaveImage(
  1013.                       "img\\out_eigenfaces.jpg", // filename
  1014.                       bigImg); // image
  1015.               cvReleaseImage(bigImg);
  1016.             }
  1017.           }
  1018.        
  1019.        
  1020.           private IplImage convertFloatImageToUcharImage(IplImage srcImg) {
  1021.                   IplImage dstImg;
  1022.                   if ((srcImg != null) && (srcImg.width() > 0 && srcImg.height() > 0)) {
  1023.                       // Spread the 32bit floating point pixels to fit within 8bit pixel range.
  1024.                       CvPoint minloc = new CvPoint();
  1025.                       CvPoint maxloc = new CvPoint();
  1026.                       double[] minVal = new double[1];
  1027.                       double[] maxVal = new double[1];
  1028.                       cvMinMaxLoc(srcImg, minVal, maxVal, minloc, maxloc, null);
  1029.                       // Deal with NaN and extreme values, since the DFT seems to give some NaN results.
  1030.                       if (minVal[0] < -1e30) {
  1031.                         minVal[0] = -1e30;
  1032.                       }
  1033.                       if (maxVal[0] > 1e30) {
  1034.                         maxVal[0] = 1e30;
  1035.                       }
  1036.                       if (maxVal[0] - minVal[0] == 0.0f) {
  1037.                         maxVal[0] = minVal[0] + 0.001;  // remove potential divide by zero errors.
  1038.                       }                        // Convert the format
  1039.                       dstImg = cvCreateImage(cvSize(srcImg.width(), srcImg.height()), 8, 1);
  1040.                       cvConvertScale(srcImg, dstImg, 255.0 / (maxVal[0] - minVal[0]), -minVal[0] * 255.0 / (maxVal[0] - minVal[0]));
  1041.                       return dstImg;
  1042.             }
  1043.             return null;
  1044.           }
  1045.        
  1046.        
  1047.           private int findNearestNeighbor(float projectedTestFace[], FloatPointer pConfidencePointer) {
  1048.             double leastDistSq = Double.MAX_VALUE;
  1049.             int i = 0;
  1050.             int iTrain = 0;
  1051.             int iNearest = 0;
  1052.        
  1053.             LOGGER.info("................");
  1054.             LOGGER.info("find nearest neighbor from " + nTrainFaces + " training faces");
  1055.             for (iTrain = 0; iTrain < nTrainFaces; iTrain++) {
  1056.               //LOGGER.info("considering training face " + (iTrain + 1));
  1057.               double distSq = 0;
  1058.        
  1059.               for (i = 0; i < nEigens; i++) {
  1060.                 //LOGGER.debug("  projected test face distance from eigenface " + (i + 1) + " is " + projectedTestFace[i]);
  1061.        
  1062.                 float projectedTrainFaceDistance = (float) projectedTrainFaceMat.get(iTrain, i);
  1063.                 float d_i = projectedTestFace[i] - projectedTrainFaceDistance;
  1064.                 distSq += d_i * d_i; // / eigenValMat.data_fl().get(i);  // Mahalanobis distance (might give better results than Eucalidean distance)
  1065.         //          if (iTrain < 5) {
  1066.         //            LOGGER.info("    ** projected training face " + (iTrain + 1) + " distance from eigenface " + (i + 1) + " is " + projectedTrainFaceDistance);
  1067.         //            LOGGER.info("    distance between them " + d_i);
  1068.         //            LOGGER.info("    distance squared " + distSq);
  1069.         //          }
  1070.               }
  1071.        
  1072.               if (distSq < leastDistSq) {
  1073.                 leastDistSq = distSq;
  1074.                 iNearest = iTrain;
  1075.                 LOGGER.info("  training face " + (iTrain + 1) + " is the new best match, least squared distance: " + leastDistSq);
  1076.               }
  1077.             }
  1078.        
  1079.             // Return the confidence level based on the Euclidean distance,
  1080.             // so that similar images should give a confidence between 0.5 to 1.0,
  1081.             // and very different images should give a confidence between 0.0 to 0.5.
  1082.             float pConfidence = (float) (1.0f - Math.sqrt(leastDistSq / (float) (nTrainFaces * nEigens)) / 255.0f);
  1083.             pConfidencePointer.put(pConfidence);
  1084.        
  1085.             LOGGER.info("training face " + (iNearest + 1) + " is the final best match, confidence " + pConfidence);
  1086.             return iNearest;
  1087.           }
  1088.        
  1089.          
  1090.           private String floatArrayToString(final float[] floatArray) {
  1091.             final StringBuilder stringBuilder = new StringBuilder();
  1092.             boolean isFirst = true;
  1093.             stringBuilder.append('[');
  1094.             for (int i = 0; i < floatArray.length; i++) {
  1095.               if (isFirst) {
  1096.                 isFirst = false;
  1097.               }
  1098.               else {
  1099.                 stringBuilder.append(", ");
  1100.               }
  1101.               stringBuilder.append(floatArray[i]);
  1102.             }
  1103.             stringBuilder.append(']');
  1104.        
  1105.             return stringBuilder.toString();
  1106.           }
  1107.        
  1108.  
  1109.           private String floatPointerToString(final FloatPointer floatPointer) {
  1110.             final StringBuilder stringBuilder = new StringBuilder();
  1111.             boolean isFirst = true;
  1112.             stringBuilder.append('[');
  1113.             for (int i = 0; i < floatPointer.capacity(); i++) {
  1114.               if (isFirst) {
  1115.                 isFirst = false;
  1116.               } else {
  1117.                 stringBuilder.append(", ");
  1118.               }
  1119.               stringBuilder.append(floatPointer.get(i));
  1120.             }
  1121.             stringBuilder.append(']');
  1122.        
  1123.             return stringBuilder.toString();
  1124.           }
  1125.        
  1126.  
  1127.          private String oneChannelCvMatToString(final CvMat cvMat) {
  1128.             //Preconditions
  1129.             if (cvMat.channels() != 1) {
  1130.               throw new RuntimeException("illegal argument - CvMat must have one channel");
  1131.             }
  1132.        
  1133.             final int type = cvMat.type();
  1134.             StringBuilder s = new StringBuilder("[ ");
  1135.             for (int i = 0; i < cvMat.rows(); i++) {
  1136.               for (int j = 0; j < cvMat.cols(); j++) {
  1137.                 if (type == CV_32FC1 || type == CV_32SC1) {
  1138.                   s.append(cvMat.get(i, j));
  1139.                 } else {
  1140.                   throw new RuntimeException("illegal argument - CvMat must have one channel and type of float or signed integer");
  1141.                 }
  1142.                 if (j < cvMat.cols() - 1) {
  1143.                   s.append(", ");
  1144.                 }
  1145.               }
  1146.               if (i < cvMat.rows() - 1) {
  1147.                 s.append("\n  ");
  1148.               }
  1149.             }
  1150.             s.append(" ]");
  1151.             return s.toString();
  1152.           }
  1153.         }
  1154.  

Reply to "Face recognition"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website