Models to extract faces

Storyboard

>Model

ID:(1782, 0)



Face detection model

Image

>Top


One of the models for detecting faces is Pretrained Pytorch Face Detection (MTCNN)



import cv2
from mtcnn.mtcnn import MTCNN

detector = MTCNN()
faces = detector.detect_faces(pixels)

ID:(13767, 0)



MTCNN model response

Description

>Top


The format of the model Pretrained Pytorch Face Detection (MTCNN) is

- box: array(4)
- confidence: escalar
- keypoints: {'left_eye': array(2), 'right_eye': array(2), 'nose': array(2), 'mouth_left': array(2), 'mouth_right': array(2) }

{'box': [1942, 716, 334, 415], 'confidence': 0.9999997615814209, 'keypoints': {'left_eye': (2053, 901), 'right_eye': (2205, 897), 'nose': (2139, 976), 'mouth_left': (2058, 1029), 'mouth_right': (2206, 1023)}}

ID:(13792, 0)



MTCNN model response

Image

>Top


To draw a rectangle around a face, the image can be loaded and modified depending on including the rectangle:



# draw an image with detected objects
def draw_facebox(filename, result_list):

    # load the image
    data = plt.imread(filename)

    # plot the image
    plt.imshow(data)

    # get the context for drawing boxes
    ax = plt.gca()

    # plot each box
    for result in result_list:

        # get coordinates
        x, y, width, height = result['box']

        # create the shape
        rect = plt.Rectangle((x, y), width, height,fill=False, color='orange')

        # draw the box
        ax.add_patch(rect)\

ID:(13793, 0)



Store mini images of faces

Description

>Top


import cv2

import os
import glob

from PIL import Image
from numpy import asarray
from matplotlib import pyplot
from mtcnn.mtcnn import MTCNN

dir = 'F:/go/collection/madera/*/'
wdir = 'F:/go/face_scrapper/faces/work/'
ndir = 'F:/go/face_scrapper/faces/n_work/'

required_size=(160, 160)

for file in glob.glob(dir+'*.jpg'):

    cnt = 1

    image = cv2.imread(file)
    pixels = asarray(image)

    detector = MTCNN()
    faces = detector.detect_faces(pixels) 
    
    root = os.path.basename(file).split('.')

    for face in faces:
        
        x, y, w, h = face['box']
        c = face['confidence']               

        if c > 0.899 and x >= 0 and y >= 0 and w > 0 and h > 0:
            
            roi_color = pixels[y:y + h, x:x + w]
            scnt = str(cnt)
            scnt = scnt.rjust(3, '0')

            print(dir+root[0]+'_'+scnt+'_'+str(x)+'-'+str(y)+'-'+str(w)+'-'+str(h)+'.jpg'+':'+str(c))
            
            cv2.imwrite(wdir+root[0]+'_'+scnt+'_'+str(x)+'-'+str(y)+'-'+str(w)+'-'+str(h)+'.jpg',roi_color)

            img = Image.fromarray(roi_color)
            img = img.resize(required_size)
            face_array = asarray(img)
            cv2.imwrite(ndir+'n_'+root[0]+'_'+scnt+'_'+str(x)+'-'+str(y)+'-'+str(w)+'-'+str(h)+'.jpg',face_array)

            cnt = cnt + 1

ID:(13768, 0)