<jupyter_start><jupyter_text>Performance comparision between MTCNN Vs. HAAR Cascading Vs. CNN Vs. DLIB Vs. ResNet Vs. OpenCV DNN for face detection  **HAAR**<jupyter_code>import cv2
import time
import os

# Load the cascade
face_cascade = cv2.CascadeClassifier('/content/drive/My Drive/SIH Project/haarcascade_frontalface_default.xml')
count = 0
withoutface = 0
withface = 0
totalfaces = 0
test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    img = cv2.imread(data_path)
    # Convert to grayscale
    imgframe = img
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Detect the faces
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)
    # Draw the rectangle around each face
    for (x, y, w, h) in faces:
       cv2.rectangle(imgframe, (x, y), (x+w, y+h), (255, 0, 0), 2)
       totalfaces = totalfaces + 1

    if len(faces)>0:
        withface = withface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/HaarResult/FaceDetected/img_{}.jpg'.format(count),imgframe)
    else:
        withoutface = withoutface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/HaarResult/NoFaceDetected/img_{}.jpg'.format(count),imgframe)
    count = count + 1
else:
    end = time.time()
    print("USING HAAR:")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>USING HAAR:
Total test images with faces : 134
Sucessfully tested 134 images
Execution time in seconds 83.03262686729431
Total Faces Detected 145
Images with Faces 121
Images without Faces 13<jupyter_text>**MTCNN**<jupyter_code>!pip install mtcnn
from matplotlib.patches import Rectangle
from matplotlib.patches import Circle
from mtcnn.mtcnn import MTCNN
import cv2
import time
import os

count = 0
withoutface = 0
withface = 0
totalfaces = 0
test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    data = cv2.imread(data_path)
    detector = MTCNN()
    # detect faces in the image
    result_list = detector.detect_faces(data)
    # display faces on the original image
    # plot each face as a subplot
    imgframe = data
    for i in range(len(result_list)):
        # get coordinates
        x1, y1, width, height = result_list[i]['box']
        x2, y2 = x1 + width, y1 + height
        cv2.rectangle(imgframe, (x1, y1), (x2, y2), (255, 0, 0), 2)
        totalfaces = totalfaces + 1

    if len(result_list)>0:
        withface = withface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/MTCNNResult/FaceDetected/img_{}.jpg'.format(count),imgframe)
    else:
        withoutface = withoutface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/MTCNNResult/NoFaceDetected/img_{}.jpg'.format(count),imgframe)
    count = count + 1
else:
    end = time.time()
    print("USING MTCNN:")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>Using TensorFlow backend.<jupyter_text>**DLIB** CNN_FACE_DETECTION MODEL_V1<jupyter_code>import dlib
import os
import time
import cv2

weights = '/content/drive/My Drive/SIH Project/mmod_human_face_detector.dat'
cnn_face_detector = dlib.cnn_face_detection_model_v1(weights)
count = 0
withoutface = 0
withface = 0
totalfaces = 0
test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    img = cv2.imread(data_path)
    # apply face detection (cnn)
    faces_cnn = cnn_face_detector(img, 1)
    imgframe = img
    # loop over detected faces
    for face in faces_cnn:
        x = face.rect.left()
        y = face.rect.top()
        w = face.rect.right() - x
        h = face.rect.bottom() - y
        # draw box over face
        cv2.rectangle(imgframe, (x,y), (x+w,y+h), (0,0,255), 2)
        totalfaces = totalfaces + 1
    if len(faces)>0:
        withface = withface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/DlibResult/CNN/FaceDetected/img_{}.jpg'.format(count),imgframe)
    else:
        withoutface = withoutface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/DlibResult/CNN/NoFaceDetected/img_{}.jpg'.format(count),imgframe)
    count = count + 1
else:
    end = time.time()
    print("USING DLIB CNN:")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>USING DLIB CNN:
Total test images with faces : 134
Sucessfully tested 134 images
Execution time in seconds 15.498892068862915
Total Faces Detected 138
Images with Faces 134
Images without Faces 0<jupyter_text>**DLIB** FRONTAL_FACE_DETECTOR<jupyter_code>import dlib
import os
import time
import cv2

face_detector = dlib.get_frontal_face_detector()
count = 0
withoutface = 0
withface = 0
totalfaces = 0
test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    img = cv2.imread(data_path)
    faces = face_detector(img, 1)
    imgframe = img
    for face in faces:
        x = face.left()
        y = face.top()
        w = face.right() - x
        h = face.bottom() - y
        # draw box over face
        cv2.rectangle(imgframe, (x,y), (x+w,y+h), (0,0,255), 2)
        totalfaces = totalfaces + 1
    if len(faces)>0:
        withface = withface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/DlibResult/FRONTAL_FACE_DETECTOR/FaceDetected/img_{}.jpg'.format(count),imgframe)
    else:
        withoutface = withoutface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/DlibResult/FRONTAL_FACE_DETECTOR/NoFaceDetected/img_{}.jpg'.format(count),imgframe)
    count = count + 1
else:
    end = time.time()
    print("USING DLIB FRONTAL_FACE_DETECTOR")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>USING DLIB FRONTAL_FACE_DETECTOR
Total test images with faces : 134
Sucessfully tested 134 images
Execution time in seconds 15.120457887649536
Total Faces Detected 132
Images with Faces 126
Images without Faces 8<jupyter_text>**DNN** (ResNet)<jupyter_code>import numpy as np
import cv2 as cv
import os
from google.colab.patches import cv2_imshow
import time

