コード例 #1
0
        /// <summary>
        /// Routine to train face recognizer with sample images
        /// </summary>

        /*private void TrainRecognizer(string root)
         * {
         *      // This one was actually used to train the recognizer. I didn't push much effort and satisfied once it
         *      // distinguished all detected faces on the sample image, for the real-world application you might want to
         *      // refer to the following documentation:
         *      // OpenCV documentation and samples: http://docs.opencv.org/3.0-beta/modules/face/doc/facerec/tutorial/facerec_video_recognition.html
         *      // Training sets overview: https://www.kairos.com/blog/60-facial-recognition-databases
         *      // Another OpenCV doc: http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html#face-database
         *
         *      int id = 0;
         *      var ids = new List<int>();
         *      var mats = new List<Mat>();
         *      var namesList = new List<string>();
         *
         *      foreach (string dir in Directory.GetDirectories(root))
         *      {
         *              string name = System.IO.Path.GetFileNameWithoutExtension(dir);
         *              if (name.StartsWith("-"))
         *                      continue;
         *
         *              namesList.Add(name);
         *              UnityEngine.Debug.LogFormat("{0} = {1}", id, name);
         *
         *              foreach (string file in Directory.GetFiles(dir))
         *              {
         *                      var bytes = File.ReadAllBytes(file);
         *                      var texture = new UnityEngine.Texture2D(2, 2);
         *                      texture.LoadImage(bytes); // <--- this one has changed in Unity 2017 API and on that version must be changed
         *
         *                      ids.Add(id);
         *
         *                      // each loaded texture is converted to OpenCV Mat, turned to grayscale (assuming we have RGB source) and resized
         *                      var mat = Unity.TextureToMat(texture);
         *                      mat = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
         *                      if (requiredSize.Width > 0 && requiredSize.Height > 0)
         *                              mat = mat.Resize(requiredSize);
         *                      mats.Add(mat);
         *              }
         *              id++;
         *      }
         *
         *      names = namesList.ToArray();
         *
         *      // train recognizer and save result for the future re-use, while this isn't quite necessary on small training sets, on a bigger set it should
         *      // give serious performance boost
         *      recognizer.Train(mats, ids);
         *      recognizer.Save(root + "/face-recognizer.xml");
         * }*/
        #endregion

        /// <summary>
        /// Initializes scene
        /// </summary>
        protected virtual void Awake()
        {
            // classifier
            FileStorage storageFaces = new FileStorage(faces.text, FileStorage.Mode.Read | FileStorage.Mode.Memory);

            cascadeFaces = new CascadeClassifier();
            if (!cascadeFaces.Read(storageFaces.GetFirstTopLevelNode()))
            {
                throw new System.Exception("FaceProcessor.Initialize: Failed to load faces cascade classifier");
            }

            // recognizer
            // There are three available face recognition algorithms in current version of the OpenCV library (please, refer to the OpenCV documentation for details)
            // Our particular training set was trained and saved with FisherFaceRecognizer() and shuld not work with others, however, you can refer to the "TrainRecognizer"
            // method defined above to instructions and sample code regarding training your own recognizer from the scratch
            //recognizer = FaceRecognizer.CreateLBPHFaceRecognizer();
            //recognizer = FaceRecognizer.CreateEigenFaceRecognizer();
            recognizer = FaceRecognizer.CreateFisherFaceRecognizer();

            // This pre-trained set was quite tiny and contained only those 5 persons that are detected and recognized on the image. We took 5 photos for each person from
            // public images on Google, for a real-world application you will need much more sample data for each persona, for more info refer to the OpenCV documentation
            // (there are some links in the "TrainRecognizer" sample function
            recognizer.Load(new FileStorage(recognizerXml.text, FileStorage.Mode.Read | FileStorage.Mode.Memory));

            // label names
            names = new string[] { "Cooper", "DeGeneres", "Nyongo", "Pitt", "Roberts", "Spacey" };
        }
コード例 #2
0
    /// <summary>
    /// Loads the traing data given a (string) folder location
    /// </summary>
    /// <param name="Folder_location"></param>
    /// <returns></returns>
    ///
    private void ChooseFaceRecognizer()
    {
        switch (trainParameters.RecognizerType)
        {
        case ("EMGU.CV.LBPHFaceRecognizer"):
            recognizer = new LBPHFaceRecognizer(trainParameters.LBPH.Radius,
                                                trainParameters.LBPH.Neighbors,
                                                trainParameters.LBPH.GridX,
                                                trainParameters.LBPH.GridY,
                                                trainParameters.LBPH.Treshold); //было(1, 8, 8, 8, 100)
            break;

        case ("EMGU.CV.FisherFaceRecognizer"):
            recognizer = new FisherFaceRecognizer(
                trainParameters.Fisher.Components,
                trainParameters.Fisher.Treshold);     //было (0, 3500)
            break;

        case ("EMGU.CV.EigenFaceRecognizer"):
        default:
            recognizer = new EigenFaceRecognizer(
                trainParameters.Eigen.Components,
                trainParameters.Eigen.Treshold);     //было (80, double.PositiveInfinity)
            break;
        }
    }
コード例 #3
0
        public void SetRecognizer()
        {
            _parameters.RecognizerIndex = _controls.SelectedRecognizer?.Index ?? 0;

            switch (_parameters.RecognizerIndex)
            {
            case 0:
                FaceRecognizer = new EigenFaceRecognizer();
                if (!_directoryService.CheckIfConfigFileExists(0) || _controls.IsRetrainRequired)
                {
                    TrainRecognizer(_parameters.RecognizerIndex);
                }
                break;

            case 1:
                FaceRecognizer = new FisherFaceRecognizer();
                if (!_directoryService.CheckIfConfigFileExists(1) || _controls.IsRetrainRequired)
                {
                    TrainRecognizer(_parameters.RecognizerIndex);
                }
                break;

            case 2:
                FaceRecognizer = new LBPHFaceRecognizer();
                if (!_directoryService.CheckIfConfigFileExists(2) || _controls.IsRetrainRequired)
                {
                    TrainRecognizer(_parameters.RecognizerIndex);
                }
                break;
            }
        }
コード例 #4
0
        public Form1()
        {
            this.InitializeComponent();
            this.faceRecognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
            this.faceRecognizer.Read("face.xml");
            string eyeFile = "haarcascades/haarcascade_eye.xml";

            this.cascadeClassifierForEye = new CascadeClassifier(eyeFile);
            string faceFile = "haarcascades/haarcascade_frontalface_default.xml";

            this.cascadeClassifierForFace = new CascadeClassifier(faceFile);
            CvInvoke.UseOpenCL            = true;
            this.capture = new VideoCapture(0, VideoCapture.API.Any);
            Task.Run(delegate()
            {
                while (true)
                {
                    using (Image <Bgr, byte> frameImage = this.capture.QueryFrame().ToImage <Bgr, byte>(false))
                    {
                        this.camara.Image = this.DetectFace(frameImage);
                        Thread.Sleep(100);
                    }
                }
            });
        }
コード例 #5
0
        public EmguFaceDetector(String preloadedTraining = "")
        {
            // model = new LBPHFaceRecognizer();
            // model = new EigenFaceRecognizer();

            model = new FisherFaceRecognizer(2, 3000);

            if (preloadedTraining == "")
            {
                images = new List <Image <Gray, byte> >();
                labels = new List <int>();
                prepareTrainingData();
                model.Train(images.ToArray(), labels.ToArray());
                model.Save("Default");
            }
            else
            {
                if (preloadedTraining == "Default")
                {
                    model.Load(preloadedTraining);
                }
                else
                {
                    model.Load(preloadedTraining);
                }
            }


            cascadeFace = new CascadeClassifier(AppDomain.CurrentDomain.BaseDirectory + "haarcascades\\haarcascade_frontalface_default.xml");
            cascadeEyes = new CascadeClassifier(AppDomain.CurrentDomain.BaseDirectory + "haarcascades\\haarcascade_eye.xml");
        }
