

MacOS Catalina 10.15.4
Python 3.7.6
Eine Bibliothek, die eine Bildverarbeitung wie die Gesichtserkennung mit einem trainierten Modell durchführen kann. Es wird gesagt, dass dlib verwendet wird. https://github.com/ageitgey/
Dies ist ein Code, der face_recognition verwendet. https://github.com/komiyakomiyakomiya/face_trim
terminal
$ git https://github.com/komiyakomiyakomiya/face_trim.git
opencv-python==4.2.0.34
face-recognition==1.3.0
terminal
$ pip install opencv-python==4.2.0.34 face-recognition==1.3.0
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):
    """Befehlsausführung"""
    #Löschen, wenn vor oder nach der cmd-Zeichenfolge ein Leerzeichen steht->Teilen Sie durch Leerzeichen und erstellen Sie eine Liste
    cmd_split = cmd.strip().split()
    #Erhalten Sie die Standardausgabe mit den Standardeinstellungen
    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)
    #Gibt zurück, wenn Standardausgabe vorhanden ist
    if cp.stdout is not None:
        # bytes ->Dekodiere nach str
        return cp.stdout.decode('utf-8')
def get_face_location(img_path):
    """Holen Sie sich Gesichtskoordinaten"""
    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-Werkzeugfläche_Führen Sie die Erkennung aus, um Gesichtskoordinaten zu erhalten
    load_image_file()Verwenden Sie diese Option, wenn die Methode aufgrund eines Fehlers nicht verwendet werden kann"""
    #Erkennt Gesicht und Oberseite, Right, Bottom,Befehl zur standardmäßigen Ausgabe der linken Koordinaten
    cmd_face_detection = f'face_detection {img_path}'
    # cmd_face_detection = f'face_detection --model cnn {img_path}'
    #Standardausgabe empfangen
    stdout = exec_cmd(cmd_face_detection)
    print(stdout)
    # /Users/USER_NAME/path/to/dir/input/Zinedine_Zidane_0001.jpg,89,181,192,77
    #Liste durch Kommas getrennt
    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):
    """Bild anzeigen"""
    #Bilder laden
    img = cv2.imread(img_path)
    #Erweiterung erhalten
    format = os.path.splitext(img_path)[1]
    #Verlängerung bestanden(format)Codiert im Format von
    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__':
    #Bitte ersetzen Sie es durch Ihr Lieblingsbild
    file_name = f'Zinedine_Zidane_0001.jpg'
    #Wo soll das Originalbild abgelegt werden?
    input_path = f'{cwd}/../input'
    #Ausgabeziel des zugeschnittenen Bildes
    output_path = f'{cwd}/../output'
    #Erstellen, wenn kein Ausgabezielverzeichnis vorhanden ist
    os.makedirs(output_path, exist_ok=True)
    #Holen Sie sich Gesichtskoordinaten
    top, right, bottom, left = get_face_location(f'{input_path}/{file_name}')
    #Lesen Sie die Originaldatei
    img = cv2.imread(f'{input_path}/{file_name}')
    #Anzeige
    display_image(f'{input_path}/{file_name}')
    #Trimmen
    img_face = img[top:bottom, left:right]
    #Im Ausgabeverzeichnis speichern
    cv2.imwrite(f'{output_path}/{file_name}', img_face)
    #Anzeige
    display_image(f'{output_path}/{file_name}')
if __name__ == '__main__':
    #Wo soll das Originalbild abgelegt werden?
    input_path = f'{cwd}/../input'
    #Ausgabeziel des zugeschnittenen Bildes
    output_path = f'{cwd}/../output'
    #Erstellen, wenn kein Ausgabezielverzeichnis vorhanden ist
    os.makedirs(output_path, exist_ok=True)
    #Pfadobjekt generieren
    path_obj = Path(input_path)
    #Musterabgleich mit Glob
    files_path = path_obj.glob('*')
    #Posix-Konvertierung
    files_path_posix = [file_path.as_posix() for file_path in files_path]
    print(files_path_posix)
    for file_path in files_path_posix:
        #Dateinamen abrufen
        file_name = file_path.split('/')[-1]
        #Holen Sie sich Gesichtskoordinaten
        top, right, bottom, left = get_face_location(file_path)
        #Lesen Sie die Originaldatei
        img = cv2.imread(file_path)
        #Anzeige
        display_image(file_path)
        #Trimmen
        img_face = img[top:bottom, left:right]
        #Im Ausgabeverzeichnis speichern
        cv2.imwrite(f'{output_path}/{file_name}', img_face)
        #Anzeige
        display_image(f'{output_path}/{file_name}')
Ich habe manchmal einen solchen Fehler bekommen.
AttributeError: module 'face_recognition' has no attribute 'load_image_file'
Das Problem stand auch, aber ich konnte es nicht lösen, selbst wenn ich versuchte, was hier geschrieben stand. https://github.com/ageitgey/face_recognition/issues/318
Als ich aufgab und die Brute-Force-Methode zum Abrufen der Gesichtskoordinaten aus der Standardausgabe des CLI-Tools ausprobierte, wurde sie behoben, bevor ich es wusste ...
Ich habe hier einen Artikel geschrieben. Wenn du nichts dagegen hast
Vielen Dank für das Lesen bis zum Ende! Zidane hat keine Bedeutung. Ich war zufällig an meiner Seite.
Recommended Posts