Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.23 KB | None | 0 0
  1. #include "MainWindow.h"
  2.  
  3.  
  4. int main(int argc, char *argv[])
  5. {
  6. QApplication app(argc, argv);
  7. QApplication::setApplicationName("face-demo");
  8. QApplication::setApplicationVersion("0.6.2");
  9. QApplication::setOrganizationName("stlab");
  10. QTranslator qtTranslator;
  11. qtTranslator.load("qt_" + QLocale::system().name(), QApplication::applicationDirPath()+"/translations");
  12. app.installTranslator(&qtTranslator);
  13. QThreadPool::globalInstance()->setMaxThreadCount(4);
  14. try {
  15. MainWindow window;
  16. window.show();
  17. return app.exec();
  18. } catch (e_default e) {
  19. QMessageBox::critical(0, QString::fromUtf8("Ошибка инициализации"), e.what());
  20. return -1;
  21. }
  22. }
  23.  
  24.  
  25. MainWindow::MainWindow()
  26. : QMainWindow(nullptr)
  27. {
  28. _ui.setupUi(this);
  29. // сцена
  30. _scene = new QGraphicsScene (0, 0, _ui.viewWidget->width(), _ui.viewWidget->height());
  31. _scene->setBackgroundBrush(QBrush(Qt::black));
  32. _ui.viewWidget->setScene(_scene);
  33. _rect = _scene->addRect(QRectF(0, 0, _ui.viewWidget->width(), _barHeight + 10), QPen(Qt::white), QBrush(Qt::white));
  34. _rect->setY(_ui.viewWidget->height()-_barHeight);
  35. _rect->setZValue (10);
  36. _text = _scene->addText("");
  37. _text->document()->setDocumentMargin(0);
  38. _text->setTextWidth(_ui.viewWidget->width());
  39. _text->setZValue (20);
  40. _text->setY(_ui.viewWidget->height()-_barHeight);
  41. // настройки по умолчанию
  42. _rtspParams << "--aout=dummy" << "--vout=dummy" << "--network-caching=500";
  43. if (!QSettings().contains("inputMode")) QSettings().setValue("inputMode", "webcam");
  44. if (!QSettings().contains("webcamIndex")) QSettings().setValue("webcamIndex", 0);
  45. if (!QSettings().contains("turnCheck")) QSettings().setValue("turnCheck", false);
  46. if (!QSettings().contains("showMarks")) QSettings().setValue("showMarks", false);
  47. // интерфейс
  48. _ui.webcamCheck->setChecked(QSettings().value("inputMode").toString() == "webcam");
  49. _ui.ipcamCheck->setChecked(QSettings().value("inputMode").toString() == "ipcam");
  50. _ui.webcamSpin->setValue(QSettings().value("webcamIndex").toInt());
  51. _ui.turnCheck->setChecked(QSettings().value("turnCheck").toBool());
  52. _ui.landmarksCheck->setChecked(QSettings().value("showMarks").toBool());
  53. QObject::connect (&_viewTimer, &QTimer::timeout, this, &MainWindow::on_view);
  54. QObject::connect (&_verifyTimer, &QTimer::timeout, this, &MainWindow::on_progressed);
  55. QObject::connect (this, &MainWindow::startView, this, &MainWindow::startView);
  56. QObject::connect (this, &MainWindow::stopView, this, &MainWindow::stopView);
  57. // сети
  58. QStringList protos;
  59. QFile resource;
  60. resource.setFileName("://det1.prototxt");
  61. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  62. protos.push_back(resource.readAll());
  63. resource.setFileName("://det2_input.prototxt");
  64. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  65. protos.push_back(resource.readAll());
  66. resource.setFileName("://det2.prototxt");
  67. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  68. protos.push_back(resource.readAll());
  69. resource.setFileName("://det3_input.prototxt");
  70. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  71. protos.push_back(resource.readAll());
  72. resource.setFileName("://det3.prototxt");
  73. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  74. protos.push_back(resource.readAll());
  75. resource.setFileName("://det4.prototxt");
  76. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  77. protos.push_back(resource.readAll());
  78. _detector = new FaceDetectorMtcnn(QApplication::applicationDirPath()+"/data/", protos, 80, 0.75);
  79. resource.setFileName("://cnn-deploy-x128.prototxt");
  80. if (!resource.open(QFile::ReadOnly)) throw e_failure("MainWindow: Can't load resource");
  81. protos.push_back(resource.readAll());
  82. _extractor = new FaceExtractorStlab(QApplication::applicationDirPath()+"/data/", protos[6]);
  83. _headDetector = new HeadMoveDetector;
  84. _etalon = new FaceTemplateL2(*_extractor);
  85. // начальное состояние
  86. setState(AppState::NotRegistered);
  87. setState(FaceState::None);
  88. reloadUsers();
  89. startView();
  90. startProcess();
  91. }
  92.  
  93.  
  94. MainWindow::~MainWindow ()
  95. {
  96. stopProcess();
  97. stopView();
  98. delete_s(_etalon);
  99. delete_s(_headDetector);
  100. delete_s(_extractor);
  101. delete_s(_detector);
  102. }
  103.  
  104.  
  105. void MainWindow::stopView()
  106. {
  107. _viewTimer.stop();
  108. for (auto i: _items) delete i;
  109. _items.clear();
  110. delete_s (_pixmap);
  111. delete_s (_input);
  112. _frame.setTo(cv::Scalar(0,0,0));
  113. }
  114.  
  115.  
  116. void MainWindow::startView()
  117. {
  118. try {
  119. #ifdef WITH_IPCAM
  120. _input = new VideoInputStream();
  121. if (QSettings().value("inputMode").toString() == "webcam") {
  122. _input->openDevice(QSettings().value("webcamIndex").toInt(), -1, _frameSize);
  123. setState(StreamState::Ok);
  124. } else if (QSettings().value("inputMode").toString() == "ipcam") {
  125. _input->openVideoStream(QSettings().value("rtspUrl").toString(), _frameSize, {}, {}, _rtspParams, VideoInputStream::Mode::KeepAspectRatio);
  126. setState(StreamState::Accessing);
  127. QTimer::singleShot(_streamTimeout, this, &MainWindow::on_streamTimeout);
  128. }
  129. #else
  130. _input = new VideoInput();
  131. if (QSettings().value("inputMode").toString() == "webcam") {
  132. _input->openDevice(QSettings().value("webcamIndex").toInt(), -1, _frameSize);
  133. }
  134. #endif
  135. _viewTimer.start (1000/_showFps);
  136. } catch (...) {
  137. setState(StreamState::Failed);
  138. }
  139. draw();
  140. }
  141.  
  142. void MainWindow::stopProcess()
  143. {
  144. _running = false;
  145. if (_processingThread.isRunning()) _processingThread.waitForFinished();
  146. _mutex.lock();
  147. _mask.clear();
  148. _mutex.unlock();
  149. }
  150.  
  151.  
  152. void MainWindow::startProcess()
  153. {
  154. try {
  155. _running = true;
  156. _processingThread = QtConcurrent::run (this, &MainWindow::process);
  157. } catch (e_default e) {
  158. qDebug() << e.what();
  159. }
  160. }
  161.  
  162.  
  163. void MainWindow::on_view()
  164. {
  165. try {
  166. if (!_input->isFrameReady()) return;
  167. _mutex2.lock();
  168. _input->getFrame (_frame);
  169. _mutex2.unlock();
  170. if (!_frame.cols || !_frame.rows) throw e_failure("MainWindow: Empty frame");
  171. for (auto i: _items) delete(i);
  172. _items.clear();
  173. delete_s(_pixmap);
  174. _pixmap = _scene->addPixmap(QPixmap::fromImage(convert(_frame)));
  175. if (QSettings().value("showMarks").toBool() && _mask.size() == 7) {
  176. _mutex.lock();
  177. _items.push_back(_scene->addRect(_mask[0].x(), _mask[0].y(),
  178. _mask[1].x()-_mask[0].x(), _mask[1].y()-_mask[0].y(), QPen(Qt::yellow)));
  179. _items.push_back(_scene->addRect(_mask[2].x(), _mask[2].y(), 4, 4, QPen(Qt::yellow)));
  180. _items.push_back(_scene->addRect(_mask[3].x(), _mask[3].y(), 4, 4, QPen(Qt::yellow)));
  181. _items.push_back(_scene->addRect(_mask[4].x(), _mask[4].y(), 4, 4, QPen(Qt::yellow)));
  182. _items.push_back(_scene->addRect(_mask[5].x(), _mask[5].y(), 4, 4, QPen(Qt::yellow)));
  183. _items.push_back(_scene->addRect(_mask[6].x(), _mask[6].y(), 4, 4, QPen(Qt::yellow)));
  184. _mutex.unlock();
  185. }
  186. setState(StreamState::Ok);
  187. } catch (e_default e) {
  188. qDebug() << e.what();
  189. setState(StreamState::Skipping);
  190. } catch (...) {
  191. setState(StreamState::Skipping);
  192. }
  193. draw();
  194. if (_mutex2.tryLock()) _mutex2.unlock();
  195. }
  196.  
  197.  
  198. void MainWindow::on_progressed()
  199. {
  200. if (_appState != AppState::Testing) {
  201. _verifyTimer.stop();
  202. } else {
  203. _progress++;
  204. _rect->setRect(QRectF(0, 0, _ui.viewWidget->width() * MIN(100, _progress) / 100, _barHeight + 10));
  205. if (_progress >= 100) {
  206. setState(AppState::Ready);
  207. setState(FaceState::Rejected);
  208. }
  209. }
  210. }
  211.  
  212.  
  213. void MainWindow::on_streamTimeout()
  214. {
  215. if (_streamState == StreamState::Accessing) {
  216. setState(StreamState::Failed);
  217. draw();
  218. }
  219. }
  220.  
  221.  
  222. void MainWindow::draw ()
  223. {
  224. _ui.label_a->clear();
  225. _ui.label_b->clear();
  226. switch (_streamState)
  227. {
  228. case StreamState::Failed:
  229. _text->setHtml(tr("<body style=\"%0\"><br>Невозможно открыть видеопоток<br></body>").arg(_warningStyle));
  230. return;
  231. case StreamState::Skipping:
  232. _text->setHtml(tr("<body style=\"%0\"><br>Ошибка чтения кадра из видеопотока<br></body>").arg(_warningStyle));
  233. return;
  234. case StreamState::Accessing:
  235. _text->setHtml(tr("<body style=\"%0\"><br>Чтение видеопотока...<br></body>").arg(_warningStyle));
  236. return;
  237. case StreamState::Ok:
  238. break;
  239. }
  240. switch (_appState) {
  241. case AppState::NotRegistered:
  242. _rect->setRect(QRectF(0, 0, _ui.viewWidget->width(), _barHeight + 10));
  243. _text->setHtml(tr("<body style=\"%0\"><br>Пользователь не зарегистрирован<br></body>").arg(_grayStyle));
  244. break;
  245. case AppState::Training:
  246. if (_progress < 100) _text->setHtml(tr("<body style=\"%0\"><br>Регистрация лица... %1%<br></body>").arg(_grayStyle).arg(_progress));
  247. else _text->setHtml(tr("<body style=\"%0\"><br>Формирование шаблона...<br></body>").arg(_grayStyle));
  248. break;
  249. case AppState::Ready:
  250. _rect->setRect(QRectF(0, 0, _ui.viewWidget->width(), _barHeight + 10));
  251. _text->setHtml(tr("<body style=\"%0\"><br>Готово к работе<br></body>").arg(_grayStyle));
  252. break;
  253. case AppState::Testing:
  254. _text->setHtml(tr("<body style=\"%0\"><br>Верификация... %1%<br></body>").arg(_grayStyle).arg(_progress));
  255. _ui.label_a->setText(tr("Совпадение: %0%").arg(_similarity));
  256. if (QSettings().value("turnCheck").toBool()) _ui.label_b->setText(tr("Живое лицо: %0").arg(_moved?"да":"нет"));
  257. break;
  258. }
  259. switch (_faceState) {
  260. case FaceState::Accepted:
  261. _rect->setRect(QRectF(0, 0, _ui.viewWidget->width(), _barHeight + 10));
  262. _text->setHtml(tr("<body style=\"%0\"><br>Верификация успешна (%1 мс)<br></body>").arg(_greenStyle).arg(_verificationTime));
  263. break;
  264. case FaceState::Rejected:
  265. _rect->setRect(QRectF(0, 0, _ui.viewWidget->width(), _barHeight + 10));
  266. _text->setHtml(tr("<body style=\"%0\"><br>Верификация неудачна<br></body>").arg(_redStyle));
  267. break;
  268. case FaceState::Spoofing:
  269. _text->setHtml(tr("<body style=\"%0\"><br>Защита от фотографии: поверните голову<br></body>").arg(_yellowStyle));
  270. break;
  271. case FaceState::Noface:
  272. _text->setHtml(tr("<body style=\"%0\"><br>Лицо не обнаружено<br></body>").arg(_warningStyle));
  273. break;
  274. case FaceState::LowQuality:
  275. _text->setHtml(tr("<body style=\"%0\"><br>Недостаточное качество картинки<br></body>").arg(_warningStyle));
  276. break;
  277. case FaceState::None:
  278. break;
  279. }
  280. _ui.label_c->setText(tr("%0 мс / кадр").arg(_frameTime));
  281. }
  282.  
  283.  
  284. void MainWindow::reloadUsers()
  285. {
  286. _ui.usersList->clear();
  287. QDir dir(_path);
  288. for (auto file: dir.entryList({"*.face"})) {
  289. _ui.usersList->addItem(file.left(file.size()-5));
  290. }
  291. }
  292.  
  293.  
  294. QString MainWindow::getInput(QString header, QString label, QString text)
  295. {
  296. QInputDialog dialog(this);
  297. dialog.setWindowTitle(header);
  298. dialog.setLabelText(label);
  299. dialog.setTextValue(text);
  300. dialog.resize(geometry().width()-64, -1);
  301. return dialog.exec() ? dialog.textValue() : "";
  302. }
  303.  
  304.  
  305. void MainWindow::process()
  306. {
  307. while (_running) {
  308. QDateTime timestamp = QDateTime::currentDateTime();
  309. try {
  310. if (!_frame.cols || !_frame.rows) throw e_failure ("MainWindow: Empty frame");
  311. _mutex2.lock();
  312. _temp = _frame.clone();
  313. _mutex2.unlock();
  314. _detector->processDownScale(_temp, 2);
  315. _mutex.lock();
  316. _mask.clear();
  317. _mutex.unlock();
  318. if (_detector->facesFound()) {
  319. _mask.push_back(QPointF(_detector->rect().x,
  320. _detector->rect().y));
  321. _mask.push_back(QPointF(_detector->rect().x+_detector->rect().width,
  322. _detector->rect().y+_detector->rect().height));
  323. _mask.push_back(QPointF(_detector->landmarks()[0].x+_detector->rect().x,
  324. _detector->landmarks()[0].y+_detector->rect().y));
  325. _mask.push_back(QPointF(_detector->landmarks()[1].x+_detector->rect().x,
  326. _detector->landmarks()[1].y+_detector->rect().y));
  327. _mask.push_back(QPointF(_detector->landmarks()[4].x+_detector->rect().x,
  328. _detector->landmarks()[4].y+_detector->rect().y));
  329. _mask.push_back(QPointF(_detector->landmarks()[3].x+_detector->rect().x,
  330. _detector->landmarks()[3].y+_detector->rect().y));
  331. _mask.push_back(QPointF(_detector->landmarks()[2].x+_detector->rect().x,
  332. _detector->landmarks()[2].y+_detector->rect().y));
  333. }
  334. switch (_appState) {
  335. case AppState::Testing:
  336. if (!_detector->facesFound()) {
  337. setState(FaceState::Noface);
  338. throw e_runtime ("MainWindow: No face detected");
  339. }
  340. _aligned = _extractor->alignMtcnn(_temp, *_detector);
  341. if (!_verified) {
  342. _pattern = _extractor->extract(_aligned);
  343. _etalon->verifySample(_pattern, &_similarity);
  344. _verified = _similarity >= 100;
  345. }
  346. else if (!_moved) {
  347. cv::Rect actual = _extractor->usedFaceRect();
  348. if (_faceRect.area() != 0) {
  349. cv::Rect is = actual & _faceRect;
  350. float isf = (float)is.area() / (float)actual.area();
  351. qDebug() << "intersection" << isf;
  352. if (isf < 0.75f)
  353. _headDetector->reset();
  354. }
  355. float qual = _extractor->quality();
  356. qDebug() << "quality" << qual;
  357. if (qual >= _qualThreshold) {
  358. if (_progress != 100)
  359. setState(FaceState::Spoofing);
  360. _moved = _headDetector->addFrame(_extractor->alignedCenter(), _extractor->alignedNose());
  361. }
  362. else {
  363. if (_progress != 100)
  364. setState(FaceState::LowQuality);
  365. _moved = _headDetector->addEmptyFrame();
  366. }
  367. }
  368. if (_verified) {
  369. if (_moved) {
  370. _progress = 100;
  371. setState(AppState::Ready);
  372. setState(FaceState::Accepted);
  373. _verificationTime = _timestamp.msecsTo(QDateTime::currentDateTime());
  374. }
  375. }
  376. _faceRect = _extractor->usedFaceRect();
  377. break;
  378. case AppState::Training:
  379. if (!_detector->facesFound()) {
  380. setState(FaceState::Noface);
  381. throw e_failure ("MainWindow: No face detected");
  382. }
  383. setState(FaceState::None);
  384. _pattern = _extractor->extractMtcnnAlign(_temp, *_detector);
  385. if (_etalon->addSample(_pattern)) {
  386. _progress += 100/_trainFrames;
  387. }
  388. if (_progress >= 100) {
  389. saveEtalon();
  390. }
  391. break;
  392. default:;
  393. }
  394. } catch (e_default e) {
  395. qDebug() << e.what();
  396. _similarity = 0;
  397. } catch (...) {
  398. _similarity = 0;
  399. }
  400. _frameTime = timestamp.msecsTo(QDateTime::currentDateTime());
  401. }
  402. }
  403.  
  404.  
  405. void MainWindow::setState(AppState state)
  406. {
  407. _appState = state;
  408. switch (state) {
  409. case AppState::NotRegistered:
  410. _ui.addOnlineButton->setEnabled(_streamState == StreamState::Ok);
  411. _ui.addOnlineButton->setText(tr("Регистрировать с камеры"));
  412. _ui.addPhotoButton->setEnabled(true);
  413. _ui.removeButton->setEnabled(false);
  414. _ui.testButton->setEnabled(false);
  415. _ui.testButton->setText(tr("Верифицировать"));
  416. _ui.settingsBox->setEnabled(true);
  417. _ui.usersList->setEnabled(true);
  418. break;
  419. case AppState::Training:
  420. _ui.addOnlineButton->setEnabled(true);
  421. _ui.addOnlineButton->setText(tr("Остановить"));
  422. _ui.addPhotoButton->setEnabled(false);
  423. _ui.removeButton->setEnabled(false);
  424. _ui.testButton->setEnabled(false);
  425. _ui.testButton->setText(tr("Верифицировать"));
  426. _ui.settingsBox->setEnabled(false);
  427. _ui.usersList->setEnabled(false);
  428. break;
  429. case AppState::Ready:
  430. _ui.addOnlineButton->setEnabled(_streamState == StreamState::Ok);
  431. _ui.addOnlineButton->setText(tr("Регистрировать с камеры"));
  432. _ui.addPhotoButton->setEnabled(true);
  433. _ui.removeButton->setEnabled(true);
  434. _ui.testButton->setEnabled(_streamState == StreamState::Ok);
  435. _ui.testButton->setText(tr("Верифицировать"));
  436. _ui.settingsBox->setEnabled(true);
  437. _ui.usersList->setEnabled(true);
  438. break;
  439. case AppState::Testing:
  440. _ui.addOnlineButton->setEnabled(false);
  441. _ui.addOnlineButton->setText(tr("Регистрировать с камеры"));
  442. _ui.addPhotoButton->setEnabled(false);
  443. _ui.removeButton->setEnabled(false);
  444. _ui.testButton->setEnabled(true);
  445. _ui.testButton->setText(tr("Остановить"));
  446. _ui.settingsBox->setEnabled(false);
  447. _ui.usersList->setEnabled(false);
  448. break;
  449. }
  450. }
  451.  
  452.  
  453. void MainWindow::setState(MainWindow::FaceState status)
  454. {
  455. _faceState = status;
  456. }
  457.  
  458.  
  459. void MainWindow::setState(MainWindow::StreamState error)
  460. {
  461. _streamState = error;
  462. setState(_appState);
  463. }
  464.  
  465.  
  466. void MainWindow::on_testButton_clicked()
  467. {
  468. stopProcess();
  469. try {
  470. _ui.testButton->setEnabled(false);
  471. if (_appState == AppState::Testing) {
  472. setState(AppState::Ready);
  473. setState(FaceState::None);
  474. _verifyTimer.stop();
  475. } else {
  476. _progress = 0;
  477. _verifyTimer.start(_verifyTimeout/100);
  478. _verified = false;
  479. _moved = !QSettings().value("turnCheck").toBool();
  480. _headDetector->reset();
  481. setState(AppState::Testing);
  482. setState(FaceState::None);
  483. _timestamp = QDateTime::currentDateTime();
  484. }
  485. } catch (e_default e) {
  486. qDebug() << e.what();
  487. }
  488. startProcess();
  489. }
  490.  
  491.  
  492. void MainWindow::on_ipcamButton_clicked()
  493. {
  494. try {
  495. QString text = getInput(tr("Изменение настроек"), tr("Укажите адрес RTSP потока камеры:"), QSettings().value("rtspUrl").toString());
  496. if (!text.isEmpty()) {
  497. QSettings().setValue("rtspUrl", text);
  498. _ui.ipcamCheck->setChecked(true);
  499. on_ipcamCheck_toggled(true);
  500. }
  501. } catch (e_default e) {
  502. qDebug() << e.what();
  503. }
  504. }
  505.  
  506.  
  507. void MainWindow::on_webcamSpin_valueChanged(int arg)
  508. {
  509. try {
  510. QSettings().setValue("webcamIndex", arg);
  511. _ui.webcamCheck->setChecked(true);
  512. on_webcamCheck_toggled(true);
  513. } catch (e_default e) {
  514. qDebug() << e.what();
  515. }
  516. }
  517.  
  518.  
  519. void MainWindow::on_webcamCheck_toggled(bool checked)
  520. {
  521. try {
  522. if (checked) {
  523. QSettings().setValue("inputMode", "webcam");
  524. stopView();
  525. startView();
  526. on_usersList_currentIndexChanged(_ui.usersList->currentIndex());
  527. }
  528. } catch (e_default e) {
  529. qDebug() << e.what();
  530. }
  531. }
  532.  
  533.  
  534. void MainWindow::on_ipcamCheck_toggled(bool checked)
  535. {
  536. try {
  537. if (checked) {
  538. QSettings().setValue("inputMode", "ipcam");
  539. stopView();
  540. startView();
  541. on_usersList_currentIndexChanged(_ui.usersList->currentIndex());
  542. }
  543. } catch (e_default e) {
  544. qDebug() << e.what();
  545. }
  546. }
  547.  
  548.  
  549. void MainWindow::on_turnCheck_toggled(bool checked)
  550. {
  551. try {
  552. QSettings().setValue("turnCheck", checked);
  553. } catch (e_default e) {
  554. qDebug() << e.what();
  555. }
  556. }
  557.  
  558.  
  559. void MainWindow::on_addOnlineButton_clicked()
  560. {
  561. stopProcess();
  562. try {
  563. _ui.addOnlineButton->setEnabled(false);
  564. if (_appState == AppState::Training) {
  565. setState(AppState::NotRegistered);
  566. setState(FaceState::None);
  567. } else {
  568. _username = getInput(tr("Добавление пользователя"), tr("Введите имя пользователя:"), QUuid::createUuid().toString());
  569. if (_username.isEmpty()) return;
  570. _progress = 0;
  571. if (_etalon) _etalon->clear();
  572. setState(AppState::Training);
  573. setState(FaceState::None);
  574. }
  575.  
  576. } catch (e_default e) {
  577. qDebug() << e.what();
  578. }
  579. startProcess();
  580. }
  581.  
  582.  
  583. void MainWindow::on_addPhotoButton_clicked()
  584. {
  585. stopProcess();
  586. try {
  587. _username = getInput(tr("Добавление пользователя"), tr("Введите имя пользователя:"), QUuid::createUuid().toString());
  588. if (_username.isEmpty()) return;
  589. QString path = QFileDialog::getOpenFileName(this, tr("Выберите фотографию пользователя"));
  590. _temp = cv::imread(std::string(path.toLocal8Bit()));
  591. qDebug() << "photo:" << _temp.rows << _temp.cols;
  592. if (!_detector->process(_temp)) {
  593. setState(FaceState::Noface);
  594. return;
  595. }
  596. _pattern = _extractor->extractMtcnnAlign(_temp, *_detector);
  597. _etalon->clear();
  598. if (_etalon->addSample(_pattern)) {
  599. saveEtalon();
  600. } else {
  601. setState(AppState::NotRegistered);
  602. }
  603. } catch (e_default e) {
  604. qDebug() << e.what();
  605. }
  606. startProcess();
  607. }
  608.  
  609.  
  610. void MainWindow::on_removeButton_clicked()
  611. {
  612. stopProcess();
  613. try {
  614. QString path = QString("%0/%1.face").arg(_path).arg(_ui.usersList->currentText());
  615. QFile::remove(path);
  616. reloadUsers();
  617. } catch (e_default e) {
  618. qDebug() << e.what();
  619. }
  620. startProcess();
  621. }
  622.  
  623.  
  624. void MainWindow::on_landmarksCheck_toggled(bool checked)
  625. {
  626. try {
  627. QSettings().setValue("showMarks", checked);
  628. } catch (e_default e) {
  629. qDebug() << e.what();
  630. }
  631. }
  632.  
  633.  
  634. void MainWindow::on_usersList_currentIndexChanged(int index)
  635. {
  636. try {
  637. if (index >= 0) {
  638. _username = _ui.usersList->currentText();
  639. _etalon->clear();
  640. _etalon->load(QString("%0/%1.face").arg(_path).arg(_username));
  641. setState(AppState::Ready);
  642. setState(FaceState::None);
  643. } else {
  644. setState(AppState::NotRegistered);
  645. setState(FaceState::None);
  646. }
  647. } catch (e_default e) {
  648. qDebug() << e.what();
  649. }
  650. }
  651.  
  652.  
  653. void MainWindow::saveEtalon()
  654. {
  655. _progress = 100;
  656. setState(AppState::Ready);
  657. QDir().mkpath(_path);
  658. _etalon->save(QString("%0/%1.face").arg(_path).arg(_username));
  659. reloadUsers();
  660. _ui.usersList->setCurrentIndex(_ui.usersList->findText(_username, Qt::MatchExactly));
  661. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement