Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

find_faces_in_batches.py 2.4 KB

You have to be logged in to leave a comment. Sign In
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
  1. import face_recognition
  2. import cv2
  3. # This code finds all faces in a list of images using the CNN model.
  4. #
  5. # This demo is for the _special case_ when you need to find faces in LOTS of images very quickly and all the images
  6. # are the exact same size. This is common in video processing applications where you have lots of video frames
  7. # to process.
  8. #
  9. # If you are processing a lot of images and using a GPU with CUDA, batch processing can be ~3x faster then processing
  10. # single images at a time. But if you aren't using a GPU, then batch processing isn't going to be very helpful.
  11. #
  12. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read the video file.
  13. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
  14. # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
  15. # Open video file
  16. video_capture = cv2.VideoCapture("short_hamilton_clip.mp4")
  17. frames = []
  18. frame_count = 0
  19. while video_capture.isOpened():
  20. # Grab a single frame of video
  21. ret, frame = video_capture.read()
  22. # Bail out when the video file ends
  23. if not ret:
  24. break
  25. # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
  26. frame = frame[:, :, ::-1]
  27. # Save each frame of the video to a list
  28. frame_count += 1
  29. frames.append(frame)
  30. # Every 128 frames (the default batch size), batch process the list of frames to find faces
  31. if len(frames) == 128:
  32. batch_of_face_locations = face_recognition.batch_face_locations(frames, number_of_times_to_upsample=0)
  33. # Now let's list all the faces we found in all 128 frames
  34. for frame_number_in_batch, face_locations in enumerate(batch_of_face_locations):
  35. number_of_faces_in_frame = len(face_locations)
  36. frame_number = frame_count - 128 + frame_number_in_batch
  37. print("I found {} face(s) in frame #{}.".format(number_of_faces_in_frame, frame_number))
  38. for face_location in face_locations:
  39. # Print the location of each face in this frame
  40. top, right, bottom, left = face_location
  41. print(" - A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
  42. # Clear the frames array to start the next batch
  43. frames = []
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...