private void FisherFaceRecognition(object sender, EventArgs e) { Frame = _capture.QueryFrame().ToImage <Bgr, byte>(); var frame = Frame.Resize(frameW, frameH, Inter.Cubic); grayFrame = frame.Convert <Gray, Byte>(); var faces = cascadeClassifier.DetectMultiScale(grayFrame, 1.1, 10, Size.Empty); foreach (var f in faces) { fisherFaceRecognizer = new FisherFaceRecognizer(Count, double.PositiveInfinity); fisherFaceRecognizer.Train(trainingImages.ToArray(), indexLabels.ToArray()); var result = fisherFaceRecognizer.Predict(frame.Copy(f).Convert <Gray, Byte>().Resize(100, 100, Inter.Cubic)); if (result.Label == -1) { frame.Draw(f, new Bgr(Color.Red), 2); frame.Draw("Unknown", new Point(f.X, f.Y - 10), font, 0.8, new Bgr(Color.Blue), 2, new LineType(), false); } else { frame.Draw(f, new Bgr(Color.Green), 2); frame.Draw(nameLabels[result.Label], new Point(f.X, f.Y - 10), font, 0.8, new Bgr(Color.Blue), 2, new LineType(), false); } alertMessage.Text = (alert + "เริ่มการ Face Recognition ด้วยวิธีการ " + RecognitionType.Text + " แล้ว \r\n" + "Distance " + result.Distance + "\r\n Faces " + faces.Length.ToString()); } imgFrame.Image = frame.Resize(imgBoxW, imgBoxH, Inter.Cubic); }
private bool LoadTrainingData() { mydb = new DBConn(); imagelabel = mydb.getLabelNumList().ToArray(); imageStringlabel = mydb.getLabelList().ToArray(); trainingImages = mydb.getTrainedImageList(); Itrainingimage = trainingImages; if (mydb.getImageCount() > 0) { if (trainingImages.Length != 0) { f_recognize = new FisherFaceRecognizer(0, 123.0); f_recognize.Train(Itrainingimage, imagelabel); return(true); } else { return(false); } } else { return(false); } }
private bool CdmFaceTrain(bool minus = false) { try { if (minus && trainingImages.Count > 1) { trainingImages.RemoveAt(0); Names_List_ID.RemoveAt(0); } else if (trainingImages.Count < 1) { UpdateStatus(string.Format(" {0} ,not trained.", trainingImages.Count)); return(true); } UpdateStatus(string.Format(" {0} photo for trainin.", trainingImages.Count)); recognizer.Train(trainingImages.ToArray(), Names_List_ID.ToArray()); UpdateStatus(string.Format("trained trained {0}", trainingImages.Count)); return(true); } catch (Exception ex) { UpdateStatus(string.Format("trained error {0}", ex)); return(false); } }
private static FaceRecognizer CreateRollCallRecognizer(int RollCallID) { //Tu rollcall ID, tao face recognizer, train //FaceRecognizer FaceRec = new LBPHFaceRecognizer(1, 8, 8, 8, 75); FaceRecognizer FaceRec = new FisherFaceRecognizer(80, RECOGNIZER_THREEHOLD); List <int> StudentIDs = new List <int>(); List <Image <Gray, byte> > StudentImages = new List <Image <Gray, byte> >(); RollCallBusiness RollBO = new RollCallBusiness(); //Load danh sach student cua roll call RollCall RollCall = RollBO.GetRollCallByID(RollCallID); foreach (var Student in RollCall.Students) { foreach (var Image in Student.StudentImages) { //Load ID va anh de train cho bo recognizer StudentIDs.Add(Image.StudentID); String TrainingImagePath = TRAINING_FOLDER_PATH + "/" + Image.ImageLink; Image <Gray, byte> TrainingImage = new Image <Gray, byte>(TrainingImagePath); TrainingImage._EqualizeHist(); StudentImages.Add(TrainingImage); } } FaceRec.Train(StudentImages.ToArray(), StudentIDs.ToArray()); return(FaceRec); }
public void TrainImages() { string path = Application.StartupPath + @"/../../Images/"; string[] files = Directory.GetFiles(path, "*.jpg", SearchOption.AllDirectories); // int[] labelsDb = _context.Labels.Select(_ => _.LabelNumber).ToArray(); List <int> labelsDb = new List <int>(); Mat[] matImages = new Mat[files.Length]; for (int i = 0; i < files.Length; i++) { matImages[i] = new Image <Gray, byte>(files[i]).Mat; string[] strings = files[i].Split('-'); string number = strings[strings.Length - 1].Split('.')[0]; labelsDb.Add(int.Parse(number)); } VectorOfMat images = new VectorOfMat(matImages); VectorOfInt labels = new VectorOfInt(labelsDb.ToArray()); faceRecognizer.Train(images, labels); faceRecognizer.Write(Application.StartupPath + @"/../../Images/eigenRecognizer.yml"); fisherRecognizer.Train(images, labels); fisherRecognizer.Write(Application.StartupPath + @"/../../Images/fisherRecognizer.yml"); LBPHFaceRecognizer.Train(images, labels); LBPHFaceRecognizer.Write(Application.StartupPath + @"/../../Images/lpbhRecognizer.yml"); isTrained = true; }
/// <summary> /// Face recognition based on Fisher classifier using eigen /// fisher faces</summary> /// <param name="labels">The set of labels in the training set</param> /// <param name="trainingImages">The set of images(faces) in the /// training set</param> /// <param name="face">The face detected in gray scale /// to be recognized. The dimension of the image must be /// equal to the dimension of the images in the training set</param> /// <returns>A string representing the label of the face recognized /// or an empty string if no matches were found</returns> public String recognizeFisherFace(List <String> labels, List <Image <Gray, Byte> > trainingImages, Bitmap face) { String label = String.Empty; InitParams(); Image <Bgr, Byte> imageEmgu = new Image <Bgr, Byte>(face); Image <Gray, Byte> extractedFace = imageEmgu.Convert <Gray, Byte>().Copy().Resize( 100, 100, INTER.CV_INTER_CUBIC); extractedFace._EqualizeHist(); if (trainingImages.ToArray().Length != 0) { FisherFaceRecognizer recognizer = new FisherFaceRecognizer(0, Treshold); int[] labelsInt = new int[labels.ToArray().Length]; for (int i = 0; i < labels.ToArray().Length; i++) { labelsInt[i] = i; } recognizer.Train(trainingImages.ToArray(), labelsInt.ToArray()); FisherFaceRecognizer.PredictionResult pr; pr = recognizer.Predict(extractedFace); if (pr.Label != -1) { label = labels[pr.Label]; MostSimilarFace = trainingImages[pr.Label]; MostSimilarFaceIndex = pr.Label; MostSimilarFaceDistance = (float)pr.Distance; MostSimilarFaceLabel = labels[pr.Label]; } else { recognizer = new FisherFaceRecognizer(0, 10000); recognizer.Train(trainingImages.ToArray(), labelsInt.ToArray()); pr = recognizer.Predict(extractedFace); MostSimilarFace = trainingImages[pr.Label]; MostSimilarFaceIndex = pr.Label; MostSimilarFaceDistance = (float)pr.Distance; MostSimilarFaceLabel = labels[pr.Label]; } } return(label); }
public bool LoadTrainingData() { if (File.Exists(LabelsFile)) { try { //Clearing Lists In Case of Retrain Operation Occoured. ListOFNames.Clear(); ListOfIds.Clear(); trainingImages.Clear(); //Reading Xml File FileStream filestream = File.OpenRead(LabelsFile); long filelength = filestream.Length; byte[] xmlBytes = new byte[filelength]; filestream.Read(xmlBytes, 0, (int)filelength); filestream.Close(); MemoryStream xmlStream = new MemoryStream(xmlBytes); using (XmlReader xmlreader = XmlTextReader.Create(xmlStream)) { while (xmlreader.Read()) { if (xmlreader.IsStartElement()) { switch (xmlreader.Name) { case "NAME": if (xmlreader.Read()) { ListOfIds.Add(ListOFNames.Count); ListOFNames.Add(xmlreader.Value.Trim()); NumLabels += 1; } break; case "FILE": if (xmlreader.Read()) { //PROBLEM HERE IF TRAININGG MOVED trainingImages.Add(new Image <Gray, byte>(Variables.DataSetFolder + "\\" + xmlreader.Value.Trim())); } break; } } } } ContTrain = NumLabels; if (trainingImages.ToArray().Length != 0) { eigen.Train(trainingImages.ToArray(), ListOfIds.ToArray()); fisher.Train(trainingImages.ToArray(), ListOfIds.ToArray()); Lp.Train(trainingImages.ToArray(), ListOfIds.ToArray()); Loaded = true; return(true); } else { return(false); } } catch (Exception Exp) { HasError = true; Debug.WriteLine("Error In Loading Function : " + Exp.Message); return(false); } } else { return(false); } }
private void button1_Click(object sender, EventArgs e) { if (comboBoxAlgorithm.Text == "EigenFaces") { try { string dataDirectory = Directory.GetCurrentDirectory() + "\\TrainedFaces"; string[] files = Directory.GetFiles(dataDirectory, "*.jpg", SearchOption.AllDirectories); eigenTrainedImageCounter = 0; foreach (var file in files) { Image <Bgr, Byte> TrainedImage = new Image <Bgr, Byte>(file); if (eqHisChecked.Checked == true) { TrainedImage._EqualizeHist(); } eigenTrainingImages.Add(TrainedImage.Convert <Gray, Byte>()); eigenlabels.Add(fileName(file)); eigenIntlabels.Add(eigenTrainedImageCounter); eigenTrainedImageCounter++; richTextBox1.Text += fileName(file) + "\n"; } /* * //TermCriteria for face recognition with numbers of trained images like maxIteration * MCvTermCriteria termCrit = new MCvTermCriteria(eigenTrainedImageCounter, 0.001); * * //Eigen face recognizer * eigenObjRecognizer=new EigenObjectRecognizer( * eigenTrainingImages.ToArray(), * eigenlabels.ToArray(), * 3000, * ref termCrit); */ eigenFaceRecognizer = new EigenFaceRecognizer(eigenTrainedImageCounter, 2000); eigenFaceRecognizer.Train(eigenTrainingImages.ToArray(), eigenIntlabels.ToArray()); //eigenFaceRecognizer.Save(dataDirectory + "\\trainedDataEigen.dat"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else if (comboBoxAlgorithm.Text == "FisherFaces") { try { string dataDirectory = Directory.GetCurrentDirectory() + "\\TrainedFaces"; string[] files = Directory.GetFiles(dataDirectory, "*.jpg", SearchOption.AllDirectories); fisherTrainedImageCounter = 0; foreach (var file in files) { Image <Bgr, Byte> TrainedImage = new Image <Bgr, Byte>(file); fisherTrainingImages.Add(TrainedImage.Convert <Gray, Byte>()); if (eqHisChecked.Checked == true) { TrainedImage._EqualizeHist(); } fisherlabels.Add(fileName(file)); fisherIntlabels.Add(fisherTrainedImageCounter); fisherTrainedImageCounter++; richTextBox1.Text += fileName(file) + "\n"; } fisherFaceRecognizer = new FisherFaceRecognizer(fisherTrainedImageCounter, 2000); fisherFaceRecognizer.Train(fisherTrainingImages.ToArray(), fisherIntlabels.ToArray()); //fisherFaceRecognizer.Save(dataDirectory + "\\trainedDataFisher.dat"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else if (comboBoxAlgorithm.Text == "LBPHFaces") { try { string dataDirectory = Directory.GetCurrentDirectory() + "\\TrainedFaces"; string[] files = Directory.GetFiles(dataDirectory, "*.jpg", SearchOption.AllDirectories); lbphTrainedImageCounter = 0; foreach (var file in files) { Image <Bgr, Byte> TrainedImage = new Image <Bgr, Byte>(file); if (eqHisChecked.Checked == true) { TrainedImage._EqualizeHist(); } lbphTrainingImages.Add(TrainedImage.Convert <Gray, Byte>()); lbphlabels.Add(fileName(file)); lbphIntlabels.Add(lbphTrainedImageCounter); lbphTrainedImageCounter++; richTextBox1.Text += fileName(file) + "\n"; } lbphFaceRecognizer = new LBPHFaceRecognizer(1, 8, 8, 8, 400); lbphFaceRecognizer.Train(lbphTrainingImages.ToArray(), lbphIntlabels.ToArray()); lbphFaceRecognizer.Save(dataDirectory + "\\trainedDataLBPH.dat"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }