Guest User

Opencv

a guest
Sep 3rd, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.69 KB | None | 0 0
  1. import face_recognition
  2. import cv2
  3. import numpy as np
  4.  
  5. video_capture = cv2.VideoCapture(0)
  6.  
  7. frame_width = int(video_capture.get(3))
  8. frame_height = int(video_capture.get(4))
  9.  
  10. video_cod = cv2.VideoWriter_fourcc(*'XVID')
  11. video_output= cv2.VideoWriter('captured_video.avi',
  12. video_cod,
  13. 10,
  14. (frame_width,frame_height))
  15.  
  16. obama_image = face_recognition.load_image_file("obama.jpg")
  17. obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
  18.  
  19. biden_image = face_recognition.load_image_file("biden.jpg")
  20. biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
  21.  
  22. known_face_encodings = [
  23. obama_face_encoding,
  24. biden_face_encoding
  25. ]
  26. known_face_names = [
  27. "Barack Obama",
  28. "Joe Biden"
  29. ]
  30.  
  31. face_locations = []
  32. face_encodings = []
  33. face_names = []
  34. process_this_frame = True
  35.  
  36. while True:
  37. ret, frame = video_capture.read()
  38.  
  39. if ret == True:
  40. small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
  41.  
  42. rgb_small_frame = small_frame[:, :, ::-1]
  43.  
  44. face_locations = face_recognition.face_locations(rgb_small_frame)
  45. face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
  46.  
  47. face_names = []
  48. for face_encoding in face_encodings:
  49. matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
  50. name = "Unknown"
  51.  
  52. face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
  53. best_match_index = np.argmin(face_distances)
  54. if matches[best_match_index]:
  55. name = known_face_names[best_match_index]
  56.  
  57. face_names.append(name)
  58.  
  59. process_this_frame = not process_this_frame
  60.  
  61. for (top, right, bottom, left), name in zip(face_locations, face_names):
  62. top *= 4
  63. right *= 4
  64. bottom *= 4
  65. left *= 4
  66.  
  67. video_output.write(frame)
  68. cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
  69. cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
  70. font = cv2.FONT_HERSHEY_DUPLEX
  71. cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
  72. cv2.imshow('Video', frame)
  73.  
  74. if cv2.waitKey(1) & 0xFF == ord('x'):
  75. break
  76.  
  77. video_capture.release()
  78. cv2.destroyAllWindows()
  79.  
Advertisement
Add Comment
Please, Sign In to add comment