Advertisement
KrimsN

Untitled

Jun 11th, 2020
1,664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.36 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import os
  4. import time
  5. from PIL import ImageGrab
  6.  
  7. recognizer = cv2.face.LBPHFaceRecognizer_create()
  8. recognizer.read('trainer/trainer.yml')
  9. cascadePath = "haarcascade_frontalface_default.xml"
  10. faceCascade = cv2.CascadeClassifier(cascadePath);
  11.  
  12. font = cv2.FONT_HERSHEY_SIMPLEX #Шрифт
  13.  
  14. #инициировать счетчик идентификаторов
  15. id = 0
  16.  
  17. # имена, связанные с идентификаторами: пример ==> Александр: id=1 и т. д
  18. names = ['None', 'Alexandr', 'Sergey']
  19.  
  20. human_found = False
  21.  
  22. while True:
  23.     img = ImageGrab.grab()
  24.     img_np = np.array(img)
  25.     frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  26.    
  27.     faces = faceCascade.detectMultiScale(
  28.         frame,
  29.         scaleFactor = 1.2,
  30.         minNeighbors = 5,
  31.         minSize = (30, 30),
  32.        )
  33.        persons = dict()
  34.  
  35.         for x, y, w, h in faces:
  36.             cv2.rectangle(img_np, (x, y), (x+w, y+h), (0, 255, 0), 2)
  37.             id, confidence = recognizer.predict(frame[y:y+h,x:x+w]) #Функция recognizer.predict () Принимает в качестве параметра захваченную часть лица, подлежащую анализу, и
  38.             #возвращает своего вероятного владельца, указывая его идентификатор и степень уверенности распознавателя в связи с этим совпадением.
  39.             if id not in persons:
  40.                 persons[id] = 1
  41.             else:
  42.                 persons[id] += 1
  43.            
  44.            
  45.  
  46.  
  47.  
  48.        
  49.             if id and  human_found == False:
  50.                 before_image_time = time.time()
  51.                 print ("before_image_time", before_image_time)
  52.                 human_found = True
  53.             elif id and human_found == True:
  54.                 after_image_time = time.time()
  55.                 round (after_image_time)
  56.                 print ("after_image_time" , after_image_time)
  57.  
  58.             if confidence < 100:
  59.                 id = names[id]
  60.                 confidence = "  {0}%".format(round(100 - confidence))
  61.             else:
  62.                 id = "unknown"
  63.                 confidence = "  {0}%".format(round(100 - confidence))
  64.            
  65.             cv2.putText(img_np, str(id), (x+5,y-5), font, 1, (255,255,255), 2) #Вывод имени идентификатора
  66.             cv2.putText(img_np, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  #Вывод достоверности
  67.  
  68.         if len(faces) == 0 and human_found == True:
  69.             total_time = after_image_time - before_image_time
  70.             if not id:
  71.                 print(f'{names[id]}: {persons[id]} frames')
  72.             print ("total_time names[id]", total_time, names[id])
  73.             human_found = False
  74.    
  75.     cv2.imshow('Screen', img_np) #imshow отображает изображение в указанном окне.Если окно не было создано,то создается новое.«camera» — имя окна, img—массив картинки.
  76.  
  77.     k = cv2.waitKey(10) & 0xff # Нажмите 'ESC' для выхода из видео
  78.     if k == 27:
  79.         break
  80.  
  81. print("\n [INFO] Выход из программы и очистка материала")
  82. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement