Advertisement
renix1

Face recognizer with opencv

Apr 4th, 2019
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.59 KB | None | 0 0
  1. # coding:utf-8
  2. from constants import *
  3. from os import path, getcwd, listdir
  4. import cv2
  5. import numpy as np
  6. import time
  7. import sys
  8.  
  9.  
  10. def load_cascade():
  11.     """
  12.        Carregando XML com dados para detecção de rosto(s)
  13.    """
  14.     return cv2.CascadeClassifier(path.join(getcwd(), "haarcascade_frontalface_default.xml"))
  15.  
  16. def load_image(image=None):
  17.     """
  18.        Carrega a imagem do diretório atual (se houver), caso contrário, irá buscar a imagem dentro da pasta
  19.    """
  20.     if path.exists(image):
  21.         return cv2.imread(image)
  22.     elif path.exists(path.join(IMAGES_PATH, image)):
  23.         return cv2.imread(path.join(IMAGES_PATH, image))
  24.     else:
  25.         raise FileNotFoundError("Imagem não existe")
  26.  
  27. def treatment(image=None):
  28.     """
  29.        Aqui fazemos o tratamento da imagem para uma melhor visão computacional
  30.    """
  31.     blur = cv2.GaussianBlur(image, (5,5), 0)
  32.     image = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
  33.     return image
  34.  
  35. def detect_face(image):
  36.     """
  37.        Função responsável por fazer a detecção do rost da pessoa na foto
  38.    """
  39.     face_cascade = load_cascade()
  40.     faces = face_cascade.detectMultiScale(image, 1.1, 5)
  41.     if len(faces) == 0:
  42.         return None
  43.     else:
  44.         (x, y, w, h) = faces[0]
  45.         (width, height) = ((x+w)-w), int(y*2.3)
  46.         return image[y:y+w, x:x+h], faces[0]
  47.  
  48. def prepare_training_data(data_folder_path):
  49.     """
  50.        Treinamos os rostos conhecidos com os nomes que temos e fazemos comparação com os novos
  51.    """
  52.     dirs = listdir(data_folder_path)
  53.     faces = []
  54.     labels = []
  55.     for dir_name in dirs:
  56.         if not dir_name.startswith('s'):
  57.             continue
  58.         label = int(dir_name.replace('s', ''))
  59.         subject_dir_path = path.join(data_folder_path, dir_name)
  60.         subject_images_names = listdir(subject_dir_path)
  61.         for image_name in subject_images_names:
  62.             if image_name.startswith('.'):
  63.                 continue
  64.             else:
  65.                 print("Treinando imagem %s " % (image_name))
  66.                 image_path = path.join(subject_dir_path, image_name)
  67.                 image = cv2.imread(image_path)
  68.                 face, rect = detect_face(image)
  69.                 if face is not None:
  70.                     face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
  71.                     faces.append(face)
  72.                     labels.append(label)
  73.     return faces, labels
  74.  
  75. def draw_rectangle(img, rect):
  76.     (x,y,w,h) = rect
  77.     cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)
  78.  
  79. def draw_text(img, text, x, y):
  80.     cv2.putText(img, text, (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 0, 0), 2)
  81.  
  82. def predict(fr, test_img):
  83.     img = test_img.copy()
  84.     face, rect = detect_face(img)
  85.     label = fr.predict(face)
  86.     label_text = SUBJECTS[label[0]]
  87.     draw_rectangle(img, rect)
  88.     draw_text(img, label_text, rect[0], rect[1]+40)
  89.     return img, label_text, label[1]
  90.  
  91. def wait():
  92.     sys.stdout.write('.')
  93.     sys.stdout.flush()
  94.  
  95. def main():
  96.     """
  97.        Função principal de nosso programa que fará chamadas para outras
  98.    """
  99.     print("Treinando dados...")
  100.     start = time.time()
  101.     if not path.exists("dados_treino.xml"):
  102.         print("Criando novo modelo de dados")
  103.         faces, labels = prepare_training_data("known_faces")
  104.         print("Total de rostos conhecidos {}\nTotal de etiquetas conhecidas: {}\n".format(len(faces), len(labels)))
  105.         face_recognizer = cv2.face.LBPHFaceRecognizer_create()
  106.         face_recognizer.train(faces, np.array(labels))
  107.     else:
  108.         face_recognizer = cv2.face.LBPHFaceRecognizer_create()
  109.         face_recognizer.read('dados_treino.xml')
  110.     end = time.time()
  111.     print("Levou %f segundos" % (end - start))
  112.     print("Salvando resultado do treino...")
  113.     face_recognizer.save("dados_treino.xml")
  114.     print("Comparando rostos...")
  115.     s = raw_input("Quer continuar? (S/n): ")
  116.     while s.lower() == 's':
  117.         try:
  118.             image = raw_input("Coloque a imagem aqui e compararemos com nosso banco de dados...\n")
  119.             image = treatment(load_image(image))
  120.             face, rect = detect_face(image)
  121.             face_similar, name, probability = predict(face_recognizer, face)
  122.             print("Tem {}% de chance de ser o {}".format(probability, name))
  123.             cv2.imshow("Resultado", face_similar)
  124.             cv2.waitKey(0)
  125.             cv2.destroyAllWindows()
  126.         except KeyboardInterrupt:
  127.             print("Saindo...")
  128.             exit(0)
  129.  
  130. if __name__ == "__main__":
  131.     try:
  132.         main()
  133.     except KeyboardInterrupt:
  134.         print("Saindo...")
  135.         exit(0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement