Guest User

Untitled

a guest
May 23rd, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3. import os
  4.  
  5. def face_detection(img):
  6. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  7. face_cascade_Haar=cv2.CascadeClassifier('C:\Users\nic 005\Downloads\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
  8. faces = face_cascade_Haar.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5)
  9. if(len(faces)==0):
  10. return None, None
  11. (x,y,w,h)=faces[0]
  12. return gray[y:y+w, x:x+h], faces[0]
  13.  
  14. def prep_training_data(path):
  15. dirs=os.listdir(path)
  16. faces=[]
  17. labels=[]
  18. k=0
  19. for dir_names in dirs:
  20. label=k+1
  21. subject_dir_path= path + "/" + dir_names
  22. subject_images_names= os.listdir(subject_dir_path)
  23. for image_name in subject_images_names:
  24. if image_name.startswith("."):
  25. continue
  26. image=cv2.imread(subject_dir_path+ "/" + image_name)
  27. face, rect = face_detection(image)
  28. faces.append(face)
  29. labels.append(label)
  30. k=k+1
  31. return faces,labels
  32.  
  33. def draw_rectangle(img, rect):
  34. (x, y, w, h) = rect
  35. cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
  36.  
  37. def draw_text(img, text, x, y):
  38. cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
  39.  
  40. def predict(test_img):
  41. img=test_img.copy()
  42. face, rect=face_detection(img)
  43. label=face_recognizer.predict(face)
  44. label_name=subjects[labels[0]]
  45. draw_rectangle(test_img,rect)
  46. draw_text(test_img, label_name, rect[0], rect[1]-5)
  47. return test_img
  48.  
  49. faces, labels = prep_training_data('C:\Users\nic 005\Desktop\face_recognition\db\training')
  50. face_recognizer= cv2.face.LBPHFaceRecognizer_create()
  51. face_recognizer.train(faces, np.array(labels))
  52. test_img=cv2.imread('C:\Users\nic 005\Desktop\face_recognition\testing\anonym.20.jpg')
  53. predicted_img=predict(test_img)
  54. cv2.imshow("img",predicted_img)
  55. cv2.waitKey(0)
  56. cv2.destroyAllWindows()
Add Comment
Please, Sign In to add comment