Path: blob/master/face_detection/video_face.py
454 views
# -*- coding: utf-8 -*-1"""2Created on Thu Jul 2 03:40:59 202034@author: hp5"""6import cv27import dlib8from mtcnn.mtcnn import MTCNN9import numpy as np1011detector1 = MTCNN()12detector2 = dlib.get_frontal_face_detector()13modelFile = "models/res10_300x300_ssd_iter_140000.caffemodel"14configFile = "models/deploy.prototxt.txt"15net = cv2.dnn.readNetFromCaffe(configFile, modelFile)16classifier2 = cv2.CascadeClassifier('models/haarcascade_frontalface2.xml')1718cap = cv2.VideoCapture('video/occlusion.mp4')19font = cv2.FONT_HERSHEY_SIMPLEX20while(True):21ret, img = cap.read()22if ret == True:23img = cv2.resize(img, None, fx=0.5, fy=0.5)24height, width = img.shape[:2]25img1 = img.copy()26img2 = img.copy()27img3 = img.copy()28# detect faces in the image29faces1 = detector1.detect_faces(img)30gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)31faces2 = detector2(gray, 1)32blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)),331.0, (300, 300), (104.0, 117.0, 123.0))34net.setInput(blob)35faces3 = net.forward()36faces4 = classifier2.detectMultiScale(img)3738# display faces on the original image39for result in faces1:40x, y, w, h = result['box']41x1, y1 = x + w, y + h42cv2.rectangle(img, (x, y), (x1, y1), (0, 0, 255), 2)43cv2.putText(img, 'mtcnn', (30, 30), font, 1, (255, 255, 0), 2, cv2.LINE_AA)4445for result in faces2:46x = result.left()47y = result.top()48x1 = result.right()49y1 = result.bottom()50cv2.rectangle(img1, (x, y), (x1, y1), (0, 0, 255), 2)51cv2.putText(img1, 'dlib', (30, 30), font, 1, (255, 255, 0), 2, cv2.LINE_AA)5253for i in range(faces3.shape[2]):54confidence = faces3[0, 0, i, 2]55if confidence > 0.5:56box = faces3[0, 0, i, 3:7] * np.array([width, height, width, height])57(x, y, x1, y1) = box.astype("int")58cv2.rectangle(img2, (x, y), (x1, y1), (0, 0, 255), 2)59cv2.putText(img2, 'dnn', (30, 30), font, 1, (255, 255, 0), 2, cv2.LINE_AA)6061for result in faces4:62x, y, w, h = result63x1, y1 = x + w, y + h64cv2.rectangle(img3, (x, y), (x1, y1), (0, 0, 255), 2)65cv2.putText(img3, 'haar', (30, 30), font, 1, (255, 255, 0), 2, cv2.LINE_AA)6667h1 = cv2.hconcat([img3, img1])68h2 = cv2.hconcat([img, img2])69fin = cv2.vconcat([h1, h2])7071cv2.imshow("mtcnn", img)72cv2.imshow("dlib", img1)73cv2.imshow("dnn", img2)74cv2.imshow("haar", img3)75if cv2.waitKey(1) & 0xFF == ord('q'):76break77else:78break79808182cap.release()83cv2.destroyAllWindows()848586