In [1]:
%matplotlib inline
import cv2
import os
import scipy
import matplotlib.pyplot as plt
import pandas as pd

pwd = os.getcwd()

In [2]:
def detect(filename, cascade_file = '/'.join([pwd, "lbpcascade_animeface.xml"])):
    """Modifed from example: github.com/nagadomi/lbpcascade_animeface."""
    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 = (24, 24))

    name = filename.split('/')[-1].split('.')[0]
    j_faces = [[s, faces[0][e]] for e, s in enumerate(list('xywh'))]
    pd.DataFrame(j_faces).set_index(0).to_json("faces/jsons/"+name+".json")

    if (len(faces)>0):
        cv2.imwrite("faces/pngs/"+name+".png", image)
    return faces

In [4]:
def loadImage(f):
    x, y, w, h = detect(f)
    img = {'full': scipy.ndimage.imread(f)}
    w4, h4, Y = w/4.0, h/4.0, img['full'].shape[0]
    img['hair'] = img['full'][x:x+w, y-h4:y+h4]
    img['deco'] = img['full'][x+w4:x+3*w4, y+h4:Y]
    return img

In [8]:
files = ['/'.join([pwd, 'faces/pngs', x]) for x in os.listdir('faces/pngs')]
for f in files:
    detect(f)

In [ ]: