File size: 590 Bytes
64b550a
 
 
 
 
8fef041
64b550a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8fef041
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import cv2
import numpy as np
from PIL import Image


def detect(image_pil, cascade_file="lbpcascade_animeface.xml"):
    cascade = cv2.CascadeClassifier(cascade_file)

    image = np.array(image_pil)
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    gray = cv2.equalizeHist(gray)

    faces = cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(24, 24),
    )

    # No faces found
    if len(faces) == 0:
        return image_pil

    x, y, w, h = faces[0]
    face = image[y : y + h, x : x + w]

    return Image.fromarray(face)