如何从旋转图像中提取人脸部分?

How to extract face portion from rotated images?

我想从不同角度的图像中提取人脸image/portion。

我有如下图片:

我试过以下代码。

import cv2
import sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline

# imagePath = sys.argv[1]

image = cv2.imread('_img_1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.3,
    minNeighbors=3,
    minSize=(30, 30)
)

print("[INFO] Found {0} Faces.".format(len(faces)))

for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
    roi_color = image[y:y + h, x:x + w]
    print("[INFO] Object found. Saving locally.")
    cv2.imwrite(str(w) + str(h) + '_faces.jpg', roi_color)
    plt.imshow(roi_color)
    plt.show()

status = cv2.imwrite('faces_detected.jpg', image)
print("[INFO] Image faces_detected.jpg written to filesystem: ", status)

如何从旋转的图像中提取人脸 image/portion?

首先考虑旋转图像!

您可以通过猜测 ID 的方向或对矩形进行更深入的检测来实现此目的

height, width, _ = image.shape
if height > width:
    image = cv2.rotate(image, cv2.ROTATE_90_COUNTERCLOCKWISE)