file_path = '/content/drive/My Drive/ML project/'
threshold = 0.5  # human face's confidence threshold

# Load the pre-trained ResNetSSD caffe model
prototxt_file = file_path + 'Resnet_SSD_deploy.prototxt'
caffemodel_file = file_path + 'Res10_300x300_SSD_iter_140000.caffemodel'
net = cv.dnn.readNetFromCaffe(prototxt_file, caffeModel=caffemodel_file)
# print('MobileNetSSD caffe model loaded successfully')

# Read picture
# image = cv.imread('/content/drive/My Drive/SIH Project/FaceTestData/people-10.jpg')
# Fill text background of painted text
#       cv.rectangle(image, (x_start, y_start - 18), (x_end, y_start), (0, 0, 255), -1)
#        cv.putText(image, label, (x_start+2, y_start-5), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)

count = 0
withoutface = 0
withface = 0
totalfaces = 0
test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    image = cv.imread(data_path)
    imgframe = image
    origin_h, origin_w = image.shape[:2]
    blob = cv.dnn.blobFromImage(cv.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
    net.setInput(blob)
    faces = net.forward()
    # Traverse each face
    for i in range(faces.shape[2]):
        confidence = faces[0, 0, i, 2]
        if confidence > threshold:
            # Take out the position value of the bounding box and restore it to the original image
            bounding_box = faces[0, 0, i, 3:7] * np.array([origin_w, origin_h, origin_w, origin_h])
            x_start, y_start, x_end, y_end = bounding_box.astype('int')
            # label = '{0:.2f}%'.format(confidence * 100)
            cv.rectangle(image, (x_start, y_start), (x_end, y_end), (0, 0, 255), 1)
            totalfaces = totalfaces + 1
    if len(detections)>0:
        withface = withface + 1
        cv.imwrite('/content/drive/My Drive/SIH Project/ResNetResult/FaceDetected/img_{}.jpg'.format(count),imgframe)
    else:
        withoutface = withoutface + 1
        cv.imwrite('/content/drive/My Drive/SIH Project/ResNetResult/NoFaceDetected/img_{}.jpg'.format(count),imgframe)
    count = count + 1
else:
    end = time.time()
    print("USING RESNET FACE_DETECTOR")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>USING RESNET FACE_DETECTOR
Total test images with faces : 134
Sucessfully tested 134 images
Execution time in seconds 12.185476303100586
Total Faces Detected 191
Images with Faces 134
Images without Faces 0<jupyter_text>**LBP Cascading**<jupyter_code>import numpy as np
import time
import matplotlib.pyplot as plt
import os
import cv2

#load cascade classifier training file for lbpcascade
lbp_face_cascade = cv2.CascadeClassifier('/content/drive/My Drive/ML project/lbpcascade_frontalface.xml')
count = 0
withoutface = 0
withface = 0
totalfaces = 0

def convertToRGB(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

test_filenames = filter(lambda x: x.endswith('.jpg'), os.listdir('/content/drive/My Drive/SIH Project/FaceTestData/'))
# Get full paths to test images
paths_to_test_images = ['/content/drive/My Drive/SIH Project/FaceTestData/' + x for x in test_filenames]
start = time.time()
for data_path in paths_to_test_images:
    image = cv2.imread(data_path)
    imgframe = image
    # detect_faces(lbp_face_cascade, image)
    img_copy = np.copy(image)
    #convert the test image to gray image as opencv face detector expects gray images
    gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
    #let's detect multiscale (some images may be closer to camera than others) images
    faces = lbp_face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5);
    # img = img_copy
    #go over list of faces and draw them as rectangles on original colored img
    for (x, y, w, h) in faces:
        cv2.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 10)
        totalfaces = totalfaces + 1
    if len(faces)>0:
        withface = withface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/ResNetResult/FaceDetected/img_{}.jpg'.format(count),img_copy)
    else:
        withoutface = withoutface + 1
        cv2.imwrite('/content/drive/My Drive/SIH Project/ResNetResult/NoFaceDetected/img_{}.jpg'.format(count),img_copy)
    count = count + 1
else:
    end = time.time()
    print("USING LBP FACE_DETECTOR")
    print("Total test images with faces : {}".format(len(paths_to_test_images)))
    print("Sucessfully tested {} images".format(count))
    print("Execution time in seconds {}".format(end-start))
    print("Total Faces Detected {}".format(totalfaces))
    print("Images with Faces {}".format(withface))
    print("Images without Faces {}".format(withoutface))<jupyter_output>USING LBP FACE_DETECTOR
Total test images with faces : 134
Sucessfully tested 134 images
Execution time in seconds 159.4853332042694
Total Faces Detected 111
Images with Faces 106
Images without Faces 28
{'fraction_non_alphanumeric': 0.11835066864784546, 'fraction_numerical': 0.028157503714710253, 'mean_word_length': 3.965326447805238, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '111068', 'license': 'MIT', 'n_tokens_mistral': 4825, 'n_tokens_neox': 4510, 'n_words': 1172, 'path': 'MTCNN_vs_HAAR_vs_DLIB_vs_CNN_vs_ResNet_vs_LBP.ipynb', 'repo_name': 'KevinPatel04/FaceDetection', 'size': '13460'}