Skip to content

Provide demonstration script for producing images cropped to the face #1

Open
@gwern

Description

I experimented with using facedetect's cropping script on anime images to try to crop faces into separate files (the goal here being to experiment with modeling faces using WGAN to see if it improves on IllustrationGAN), but it didn't work at all. I tried using this, and it works much better but doesn't provide a simple interface/program for cropping images down to the face. I modified the example file to do this, and it seems to work OK:

import cv2
import sys
import os.path

def detect(cascade_file, filename, outputname):
    if not os.path.isfile(cascade_file):
        raise RuntimeError("%s: not found" % cascade_file)

    cascade = cv2.CascadeClassifier(cascade_file)
    image = cv2.imread(filename)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    faces = cascade.detectMultiScale(gray,
                                     # detector options
                                     scaleFactor = 1.1,
                                     minNeighbors = 5,
                                     minSize = (50, 50))
    i=0
    for (x, y, w, h) in faces:
        cropped = image[y: y + h, x: x + w]
        cv2.imwrite(outputname+str(i)+".png", cropped)
        i=i+1

if len(sys.argv) != 4:
    sys.stderr.write("usage: detect.py <animeface.xml file>  <input> <output prefix>\n")
    sys.exit(-1)

detect(sys.argv[1], sys.argv[2], sys.argv[3])

Saved as cropy.py, this can then be run on a single file like

python ~/src/lbpcascade_animeface/examples/crop.py ~/src/lbpcascade_animeface/lbpcascade_animeface.xml foo.jpg cropped

or run in parallel on many files using parallel like this:

cropFaces() {
    name=$(basename "$@")
    python ~/src/lbpcascade_animeface/examples/crop.py ~/src/lbpcascade_animeface/lbpcascade_animeface.xml "$@" faces/danbooru/"$name"
    }
export -f cropFaces
find ./danbooru/ -type f -name "*.jpg" | parallel cropFaces

It would be great if you could provide something like this Python crop program in the repo.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions