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": x + 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