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

facerec_from_webcam_multiprocessing.py 7.5 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
  1. import face_recognition
  2. import cv2
  3. from multiprocessing import Process, Manager, cpu_count, set_start_method
  4. import time
  5. import numpy
  6. import threading
  7. import platform
  8. # This is a little bit complicated (but fast) example of running face recognition on live video from your webcam.
  9. # This example is using multiprocess.
  10. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
  11. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
  12. # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
  13. # Get next worker's id
  14. def next_id(current_id, worker_num):
  15. if current_id == worker_num:
  16. return 1
  17. else:
  18. return current_id + 1
  19. # Get previous worker's id
  20. def prev_id(current_id, worker_num):
  21. if current_id == 1:
  22. return worker_num
  23. else:
  24. return current_id - 1
  25. # A subprocess use to capture frames.
  26. def capture(read_frame_list, Global, worker_num):
  27. # Get a reference to webcam #0 (the default one)
  28. video_capture = cv2.VideoCapture(0)
  29. # video_capture.set(3, 640) # Width of the frames in the video stream.
  30. # video_capture.set(4, 480) # Height of the frames in the video stream.
  31. # video_capture.set(5, 30) # Frame rate.
  32. print("Width: %d, Height: %d, FPS: %d" % (video_capture.get(3), video_capture.get(4), video_capture.get(5)))
  33. while not Global.is_exit:
  34. # If it's time to read a frame
  35. if Global.buff_num != next_id(Global.read_num, worker_num):
  36. # Grab a single frame of video
  37. ret, frame = video_capture.read()
  38. read_frame_list[Global.buff_num] = frame
  39. Global.buff_num = next_id(Global.buff_num, worker_num)
  40. else:
  41. time.sleep(0.01)
  42. # Release webcam
  43. video_capture.release()
  44. # Many subprocess use to process frames.
  45. def process(worker_id, read_frame_list, write_frame_list, Global, worker_num):
  46. known_face_encodings = Global.known_face_encodings
  47. known_face_names = Global.known_face_names
  48. while not Global.is_exit:
  49. # Wait to read
  50. while Global.read_num != worker_id or Global.read_num != prev_id(Global.buff_num, worker_num):
  51. # If the user has requested to end the app, then stop waiting for webcam frames
  52. if Global.is_exit:
  53. break
  54. time.sleep(0.01)
  55. # Delay to make the video look smoother
  56. time.sleep(Global.frame_delay)
  57. # Read a single frame from frame list
  58. frame_process = read_frame_list[worker_id]
  59. # Expect next worker to read frame
  60. Global.read_num = next_id(Global.read_num, worker_num)
  61. # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
  62. rgb_frame = frame_process[:, :, ::-1]
  63. # Find all the faces and face encodings in the frame of video, cost most time
  64. face_locations = face_recognition.face_locations(rgb_frame)
  65. face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
  66. # Loop through each face in this frame of video
  67. for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
  68. # See if the face is a match for the known face(s)
  69. matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
  70. name = "Unknown"
  71. # If a match was found in known_face_encodings, just use the first one.
  72. if True in matches:
  73. first_match_index = matches.index(True)
  74. name = known_face_names[first_match_index]
  75. # Draw a box around the face
  76. cv2.rectangle(frame_process, (left, top), (right, bottom), (0, 0, 255), 2)
  77. # Draw a label with a name below the face
  78. cv2.rectangle(frame_process, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
  79. font = cv2.FONT_HERSHEY_DUPLEX
  80. cv2.putText(frame_process, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
  81. # Wait to write
  82. while Global.write_num != worker_id:
  83. time.sleep(0.01)
  84. # Send frame to global
  85. write_frame_list[worker_id] = frame_process
  86. # Expect next worker to write frame
  87. Global.write_num = next_id(Global.write_num, worker_num)
  88. if __name__ == '__main__':
  89. # Fix Bug on MacOS
  90. if platform.system() == 'Darwin':
  91. set_start_method('forkserver')
  92. # Global variables
  93. Global = Manager().Namespace()
  94. Global.buff_num = 1
  95. Global.read_num = 1
  96. Global.write_num = 1
  97. Global.frame_delay = 0
  98. Global.is_exit = False
  99. read_frame_list = Manager().dict()
  100. write_frame_list = Manager().dict()
  101. # Number of workers (subprocess use to process frames)
  102. if cpu_count() > 2:
  103. worker_num = cpu_count() - 1 # 1 for capturing frames
  104. else:
  105. worker_num = 2
  106. # Subprocess list
  107. p = []
  108. # Create a thread to capture frames (if uses subprocess, it will crash on Mac)
  109. p.append(threading.Thread(target=capture, args=(read_frame_list, Global, worker_num,)))
  110. p[0].start()
  111. # Load a sample picture and learn how to recognize it.
  112. obama_image = face_recognition.load_image_file("obama.jpg")
  113. obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
  114. # Load a second sample picture and learn how to recognize it.
  115. biden_image = face_recognition.load_image_file("biden.jpg")
  116. biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
  117. # Create arrays of known face encodings and their names
  118. Global.known_face_encodings = [
  119. obama_face_encoding,
  120. biden_face_encoding
  121. ]
  122. Global.known_face_names = [
  123. "Barack Obama",
  124. "Joe Biden"
  125. ]
  126. # Create workers
  127. for worker_id in range(1, worker_num + 1):
  128. p.append(Process(target=process, args=(worker_id, read_frame_list, write_frame_list, Global, worker_num,)))
  129. p[worker_id].start()
  130. # Start to show video
  131. last_num = 1
  132. fps_list = []
  133. tmp_time = time.time()
  134. while not Global.is_exit:
  135. while Global.write_num != last_num:
  136. last_num = int(Global.write_num)
  137. # Calculate fps
  138. delay = time.time() - tmp_time
  139. tmp_time = time.time()
  140. fps_list.append(delay)
  141. if len(fps_list) > 5 * worker_num:
  142. fps_list.pop(0)
  143. fps = len(fps_list) / numpy.sum(fps_list)
  144. print("fps: %.2f" % fps)
  145. # Calculate frame delay, in order to make the video look smoother.
  146. # When fps is higher, should use a smaller ratio, or fps will be limited in a lower value.
  147. # Larger ratio can make the video look smoother, but fps will hard to become higher.
  148. # Smaller ratio can make fps higher, but the video looks not too smoother.
  149. # The ratios below are tested many times.
  150. if fps < 6:
  151. Global.frame_delay = (1 / fps) * 0.75
  152. elif fps < 20:
  153. Global.frame_delay = (1 / fps) * 0.5
  154. elif fps < 30:
  155. Global.frame_delay = (1 / fps) * 0.25
  156. else:
  157. Global.frame_delay = 0
  158. # Display the resulting image
  159. cv2.imshow('Video', write_frame_list[prev_id(Global.write_num, worker_num)])
  160. # Hit 'q' on the keyboard to quit!
  161. if cv2.waitKey(1) & 0xFF == ord('q'):
  162. Global.is_exit = True
  163. break
  164. time.sleep(0.01)
  165. # Quit
  166. cv2.destroyAllWindows()
Tip!

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

Comments

Loading...