I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~

things to do

this

Zinedine_Zidane_0001

like this

Zinedine_Zidane_0001 jpg 03-36-34-700

environment

MacOS Catalina 10.15.4
Python 3.7.6

What is face_recognition?

A library that can perform some image processing such as face detection using a trained model. It is said that dlib is used. https://github.com/ageitgey/

Repository

This is a code that uses face_recognition. https://github.com/komiyakomiyakomiya/face_trim

terminal


$ git https://github.com/komiyakomiyakomiya/face_trim.git

Library

opencv-python==4.2.0.34
face-recognition==1.3.0

Installation

terminal


$ pip install opencv-python==4.2.0.34 face-recognition==1.3.0

code

face_trim.py


import os
from pathlib import Path
import subprocess
import sys

import cv2
import face_recognition
from IPython.display import display
from IPython.display import Image


cwd = Path().resolve()


def exec_cmd(cmd):
    """Command execution"""
    #Delete any spaces before or after the cmd string->Divide by space and make a list
    cmd_split = cmd.strip().split()
    #Get standard output with stdout settings
    cp = subprocess.run(cmd_split, stdout=subprocess.PIPE)
    # cp = subprocess.check_output(cmd_split)
    if cp.returncode != 0:
        print(f'{cmd_split[0]} faild.', file=sys.stderr)
        sys.exit(1)
    #Returns if there is standard output
    if cp.stdout is not None:
        # bytes ->Decode to str
        return cp.stdout.decode('utf-8')


def get_face_location(img_path):
    """Get face coordinates"""
    img = face_recognition.load_image_file(img_path)
    # location = face_recognition.face_locations(img, model='cnn')
    location = face_recognition.face_locations(img, model='hog')
    print(location)
    # [(82, 175, 180, 76)]
    top = location[0][0]
    right = location[0][1]
    bottom = location[0][2]
    left = location[0][3]
    return top, right, bottom, left


def get_face_location_cli(img_path):
    """CLI tool face_Execute detection to get face coordinates
    load_image_file()Use this if the method cannot be used due to a bug"""
    #Detects face and Top, Right, Bottom,Command to output the coordinates of Left as standard
    cmd_face_detection = f'face_detection {img_path}'
    # cmd_face_detection = f'face_detection --model cnn {img_path}'
    #Receive standard output
    stdout = exec_cmd(cmd_face_detection)
    print(stdout)
    # /Users/USER_NAME/path/to/dir/input/Zinedine_Zidane_0001.jpg,89,181,192,77
    #List separated by commas
    stdout_list = stdout.strip().split(',')
    top = int(stdout_list[1])
    right = int(stdout_list[2])
    bottom = int(stdout_list[3])
    left = int(stdout_list[4])
    return top, right, bottom, left


def display_image(img_path):
    """Display image"""
    #Loading images
    img = cv2.imread(img_path)
    #Get extension
    format = os.path.splitext(img_path)[1]
    #Extension passed(format)Encoded in the format of
    decoded_bytes = cv2.imencode(format, img)[1].tobytes()
    print(cv2.imencode(format, img)[1])
    # [[255]
    # [216]
    # [255]
    # ...
    # [103]
    # [255]
    # [217]]
    # print(decoded_bytes)
    # b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x0......
    display(Image(data=decoded_bytes))


if __name__ == '__main__':
    #Please replace it with your favorite image
    file_name = f'Zinedine_Zidane_0001.jpg'
    #Where to put the original image
    input_path = f'{cwd}/../input'
    #Output destination of cropped image
    output_path = f'{cwd}/../output'
    #Create if there is no output directory
    os.makedirs(output_path, exist_ok=True)

    #Get face coordinates
    top, right, bottom, left = get_face_location(f'{input_path}/{file_name}')

    #Reading the original file
    img = cv2.imread(f'{input_path}/{file_name}')
    #display
    display_image(f'{input_path}/{file_name}')
    #trimming
    img_face = img[top:bottom, left:right]
    #Save to output directory
    cv2.imwrite(f'{output_path}/{file_name}', img_face)
    #display
    display_image(f'{output_path}/{file_name}')

Crop images in the directory together

