Created
September 8, 2019 12:36
-
-
Save Proteusiq/6a8f49a6a4962e00ad778565b8b6a2bb to your computer and use it in GitHub Desktop.
face detection with CNN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################### | |
# conda create -n opencnn python=3.7 tensorflow # | |
# conda activate opencnn # | |
# pip install opencv-python mtcnn # | |
################################################### | |
import logging | |
import os | |
import cv2 | |
from mtcnn.mtcnn import MTCNN | |
# Disable warnings | |
logging.disable(logging.WARNING) | |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' | |
# os.environ['OMP_NUM_THREADS'] = '4' | |
# os.environ['KMP_AFFINITY'] = 'none' | |
def draw_roi(image,results): | |
# image to which we draw the roi | |
# results is an array with all the bounding boxes detected. | |
for result in results: | |
bounding_box = result['box'] | |
keypoints = result['keypoints'] | |
cv2.rectangle(image, | |
(bounding_box[0], bounding_box[1]), | |
(bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]), | |
(0,155,255), | |
2) | |
cv2.circle(image,(keypoints['left_eye']), 2, (0,155,255), 2) | |
cv2.circle(image,(keypoints['right_eye']), 2, (0,155,255), 2) | |
cv2.circle(image,(keypoints['nose']), 2, (0,155,255), 2) | |
cv2.circle(image,(keypoints['mouth_left']), 2, (0,155,255), 2) | |
cv2.circle(image,(keypoints['mouth_right']), 2, (0,155,255), 2) | |
class Face: | |
def __init__(self, model:MTCNN, | |
camera_index:int=0): | |
self.capture = cv2.VideoCapture(camera_index) | |
self.detector = model() | |
def __enter__(self): | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.capture.release() | |
cv2.destroyAllWindows() | |
def detect(self): | |
'''Find Face, Eyes, Nose and Mouth | |
''' | |
while True: | |
has_frame, frame = self.capture.read() | |
assert has_frame, 'No frame' | |
frame_RGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
results = self.detector.detect_faces(frame_RGB) | |
draw_roi(frame, results) | |
cv2.imshow('Video', frame) | |
# Break while loop | |
if cv2.waitKey(20) & 0xFF == ord('q'): | |
break | |
# Release capture | |
self.capture.release() | |
cv2.destroyAllWindows() | |
if __name__ == '__main__': | |
# Run face detection capturing Eyes, Nose and Mouth | |
detect = Face(model=MTCNN) | |
detect.detect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment