Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. # import the necessary packages
  2. from threading import Thread, Lock
  3.  
  4. from mtcnn.mtcnn import MTCNN
  5. import cv2
  6. import threading
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13. class AsynchronousFaceDetector:
  14. def __init__(self, name="AsynchronousFaceDetector"):
  15.  
  16. print("Detector init ...", flush=True)
  17.  
  18.  
  19. # initialize the thread name
  20. self.name = name
  21.  
  22. # initialize the variable used to indicate if the thread should be stopped
  23. self.stopped = False
  24. self.detector = MTCNN()
  25. self.faces_json = None
  26. self.last_frame = None
  27.  
  28. self.lock = Lock()
  29.  
  30. self.total_frames = 0
  31. self.frames_with_face = 0
  32.  
  33. self.wait_for_event = threading.Event()
  34.  
  35. def start(self):
  36.  
  37. self.t = Thread(target=self.detect_faces, name=self.name, args=())
  38. self.t.daemon = True
  39. self.t.start()
  40. return self
  41.  
  42. def detect_faces(self):
  43. # keep looping infinitely until the thread is stopped
  44. self.wait_for_event.wait()
  45. #while True:
  46. # print("Detector on while loop ...", flush=True)
  47. # if the thread indicator variable is set, stop the thread
  48. if self.stopped:
  49. print("Detector stopped")
  50. return
  51.  
  52. if self.last_frame is not None:
  53. self.total_frames += 1
  54. self.lock.acquire()
  55. self.last_frame = cv2.cvtColor(self.last_frame, cv2.COLOR_BGR2RGB)
  56. self.faces_json = self.detector.detect_faces(self.last_frame)
  57. self.lock.release()
  58. if len(self.faces_json) > 0:
  59. self.frames_with_face += 1
  60.  
  61. def get_cur_face_box(self):
  62. return self.faces_json
  63.  
  64. def get_frame_counters(self):
  65. return self.frames_with_face, self.total_frames
  66.  
  67. def update_frame_queue(self, frame):
  68. self.lock.acquire()
  69. self.last_frame = frame[:]
  70. self.wait_for_event.set()
  71. self.lock.release()
  72.  
  73. def stop(self):
  74. self.stopped = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement