FormGuard.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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 static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
  24. namespace ImpulseVision
  25. {
  26. public partial class FormGuard : Form
  27. {
  28. public FormGuard()
  29. {
  30. InitializeComponent();
  31. CaptureTimer = new Timer()
  32. {
  33. Interval = Config.TimerResponseValue
  34. };
  35. CaptureTimer.Tick += CaptureTimer_Tick;
  36. }
  37. private void CaptureTimer_Tick(object sender, EventArgs e)
  38. {
  39. TslDate.Text = $"Сейчас: {DateTime.Now.ToString("HH:mm")} {DateTime.Now.ToString("dd.MM.yyyy")}";
  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; } = "Лицо не обнаружено";
  55. /// <summary>
  56. /// ID пользователя, который обнаружен
  57. /// </summary>
  58. private string CurrentUserID = string.Empty;
  59. public struct VisitInput
  60. {
  61. public string FIO, TimeEntrance, TimeExit, Identification;
  62. }
  63. List<VisitInput> LstVisitInput = new List<VisitInput>();
  64. #region FaceName
  65. private string faceName;
  66. public string FaceName
  67. {
  68. get { return faceName; }
  69. set
  70. {
  71. faceName = value;
  72. if (faceName == "Лицо не обнаружено")
  73. {
  74. IsRecognized = false;
  75. }
  76. else
  77. {
  78. IsRecognized = true;
  79. }
  80. UserName = faceName;
  81. NotifyPropertyChanged();
  82. }
  83. }
  84. #endregion
  85. #region CameraCaptureImage
  86. private Bitmap cameraCapture;
  87. //Image<Bgr, byte> bgrFrame, Rectangle face
  88. Rectangle CurrentFace;
  89. public Bitmap CameraCapture
  90. {
  91. get { return cameraCapture; }
  92. set
  93. {
  94. cameraCapture = value;
  95. DrawName(cameraCapture, CurrentFace);
  96. PbxEther.Image = cameraCapture;
  97. NotifyPropertyChanged();
  98. }
  99. }
  100. /// <summary>
  101. /// отрисовка имени над прямоугольком
  102. /// </summary>
  103. private void DrawName(Bitmap cameraCapture, Rectangle face)
  104. {
  105. Pen PenForFace = new Pen(Brushes.Red, 5);
  106. Brush BrushForFace = Brushes.White;
  107. Font MyFont = new Font("Segoe UI Variable Small Semibol; 12pt; style=Bold", 12, FontStyle.Regular);
  108. Brush BrushInfo = Brushes.White;
  109. Pen PenInfo = new Pen(Brushes.White, 4);
  110. Graphics Graph = Graphics.FromImage(cameraCapture);
  111. //Graph.DrawRectangle(PenForFace, face.X, face.Y, face.Width, face.Height);
  112. //позиция отрисовки имени человека
  113. Point PointName = new Point(face.X, face.Y - 25);
  114. Graph.DrawString($"{UserName}", MyFont, BrushForFace, PointName);
  115. }
  116. #endregion
  117. #region CameraCaptureFaceImage
  118. private Bitmap cameraCaptureFace;
  119. public Bitmap CameraCaptureFace
  120. {
  121. get { return cameraCaptureFace; }
  122. set
  123. {
  124. cameraCaptureFace = value;
  125. PbxEther.Image = cameraCapture;
  126. NotifyPropertyChanged();
  127. }
  128. }
  129. #endregion
  130. //уведомление о том, что пользователь распознан
  131. bool IsRecognized = false;
  132. //включена ли на данный момент камера
  133. bool IsWorking = false;
  134. //выбранная камера
  135. int SelectedCameraID = 0;
  136. //доступные видеокамеры
  137. private DsDevice[] WebCams = null;
  138. int CountCams = -1;
  139. //множество для хранения списка камер
  140. HashSet<string> HtBefore = new HashSet<string>();
  141. SqlConnection SCon = new SqlConnection(Properties.Settings.Default.ImpulseVisionAppConnectionString);
  142. #endregion
  143. /// <summary>
  144. /// получение данных об изображениях
  145. /// </summary>
  146. public void GetFacesList()
  147. {
  148. //файл Хаара
  149. if (!File.Exists(Config.HaarCascadePath))
  150. {
  151. string text = "Не удаётся найти файл данных - каскад Хаара:\n\n";
  152. text += Config.HaarCascadePath;
  153. DialogResult result = MessageBox.Show(text, "Ошибка",
  154. MessageBoxButtons.OK, MessageBoxIcon.Error);
  155. }
  156. HaarCascade = new CascadeClassifier(Config.HaarCascadePath);
  157. FaceList.Clear();
  158. FaceData FaceItem = null;
  159. // создание директории если она отсутствовала
  160. if (!Directory.Exists(Config.FacePhotosPath))
  161. {
  162. Directory.CreateDirectory(Config.FacePhotosPath);
  163. }
  164. //получить из БД инфо о пользователе (id, имя, фамилия, путь до фото)
  165. SCon.Open();
  166. string QueryGetInfoAboutUser = $@"select Users.ID ,Users.Lastname, Users.Firstname, Users.Patronymic, FaceImages.Picture
  167. from Users join FaceImages on Users.ID = FaceImages.UserID";
  168. SqlCommand Cmd = new SqlCommand(QueryGetInfoAboutUser, SCon);
  169. SqlDataReader Res = Cmd.ExecuteReader();
  170. if(Res.HasRows)
  171. {
  172. while (Res.Read())
  173. {
  174. FaceItem = new FaceData();
  175. FaceItem.FaceImage = new Image<Gray, byte>(Application.StartupPath +"\\"+ Res["Picture"].ToString());
  176. FaceItem.PersonName = Res["Firstname"].ToString();
  177. FaceItem.LastName = Res["Lastname"].ToString();
  178. FaceItem.Patronymic = Res["Patronymic"].ToString();
  179. FaceItem.UserID = Res["ID"].ToString();
  180. FaceList.Add(FaceItem);
  181. }
  182. }
  183. else
  184. {
  185. SCon.Close();
  186. MessageBox.Show("Данные о пользователях отсутствуют!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  187. return;
  188. }
  189. SCon.Close();
  190. int i = 0;
  191. foreach (var face in FaceList)
  192. {
  193. ImageList.Push(face.FaceImage.Mat);
  194. NameList.Add(face.PersonName + " " + face.LastName);
  195. LabelList.Push(new[] { i++ });
  196. }
  197. // Тренировка распознавания
  198. if (ImageList.Size > 0)
  199. {
  200. recognizer = new EigenFaceRecognizer(ImageList.Size);
  201. recognizer.Train(ImageList, LabelList);
  202. }
  203. }
  204. private Image<Bgr, Byte> CurrentFrame = null;
  205. /// <summary>
  206. /// получение данных с камеры и обработка изображени
  207. /// </summary>
  208. private void ProcessFrame()
  209. {
  210. BgrFrame = Capture.QueryFrame().ToImage<Bgr, Byte>().Flip(FlipType.Horizontal);
  211. if (BgrFrame != null)
  212. {
  213. try
  214. {
  215. Image<Gray, byte> grayframe = BgrFrame.Convert<Gray, byte>();
  216. Rectangle[] faces = HaarCascade.DetectMultiScale(grayframe, 1.2, 10, new System.Drawing.Size(50, 50), new System.Drawing.Size(200, 200));
  217. FaceName = "Лицо не обнаружено";
  218. foreach (var face in faces)
  219. {
  220. CurrentFace = face;
  221. BgrFrame.Draw(face, new Bgr(53, 23, 247), 2);
  222. DetectedFace = BgrFrame.Copy(face).Convert<Gray, byte>();
  223. FaceRecognition();
  224. break;
  225. }
  226. CameraCapture = BgrFrame.ToBitmap();
  227. }
  228. catch (Exception ex)
  229. {
  230. MessageBox.Show(ex.Message);
  231. }
  232. }
  233. }
  234. /// <summary>
  235. /// распознавание лица
  236. /// </summary>
  237. private void FaceRecognition()
  238. {
  239. if (ImageList.Size != 0)
  240. {
  241. FaceRecognizer.PredictionResult result = recognizer.Predict(DetectedFace.Resize(100, 100, Inter.Cubic));
  242. FaceName = NameList[result.Label];
  243. CurrentUserID = FaceList[result.Label].UserID;
  244. CameraCaptureFace = DetectedFace.ToBitmap();
  245. PbxSourceImage.Image = FaceList[result.Label].FaceImage.ToBitmap();
  246. }
  247. else
  248. {
  249. FaceName = "Пожалуйста добавьте лицо";
  250. }
  251. }
  252. protected virtual void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
  253. {
  254. var handler = PropertyChanged;
  255. if (handler != null)
  256. handler(this, new PropertyChangedEventArgs(propertyName));
  257. }
  258. private void FormGuard_Load(object sender, EventArgs e)
  259. {
  260. // TODO: This line of code loads data into the 'impulseVisionAppDataSet1.Staffs' table. You can move, or remove it, as needed.
  261. this.staffsTableAdapter.Fill(this.impulseVisionAppDataSet1.Staffs);
  262. LblID.Hide();
  263. GetCams();
  264. Task.Factory.StartNew(() => {
  265. PbxEther.Image = Properties.Resources.loading_7;
  266. PbxSourceImage.Image = Properties.Resources.loading_7;
  267. });
  268. IsWorking = true;//камера включена
  269. GetFacesList();
  270. Capture = new VideoCapture(SelectedCameraID);
  271. //настройка кадров
  272. Capture.SetCaptureProperty(CapProp.Fps, 30);
  273. Capture.SetCaptureProperty(CapProp.FrameHeight, 450);
  274. Capture.SetCaptureProperty(CapProp.FrameWidth, 370);
  275. CaptureTimer.Start();
  276. GetVisits();
  277. }
  278. /// <summary>
  279. /// получение списка доступных камер
  280. /// </summary>
  281. private void GetCams()
  282. {
  283. WebCams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  284. CountCams = WebCams.Length;
  285. CmbCams.Items.Clear();
  286. for (int i = 0; i < CountCams; i++)
  287. {
  288. CmbCams.Items.Add(WebCams[i].Name);
  289. HtBefore.Add(WebCams[i].Name);
  290. }
  291. if (CountCams > 0)
  292. {
  293. CmbCams.SelectedIndex = 0;
  294. SelectedCameraID = 0;
  295. }
  296. }
  297. private void CmbCams_SelectedIndexChanged(object sender, EventArgs e)
  298. {
  299. try
  300. {
  301. if (BgrFrame != null)
  302. {
  303. BgrFrame = null;
  304. Capture.Dispose();
  305. CaptureTimer.Tick -= CaptureTimer_Tick;
  306. }
  307. }
  308. catch (Exception ex)
  309. {
  310. MessageBox.Show(ex.Message, "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  311. }
  312. SelectedCameraID = CmbCams.SelectedIndex;
  313. Capture = new VideoCapture(SelectedCameraID);
  314. //настройка кадров
  315. Capture.SetCaptureProperty(CapProp.Fps, 30);
  316. Capture.SetCaptureProperty(CapProp.FrameHeight, 450);
  317. Capture.SetCaptureProperty(CapProp.FrameWidth, 370);
  318. CaptureTimer.Tick += CaptureTimer_Tick;
  319. CaptureTimer.Start();
  320. }
  321. private void TimerCam_Tick(object sender, EventArgs e)
  322. {
  323. DsDevice[] Cams = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
  324. int Count = Cams.Length;
  325. //если количество подключённых камер изменилось
  326. if (Count != CountCams)
  327. {
  328. //if (Count > CountCams)
  329. //{
  330. // StatusAddNewDevice(Cams);
  331. //}
  332. //else if (Count < CountCams)
  333. //{
  334. // StatusOffDevice(Cams);
  335. //}
  336. GetCams();
  337. }
  338. }
  339. private void CameraOff()
  340. {
  341. if (BgrFrame != null)
  342. {
  343. BgrFrame = null;
  344. Capture.Dispose();
  345. CaptureTimer.Tick -= CaptureTimer_Tick;
  346. }
  347. PbxEther.Image = Properties.Resources._9110852_video_no_icon;
  348. CaptureTimer.Tick -= CaptureTimer_Tick;
  349. }
  350. private void DgbOutput_CellContentClick(object sender, DataGridViewCellEventArgs e)
  351. {
  352. }
  353. private void FormGuard_FormClosing(object sender, FormClosingEventArgs e)
  354. {
  355. CameraOff();
  356. }
  357. /// <summary>
  358. /// добавление в БД информации о входе
  359. /// </summary>
  360. private void BtnSkip_Click(object sender, EventArgs e)
  361. {
  362. RegisterVisit(1);
  363. GetVisits();
  364. }
  365. /// <summary>
  366. /// регистрация посещения
  367. /// </summary>
  368. /// <param name="IsIdentification">успешность идентификации (1-успешно, 0- нет)</param>
  369. private void RegisterVisit(int IsIdentification)
  370. {
  371. if (!IsRecognized)
  372. {
  373. MessageBox.Show("Убедитесь, что лицо находится в кадре и обведено красным прямоугольником!", "Ошибка распознавания!");
  374. return;
  375. }
  376. if (RbtIn.Checked)
  377. {
  378. if (IsIdentification == 1)
  379. {
  380. #region Предупреждение при попытке повторной идентификации пользователя за один день
  381. SCon.Open();
  382. string QueryCheckExistsVisit = $@"select Count(ID) as Cnt
  383. from UserTraffic
  384. where UserID = '{CurrentUserID}' and [Date] = CAST(GETDATE() as date)";
  385. SqlCommand CmdCheckVisit = new SqlCommand(QueryCheckExistsVisit, SCon);
  386. SqlDataReader Res = CmdCheckVisit.ExecuteReader();
  387. Res.Read();
  388. int n = int.Parse(Res["Cnt"].ToString());
  389. if (n >= 1)
  390. {
  391. MessageBox.Show("Сегодня данный пользователь уже прошёл идентификацию при входе!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  392. SCon.Close();
  393. return;
  394. }
  395. SCon.Close();
  396. #endregion
  397. }
  398. SCon.Open();
  399. string QueryAddVisit = $@"set dateformat dmy insert into UserTraffic (UserID,TimeEntrance,Identification,[Date])
  400. values ('{CurrentUserID}','{DateTime.Now.ToString("HH:mm:ss")}','{IsIdentification}','{DateTime.Now.ToString("dd.MM.yyyy")}')";
  401. SqlCommand Cmd = new SqlCommand(QueryAddVisit, SCon);
  402. Cmd.ExecuteNonQuery();
  403. SCon.Close();
  404. }
  405. else
  406. {
  407. SCon.Open();
  408. string QueryCheckRecord = $@"set dateformat dmy
  409. select *
  410. from UserTraffic
  411. where UserID = '{CurrentUserID}' and [Date] = cast(GETDATE() as date) and TimeExit is null
  412. ";
  413. SqlCommand CmdCheck = new SqlCommand(QueryCheckRecord, SCon);
  414. SqlDataReader Res = CmdCheck.ExecuteReader();
  415. if (!Res.HasRows)
  416. {
  417. MessageBox.Show("Данный пользователь уже вышел!", "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  418. SCon.Close();
  419. return;
  420. }
  421. SCon.Close();
  422. //!!! Выход пользователя, который не прошёл идентификацию не регистрируется
  423. SCon.Open();
  424. string QueryTimeExit = $@"update UserTraffic
  425. set TimeExit = '{DateTime.Now.ToString("HH:mm:ss")}'
  426. where UserID = '{CurrentUserID}' and [Date] = cast(GETDATE() as date) and Identification != 0 ";
  427. SqlCommand Cmd = new SqlCommand(QueryTimeExit, SCon);
  428. Cmd.ExecuteNonQuery();
  429. SCon.Close();
  430. }
  431. }
  432. /// <summary>
  433. /// получение списка посещений за текущую дату
  434. /// </summary>
  435. private void GetVisits()
  436. {
  437. SCon.Open();
  438. string QueryGetVisits = $@"select Users.Lastname+' '+Users.Firstname + ' ' + Users.Patronymic as FIO, TimeEntrance,TimeExit, Identification
  439. from UserTraffic ut join Users on ut.UserID = Users.ID
  440. where ut.[Date] = cast(GETDATE() as date)";
  441. SqlCommand Cmd = new SqlCommand(QueryGetVisits, SCon);
  442. SqlDataReader Res = Cmd.ExecuteReader();
  443. if (Res.HasRows)
  444. {
  445. LstVisitInput.Clear();
  446. while (Res.Read())
  447. {
  448. VisitInput visit = new VisitInput();
  449. visit.FIO = Res["FIO"].ToString();
  450. visit.TimeEntrance = Res["TimeEntrance"].ToString();
  451. visit.TimeExit = Res["TimeExit"].ToString();
  452. visit.Identification = Res["Identification"].ToString();
  453. LstVisitInput.Add(visit);
  454. }
  455. }
  456. SCon.Close();
  457. DgbInput.Rows.Clear();
  458. foreach (VisitInput item in LstVisitInput)
  459. {
  460. DgbInput.Rows.Add(item.FIO + $" {item.TimeEntrance}");
  461. if (item.Identification.ToLower() == "false")
  462. {
  463. DgbInput.Rows[DgbInput.RowCount - 1].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#E84855");
  464. DgbInput.Rows[DgbInput.RowCount - 1].DefaultCellStyle.ForeColor = Color.White;
  465. }
  466. }
  467. DgbOutput.Rows.Clear();
  468. string STime = string.Empty;
  469. foreach (VisitInput item in LstVisitInput)
  470. {
  471. STime = item.TimeExit;
  472. if (STime != string.Empty)
  473. {
  474. DgbOutput.Rows.Add(item.FIO + $" {STime}");
  475. if (item.Identification.ToLower() == "false")
  476. {
  477. DgbInput.Rows[DgbInput.RowCount - 1].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#E84855");
  478. DgbInput.Rows[DgbInput.RowCount - 1].DefaultCellStyle.ForeColor = Color.White;
  479. }
  480. }
  481. }
  482. }
  483. private void BtnReject_Click(object sender, EventArgs e)
  484. {
  485. RegisterVisit(0);
  486. if (!IsRecognized)
  487. return;
  488. try
  489. {
  490. Image<Bgr, byte> Img = BgrFrame.Copy();
  491. string PathLog = Application.StartupPath + $"\\Source\\log\\{"User_" + CurrentUserID + "_" + DateTime.Now.ToString("HHmmss") + "_" + DateTime.Now.ToString("dd.MM.yyyy") + "_" + Guid.NewGuid().ToString().Substring(0, 4)}.bmp";
  492. Img.Save(PathLog);
  493. }
  494. catch(Exception ex)
  495. {
  496. MessageBox.Show(ex.Message, "ImpulseVision", MessageBoxButtons.OK, MessageBoxIcon.Error);
  497. }
  498. GetVisits();
  499. }
  500. private void FormGuard_KeyDown(object sender, KeyEventArgs e)
  501. {
  502. if(e.KeyCode == Keys.S)
  503. {
  504. BtnSkip_Click(sender, e);
  505. }
  506. if(e.KeyCode == Keys.D)
  507. {
  508. BtnReject_Click(sender, e);
  509. }
  510. }
  511. }
  512. }