-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecognize_from_video_file.py
More file actions
68 lines (52 loc) · 2.43 KB
/
recognize_from_video_file.py
File metadata and controls
68 lines (52 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import cv2
import face_recognition
import recognize_face
from pathlib import Path
# This is a demo of running face recognition on a video file and saving the results to a new video file.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
# Open the input movie file
input_movie = cv2.VideoCapture("data/videos/everyone.mov")
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
# Create an output movie file (make sure resolution/frame rate matches input video!)
fourcc = cv2.VideoWriter_fourcc(*'MP42')
output_movie = cv2.VideoWriter('everyone.mp4', fourcc, 29.97, (1920, 1080))
known_path = Path("data/sample-2/jpeg/picked/known")
known_images = list(known_path.glob('*.jpeg'))
# Load some sample pictures and learn how to recognize them.
known_faces = [recognize_face.image_to_known_face(str(image_path), image_path.stem) for image_path in known_images]
# Initialize some variables
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
detected_faces = recognize_face.recognize(known_faces, rgb_frame)
known_color = (0, 255, 0)
unknown_color = (0, 0, 255)
# Label the results
for name, (top, right, bottom, left), distance in detected_faces:
if name == 'Unknown':
color = unknown_color
else:
color = known_color
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), color, 2)
# Draw a label with a name below the face
label = name + ' - ' + str("{0:.2f}".format(distance))
cv2.rectangle(frame, (left, bottom - 25), (right, bottom), color, cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, label, (left + 6, bottom - 6), font, 2, (255, 0, 0), 1)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()