コード例 #6
0
 public FaceRecognitionService(String databasePath, String recognizerFilePath)
 {
     _recognizerFilePath = recognizerFilePath;
     _dataStoreAccess    = new DataStoreAccess(databasePath);
     _faceRecognizer     = new EigenFaceRecognizer(80, 1.1);
     _LBPHFaceRecognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100);
 }
        /// <summary>
        /// متد سازنده <c>FaceRecognitionService</c>
        /// </summary>
        public FaceRecognitionService()
        {
            m_cascadeClassifier = new CascadeClassifier(@"data/haarcascade_frontalface_default.xml");

            ///[Initializing EigenFaceRecognizer]
            double l_threshold;

            if (Settings.Default.EigenFaceRecognizerThresholdInfinity)
            {
                l_threshold = double.PositiveInfinity;
            }
            else
            {
                l_threshold = Settings.Default.EigenFaceRecognizerThreshold;
            }
            m_faceRecognizer = new EigenFaceRecognizer(Settings.Default.EigenFaceRecognizerNumComponents, l_threshold);


            trainFaceRecognizer();
            ///[Initializing EigenFaceRecognizer]
            Settings.Default.EigenFaceRecognizerThreshold = 2;

            ///[Initializing Settings]
            this.FRSSettings = new FRSSettings()
            {
                CascadeClassifierMaxSize             = Settings.Default.CascadeClassifierMaxSize,
                CascadeClassifierMinSize             = Settings.Default.CascadeClassifierMinSize,
                CascadeClassifierScaleFactor         = Settings.Default.CascadeClassifierScaleFactor,
                CascadeClassifierMinNeighbours       = Settings.Default.CascadeClassifierMinNeighbours,
                EigenFaceRecognizerThreshold         = Settings.Default.EigenFaceRecognizerThreshold,
                EigenFaceRecognizerThresholdInfinity = Settings.Default.EigenFaceRecognizerThresholdInfinity,
                EigenFaceRecognizerNumComponents     = Settings.Default.EigenFaceRecognizerNumComponents,
            };
            ///[Initializing Settings]
        }
 private bool LoadTrainingData()
 {
     mydb           = new DBConn();
     allname        = mydb.getLabelList();
     trainingImages = mydb.getTrainedImageList();
     int[] temp = Enumerable.Range(0, (allname.Count)).ToArray();
     if (mydb.getImageCount() > 0)
     {
         if (trainingImages.Length != 0)
         {
             //set round and ...
             //termCrit = new MCvTermCriteria(mydb.getImageCount(), 0.001);
             //Eigen face recognizer
             recognizer = new FisherFaceRecognizer(0, 3200);//4000
             recognizer.Train(trainingImages, temp);
             return(true);
         }
         else
         {
             return(false);
         }
     }
     else
     {
         return(false);
     }
 }
コード例 #9
0
 public static void InitializeFaceRecognizer()
 {
     _faceRecognizer?.Dispose();
     _faceRecognizer = new LBPHFaceRecognizer(Properties.Settings.Default.RecognitionRadius, Properties.Settings.Default.RecognitionNeighbours, 8, 8, Properties.Settings.Default.RecognitionThreshold);
     if (!File.Exists(Properties.Settings.Default.RecognitionTrainFile))
     {
         try
         {
             Directory.CreateDirectory(Path.GetDirectoryName(Properties.Settings.Default.RecognitionTrainFile));
             File.Create(Properties.Settings.Default.RecognitionTrainFile).Close();
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Could not create recognition file: " + ex);
         }
     }
     else
     {
         try
         {
             _faceRecognizer.Load(Properties.Settings.Default.RecognitionTrainFile);
             _trained = true;
         }
         catch (Exception ex)
         {
             Debug.WriteLine("Could not load recognition file: " + ex);
         }
     }
 }
コード例 #10
0
        private void Detect(FaceRecognizer recognizer, CascadeClassifier haar_cascade, Mat original, List <NetworkStream> displays, string[] indexToName)
        {
            var sw = new Stopwatch();

            sw.Start();

            var gray = original.CvtColor(ColorConversion.BgrToGray);

            var users = new List <string>();

            var faces = haar_cascade.DetectMultiScale(gray);

            foreach (var faceRect in faces)
            {
                var face        = gray.SubMat(faceRect);
                var faceResized = face.Resize(new OpenCvSharp.CPlusPlus.Size(100, 100), 1, 1, Interpolation.Cubic);

                int    label;
                double confidence;
                recognizer.Predict(faceResized, out label, out confidence);
                //if (confidence > 600)
                {
                    Debug.WriteLine("{0} {1}", label, confidence);
                    users.Add(indexToName[label]);
                }

                original.Rectangle(faceRect, new Scalar(0, 255, 0), 3);
                original.PutText(label.ToString(), faceRect.Location, FontFace.HersheyPlain, 1, new Scalar(0, 255, 0));

                // faceResized.SaveImage("data/people/hekwal/" + Guid.NewGuid() + ".jpg");
            }

            var json = JArray.FromObject(users).ToString();

            foreach (var disply in displays)
            {
                try
                {
                    var arr = BitConverter.GetBytes(json.Length);
                    disply.Write(arr, 0, arr.Length);

                    arr = Encoding.UTF8.GetBytes(json);
                    disply.Write(arr, 0, arr.Length);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }

            sw.Stop();
            Debug.WriteLine("Processed frame in " + sw.ElapsedMilliseconds);

            sw.Start();
            pictureBox1.Image = Bitmap.FromStream(new MemoryStream(original.Resize(new OpenCvSharp.CPlusPlus.Size(256, 256), 1, 1, Interpolation.Cubic).ToBytes()));
            // pictureBox1.Image = new Bitmap(original.Cols, original.Rows, original.ElemSize(), System.Drawing.Imaging.PixelFormat.Format24bppRgb, original.Data);
            sw.Stop();
            Debug.WriteLine("Updated UI in " + sw.ElapsedMilliseconds);
        }
 private void Train()
 {
     //  recognizerEMGUCV = new LBPHFaceRecognizer(1, 4, 8, 8, 50);
     recognizerEMGUCV = new LBPHFaceRecognizer(1, 8, 8, 8, 65);
     //     recognizerEMGUCV = new FisherFaceRecognizer(0, 3500);
     //    recognizerEMGUCV = new EigenFaceRecognizer(80, double.PositiveInfinity);
     recognizerEMGUCV.Train(trainingImage.ImageToArray(), trainingImage.LabelToArray());
 }
 public void Dispose()
 {
     recognizer     = null;
     trainingImages = null;
     allname        = null;
     Error          = null;
     GC.Collect();
 }
コード例 #13
0
ファイル: Form1.cs プロジェクト: asamirel/GraduationProject
 public Form1()
 {
     InitializeComponent();
     fr1     = new EigenFaceRecognizer(80, double.PositiveInfinity);         //The recognitoion object
     fr2     = new FisherFaceRecognizer(-1, 3100);                           //The recognitoion object
     fr3     = new LBPHFaceRecognizer(1, 8, 8, 8, 100);                      //50
     cascade = new CascadeClassifier("haarcascade_frontalface_default.xml"); //this file contains the training
 }
コード例 #14
0
 /// <summary>
 /// Dispose of Class call Garbage Collector
 /// </summary>
 public void Dispose()
 {
     recognizer     = null;
     trainingImages = null;
     Names_List     = null;
     Error          = null;
     GC.Collect();
 }
コード例 #15
0
        public EigenFaceRecognition(string faceDetectionTrainingFilePath, int faceImagesPerUser, IExceptionLogger exceptionLogger)
        {
            _exceptionLogger   = exceptionLogger;
            _faceImagesPerUser = faceImagesPerUser;

            _recognizer = new EigenFaceRecognizer(ComponentsNumber, Threshold);
            _detector   = new CascadeClassifier(new DirectoryInfo(Application.StartupPath).Parent.Parent.FullName + faceDetectionTrainingFilePath);
        }
コード例 #16
0
        public EigenFaceRecognition(string faceDetectionTrainingFilePath, int faceImagesPerUser)
        {
            _faceImagesPerUser = faceImagesPerUser;

            _recognizer = new EigenFaceRecognizer(ComponentsNumber, Threshold);

            _cascade = new CascadeClassifier(faceDetectionTrainingFilePath);
        }
コード例 #17
0
        // Use this for initialization
        void Start()
        {
            List <Mat> images     = new List <Mat> ();
            List <int> labelsList = new List <int> ();
            MatOfInt   labels     = new MatOfInt();

            images.Add(Highgui.imread(Utils.getFilePath("facerec/facerec_0.bmp"), 0));
            images.Add(Highgui.imread(Utils.getFilePath("facerec/facerec_1.bmp"), 0));

            labelsList.Add(0);
            labelsList.Add(1);
            labels.fromList(labelsList);

            Mat testSampleMat = Highgui.imread(Utils.getFilePath("facerec/facerec_sample.bmp"), 0);

            int testSampleLabel = 0;


//						foreach (Mat item in images) {
//								Debug.Log ("images.ToString " + item.ToString ());
//						}
//						foreach (int item in labelsList) {
//								Debug.Log ("labels.ToString " + item.ToString ());
//						}

            int[]    predictedLabel      = new int[1];
            double[] predictedConfidence = new double[1];


            FaceRecognizer faceRecognizer = FaceRecognizer.createEigenFaceRecognizer();

            faceRecognizer.train(images, labels);

            faceRecognizer.predict(testSampleMat, predictedLabel, predictedConfidence);


            Debug.Log("Predicted class: " + predictedLabel [0] + " / " + "Actual class: " + testSampleLabel);
            Debug.Log("Confidence: " + predictedConfidence [0]);


            Mat predictedMat = images [predictedLabel [0]];

            Mat baseMat = new Mat(testSampleMat.rows(), predictedMat.cols() + testSampleMat.cols(), CvType.CV_8UC1);

            predictedMat.copyTo(baseMat.submat(new OpenCVForUnity.Rect(0, 0, predictedMat.cols(), predictedMat.rows())));
            testSampleMat.copyTo(baseMat.submat(new OpenCVForUnity.Rect(predictedMat.cols(), 0, testSampleMat.cols(), testSampleMat.rows())));

            Core.putText(baseMat, "Predicted", new Point(10, baseMat.rows() - 5), Core.FONT_HERSHEY_SIMPLEX, 0.4, new Scalar(255), 1, Core.LINE_AA, false);
            Core.putText(baseMat, "TestSample", new Point(predictedMat.cols() + 10, baseMat.rows() - 5), Core.FONT_HERSHEY_SIMPLEX, 0.4, new Scalar(255), 1, Core.LINE_AA, false);


            Texture2D texture = new Texture2D(baseMat.cols(), baseMat.rows(), TextureFormat.RGBA32, false);

            Utils.matToTexture2D(baseMat, texture);

            gameObject.GetComponent <Renderer> ().material.mainTexture = texture;
        }
コード例 #18
0
 public ReconizerEngine()
 {
     this.recognizeFilePath = Environment.CurrentDirectory + ConfigurationManager.AppSettings["recognizerPath"];
     this.dataStoreAccess   = new DataStoreAccess();
     //EigenFaceRecognizer 基于PCA变换的人脸识别
     //FisherFaceRecognizer 基于Fisher变换的人脸识别
     //LBPHFaceRecognizer 基于局部二值模式的人脸识别
     this.faceRecognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
 }
コード例 #19
0
 public TrainData(String courseName)
 {
     InitializeComponent();
     courseName_ = courseName;                                                   // set courseName ------------------->
     fr1         = new EigenFaceRecognizer(80, double.PositiveInfinity);         //The recognitoion object
     fr2         = new FisherFaceRecognizer(-1, 3100);                           //The recognitoion object
     fr3         = new LBPHFaceRecognizer(1, 8, 8, 8, 100);                      //50
     cascade     = new CascadeClassifier("haarcascade_frontalface_default.xml"); //this file contains the training
 }
コード例 #20
0
        public RecognizerEngine(string recognizerFilePath)
        {
            recognizerPath = recognizerFilePath;
            faceRecognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100);
            //recognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
            //recognizer = new FisherFaceRecognizer(0, 3500);//4000

            _context = new KataskopeyaContext();
        }