if __name__ == '__main__':
    #Where to put the original image
    input_path = f'{cwd}/../input'
    #Output destination of cropped image
    output_path = f'{cwd}/../output'
    #Create if there is no output directory
    os.makedirs(output_path, exist_ok=True)

    #Generate path object
    path_obj = Path(input_path)
    #Pattern matching with glob
    files_path = path_obj.glob('*')
    #posix conversion
    files_path_posix = [file_path.as_posix() for file_path in files_path]
    print(files_path_posix)

    for file_path in files_path_posix:
        #Get file name
        file_name = file_path.split('/')[-1]
        #Get face coordinates
        top, right, bottom, left = get_face_location(file_path)
        #Reading the original file
        img = cv2.imread(file_path)
        #display
        display_image(file_path)
        #trimming
        img_face = img[top:bottom, left:right]
        #Save to output directory
        cv2.imwrite(f'{output_path}/{file_name}', img_face)
        #display
        display_image(f'{output_path}/{file_name}')

error

I sometimes got an error like this.

AttributeError: module 'face_recognition' has no attribute 'load_image_file'

The issue was also standing, but I couldn't solve it even if I tried what was written here. https://github.com/ageitgey/face_recognition/issues/318

When I gave up and tried the brute force method of getting the face coordinates from the standard output of the CLI tool, it was fixed before I knew it.

Cluster cropped images

I wrote an article here. If you do not mind

-Clustering image data of multiple people without correct label with FaceNet and outputting to different directories

The end

Thank you for reading until the end! Zidane has no meaning. I happened to be by my side.

Recommended Posts

I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
Face detection from multiple image files with openCV, cut out and save
It is difficult to install a green screen, so I cut out only the face and superimposed it on the background image
[python] Send the image captured from the webcam to the server and save it
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
I made a server with Python socket and ssl and tried to access it from a browser
Start the webcam to take a still image and save it locally
I want to use only the SMTP MAIL FROM command and RCPT TO command without sending mail with Python's smtplib
The story of making a tool to load an image with Python ⇒ save it as another name
I want to pass an argument to a python function and execute it from PHP on a web server
I want to write to a file with Python
The file edited with vim was readonly but I want to save it
I want to write an element to a file with numpy and check it.
I want to handle optimization with python and cplex
I want to inherit to the back with python dataclass
I want to work with a robot in python.
I want to run a quantum computer with Python
[Python] I made a system to introduce "recipes I really want" from the recipe site!
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
I want to replace the variables in the python template file and mass-produce it in another file.
Image processing with Python (I tried binarizing it into a mosaic art of 0 and 1)
I tried to find the entropy of the image with python
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
Recursively get the Excel list in a specific folder with python and write it to Excel.
Return the image data with Flask of Python and draw it to the canvas element of HTML
[Python] I installed the game from pip and played it
I want to install a package from requirements.txt with poetry
I want to send a message from Python to LINE Bot
I made a function to crop the image of python openCV, so please use it.
I also tried to imitate the function monad and State monad with a generator in Python
I want to know the features of Python and pip
I tried to sort out the objects from the image of the steak set meal-① Object detection
[Python] I want to be a gourmet person [Data Driven approach] Choosing a store for the year-end and New Year holidays
I want to make a voice changer using Python and SPTK with reference to a famous site
(Memo) Until you extract only the part you want from a certain Web page, convert it to a Sphinx page, and print it as a PDF
I want to get information from fstab at the ssh connection destination and execute a command
I made a Line bot that guesses the gender and age of a person from an image
I want to extract an arbitrary URL from the character string of the html source with python
Chapter 1 Introduction to Python Cut out only the good points of deep learning made from scratch
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
I want to record the execution time and keep a log.
I want to use a wildcard that I want to shell with Python remove
I want to know the weather with LINE bot feat.Heroku + Python
I want to output the beginning of the next month with Python
Try to extract a character string from an image with Python3
I want to do a full text search with elasticsearch + python
I tried to make a periodical process with Selenium and Python
I wanted to solve the ABC164 A ~ D problem with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to create a pipfile and reflect it in docker
I want to check the position of my face with OpenCV!
Operate Firefox with Selenium from python and save the screen capture
Cut out an image with python
Cut out face with Python + OpenCV
Let's cut the face from the image
I want to debug with Python
Python --Get bitcoin rate BTC / JPY from bitflyer at regular intervals and save it to a file
Output the report as PDF from DB with Python and automatically attach it to an email and send it
I tried to sort out the objects from the image of the steak set meal --③ Similar image Heat map detection