소스 검색

Подпись имени над изображением лица

Вячеслав Терешенко 2 년 전
부모
커밋
036d63be88

+ 46 - 70
ImpulseVision/FormGuard.cs

@@ -57,7 +57,7 @@ namespace ImpulseVision
         private EigenFaceRecognizer recognizer;
         private Timer CaptureTimer;
 
-        public string UserName { get; set; } = "FACE NOT EXISTS";
+        public string UserName { get; set; } = "Лицо не обнаружено";
 
         #region FaceName
         private string faceName;
@@ -66,30 +66,57 @@ namespace ImpulseVision
             get { return faceName; }
             set
             {
-                faceName = value.ToUpper();
-
-                this.Text = faceName;
+                faceName = value;
+                if (faceName == "Лицо не обнаружено")
+                {
+                    IsRecognized = false;
+                }
+                else
+                {
+                    IsRecognized = true;
+                }
+                this.Text = IsRecognized.ToString();
                 UserName = faceName;
-                //PbxFaces.Invoke(DispatcherPriority.Normal, new Action(() => { lblFaceName.Content = faceName; }));
                 NotifyPropertyChanged();
             }
         }
         #endregion
         #region CameraCaptureImage
         private Bitmap cameraCapture;
+        //Image<Bgr, byte> bgrFrame, Rectangle face
+        Rectangle CurrentFace;
         public Bitmap CameraCapture
         {
             get { return cameraCapture; }
             set
             {
                 cameraCapture = value;
-                //imgCamera.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { imgCamera.Source = BitmapToImageSource(cameraCapture); }));
+
+                DrawName(cameraCapture, CurrentFace);
 
                 PbxEther.Image = cameraCapture;
-                //PbxFaces.Image = BitmapToImageSource(cameraCapture);
                 NotifyPropertyChanged();
             }
         }
+        /// <summary>
+        /// надпись над именем
+        /// </summary>
+        private void DrawName(Bitmap cameraCapture, Rectangle face)
+        {
+            Pen PenForFace = new Pen(Brushes.Red, 5);
+            Brush BrushForFace = Brushes.White;
+            Font MyFont = new Font("Segoe UI Variable Small Semibol; 12pt; style=Bold", 12, FontStyle.Regular);
+
+            Brush BrushInfo = Brushes.White;
+            Pen PenInfo = new Pen(Brushes.White, 4);
+
+            Graphics Graph = Graphics.FromImage(cameraCapture);
+
+            //Graph.DrawRectangle(PenForFace, face.X, face.Y, face.Width, face.Height);
+            //позиция отрисовки имени человека
+            Point PointName = new Point(face.X, face.Y - 25);
+            Graph.DrawString($"{UserName}", MyFont, BrushForFace, PointName);
+        }
         #endregion
         #region CameraCaptureFaceImage
         private Bitmap cameraCaptureFace;
@@ -106,10 +133,10 @@ namespace ImpulseVision
                 NotifyPropertyChanged();
             }
         }
-
         #endregion
 
-
+        //уведомление о том, что пользователь распознан
+        bool IsRecognized = false;
         //включена ли на данный момент камера
         bool IsWorking = false;
         //выбранная камера
@@ -122,9 +149,7 @@ namespace ImpulseVision
         HashSet<string> HtBefore = new HashSet<string>();
         //пути доступа к изображениям пользователей
         List<Pictures> LstUserPictures = new List<Pictures>();
-
         SqlConnection SCon = new SqlConnection(Properties.Settings.Default.ImpulseVisionAppConnectionString);
-
         //идентификаторы пользователей, лица которых будут распознаваться
         List<string> LstUserID = new List<string>();
         #endregion
@@ -142,7 +167,7 @@ namespace ImpulseVision
             //haar cascade classifier
             if (!File.Exists(Config.HaarCascadePath))
             {
-                string text = "Не удаётся найти файл данных каскад Хаара:\n\n";
+                string text = "Не удаётся найти файл данных - каскад Хаара:\n\n";
                 text += Config.HaarCascadePath;
                 DialogResult result = MessageBox.Show(text, "Ошибка",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
@@ -158,26 +183,6 @@ namespace ImpulseVision
             {
                 Directory.CreateDirectory(Config.FacePhotosPath);
             }
-            //
-            /*
-            if (!File.Exists(Config.FaceListTextFile))
-            {
-                string text = "Не удается найти файл с данными о лице:\n\n";
-                text += Config.FaceListTextFile + "\n\n";
-                text += "Если вы впервые запускаете приложение, для вас будет создан пустой файл.";
-                DialogResult result = MessageBox.Show(text, "Предупреждение",
-                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
-                switch (result)
-                {
-                    case DialogResult.OK:
-                        String dirName = Path.GetDirectoryName(Config.FaceListTextFile);
-                        Directory.CreateDirectory(dirName);
-                        File.Create(Config.FaceListTextFile).Close();
-                        break;
-                }
-            }
-            */
-            //
             //получить из БД инфо о пользователе (id, имя, фамилия, путь до фото)
             SCon.Open();
             string QueryGetInfoAboutUser = $@"select Users.ID ,Users.Lastname, Users.Firstname, Users.Patronymic, FaceImages.Picture
@@ -189,7 +194,7 @@ namespace ImpulseVision
                 FaceItem = new FaceData();
                 while (Res.Read())
                 {
-                    FaceItem.FaceImage = new Image<Gray, byte>(Res["Picture"].ToString());
+                    FaceItem.FaceImage = new Image<Gray, byte>(Application.StartupPath +"\\"+ Res["Picture"].ToString());
                     FaceItem.PersonName = Res["Firstname"].ToString();
                     FaceItem.LastName = Res["Lastname"].ToString();
                     FaceItem.Patronymic = Res["Patronymic"].ToString();
@@ -205,22 +210,10 @@ namespace ImpulseVision
             }
             SCon.Close();
             int i = 0;
-            /*
-            StreamReader reader = new StreamReader(Config.FaceListTextFile);
-            while ((line = reader.ReadLine()) != null)
-            {
-                string[] lineParts = line.Split(':');
-                FaceItem = new FaceData();
-                FaceItem.FaceImage = new Image<Gray, byte>(Config.FacePhotosPath + lineParts[0] + Config.ImageFileExtension);
-                FaceItem.PersonName = lineParts[1];
-                FaceList.Add(FaceItem);
-            }
-            reader.Close();
-            */
             foreach (var face in FaceList)
             {
                 ImageList.Push(face.FaceImage.Mat);
-                NameList.Add(face.PersonName);
+                NameList.Add(face.PersonName + " " + face.LastName);
                 LabelList.Push(new[] { i++ });
             }
 
@@ -231,6 +224,7 @@ namespace ImpulseVision
                 recognizer.Train(ImageList, LabelList);
             }
         }
+        private Image<Bgr, Byte> CurrentFrame = null;
 
         /// <summary>
         /// получение данных с камеры и обработка изображени
@@ -239,14 +233,6 @@ namespace ImpulseVision
         {
             BgrFrame = Capture.QueryFrame().ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
 
-            Pen PenForFace = new Pen(Brushes.Red, 5);
-            Brush BrushForFace = Brushes.White;
-            Font MyFont = new Font("Segoe UI Variable Small Semibol; 14pt; style=Bold", 14, FontStyle.Regular);
-
-            Brush BrushInfo = Brushes.White;
-            Pen PenInfo = new Pen(Brushes.White, 4);
-
-
             if (BgrFrame != null)
             {
                 try
@@ -255,21 +241,15 @@ namespace ImpulseVision
 
                     Rectangle[] faces = HaarCascade.DetectMultiScale(grayframe, 1.2, 10, new System.Drawing.Size(50, 50), new System.Drawing.Size(200, 200));
 
+
                     //detect face
-                    FaceName = "No face detected";
+                    FaceName = "Лицо не обнаружено";
                     foreach (var face in faces)
                     {
+                        CurrentFace = face;
                         BgrFrame.Draw(face, new Bgr(53, 23, 247), 2);
-                        DetectedFace = BgrFrame.Copy(face).Convert<Gray, byte>();
-
-                        Point PointInfo = new Point(face.Width - face.Width, 0);
-                        Graphics GraphInfo = Graphics.FromImage(BgrFrame.ToBitmap());
-                        Graphics Graph = Graphics.FromImage(BgrFrame.ToBitmap());
-                        Graph.DrawRectangle(PenForFace, face.X, face.Y, face.Width, face.Height);
-                        //позиция отрисовки имени человека
-                        Point PointName = new Point(face.X, face.Y - 25);
-                        Graph.DrawString($"{UserName}", MyFont, BrushForFace, PointName);
 
+                        DetectedFace = BgrFrame.Copy(face).Convert<Gray, byte>();
                         FaceRecognition();
                         break;
                     }
@@ -298,7 +278,7 @@ namespace ImpulseVision
             }
             else
             {
-                FaceName = "Please Add Face";
+                FaceName = "Пожалуйста добавьте лицо";
             }
         }
 
