File size: 1,681 Bytes
c91fae7
 
 
 
 
 
 
 
 
 
c50a96c
c91fae7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import cv2

def discover_square_crop_points(points, image, step=3, maximum_step=30):

  x = points["x"]
  y = points["y"]
  w = points["w"]
  h = points["h"]

  if step >= maximum_step:
    return {"initial_x": x, "initial_y": y, "final_x": x + w, "final_y": y + h}

  img_height = image.shape[0]
  img_width = image.shape[1]

  crop_offset = ((w + h) / 2) / step

  initial_x = x - crop_offset
  initial_y = y - crop_offset
  final_x = x + w + crop_offset
  final_y = y + h + crop_offset

  if initial_x < 0 or initial_y < 0 or final_x > img_width or final_y > img_height:
    return discover_square_crop_points(points, image, step+1, maximum_step)
  
  initial_x = int(initial_x)
  initial_y = int(initial_y)
  final_x = int(final_x)
  final_y = int(final_y)

  print(f"step: {step}")
  return {"initial_x": initial_x, "initial_y": initial_y, "final_x": final_x, "final_y": final_y}

def crop_faces(cv2_image):
  gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')

  multiScaleValues = [1.01]

  for value in multiScaleValues:
    faces = face_cascade.detectMultiScale(image=gray, scaleFactor=value, minNeighbors=4, minSize=(512, 512))
    if len(faces) > 0:
      break

  cropped_faces = []

  for (x, y, w, h) in faces:
    points = {"x": x, "y": y, "w": w, "h": h}
    points = discover_square_crop_points(points, cv2_image)

    initial_x = points["initial_x"]
    initial_y = points["initial_y"]
    final_x = points["final_x"]
    final_y = points["final_y"]

    face = cv2_image[initial_y:final_y, initial_x:final_x]
    cropped_faces.append(face)

  return cropped_faces