FormGuard.cs 32 KB

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