@@ -627,11 +607,7 @@ namespace ImpulseVision
 
             //Application.Idle += VideoProcess;
             GetFacesList();
-            if(CmbCams.Items.Count > 0)
-            {
-                SelectedCameraID = Config.ActiveCameraIndex;
-            }
-            //задание активной камеры
+
             Capture = new VideoCapture(SelectedCameraID);
             //настройка кадров
             Capture.SetCaptureProperty(CapProp.Fps, 30);

+ 35 - 35
ImpulseVision/FormMain.cs

@@ -213,40 +213,40 @@ namespace ImpulseVision
                 Directory.CreateDirectory(Config.FacePhotosPath);
             }
 
-            if (!File.Exists(Config.FaceListTextFile))
-            {
-                string text = "Cannot find face data file:\n\n";
-                text += Config.FaceListTextFile + "\n\n";
-                text += "If this is your first time running the app, an empty file will be created for you.";
-                DialogResult result = MessageBox.Show(text, "Warning",
-                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
-                switch (result)
-                {
-                    case DialogResult.OK:
-                        String dirName = Path.GetDirectoryName(Config.FaceListTextFile);
-                        Directory.CreateDirectory(dirName);
-                        File.Create(Config.FaceListTextFile).Close();
-                        break;
-                }
-            }
-
-            StreamReader reader = new StreamReader(Config.FaceListTextFile);
-            int i = 0;
-            while ((line = reader.ReadLine()) != null)
-            {
-                string[] lineParts = line.Split(':');
-                faceInstance = new FaceData();
-                faceInstance.FaceImage = new Image<Gray, byte>(Config.FacePhotosPath + lineParts[0] + Config.ImageFileExtension);
-                faceInstance.PersonName = lineParts[1];
-                FaceList.Add(faceInstance);
-            }
-            foreach (var face in FaceList)
-            {
-                ImageList.Push(face.FaceImage.Mat);
-                NameList.Add(face.PersonName);
-                LabelList.Push(new[] { i++ });
-            }
-            reader.Close();
+            //if (!File.Exists(Config.FaceListTextFile))
+            //{
+            //    string text = "Cannot find face data file:\n\n";
+            //    text += Config.FaceListTextFile + "\n\n";
+            //    text += "If this is your first time running the app, an empty file will be created for you.";
+            //    DialogResult result = MessageBox.Show(text, "Warning",
+            //        MessageBoxButtons.OK, MessageBoxIcon.Warning);
+            //    switch (result)
+            //    {
+            //        case DialogResult.OK:
+            //            String dirName = Path.GetDirectoryName(Config.FaceListTextFile);
+            //            Directory.CreateDirectory(dirName);
+            //            File.Create(Config.FaceListTextFile).Close();
+            //            break;
+            //    }
+            //}
+
+            //StreamReader reader = new StreamReader(Config.FaceListTextFile);
+            //int i = 0;
+            //while ((line = reader.ReadLine()) != null)
+            //{
+            //    string[] lineParts = line.Split(':');
+            //    faceInstance = new FaceData();
+            //    faceInstance.FaceImage = new Image<Gray, byte>(Config.FacePhotosPath + lineParts[0] + Config.ImageFileExtension);
+            //    faceInstance.PersonName = lineParts[1];
+            //    FaceList.Add(faceInstance);
+            //}
+            //foreach (var face in FaceList)
+            //{
+            //    ImageList.Push(face.FaceImage.Mat);
+            //    NameList.Add(face.PersonName);
+            //    LabelList.Push(new[] { i++ });
+            //}
+            //reader.Close();
 
             // Train recogniser
             if (ImageList.Size > 0)
@@ -358,7 +358,7 @@ where ID = '{IdUser}'";
             try
             {
                 //удалить из папки фотографию пользователя
-                File.Delete(Application.StartupPath + Config.FacePhotosPath + $"{PhotoName}.bmp");
+                File.Delete(Application.StartupPath + "\\" + Config.FacePhotosPath + $"{PhotoName}.bmp");
             }
             catch
             {

BIN
ImpulseVision/bin/Debug/ImpulseVision.exe


BIN
ImpulseVision/bin/Debug/Source/TrainedImages/Вячеслав5968789654.bmp


BIN
ImpulseVision/bin/Debug/Source/TrainedImages/Максим9649295469.bmp


BIN
ImpulseVision/bin/Debug/Source/TrainedImages/Петр8594859619.bmp