FormGuard.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. using DirectShowLib;
  2. using Emgu.CV;
  3. using Emgu.CV.CvEnum;
  4. using Emgu.CV.Face;
  5. using Emgu.CV.Ocl;
  6. using Emgu.CV.Structure;
  7. using Emgu.CV.Util;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Data.SqlClient;
  13. using System.Diagnostics;
  14. using System.Drawing;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Runtime.CompilerServices;
  18. using System.Text;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using System.Windows.Forms;
  22. using Timer = System.Windows.Forms.Timer;
  23. using System.Runtime.CompilerServices;
  24. using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
  25. namespace ImpulseVision
  26. {
  27. public partial class FormGuard : Form
  28. {
  29. public FormGuard()
  30. {
  31. InitializeComponent();
  32. CaptureTimer = new Timer()
  33. {
  34. Interval = Config.TimerResponseValue
  35. };
  36. CaptureTimer.Tick += CaptureTimer_Tick;
  37. }
  38. private void CaptureTimer_Tick(object sender, EventArgs e)
  39. {
  40. ProcessFrame();
  41. }
  42. #region <Переменные>
  43. public event PropertyChangedEventHandler PropertyChanged;
  44. private VideoCapture Capture;
  45. private CascadeClassifier HaarCascade;
  46. private Image<Bgr, Byte> BgrFrame = null;
  47. private Image<Gray, Byte> DetectedFace = null;
  48. private List<FaceData> FaceList = new List<FaceData>();
  49. private VectorOfMat ImageList = new VectorOfMat();
  50. private List<string> NameList = new List<string>();
  51. private VectorOfInt LabelList = new VectorOfInt();
  52. private EigenFaceRecognizer recognizer;
  53. private Timer CaptureTimer;
  54. public string UserName { get; set; } = "FACE NOT EXISTS";
  55. #region FaceName
  56. private string faceName;
  57. public string FaceName
  58. {
  59. get { return faceName; }
  60. set
  61. {
  62. faceName = value.ToUpper();
  63. this.Text = faceName;
  64. UserName = faceName;
  65. //PbxFaces.Invoke(DispatcherPriority.Normal, new Action(() => { lblFaceName.Content = faceName; }));
  66. NotifyPropertyChanged();
  67. }
  68. }
  69. #endregion
  70. #region CameraCaptureImage
  71. private Bitmap cameraCapture;
  72. public Bitmap CameraCapture
  73. {
  74. get { return cameraCapture; }
  75. set
  76. {
  77. cameraCapture = value;
  78. //imgCamera.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { imgCamera.Source = BitmapToImageSource(cameraCapture); }));
  79. PbxEther.Image = cameraCapture;
  80. //PbxFaces.Image = BitmapToImageSource(cameraCapture);
  81. NotifyPropertyChanged();
  82. }
  83. }
  84. #endregion
  85. #region CameraCaptureFaceImage
  86. private Bitmap cameraCaptureFace;
  87. public Bitmap CameraCaptureFace
  88. {
  89. get { return cameraCaptureFace; }
  90. set
  91. {
  92. cameraCaptureFace = value;
  93. //imgDetectFace.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { imgDetectFace.Source = BitmapToImageSource(cameraCaptureFace); }));
  94. //PbxFaces.Image = BitmapToImageSource(cameraCapture);
  95. PbxEther.Image = cameraCapture;
  96. NotifyPropertyChanged();
  97. }
  98. }
  99. #endregion
  100. //включена ли на данный момент камера
  101. bool IsWorking = false;
  102. //выбранная камера
  103. int SelectedCameraID = 0;
  104. //доступные видеокамеры
  105. private DsDevice[] WebCams = null;
  106. int CountCams = -1;
  107. //множество для хранения списка камер
  108. HashSet<string> HtBefore = new HashSet<string>();
  109. //пути доступа к изображениям пользователей
  110. List<Pictures> LstUserPictures = new List<Pictures>();
  111. SqlConnection SCon = new SqlConnection(Properties.Settings.Default.ImpulseVisionAppConnectionString);
  112. //идентификаторы пользователей, лица которых будут распознаваться
  113. List<string> LstUserID = new List<string>();
  114. #endregion
  115. struct Pictures
  116. {
  117. public string UserID, PicturePath;
  118. }
  119. /// <summary>
  120. /// получение данных об изображениях
  121. /// </summary>
  122. public void GetFacesList()
  123. {
  124. //haar cascade classifier
  125. if (!File.Exists(Config.HaarCascadePath))
  126. {
  127. string text = "Не удаётся найти файл данных каскад Хаара:\n\n";
  128. text += Config.HaarCascadePath;
  129. DialogResult result = MessageBox.Show(text, "Ошибка",
  130. MessageBoxButtons.OK, MessageBoxIcon.Error);
  131. }
  132. HaarCascade = new CascadeClassifier(Config.HaarCascadePath);
  133. FaceList.Clear();
  134. string line;
  135. FaceData FaceItem = null;
  136. // Create empty directory / file for face data if it doesn't exist
  137. if (!Directory.Exists(Config.FacePhotosPath))
  138. {
  139. Directory.CreateDirectory(Config.FacePhotosPath);
  140. }
  141. //
  142. /*
  143. if (!File.Exists(Config.FaceListTextFile))
  144. {
  145. string text = "Не удается найти файл с данными о лице:\n\n";
  146. text += Config.FaceListTextFile + "\n\n";
  147. text += "Если вы впервые запускаете приложение, для вас будет создан пустой файл.";
  148. DialogResult result = MessageBox.Show(text, "Предупреждение",
  149. MessageBoxButtons.OK, MessageBoxIcon.Warning);
  150. switch (result)
  151. {
  152. case DialogResult.OK:
  153. String dirName = Path.GetDirectoryName(Config.FaceListTextFile);
  154. Directory.CreateDirectory(dirName);
  155. File.Create(Config.FaceListTextFile).Close();
  156. break;
  157. }
  158. }
  159. */
  160. //
  161. //получить из БД инфо о пользователе (id, имя, фамилия, путь до фото)
  162. SCon.Open();
  163. string QueryGetInfoAboutUser = $@"select Users.ID ,Users.Lastname, Users.Firstname, Users.Patronymic, FaceImages.Picture
  164. from Users join FaceImages on Users.ID = FaceImages.UserID";
  165. SqlCommand Cmd = new SqlCommand(QueryGetInfoAboutUser, SCon);
  166. SqlDataReader Res = Cmd.ExecuteReader();
  167. if(Res.HasRows)
  168. {
  169. FaceItem = new FaceData();
  170. while (Res.Read())
  171. {
  172. FaceItem.FaceImage = new Image<Gray, byte>(Res["Picture"].ToString());
  173. FaceItem.PersonName = Res["Firstname"].ToString();
  174. FaceItem.LastName = Res["Lastname"].ToString();
  175. FaceItem.Patronymic = Res["Patronymic"].ToString();
  176. FaceItem.UserID = Res["ID"].ToString();
  177. FaceList.Add(FaceItem);
  178. }
  179. }
  180. else
  181. {
  182. SCon.Close();
  183. MessageBox.Show("Данные о пользователях отсутствуют!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  184. return;
  185. }
  186. SCon.Close();
  187. int i = 0;
  188. /*
  189. StreamReader reader = new StreamReader(Config.FaceListTextFile);
  190. while ((line = reader.ReadLine()) != null)
  191. {
  192. string[] lineParts = line.Split(':');
  193. FaceItem = new FaceData();
  194. FaceItem.FaceImage = new Image<Gray, byte>(Config.FacePhotosPath + lineParts[0] + Config.ImageFileExtension);
  195. FaceItem.PersonName = lineParts[1];
  196. FaceList.Add(FaceItem);
  197. }
  198. reader.Close();
  199. */
  200. foreach (var face in FaceList)
  201. {
  202. ImageList.Push(face.FaceImage.Mat);
  203. NameList.Add(face.PersonName);
  204. LabelList.Push(new[] { i++ });
  205. }
  206. // Тренировка распознавания
  207. if (ImageList.Size > 0)
  208. {
  209. recognizer = new EigenFaceRecognizer(ImageList.Size);
  210. recognizer.Train(ImageList, LabelList);
  211. }
  212. }
  213. /// <summary>
  214. /// получение данных с камеры и обработка изображени
  215. /// </summary>
  216. private void ProcessFrame()
  217. {
  218. BgrFrame = Capture.QueryFrame().ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
  219. Pen PenForFace = new Pen(Brushes.Red, 5);
  220. Brush BrushForFace = Brushes.White;
  221. Font MyFont = new Font("Segoe UI Variable Small Semibol; 14pt; style=Bold", 14, FontStyle.Regular);
  222. Brush BrushInfo = Brushes.White;
  223. Pen PenInfo = new Pen(Brushes.White, 4);
  224. if (BgrFrame != null)
  225. {
  226. try
  227. {//for emgu cv bug
  228. Image<Gray, byte> grayframe = BgrFrame.Convert<Gray, byte>();
  229. Rectangle[] faces = HaarCascade.DetectMultiScale(grayframe, 1.2, 10, new System.Drawing.Size(50, 50), new System.Drawing.Size(200, 200));
  230. //detect face
  231. FaceName = "No face detected";
  232. foreach (var face in faces)
  233. {
  234. BgrFrame.Draw(face, new Bgr(53, 23, 247), 2);
  235. DetectedFace = BgrFrame.Copy(face).Convert<Gray, byte>();
  236. Point PointInfo = new Point(face.Width - face.Width, 0);
  237. Graphics GraphInfo = Graphics.FromImage(BgrFrame.ToBitmap());
  238. Graphics Graph = Graphics.FromImage(BgrFrame.ToBitmap());
  239. Graph.DrawRectangle(PenForFace, face.X, face.Y, face.Width, face.Height);
  240. //позиция отрисовки имени человека
  241. Point PointName = new Point(face.X, face.Y - 25);
  242. Graph.DrawString($"{UserName}", MyFont, BrushForFace, PointName);
  243. FaceRecognition();
  244. break;
  245. }
  246. CameraCapture = BgrFrame.ToBitmap();
  247. }
  248. catch (Exception ex)
  249. {
  250. //todo log
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// распознавание лица
  256. /// </summary>
  257. private void FaceRecognition()
  258. {
  259. if (ImageList.Size != 0)
  260. {
  261. //Eigen Face Algorithm
  262. FaceRecognizer.PredictionResult result = recognizer.Predict(DetectedFace.Resize(100, 100, Inter.Cubic));
  263. FaceName = NameList[result.Label];
  264. CameraCaptureFace = DetectedFace.ToBitmap();
  265. }
  266. else
  267. {
  268. FaceName = "Please Add Face";
  269. }
  270. }
  271. protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
  272. {
  273. var handler = PropertyChanged;
  274. if (handler != null)
  275. handler(this, new PropertyChangedEventArgs(propertyName));
  276. }
  277. /// <summary>
  278. /// получение id и путей доступа к изображениям пользователей
  279. /// </summary>
  280. private bool GetPicturesPath()
  281. {
  282. SCon.Open();
  283. string Query1 = $@"select UserID,Picture
  284. from FaceImages";
  285. SqlCommand Cmd = new SqlCommand(Query1, SCon);
  286. SqlDataReader Res = Cmd.ExecuteReader();
  287. if(Res.HasRows)
  288. {
  289. LstUserPictures.Clear();
  290. while(Res.Read())
  291. {
  292. Pictures Pic = new Pictures();
  293. Pic.UserID = Res["UserID"].ToString();
  294. Pic.PicturePath = Res["Picture"].ToString();
  295. LstUserPictures.Add(Pic);
  296. }
  297. }
  298. else
  299. {
  300. MessageBox.Show("Не удалось получить информацию об изображениях!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Error);
  301. SCon.Close();
  302. return false;
  303. }
  304. SCon.Close();
  305. return true;
  306. }
  307. private void BtnCheck_Click(object sender, EventArgs e)
  308. {
  309. if(!GetPicturesPath())
  310. {
  311. return;
  312. }
  313. string CurrentID = LstUserPictures[0].UserID;
  314. for (int i = 0; i < LstUserPictures.Count; i++)
  315. {
  316. if (!LstUserID.Contains(LstUserPictures[i].UserID))
  317. {
  318. LstUserID.Add(LstUserPictures[i].UserID);
  319. }
  320. }
  321. if(LstUserID.Count > 0)
  322. {
  323. //TrainImageFromDir(LstUserID[iterator]);
  324. }
  325. /*
  326. for (int i = 0; i < LstUserID.Count; i++)
  327. {
  328. //Thread.Sleep(5000);
  329. IsTrained = false;
  330. NextFace = false;
  331. //тренировать изображения текущего пользователя
  332. TrainImageFromDir(LstUserID[i]);
  333. ////подождать некоторое время
  334. //Task.Delay(5000);
  335. }
  336. //TrainImageFromDir(LstUserID[0]);
  337. */
  338. //IsTrained = true;
  339. }
  340. /// <summary>
  341. /// распознавание изображения, его отображение и сохранение
  342. /// </summary>
  343. /*
  344. private void VideoProcess(object sender, EventArgs e)
  345. {
  346. int CountAllRectangle = 0;
  347. int CountRecognize = 0;
  348. if (VideoCapture == null && VideoCapture.Ptr == IntPtr.Zero)
  349. return;
  350. //1. Захват видео
  351. VideoCapture.Retrieve(Frame, 0);//восстановить нулевой кадр
  352. CurrentFrame = Frame.ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
  353. //2. Обнаружение лиц
  354. if (FacesDetectionEnabled)
  355. {
  356. //преобразовать изображение в серое
  357. Mat GrayImage = new Mat();
  358. CvInvoke.CvtColor(CurrentFrame, GrayImage, ColorConversion.Bgr2Gray);
  359. //выравнивание гистограммы изображения
  360. CvInvoke.EqualizeHist(GrayImage, GrayImage);
  361. #region --Объекты для отрисовки надписей над изображением лица--
  362. Pen PenForFace = new Pen(Brushes.Red, 5);
  363. Brush BrushForFace = Brushes.White;
  364. Font MyFont = new Font("Segoe UI Variable Small Semibol; 14pt; style=Bold", 14, FontStyle.Regular);
  365. Brush BrushInfo = Brushes.White;
  366. Pen PenInfo = new Pen(Brushes.White, 4);
  367. Point PointInfo = new Point(CurrentFrame.Width - CurrentFrame.Width, 0);
  368. Graphics GraphInfo = Graphics.FromImage(CurrentFrame.Bitmap);
  369. #endregion
  370. //записать распознанные изображения в массив
  371. Rectangle[] RectFaces = CasClassifier.DetectMultiScale(GrayImage, 1.1, 3, Size.Empty, Size.Empty);
  372. //имя распознанного пользователя, которое будет выводиться в сообщении
  373. string NameUserRecognize = string.Empty;
  374. //если лица обнаружены
  375. if (RectFaces.Length > 0)
  376. {
  377. foreach (var CurrentFace in RectFaces)
  378. {
  379. CountAllRectangle++;
  380. //нарисовать прямоугольники вокруг лиц
  381. Point PointForFace = new Point(CurrentFace.X, CurrentFace.Y);
  382. //результирующее изображение
  383. //Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
  384. Graphics Graph = Graphics.FromImage(CurrentFrame.Bitmap);
  385. Graph.DrawRectangle(PenForFace, PointForFace.X, PointForFace.Y, CurrentFace.Width, CurrentFace.Height);
  386. //позиция отрисовки имени человека
  387. Point PersonName = new Point(CurrentFace.X, CurrentFace.Y - 25);
  388. //Graph.DrawString("Распознано", MyFont, MyBrush, PersonName);
  389. //3. Добавление человека (лица)
  390. ////результирующее изображение
  391. Image<Bgr, Byte> ResultImage = CurrentFrame.Convert<Bgr, Byte>();
  392. ResultImage.ROI = CurrentFace;
  393. //отобразить на форме найденное изображение
  394. //PbxDetected.Image = ResultImage.ToBitmap();
  395. //******************
  396. TempImageForRazn = ResultImage;
  397. //если сохранение изображения включено
  398. //if (EnableSaveImage)
  399. //{
  400. // //создать каталог, если он не существует
  401. // string Path = Directory.GetCurrentDirectory() + $@"\TrainedImages\{TbxFirstname.Text.Trim()}{TbxPasportSeria.Text.Trim()}{TbxPasportNum.Text.Trim()}";
  402. // string PathPhoto = $@"\TrainedImages\{TbxFirstname.Text.Trim()}{TbxPasportSeria.Text.Trim()}{TbxPasportNum.Text.Trim()}";
  403. // if (!Directory.Exists(Path))
  404. // {
  405. // Directory.CreateDirectory(Path);
  406. // }
  407. // //сохранить 30 изображений
  408. // //Task.Factory.StartNew(() =>
  409. // //{
  410. // // Saving = false;
  411. // // LstPathImage.Clear();
  412. // // for (int i = 0; i < 30; i++)
  413. // // {
  414. // // PathPhoto = $@"\TrainedImages\{TbxFirstname.Text.Trim()}{TbxPasportSeria.Text.Trim()}{TbxPasportNum.Text.Trim()}";
  415. // // ResultImage.Resize(200, 200, Inter.Cubic).Save(Path + @"\" + TbxLastname.Text.Trim() + "+" + TbxFirstname.Text.Trim() + "__" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + Guid.NewGuid().ToString().Substring(0, 6) + ".jpg");
  416. // // PathPhoto += @"\" + TbxLastname.Text.Trim() + "+" + TbxFirstname.Text.Trim() + "__" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + Guid.NewGuid().ToString().Substring(0, 6) + ".jpg";
  417. // // LstPathImage.Add(PathPhoto);
  418. // // Thread.Sleep(200);
  419. // // }
  420. // // Saving = true;
  421. // // MessageBox.Show("Сохранение завершено!", "Результат операции.", MessageBoxButtons.OK, MessageBoxIcon.Information);
  422. // // //TrainImageFromDir();
  423. // //});
  424. //}
  425. //EnableSaveImage = false;
  426. //if (BtnSave.InvokeRequired)
  427. //{
  428. // BtnSave.Invoke(new ThreadStart(delegate
  429. // {
  430. // BtnSave.Enabled = true;
  431. // }));
  432. //}
  433. //5. Узнавание изображения
  434. if (IsTrained)
  435. {
  436. Image<Gray, byte> grayFaceResult = ResultImage.Convert<Gray, byte>().Resize(200, 200, Inter.Cubic);
  437. CvInvoke.EqualizeHist(grayFaceResult, grayFaceResult);
  438. var Result = Recognizer.Predict(grayFaceResult);
  439. Debug.WriteLine(Result.Label + " | " + Result.Distance);
  440. // если лица найдены
  441. if (Result.Label != -1 && Result.Distance < 2000)
  442. {
  443. CountRecognize++;
  444. PenForFace = new Pen(Color.Green, 5);
  445. Graph.DrawRectangle(PenForFace, PointForFace.X, PointForFace.Y, CurrentFace.Width, CurrentFace.Height);
  446. BrushForFace = Brushes.LightGreen;
  447. Graph.DrawString($"{LstPersonNames[Result.Label]}", MyFont, BrushForFace, PersonName);
  448. NameUserRecognize = LstPersonNames[Result.Label];
  449. GraphInfo.DrawString($"На изображении: {LstPersonNames[Result.Label]}", MyFont, BrushInfo, PointInfo);
  450. //CvInvoke.Rectangle(CurrentFrame, CurrentFace, new Bgr(Color.Green).MCvScalar, 2);
  451. }
  452. else
  453. {
  454. BrushForFace = Brushes.LightPink;
  455. Graph.DrawString("Неизвестный", MyFont, BrushForFace, PersonName);
  456. }
  457. }
  458. }
  459. //if (CountRecognize > CountRecognize / 2)
  460. //{
  461. // MessageBox.Show($"Распознан: {NameUserRecognize}");
  462. //}
  463. }
  464. }
  465. //NormalizeImage(CurrentFrame);
  466. try
  467. {
  468. //вывести изображение в PictureBox
  469. PbxEther.Image = CurrentFrame.Bitmap;
  470. }
  471. catch (Exception ex)
  472. {
  473. MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  474. }
  475. }
  476. */
  477. /// <summary>
  478. /// тренировка изображения
  479. /// </summary>
  480. /// <returns>результат тренировки (true или false)</returns>
  481. /*
  482. private void TrainImageFromDir(string UserID)
  483. {
  484. int CountImage = 0;
  485. //порог
  486. double Threshold = 2000;
  487. //LstTrainedFaces.Clear();
  488. //PersonLabes.Clear();
  489. //LstPersonNames.Clear();
  490. //ProgressTrain.Value += 15;
  491. //string MyPath = Directory.GetCurrentDirectory() + @"\TrainedImages\";
  492. //string[] Files = Directory.GetFiles(MyPath, "*.jpg", SearchOption.AllDirectories);
  493. int n = LstUserPictures.Count;
  494. foreach (Pictures picPath in LstUserPictures)
  495. {
  496. if (picPath.UserID == UserID)
  497. {
  498. Image<Gray, Byte> TrainedImage = new Image<Gray, Byte>(Application.StartupPath + picPath.PicturePath.Trim()).Resize(200, 200, Inter.Cubic);
  499. //выровнять гистограмму изображения
  500. CvInvoke.EqualizeHist(TrainedImage, TrainedImage);
  501. //добавить обученное изображение
  502. LstTrainedFaces.Add(TrainedImage);
  503. PersonLabes.Add(CountImage);
  504. string CurrentFileName = Path.GetFileName(Application.StartupPath + picPath.PicturePath);
  505. string Name = CurrentFileName.Remove(CurrentFileName.IndexOf("_"), CurrentFileName.Length - CurrentFileName.IndexOf("_"));
  506. //добавить имя
  507. LstPersonNames.Add(Name.Replace("+", " "));
  508. CountImage++;
  509. }
  510. }
  511. if(LstTrainedFaces.Count() > 0)
  512. {
  513. //тренировка изображения
  514. Recognizer = new EigenFaceRecognizer(CountImage, Threshold);
  515. Recognizer.Train(LstTrainedFaces.ToArray(), PersonLabes.ToArray());
  516. //записать, что обучен
  517. IsTrained = true;
  518. MessageBox.Show("Тренировка изображений выполнена!");
  519. }
  520. else
  521. {
  522. IsTrained = false;
  523. MessageBox.Show("Ошибка при распознавании лица!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Error);
  524. return;
  525. }
  526. }
  527. */
  528. private void FormGuard_Load(object sender, EventArgs e)
  529. {
  530. // TODO: This line of code loads data into the 'impulseVisionAppDataSet1.Staffs' table. You can move, or remove it, as needed.
  531. this.staffsTableAdapter.Fill(this.impulseVisionAppDataSet1.Staffs);
  532. GetCams();
  533. //if (VideoCapture != null)
  534. //{
  535. // IsWorking = false;
  536. // VideoCapture.Stop();
  537. // VideoCapture.Dispose();
  538. // //VideoCapture = null;
  539. //}
  540. IsWorking = true;//камера включена
  541. ////при нескольких веб- камерах в параметрах передаётся её индекс
  542. //VideoCapture = new Capture(SelectedCameraID);
  543. //Application.Idle += VideoProcess;
  544. GetFacesList();
  545. if(CmbCams.Items.Count > 0)
  546. {
  547. SelectedCameraID = Config.ActiveCameraIndex;
  548. }
  549. //задание активной камеры
  550. Capture = new VideoCapture(SelectedCameraID);
  551. //настройка кадров
  552. Capture.SetCaptureProperty(CapProp.Fps, 30);
  553. Capture.SetCaptureProperty(CapProp.FrameHeight, 450);
  554. Capture.SetCaptureProperty(CapProp.FrameWidth, 370);
  555. CaptureTimer.Start();
  556. }
  557. /// <summary>
  558. /// получение списка доступных камер
  559. /// </summary>
  560. private void GetCams()
  561. {
  562. WebCams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  563. CountCams = WebCams.Length;
  564. CmbCams.Items.Clear();
  565. for (int i = 0; i < CountCams; i++)
  566. {
  567. CmbCams.Items.Add(WebCams[i].Name);
  568. HtBefore.Add(WebCams[i].Name);
  569. }
  570. if (CountCams > 0)
  571. {
  572. CmbCams.SelectedIndex = 0;
  573. SelectedCameraID = 0;
  574. }
  575. }
  576. private void CmbCams_SelectedIndexChanged(object sender, EventArgs e)
  577. {
  578. try
  579. {
  580. //если захват видео уже идёт
  581. if (Capture != null)
  582. {
  583. //captureTimer.Stop();
  584. Capture.Dispose();
  585. Capture = null;
  586. PbxEther.Image = null;
  587. }
  588. }
  589. catch (Exception ex)
  590. {
  591. MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  592. }
  593. SelectedCameraID = CmbCams.SelectedIndex;
  594. Capture = new VideoCapture(SelectedCameraID);
  595. //настройка кадров
  596. Capture.SetCaptureProperty(CapProp.Fps, 30);
  597. Capture.SetCaptureProperty(CapProp.FrameHeight, 450);
  598. Capture.SetCaptureProperty(CapProp.FrameWidth, 370);
  599. CaptureTimer.Start();
  600. }
  601. private void TimerCam_Tick(object sender, EventArgs e)
  602. {
  603. DsDevice[] Cams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  604. int Count = Cams.Length;
  605. //если количество подключённых камер изменилось
  606. if (Count != CountCams)
  607. {
  608. //if (Count > CountCams)
  609. //{
  610. // StatusAddNewDevice(Cams);
  611. //}
  612. //else if (Count < CountCams)
  613. //{
  614. // StatusOffDevice(Cams);
  615. //}
  616. GetCams();
  617. }
  618. }
  619. }
  620. }