コード例 #21
0
        public RecognizerEngine(string databasePath, string recognizerFilePath)
        {
            _recognizerFilePath = recognizerFilePath;
            _dataStoreAccess    = new WebApiHelper(databasePath);
            _faceRecognizer     = new EigenFaceRecognizer(80, double.PositiveInfinity);

            // Закешировал данные из БД.
            GetAllEmployee();
        }
コード例 #22
0
        //CudaCascadeClassifier cuda_ccAltFace;



        public FaceRecognition()
        {
            this.names = new List <Tuple <int, string> >();

            //recognizer = new EigenFaceRecognizer(80,double.PositiveInfinity);
            recognizer = new LBPHFaceRecognizer(1, 8, 8, 8);
            //recognizer = new FisherFaceRecognizer(0, 3500);

            LoadRecognizer();
        }
コード例 #23
0
        public void loadRecognizer()
        {
            try
            {
                //Eigen face recognizer
                //Parameters:
                //      num_components – The number of components (read: Eigenfaces) kept for this Prinicpal
                //          Component Analysis. As a hint: There’s no rule how many components (read: Eigenfaces)
                //          should be kept for good reconstruction capabilities. It is based on your input data,
                //          so experiment with the number. Keeping 80 components should almost always be sufficient.
                //
                //      threshold – The threshold applied in the prediciton. This still has issues as it work inversly to LBH and Fisher Methods.
                //          if you use 0.0 recognizer.Predict will always return -1 or unknown if you use 5000 for example unknow won't be reconised.
                //          As in previous versions I ignore the built in threhold methods and allow a match to be found i.e. double.PositiveInfinity
                //          and then use the eigen distance threshold that is return to elliminate unknowns.
                //
                //NOTE: The following causes the confusion, sinc two rules are used.
                //--------------------------------------------------------------------------------------------------------------------------------------
                //Eigen Uses
                //          0 - X = unknown
                //          > X = Recognised
                //
                //Fisher and LBPH Use
                //          0 - X = Recognised
                //          > X = Unknown
                //
                // Where X = Threshold value



                switch (Recognizer_Type)
                {
                case ("EMGU.CV.LBPHFaceRecognizer"):
                    recognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100);    //50
                    break;

                case ("EMGU.CV.FisherFaceRecognizer"):
                    recognizer = new FisherFaceRecognizer(0, 3500);    //4000
                    break;

                case ("EMGU.CV.EigenFaceRecognizer"):
                default:
                    recognizer = new EigenFaceRecognizer(90, double.PositiveInfinity);
                    break;
                }

                recognizer.Train(imgList.ToArray(), imgIds.ToArray());
                isTrained = true;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #24
0
    public bool Update(List <string> listFace, List <int> listLabel)
    {
        try
        {
            trainingImages.Clear();
            for (int i = 0; i < listFace.Count; i++)
            {
                trainingImages.Add(new Image <Gray, byte>(Application.StartupPath + "\\" + listFace[i]));
            }
            Names_List_ID = listLabel;

            if (trainingImages.ToArray().Length != 0)
            {
                //Eigen face recognizer
                //Parameters:
                //      num_components – The number of components (read: Eigenfaces) kept for this Prinicpal
                //          Component Analysis. As a hint: There’s no rule how many components (read: Eigenfaces)
                //          should be kept for good reconstruction capabilities. It is based on your input data,
                //          so experiment with the number. Keeping 80 components should almost always be sufficient.
                //
                //      threshold – The threshold applied in the prediciton. This still has issues as it work inversly to LBH and Fisher Methods.
                //          if you use 0.0 recognizer.Predict will always return -1 or unknown if you use 5000 for example unknow won't be reconised.
                //          As in previous versions I ignore the built in threhold methods and allow a match to be found i.e. double.PositiveInfinity
                //          and then use the eigen distance threshold that is return to elliminate unknowns.
                //
                //NOTE: The following causes the confusion, sinc two rules are used.
                //--------------------------------------------------------------------------------------------------------------------------------------
                //Eigen Uses
                //          0 - X = unknown
                //          > X = Recognised
                //
                //Fisher and LBPH Use
                //          0 - X = Recognised
                //          > X = Unknown
                //
                // Where X = Threshold value


                recognizer = new FisherFaceRecognizer(0, 3500);//4000

                recognizer.Train(trainingImages.ToArray(), Names_List_ID.ToArray());
                _IsTrained = true;
                return(true);
            }
            else
            {
                return(false);
            }
        }
        catch {
            _IsTrained = false;
            return(false);
        }
    }
コード例 #25
0
        public EigenFaceRecognition(string faceDetectionTrainingFilePath, List <Image <Gray, byte> > trainingSet, List <string> namesList, int faceImagesPerUser)
        {
            //check if parameters are okey

            this.trainingSet       = trainingSet;
            this.namesList         = namesList;
            this.faceImagesPerUser = faceImagesPerUser;

            recognizer = new EigenFaceRecognizer(COMPONENTS_NUMBER, THRESHOLD);
            cascade    = new CascadeClassifier(faceDetectionTrainingFilePath);

            Train();
        }
コード例 #26
0
 private void BtnLoad_Click(object sender, System.EventArgs e)
 {
     faceRecognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100.0);
     if (File.Exists("trainedData.xml"))
     {
         modeltrained = true;
         faceRecognizer.Load("trainedData.xml");
     }
     else
     {
         MessageBox.Show("you didnt train the model. Press train button!");
     }
 }
