Path: blob/master/face_detection/faces_detection.py
454 views
from mtcnn.mtcnn import MTCNN1import cv22import dlib3import numpy as np4import os56detector1 = MTCNN()7detector2 = dlib.get_frontal_face_detector()8modelFile = "models/res10_300x300_ssd_iter_140000.caffemodel"9configFile = "models/deploy.prototxt.txt"10net = cv2.dnn.readNetFromCaffe(configFile, modelFile)1112classifier2 = cv2.CascadeClassifier('models/haarcascade_frontalface2.xml')13images = os.listdir('faces')14# os.makedirs('faces/dlib')15# os.makedirs('faces/mtcnn')16# os.makedirs('faces/dnn')17# os.makedirs('faces/haar')1819for image in images:20img = cv2.imread(os.path.join('faces', image))21# img = cv2.resize(img, None, fx=2, fy=2)22height, width = img.shape[:2]23img1 = img.copy()24img2 = img.copy()25img3 = img.copy()26gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)27img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)28# detect faces in the image29faces1 = detector1.detect_faces(img_rgb)3031faces2 = detector2(gray, 2)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#MTCNN39for 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)43#DLIB44for result in faces2:45x = result.left()46y = result.top()47x1 = result.right()48y1 = result.bottom()49cv2.rectangle(img1, (x, y), (x1, y1), (0, 0, 255), 2)5051#OPENCV DNN52for i in range(faces3.shape[2]):53confidence = faces3[0, 0, i, 2]54if confidence > 0.5:55box = faces3[0, 0, i, 3:7] * np.array([width, height, width, height])56(x, y, x1, y1) = box.astype("int")57cv2.rectangle(img2, (x, y), (x1, y1), (0, 0, 255), 2)58#HAAR59for result in faces4:60x, y, w, h = result61x1, y1 = x + w, y + h62cv2.rectangle(img3, (x, y), (x1, y1), (0, 0, 255), 2)6364# cv2.imwrite(os.path.join('faces', 'mtcnn', image), img)65# cv2.imwrite(os.path.join('faces', 'dlib', image), img1)66# cv2.imwrite(os.path.join('faces', 'dnn', image), img2)67# cv2.imwrite(os.path.join('faces', 'haar', image), img3)68cv2.imshow("mtcnn", img)69cv2.imshow("dlib", img1)70cv2.imshow("dnn", img2)71cv2.imshow("haar", img3)72cv2.waitKey(0)73cv2.destroyAllWindows()747576