FormMain.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. //подключение библиотек
  11. using Emgu.CV;
  12. using Emgu.CV.Structure;
  13. using Emgu.CV.Face;
  14. using Emgu.CV.CvEnum;
  15. using System.IO;
  16. using System.Threading;
  17. using System.Xml;
  18. using System.Drawing.Imaging;
  19. using DirectShowLib;
  20. namespace ImpulseVision
  21. {
  22. /*
  23. * При выключении камеры, сделать так, чтобы картинка отсутствия изображения отображалась корректно
  24. *
  25. * */
  26. public partial class FormMain : Form
  27. {
  28. #region <Переменные>
  29. //для захвата вилео с веб-камеры
  30. private Capture VideoCapture = null;
  31. //текущее изображение лица
  32. private Image<Bgr, Byte> CurrentFrame = null;
  33. Mat Frame = new Mat();//кадры изображения
  34. //на начало работы распознавание лиц включено
  35. bool FacesDetectionEnabled = true;
  36. //каскадный классификатор
  37. CascadeClassifier Classifier = new CascadeClassifier("haarcascade_frontalface_alt_tree.xml");
  38. Image<Bgr, Byte> FaceResult = null;
  39. public static List<Image<Gray, Byte>> LstTrainedFaces = new List<Image<Gray, byte>>();
  40. public static List<int> PersonLabes = new List<int>();
  41. bool EnableSaveImage = false;
  42. public static List<string> LstPersonNames = new List<string>();
  43. private static bool IsTrained = false;
  44. //тренировщик изображения
  45. private static EigenFaceRecognizer Recognizer = null;
  46. private static Image<Bgr, byte> TempImageForRazn = null;
  47. int SelectedCameraID = -1;
  48. //доступные видеокамеры
  49. private DsDevice[] WebCams = null;
  50. int CountCams = -1;
  51. //множество для хранения списка камер
  52. HashSet<string> HtBefore = new HashSet<string>();
  53. //включена ли на данный момент камера
  54. bool IsWorking = false;
  55. #endregion
  56. public FormMain()
  57. {
  58. InitializeComponent();
  59. }
  60. private void FormMain_Load(object sender, EventArgs e)
  61. {
  62. HideAdding();
  63. //скрытие заголовков вкладок в TabControl
  64. TbPage.Appearance = TabAppearance.FlatButtons;
  65. TbPage.ItemSize = new Size(0, 1);
  66. TbPage.SizeMode = TabSizeMode.Fixed;
  67. this.Show();
  68. GetCams();
  69. ColorRegular(false);
  70. TrainImageFromDir();
  71. }
  72. private void GetCams()
  73. {
  74. WebCams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  75. CountCams = WebCams.Length;
  76. CmbCams.Items.Clear();
  77. for (int i = 0; i < CountCams; i++)
  78. {
  79. CmbCams.Items.Add(WebCams[i].Name);
  80. HtBefore.Add(WebCams[i].Name);
  81. }
  82. if (CountCams > 0)
  83. {
  84. CmbCams.SelectedIndex = 0;
  85. SelectedCameraID = 0;
  86. }
  87. }
  88. private void BtnAdd_Click(object sender, EventArgs e)
  89. {
  90. ShowAdding();
  91. }
  92. /// <summary>
  93. /// показ окна добавления
  94. /// </summary>
  95. private void ShowAdding()
  96. {
  97. TableLayoutWorks.ColumnStyles[0].Width = 250;
  98. TableLayoutWorks.BackColor = Color.White;
  99. }
  100. /// <summary>
  101. /// скрытие окна добавления
  102. /// </summary>
  103. private void HideAdding()
  104. {
  105. TableLayoutWorks.ColumnStyles[0].Width = 0;
  106. TableLayoutWorks.BackColor = Color.Black;
  107. }
  108. private void PbxEther_Click(object sender, EventArgs e)
  109. {
  110. HideAdding();
  111. }
  112. private void BtnOn_Click(object sender, EventArgs e)
  113. {
  114. if (IsWorking)
  115. return;
  116. BtnAdd.Enabled = true;
  117. TableLayoutWorks.BackColor = Color.Black;
  118. IsWorking = true;//камера включена
  119. //при нескольких веб- камерах в параметрах передаётся её индекс
  120. VideoCapture = new Capture(SelectedCameraID);
  121. VideoCapture.ImageGrabbed += VideoCapture_ImageGrabbed;
  122. VideoCapture.Start();
  123. FacesDetectionEnabled = true;//включить распознавание
  124. CvInvoke.UseOpenCL = true;
  125. ColorRegular(IsWorking);
  126. }
  127. /// <summary>
  128. /// вычисление разницы между изображениями
  129. /// </summary>
  130. void FaceDifferent()
  131. {
  132. if(File.Exists(Application.StartupPath+ @"\CurrentFace\imgFace.jpg"))
  133. {
  134. File.Delete(Application.StartupPath + @"\CurrentFace\imgFace.jpg");
  135. }
  136. TempImageForRazn.Save(Application.StartupPath + $@"\CurrentFace\imgFace.jpg");
  137. using (Image<Gray, byte> sourceImage = new Image<Gray, byte>(Application.StartupPath + @"\CurrentFace\Вячеслав__12-02-2023-07-35-36afe633.jpg"))
  138. {
  139. using (Image<Gray, byte> templateImage = new Image<Gray, byte>(Application.StartupPath + @"\CurrentFace\imgFace.jpg"))
  140. {
  141. Image<Gray, byte> resultImage = new Image<Gray, byte>(sourceImage.Width, templateImage.Height);
  142. CvInvoke.AbsDiff(sourceImage, templateImage, resultImage);
  143. //resultImage.Save(@"some path" + "imagename.jpeg");
  144. int diff = CvInvoke.CountNonZero(resultImage);
  145. //if diff = 0 exact match, otherwise there are some difference.
  146. this.Text = $"Разница: {diff}";
  147. }
  148. }
  149. }
  150. /// <summary>
  151. /// распознавание изображения, его отображение и сохранение
  152. /// </summary>
  153. private void VideoCapture_ImageGrabbed(object sender, EventArgs e)
  154. {
  155. if (VideoCapture == null && VideoCapture.Ptr == IntPtr.Zero)
  156. return;
  157. //1. Захват видео
  158. VideoCapture.Retrieve(Frame, 0);//восстановить нулевой кадр
  159. CurrentFrame = Frame.ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
  160. //2. Обнаружение лиц
  161. if (FacesDetectionEnabled)
  162. {
  163. //преобразовать изображение в серое
  164. Mat GrayImage = new Mat();
  165. CvInvoke.CvtColor(CurrentFrame, GrayImage, ColorConversion.Bgr2Gray);
  166. //выравнивание гистограммы изображения
  167. CvInvoke.EqualizeHist(GrayImage, GrayImage);
  168. CvInvoke.EqualizeHist(GrayImage, GrayImage);
  169. CvInvoke.EqualizeHist(GrayImage, GrayImage);
  170. //PbxTemplateImage.Image = GrayImage;
  171. //записать распознанные изображения в массив
  172. Rectangle[] RectFaces = Classifier.DetectMultiScale(GrayImage, 1.1, 3, Size.Empty, Size.Empty);
  173. //если лица обнаружены
  174. if (RectFaces.Length > 0)
  175. {
  176. Pen PenForFace = new Pen(Brushes.Red, 5);
  177. Brush BrushForFace = Brushes.White;
  178. Font MyFont = new Font("Segoe UI Variable Small Semibol; 14pt; style=Bold", 14, FontStyle.Regular);
  179. Brush BrushInfo = Brushes.WhiteSmoke;
  180. Pen PenInfo = new Pen(Brushes.White, 4);
  181. Point PointInfo = new Point(CurrentFrame.Width - CurrentFrame.Width, 0);
  182. foreach (Rectangle CurrentFace in RectFaces)
  183. {
  184. //нарисовать прямоугольники вокруг лиц
  185. //CvInvoke.Rectangle(CurrentFrame, CurrentFace, new Bgr(Color.White).MCvScalar, 5);
  186. Point PointForFace = new Point(CurrentFace.X, CurrentFace.Y);
  187. //результирующее изображение
  188. Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
  189. Graphics Graph = Graphics.FromImage(CurrentFrame.Bitmap);
  190. Graphics GraphInfo = Graphics.FromImage(CurrentFrame.Bitmap);
  191. Graph.DrawRectangle(PenForFace, PointForFace.X, PointForFace.Y, CurrentFace.Width, CurrentFace.Height);
  192. //позиция отрисовки имени человека
  193. Point PersonName = new Point(CurrentFace.X, CurrentFace.Y - 25);
  194. //Graph.DrawString("Распознано", MyFont, MyBrush, PersonName);
  195. //3. Добавление человека (лица)
  196. ////результирующее изображение
  197. //Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
  198. ResultImage.ROI = CurrentFace;
  199. //отобразить на форме найденное изображение
  200. //PbxDetected.Image = ResultImage.ToBitmap();
  201. //******************
  202. TempImageForRazn = ResultImage;
  203. //если сохранение изображения включено
  204. if (EnableSaveImage)
  205. {
  206. //создать каталог, если он не существует
  207. string Path = Directory.GetCurrentDirectory() + @"\TrainedImages";
  208. if (!Directory.Exists(Path))
  209. {
  210. Directory.CreateDirectory(Path);
  211. }
  212. //сохранить 10 изображений
  213. Task.Factory.StartNew(() =>
  214. {
  215. for (int i = 0; i < 30; i++)
  216. {
  217. 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");
  218. Thread.Sleep(200);
  219. }
  220. MessageBox.Show("Сохранение завершено!", "Результата операции.", MessageBoxButtons.OK, MessageBoxIcon.Information);
  221. TrainImageFromDir();
  222. });
  223. }
  224. EnableSaveImage = false;
  225. if (BtnSave.InvokeRequired)
  226. {
  227. BtnSave.Invoke(new ThreadStart(delegate {
  228. BtnSave.Enabled = true;
  229. }));
  230. }
  231. //5. Узнавание изображения
  232. if (IsTrained)
  233. {
  234. Image<Gray, byte> GrayFaceResult = ResultImage.Convert<Gray, byte>().Resize(400, 400, Inter.Cubic);
  235. CvInvoke.EqualizeHist(GrayFaceResult, GrayFaceResult);
  236. var Result = Recognizer.Predict(GrayFaceResult);
  237. if (Result.Label > 0)//если лица найдены
  238. {
  239. BrushForFace = Brushes.LightGreen;
  240. Graph.DrawString($"{LstPersonNames[Result.Label]}", MyFont, BrushForFace, PersonName);
  241. GraphInfo.DrawString($"На изображении: {LstPersonNames[Result.Label]}", MyFont, BrushInfo, PointInfo);
  242. }
  243. else
  244. {
  245. BrushForFace = Brushes.LightPink;
  246. Graph.DrawString("Неизвестный", MyFont, BrushForFace, PersonName);
  247. GraphInfo.DrawString("Обнаруженные лица отсутствуют", MyFont, BrushInfo, PointInfo);
  248. }
  249. }
  250. }
  251. }
  252. }
  253. //NormalizeImage(CurrentFrame);
  254. try
  255. {
  256. //вывести изображение в PictureBox
  257. PbxEther.Image = CurrentFrame.Bitmap;
  258. }
  259. catch(Exception ex)
  260. {
  261. MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  262. }
  263. }
  264. private void BtnOff_Click(object sender, EventArgs e)
  265. {
  266. HideAdding();
  267. BtnAdd.Enabled = false;
  268. if (VideoCapture != null)
  269. {
  270. FacesDetectionEnabled = false;
  271. VideoCapture.ImageGrabbed -= VideoCapture_ImageGrabbed;
  272. VideoCapture.Stop();
  273. VideoCapture.Dispose();
  274. VideoCapture = null;
  275. //CurrentFrame = null;
  276. }
  277. PbxEther.Image = Properties.Resources._9110852_video_no_icon;
  278. TableLayoutWorks.BackColor = Color.Gray;
  279. IsWorking = false;
  280. ColorRegular(IsWorking);
  281. }
  282. /// <summary>
  283. /// переключение цветов кнопок включения/выключения
  284. /// </summary>
  285. /// <param name="IsWorking">статус работы камеры</param>
  286. private void ColorRegular(bool IsWorking)
  287. {
  288. if(IsWorking)
  289. {
  290. BtnOn.BackColor = Color.LightGreen;
  291. BtnOff.BackColor = Color.White;
  292. }
  293. else
  294. {
  295. BtnOn.BackColor = Color.White;
  296. BtnOff.BackColor = Color.LightPink;
  297. }
  298. }
  299. private void BtnSave_Click(object sender, EventArgs e)
  300. {
  301. if(TbxName.Text.Trim() == string.Empty)
  302. {
  303. MessageBox.Show("Укажите имя и повторите попытку!", "Ошибка добавления!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  304. return;
  305. }
  306. TslStatus.Text = "Сохранение данных о пользователе..";
  307. ProgressTrain.Value = 0;
  308. EnableSaveImage = true;
  309. BtnSave.Text = "Сохранение...";
  310. IsTrained = false;
  311. TrainImageFromDir();
  312. BtnSave.Text = "Сохранить";
  313. BtnSave.Enabled = false;
  314. TslStatus.Text = "Готов";
  315. ProgressTrain.Value = 100;
  316. }
  317. /// <summary>
  318. /// тренировка изображения
  319. /// </summary>
  320. /// <returns>результат тренировки (true или false)</returns>
  321. private void TrainImageFromDir()
  322. {
  323. int CountImage = 0;
  324. //порог
  325. double Threshold = 10000;
  326. LstTrainedFaces.Clear();
  327. PersonLabes.Clear();
  328. LstPersonNames.Clear();
  329. try
  330. {
  331. //ProgressTrain.Value += 15;
  332. string MyPath = Directory.GetCurrentDirectory() + @"\TrainedImages\";
  333. string[] Files = Directory.GetFiles(MyPath, "*.jpg", SearchOption.AllDirectories);
  334. int n = Files.Length;
  335. double PlusDigit = 75 / n;
  336. foreach (string file in Files)
  337. {
  338. //ProgressTrain.Value += (int)PlusDigit;
  339. Image<Gray, Byte> TrainedImage = new Image<Gray, Byte>(file);
  340. //добавить обученное изображение
  341. LstTrainedFaces.Add(TrainedImage);
  342. PersonLabes.Add(CountImage);
  343. string CurrentFileName = Path.GetFileName(file);
  344. string Name = CurrentFileName.Remove(CurrentFileName.IndexOf("_"), CurrentFileName.Length - CurrentFileName.IndexOf("_"));
  345. //(0, CurrentFileName.Length - CurrentFileName.IndexOf("_") + 1);
  346. //добавить имя
  347. LstPersonNames.Add(Name);
  348. CountImage++;
  349. }
  350. if (CountImage == 0)
  351. {
  352. IsTrained = false;
  353. return;
  354. }
  355. //тренировка изображения
  356. Recognizer = new EigenFaceRecognizer(CountImage, Threshold);
  357. Recognizer.Train(LstTrainedFaces.ToArray(), PersonLabes.ToArray());
  358. //ProgressTrain.Value += 100 - ProgressTrain.Value;
  359. //записать, что обучен
  360. IsTrained = true;
  361. MessageBox.Show("Тренировка изображений выполнена!");
  362. }
  363. catch (Exception ex)
  364. {
  365. IsTrained = false;
  366. }
  367. }
  368. /// <summary>
  369. /// разница между изображениями
  370. /// </summary>
  371. private void ImageDifferens()
  372. {
  373. string[] ArrFiles = Directory.GetFiles(Application.StartupPath + @"\TrainedImages\", @"*.jpg", SearchOption.AllDirectories);
  374. List<Image> LstImages = new List<Image>();
  375. Image Im = null;
  376. LstImages.Clear();
  377. foreach (string file in ArrFiles)
  378. {
  379. Im = Image.FromFile(file);
  380. LstImages.Add(Im);
  381. }
  382. Image<Gray, byte> Pic1 = new Image<Gray, byte>(ArrFiles[0]);
  383. Image<Gray, byte> Pic2 = new Image<Gray, byte>(ArrFiles[1]);
  384. Image<Gray, byte> DifferensImage = Pic2 - Pic1;
  385. //PbxDifferens.Image = DifferensImage.Bitmap;
  386. //LblRazn.Text;
  387. }
  388. private void CmbCams_SelectedIndexChanged(object sender, EventArgs e)
  389. {
  390. try
  391. {
  392. //если захват видео уже идёт
  393. if(VideoCapture != null)
  394. {
  395. VideoCapture.Pause();
  396. VideoCapture.Stop();
  397. VideoCapture.Dispose();
  398. VideoCapture = null;
  399. PbxEther.Image = null;
  400. SelectedCameraID = -1;
  401. }
  402. }
  403. catch(Exception ex)
  404. {
  405. MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  406. }
  407. SelectedCameraID = CmbCams.SelectedIndex;
  408. if (IsWorking)
  409. {
  410. VideoCapture = new Capture(SelectedCameraID);
  411. VideoCapture.ImageGrabbed += VideoCapture_ImageGrabbed;
  412. VideoCapture.Start();
  413. FacesDetectionEnabled = true;//включить распознавание
  414. CvInvoke.UseOpenCL = true;
  415. }
  416. }
  417. private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
  418. {
  419. Application.ExitThread();
  420. }
  421. private void TimerNewCam_Tick(object sender, EventArgs e)
  422. {
  423. DsDevice[] Cams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  424. int Count = Cams.Length;
  425. //если количество подключённых камер изменилось
  426. if(Count != CountCams)
  427. {
  428. if (Count > CountCams)
  429. {
  430. StatusAddNewDevice(Cams);
  431. }
  432. else if(Count < CountCams)
  433. {
  434. StatusOffDevice(Cams);
  435. }
  436. GetCams();
  437. }
  438. }
  439. /// <summary>
  440. /// уведомление об отключении web-камеры
  441. /// </summary>
  442. /// <param name="cams">массив с доступными камерами</param>
  443. async void StatusOffDevice(DsDevice[] cams)
  444. {
  445. HashSet<string> HtAfter = new HashSet<string>();
  446. foreach(DsDevice device in cams)
  447. {
  448. HtAfter.Add(device.Name);
  449. }
  450. HtBefore.Except(HtAfter);
  451. ProgressTrain.Value = 0;
  452. TslStatus.Text = $"Устройство: {string.Join(" ",HtBefore)} - отключено";
  453. await Task.Delay(1000);
  454. ProgressTrain.Value = 100;
  455. TslStatus.Text = "Готов";
  456. }
  457. /// <summary>
  458. /// уведомление о подключении нового устройствва
  459. /// </summary>
  460. /// <param name="Cams">массив с доступными web-камерами</param>
  461. async void StatusAddNewDevice(DsDevice[] Cams)
  462. {
  463. TslStatus.Text = "Добавление нового устройства..";
  464. ProgressTrain.Value = 0;
  465. while(ProgressTrain.Value < 100)
  466. {
  467. ProgressTrain.Value += 5;
  468. await Task.Delay(50);
  469. }
  470. TslStatus.Text = "Добавлено новое устройство";
  471. await Task.Delay(1000);
  472. TslStatus.Text = $"{Cams[Cams.Length-1].Name}";
  473. await Task.Delay(1000);
  474. ProgressTrain.Value = 100;
  475. TslStatus.Text = "Готов";
  476. }
  477. private void BtnCheck_Click(object sender, EventArgs e)
  478. {
  479. TslStatus.Text = "Подождите.. выполняется анализ лица..";
  480. ProgressTrain.Value = 45;
  481. //TrainImageFromDir();
  482. FaceDifferent();
  483. //Task.Factory.StartNew(new Action(() => TrainImageFromDir()));
  484. //ProgressTrain.Value = 55;
  485. //TslStatus.Text = "Готов";
  486. }
  487. private void TimerCheckTrain_Tick(object sender, EventArgs e)
  488. {
  489. if(IsTrained)
  490. {
  491. TimerCheckTrain.Stop();
  492. }
  493. }
  494. private void PbxEther_Click_1(object sender, EventArgs e)
  495. {
  496. HideAdding();
  497. }
  498. private void STools_Click(object sender, EventArgs e)
  499. {
  500. TbPage.SelectTab(1);
  501. ToolsMenu.Enabled = false;
  502. ImList.Images.Clear();
  503. LswView.Items.Clear();
  504. }
  505. /// <summary>
  506. /// получить изображения пользователей системы
  507. /// </summary>
  508. private void SUsers_Click(object sender, EventArgs e)
  509. {
  510. TbPage.SelectTab(2);
  511. ToolsMenu.Enabled = false;
  512. ImList.Images.Clear();
  513. LswView.Items.Clear();
  514. string[] ArrFiles = Directory.GetFiles(Application.StartupPath + @"\TrainedImages\", "*.JPG", SearchOption.AllDirectories);
  515. for (int i = 0; i < ArrFiles.Length; i++)
  516. {
  517. try
  518. {
  519. string Path = ArrFiles[i].ToString();
  520. Image Pic = Image.FromFile(Path);
  521. ImList.Images.Add(i.ToString(), Pic);
  522. LswView.Items.Add($"{i.ToString()}", ImList.Images.Count - 1);
  523. }
  524. catch
  525. {
  526. continue;
  527. }
  528. }
  529. }
  530. }
  531. }