123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- //подключение библиотек
- using Emgu.CV;
- using Emgu.CV.Structure;
- using Emgu.CV.Face;
- using Emgu.CV.CvEnum;
- using System.IO;
- using System.Threading;
- using System.Xml;
- using System.Drawing.Imaging;
- using DirectShowLib;
- namespace ImpulseVision
- {
- /*
- * При выключении камеры, сделать так, чтобы картинка отсутствия изображения отображалась корректно
- *
- * */
- public partial class FormMain : Form
- {
- #region <Переменные>
- //для захвата вилео с веб-камеры
- private Capture VideoCapture = null;
- //текущее изображение лица
- private Image<Bgr, Byte> CurrentFrame = null;
- Mat Frame = new Mat();//кадры изображения
- //на начало работы распознавание лиц включено
- bool FacesDetectionEnabled = true;
- //каскадный классификатор
- CascadeClassifier Classifier = new CascadeClassifier("haarcascade_frontalface_alt_tree.xml");
- Image<Bgr, Byte> FaceResult = null;
- public static List<Image<Gray, Byte>> LstTrainedFaces = new List<Image<Gray, byte>>();
- public static List<int> PersonLabes = new List<int>();
- bool EnableSaveImage = false;
- public static List<string> LstPersonNames = new List<string>();
- private static bool IsTrained = false;
- //тренировщик изображения
- private static EigenFaceRecognizer Recognizer = null;
- private static Image<Bgr, byte> TempImageForRazn = null;
- int SelectedCameraID = -1;
- //доступные видеокамеры
- private DsDevice[] WebCams = null;
- int CountCams = -1;
- //множество для хранения списка камер
- HashSet<string> HtBefore = new HashSet<string>();
- //включена ли на данный момент камера
- bool IsWorking = false;
- #endregion
- public FormMain()
- {
- InitializeComponent();
- }
- private void FormMain_Load(object sender, EventArgs e)
- {
- HideAdding();
- //скрытие заголовков вкладок в TabControl
- TbPage.Appearance = TabAppearance.FlatButtons;
- TbPage.ItemSize = new Size(0, 1);
- TbPage.SizeMode = TabSizeMode.Fixed;
- this.Show();
- GetCams();
- ColorRegular(false);
- TrainImageFromDir();
- }
- private void GetCams()
- {
- WebCams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
- CountCams = WebCams.Length;
- CmbCams.Items.Clear();
- for (int i = 0; i < CountCams; i++)
- {
- CmbCams.Items.Add(WebCams[i].Name);
- HtBefore.Add(WebCams[i].Name);
- }
- if (CountCams > 0)
- {
- CmbCams.SelectedIndex = 0;
- SelectedCameraID = 0;
- }
- }
- private void BtnAdd_Click(object sender, EventArgs e)
- {
- ShowAdding();
- }
- /// <summary>
- /// показ окна добавления
- /// </summary>
- private void ShowAdding()
- {
- TableLayoutWorks.ColumnStyles[0].Width = 250;
- TableLayoutWorks.BackColor = Color.White;
- }
- /// <summary>
- /// скрытие окна добавления
- /// </summary>
- private void HideAdding()
- {
- TableLayoutWorks.ColumnStyles[0].Width = 0;
- TableLayoutWorks.BackColor = Color.Black;
- }
- private void PbxEther_Click(object sender, EventArgs e)
- {
- HideAdding();
- }
- private void BtnOn_Click(object sender, EventArgs e)
- {
- if (IsWorking)
- return;
- BtnAdd.Enabled = true;
- TableLayoutWorks.BackColor = Color.Black;
- IsWorking = true;//камера включена
- //при нескольких веб- камерах в параметрах передаётся её индекс
- VideoCapture = new Capture(SelectedCameraID);
- VideoCapture.ImageGrabbed += VideoCapture_ImageGrabbed;
- VideoCapture.Start();
- FacesDetectionEnabled = true;//включить распознавание
- CvInvoke.UseOpenCL = true;
- ColorRegular(IsWorking);
- }
- /// <summary>
- /// вычисление разницы между изображениями
- /// </summary>
- void FaceDifferent()
- {
- if(File.Exists(Application.StartupPath+ @"\CurrentFace\imgFace.jpg"))
- {
- File.Delete(Application.StartupPath + @"\CurrentFace\imgFace.jpg");
- }
- TempImageForRazn.Save(Application.StartupPath + $@"\CurrentFace\imgFace.jpg");
- using (Image<Gray, byte> sourceImage = new Image<Gray, byte>(Application.StartupPath + @"\CurrentFace\Вячеслав__12-02-2023-07-35-36afe633.jpg"))
- {
- using (Image<Gray, byte> templateImage = new Image<Gray, byte>(Application.StartupPath + @"\CurrentFace\imgFace.jpg"))
- {
- Image<Gray, byte> resultImage = new Image<Gray, byte>(sourceImage.Width, templateImage.Height);
- CvInvoke.AbsDiff(sourceImage, templateImage, resultImage);
- //resultImage.Save(@"some path" + "imagename.jpeg");
- int diff = CvInvoke.CountNonZero(resultImage);
- //if diff = 0 exact match, otherwise there are some difference.
- this.Text = $"Разница: {diff}";
- }
- }
-
- }
- /// <summary>
- /// распознавание изображения, его отображение и сохранение
- /// </summary>
- private void VideoCapture_ImageGrabbed(object sender, EventArgs e)
- {
- if (VideoCapture == null && VideoCapture.Ptr == IntPtr.Zero)
- return;
- //1. Захват видео
- VideoCapture.Retrieve(Frame, 0);//восстановить нулевой кадр
- CurrentFrame = Frame.ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
- //2. Обнаружение лиц
- if (FacesDetectionEnabled)
- {
- //преобразовать изображение в серое
- Mat GrayImage = new Mat();
- CvInvoke.CvtColor(CurrentFrame, GrayImage, ColorConversion.Bgr2Gray);
- //выравнивание гистограммы изображения
- CvInvoke.EqualizeHist(GrayImage, GrayImage);
- CvInvoke.EqualizeHist(GrayImage, GrayImage);
- CvInvoke.EqualizeHist(GrayImage, GrayImage);
- //PbxTemplateImage.Image = GrayImage;
- //записать распознанные изображения в массив
- Rectangle[] RectFaces = Classifier.DetectMultiScale(GrayImage, 1.1, 3, Size.Empty, Size.Empty);
- //если лица обнаружены
- if (RectFaces.Length > 0)
- {
- 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.WhiteSmoke;
- Pen PenInfo = new Pen(Brushes.White, 4);
- Point PointInfo = new Point(CurrentFrame.Width - CurrentFrame.Width, 0);
- foreach (Rectangle CurrentFace in RectFaces)
- {
- //нарисовать прямоугольники вокруг лиц
- //CvInvoke.Rectangle(CurrentFrame, CurrentFace, new Bgr(Color.White).MCvScalar, 5);
- Point PointForFace = new Point(CurrentFace.X, CurrentFace.Y);
- //результирующее изображение
- Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
- Graphics Graph = Graphics.FromImage(CurrentFrame.Bitmap);
- Graphics GraphInfo = Graphics.FromImage(CurrentFrame.Bitmap);
- Graph.DrawRectangle(PenForFace, PointForFace.X, PointForFace.Y, CurrentFace.Width, CurrentFace.Height);
- //позиция отрисовки имени человека
- Point PersonName = new Point(CurrentFace.X, CurrentFace.Y - 25);
- //Graph.DrawString("Распознано", MyFont, MyBrush, PersonName);
- //3. Добавление человека (лица)
- ////результирующее изображение
- //Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
- ResultImage.ROI = CurrentFace;
- //отобразить на форме найденное изображение
- //PbxDetected.Image = ResultImage.ToBitmap();
- //******************
- TempImageForRazn = ResultImage;
- //если сохранение изображения включено
- if (EnableSaveImage)
- {
- //создать каталог, если он не существует
- string Path = Directory.GetCurrentDirectory() + @"\TrainedImages";
- if (!Directory.Exists(Path))
- {
- Directory.CreateDirectory(Path);
- }
- //сохранить 10 изображений
- Task.Factory.StartNew(() =>
- {
- for (int i = 0; i < 30; i++)
- {
- ResultImage.Resize(400, 400, Inter.Cubic).Save(Path + @"\" + TbxName.Text.Trim() + "__" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + Guid.NewGuid().ToString().Substring(0, 6) + ".jpg");
- Thread.Sleep(200);
- }
- MessageBox.Show("Сохранение завершено!", "Результата операции.", MessageBoxButtons.OK, MessageBoxIcon.Information);
- TrainImageFromDir();
- });
- }
- EnableSaveImage = false;
- if (BtnSave.InvokeRequired)
- {
- BtnSave.Invoke(new ThreadStart(delegate {
- BtnSave.Enabled = true;
- }));
- }
- //5. Узнавание изображения
- if (IsTrained)
- {
- Image<Gray, byte> GrayFaceResult = ResultImage.Convert<Gray, byte>().Resize(400, 400, Inter.Cubic);
- CvInvoke.EqualizeHist(GrayFaceResult, GrayFaceResult);
- var Result = Recognizer.Predict(GrayFaceResult);
- if (Result.Label > 0)//если лица найдены
- {
- BrushForFace = Brushes.LightGreen;
- Graph.DrawString($"{LstPersonNames[Result.Label]}", MyFont, BrushForFace, PersonName);
- GraphInfo.DrawString($"На изображении: {LstPersonNames[Result.Label]}", MyFont, BrushInfo, PointInfo);
- }
- else
- {
- BrushForFace = Brushes.LightPink;
- Graph.DrawString("Неизвестный", MyFont, BrushForFace, PersonName);
- GraphInfo.DrawString("Обнаруженные лица отсутствуют", MyFont, BrushInfo, PointInfo);
- }
- }
- }
- }
- }
- //NormalizeImage(CurrentFrame);
- try
- {
- //вывести изображение в PictureBox
- PbxEther.Image = CurrentFrame.Bitmap;
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void BtnOff_Click(object sender, EventArgs e)
- {
- HideAdding();
- BtnAdd.Enabled = false;
- if (VideoCapture != null)
- {
- FacesDetectionEnabled = false;
- VideoCapture.ImageGrabbed -= VideoCapture_ImageGrabbed;
- VideoCapture.Stop();
- VideoCapture.Dispose();
- VideoCapture = null;
- //CurrentFrame = null;
- }
- PbxEther.Image = Properties.Resources._9110852_video_no_icon;
- TableLayoutWorks.BackColor = Color.Gray;
- IsWorking = false;
- ColorRegular(IsWorking);
- }
- /// <summary>
- /// переключение цветов кнопок включения/выключения
- /// </summary>
- /// <param name="IsWorking">статус работы камеры</param>
- private void ColorRegular(bool IsWorking)
- {
- if(IsWorking)
- {
- BtnOn.BackColor = Color.LightGreen;
- BtnOff.BackColor = Color.White;
- }
- else
- {
- BtnOn.BackColor = Color.White;
- BtnOff.BackColor = Color.LightPink;
- }
- }
- private void BtnSave_Click(object sender, EventArgs e)
- {
- if(TbxName.Text.Trim() == string.Empty)
- {
- MessageBox.Show("Укажите имя и повторите попытку!", "Ошибка добавления!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- return;
- }
- TslStatus.Text = "Сохранение данных о пользователе..";
- ProgressTrain.Value = 0;
- EnableSaveImage = true;
- BtnSave.Text = "Сохранение...";
- IsTrained = false;
- TrainImageFromDir();
- BtnSave.Text = "Сохранить";
- BtnSave.Enabled = false;
- TslStatus.Text = "Готов";
-
- ProgressTrain.Value = 100;
- }
- /// <summary>
- /// тренировка изображения
- /// </summary>
- /// <returns>результат тренировки (true или false)</returns>
- private void TrainImageFromDir()
- {
- int CountImage = 0;
- //порог
- double Threshold = 10000;
- LstTrainedFaces.Clear();
- PersonLabes.Clear();
- LstPersonNames.Clear();
- try
- {
- //ProgressTrain.Value += 15;
- string MyPath = Directory.GetCurrentDirectory() + @"\TrainedImages\";
- string[] Files = Directory.GetFiles(MyPath, "*.jpg", SearchOption.AllDirectories);
- int n = Files.Length;
- double PlusDigit = 75 / n;
- foreach (string file in Files)
- {
- //ProgressTrain.Value += (int)PlusDigit;
- Image<Gray, Byte> TrainedImage = new Image<Gray, Byte>(file);
- //добавить обученное изображение
- LstTrainedFaces.Add(TrainedImage);
- PersonLabes.Add(CountImage);
- string CurrentFileName = Path.GetFileName(file);
- string Name = CurrentFileName.Remove(CurrentFileName.IndexOf("_"), CurrentFileName.Length - CurrentFileName.IndexOf("_"));
- //(0, CurrentFileName.Length - CurrentFileName.IndexOf("_") + 1);
- //добавить имя
- LstPersonNames.Add(Name);
- CountImage++;
- }
- if (CountImage == 0)
- {
- IsTrained = false;
- return;
- }
- //тренировка изображения
- Recognizer = new EigenFaceRecognizer(CountImage, Threshold);
- Recognizer.Train(LstTrainedFaces.ToArray(), PersonLabes.ToArray());
- //ProgressTrain.Value += 100 - ProgressTrain.Value;
- //записать, что обучен
- IsTrained = true;
- MessageBox.Show("Тренировка изображений выполнена!");
- }
- catch (Exception ex)
- {
- IsTrained = false;
- }
- }
- /// <summary>
- /// разница между изображениями
- /// </summary>
- private void ImageDifferens()
- {
- string[] ArrFiles = Directory.GetFiles(Application.StartupPath + @"\TrainedImages\", @"*.jpg", SearchOption.AllDirectories);
- List<Image> LstImages = new List<Image>();
- Image Im = null;
- LstImages.Clear();
- foreach (string file in ArrFiles)
- {
- Im = Image.FromFile(file);
- LstImages.Add(Im);
- }
- Image<Gray, byte> Pic1 = new Image<Gray, byte>(ArrFiles[0]);
- Image<Gray, byte> Pic2 = new Image<Gray, byte>(ArrFiles[1]);
- Image<Gray, byte> DifferensImage = Pic2 - Pic1;
- //PbxDifferens.Image = DifferensImage.Bitmap;
- //LblRazn.Text;
- }
- private void CmbCams_SelectedIndexChanged(object sender, EventArgs e)
- {
- try
- {
- //если захват видео уже идёт
- if(VideoCapture != null)
- {
- VideoCapture.Pause();
- VideoCapture.Stop();
- VideoCapture.Dispose();
- VideoCapture = null;
- PbxEther.Image = null;
- SelectedCameraID = -1;
- }
- }
- catch(Exception ex)
- {
- MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- }
- SelectedCameraID = CmbCams.SelectedIndex;
- if (IsWorking)
- {
- VideoCapture = new Capture(SelectedCameraID);
- VideoCapture.ImageGrabbed += VideoCapture_ImageGrabbed;
- VideoCapture.Start();
- FacesDetectionEnabled = true;//включить распознавание
- CvInvoke.UseOpenCL = true;
- }
- }
- private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
- {
- Application.ExitThread();
- }
- private void TimerNewCam_Tick(object sender, EventArgs e)
- {
- DsDevice[] Cams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
- int Count = Cams.Length;
- //если количество подключённых камер изменилось
- if(Count != CountCams)
- {
- if (Count > CountCams)
- {
- StatusAddNewDevice(Cams);
- }
- else if(Count < CountCams)
- {
- StatusOffDevice(Cams);
- }
- GetCams();
- }
- }
- /// <summary>
- /// уведомление об отключении web-камеры
- /// </summary>
- /// <param name="cams">массив с доступными камерами</param>
- async void StatusOffDevice(DsDevice[] cams)
- {
- HashSet<string> HtAfter = new HashSet<string>();
- foreach(DsDevice device in cams)
- {
- HtAfter.Add(device.Name);
- }
- HtBefore.Except(HtAfter);
- ProgressTrain.Value = 0;
- TslStatus.Text = $"Устройство: {string.Join(" ",HtBefore)} - отключено";
- await Task.Delay(1000);
- ProgressTrain.Value = 100;
- TslStatus.Text = "Готов";
- }
- /// <summary>
- /// уведомление о подключении нового устройствва
- /// </summary>
- /// <param name="Cams">массив с доступными web-камерами</param>
- async void StatusAddNewDevice(DsDevice[] Cams)
- {
- TslStatus.Text = "Добавление нового устройства..";
- ProgressTrain.Value = 0;
- while(ProgressTrain.Value < 100)
- {
- ProgressTrain.Value += 5;
- await Task.Delay(50);
- }
- TslStatus.Text = "Добавлено новое устройство";
- await Task.Delay(1000);
- TslStatus.Text = $"{Cams[Cams.Length-1].Name}";
- await Task.Delay(1000);
- ProgressTrain.Value = 100;
- TslStatus.Text = "Готов";
- }
- private void BtnCheck_Click(object sender, EventArgs e)
- {
- TslStatus.Text = "Подождите.. выполняется анализ лица..";
- ProgressTrain.Value = 45;
- //TrainImageFromDir();
- FaceDifferent();
- //Task.Factory.StartNew(new Action(() => TrainImageFromDir()));
- //ProgressTrain.Value = 55;
- //TslStatus.Text = "Готов";
- }
- private void TimerCheckTrain_Tick(object sender, EventArgs e)
- {
- if(IsTrained)
- {
- TimerCheckTrain.Stop();
- }
- }
- private void PbxEther_Click_1(object sender, EventArgs e)
- {
- HideAdding();
- }
- private void STools_Click(object sender, EventArgs e)
- {
- TbPage.SelectTab(1);
- ToolsMenu.Enabled = false;
- ImList.Images.Clear();
- LswView.Items.Clear();
- }
- /// <summary>
- /// получить изображения пользователей системы
- /// </summary>
- private void SUsers_Click(object sender, EventArgs e)
- {
- TbPage.SelectTab(2);
- ToolsMenu.Enabled = false;
- ImList.Images.Clear();
- LswView.Items.Clear();
- string[] ArrFiles = Directory.GetFiles(Application.StartupPath + @"\TrainedImages\", "*.JPG", SearchOption.AllDirectories);
- for (int i = 0; i < ArrFiles.Length; i++)
- {
- try
- {
- string Path = ArrFiles[i].ToString();
- Image Pic = Image.FromFile(Path);
- ImList.Images.Add(i.ToString(), Pic);
- LswView.Items.Add($"{i.ToString()}", ImList.Images.Count - 1);
- }
- catch
- {
- continue;
- }
- }
- }
- }
- }
|