コード例 #27
0
        public static RollSystemMobile.Models.RecognizerResult RecognizeStudentForAttendance(int RollCallID, String ImagePath)
        {
            //Dua ID cua roll call, cac hinh da up, cho ra danh sach ket qua

            FaceRecognizer FaceRec = CreateRollCallRecognizer(RollCallID);


            RollSystemMobile.Models.RecognizerResult Result = RecognizeFromImage(FaceRec, ImagePath);

            //Dung xong nho dispose cho nhe bo nho
            FaceRec.Dispose();
            return(Result);
        }
コード例 #28
0
        /// <summary>
        /// Loads the traing data given a (string) folder location
        /// </summary>
        /// <returns></returns>
        private bool LoadTrainingData()
        {
            try
            {
                //Load of previus trainned faces and labels for each image
                var labelsinfo = File.ReadAllText(Application.StartupPath + "\\Resources\\TrainedFaces\\TrainedLabels.txt");
                var labels     = labelsinfo.Split('%');
                _numLabels = Convert.ToInt16(labels[0]);
                _contTrain = _numLabels;

                for (var tf = 1; tf < _numLabels + 1; tf++)
                {
                    var loadFaces = "face" + tf + ".bmp";
                    trainingImages.Add(new Image <Gray, byte>(Application.StartupPath + "\\Resources\\TrainedFaces\\" + loadFaces));
                    _namesList.Add(labels[tf]);
                }

                if (trainingImages.ToArray().Length == 0)
                {
                    return(false);
                }

                switch (_recognizerType)
                {
                case RecognizerType.LBPHFaceRecognizer:
                    recognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100);    //50
                    break;

                case RecognizerType.FisherFaceRecognizer:
                    recognizer = new FisherFaceRecognizer(0, 3500);    //4000
                    break;

                case RecognizerType.EigenFaceRecognizer:
                    recognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
                    break;

                default:
                    recognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
                    break;
                }

                recognizer.Train(trainingImages.ToArray(), Enumerable.Range(0, _namesList.Count).ToArray());
                return(true);
            }
            catch (Exception ex)
            {
                GetError = ex.ToString();
                return(false);
            }
        }
コード例 #29
0
ファイル: Recog.cs プロジェクト: marceljdb/emguRecognitizion
        private void FaceTrainer(int id, List <Bitmap> listaImagens)
        {
            var listaFaces   = DetectFaceTrainer(listaImagens);
            var termCriteria = new MCvTermCriteria(listaFaces.Count, 0.001);

            List <int> listaId = new List <int>();

            foreach (var img in listaFaces)
            {
                listaId.Add(id);
            }

            recognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 80);//50
            recognizer.Train(listaFaces.ToArray(), listaId.ToArray());
        }
コード例 #30
0
 private void LoadRecognizer()
 {
     switch (_faceRecognitionType)
     {
         case FaceRecognitionType.LBPHFaceRecognizer:
             _faceRecognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 100);
             break;
         case FaceRecognitionType.FisherFaceRecognizer:
             _faceRecognizer = new FisherFaceRecognizer(0, 3500);
             break;
         case FaceRecognitionType.EigenFaceRecognizer:
             _faceRecognizer = new EigenFaceRecognizer(80, double.PositiveInfinity);
             break;
     }          
 }
コード例 #31
0
 private void btnLoadRecog_Click(object sender, EventArgs e)
 {
     FaceRecognizer fcrec = new FaceRecognizer();
     fcrec.Show();
 }