【OpenCV5】人脸识别



2022年11月19日    Author:Guofei

文章归类: 0x25_CV    文章编号: 1015

版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2022/11/19/cv5.html


模型文件下载:https://github.com/guofei9987/datasets_for_ml/blob/master/cvdata.zip

import cv2
from PIL import Image, ImageDraw, ImageColor


def detect_faces(image_path):
    img = cv2.imread(image_path)

    face_cascade = cv2.CascadeClassifier("cvdata/haarcascades/haarcascade_frontalface_default.xml")
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img

    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(10, 10),
                                          flags=cv2.CASCADE_SCALE_IMAGE)
    result = []

    for (x, y, width, height) in faces:
        result.append((x, y, x + width, y + height))
    return result


def draw_faces(image_path, new_path):
    """
    Open the image based on the image_path and draw a rectangle on the faces.
    Save to new_path after draw.
    """
    faces = detect_faces(image_path)
    if faces:
        img = Image.open(image_path)
        draw_instance = ImageDraw.Draw(img)
        for (x1, y1, x2, y2) in faces:
            draw_instance.rectangle((x1, y1, x2, y2), outline=(255, 0, 0))
        img.save(new_path)


draw_faces(img_path, img_new_path)

额外

  • 模型文件中还有身体识别、眼睛识别之类的,替换模型文件即可,代码一样。
  • todo: 不转化为gray是否可以识别

下面这个是旧版本

import cv2

# 读取待检测的图像
image = cv2.imread('dface2.jpeg')

# 获取 XML 文件,加载人脸检测器
# 这个地方只能用绝对路径,GitHub下载的也报错
faceCascade = cv2.CascadeClassifier(
    '/Users/guofei/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_frontalface_default.xml')
# eye_cascade = cv2.CascadeClassifier('/Users/guofei/opt/anaconda3/lib/python3.8/site-packages/cv2/data/haarcascade_eye.xml')


# 色彩转换,转换为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 调用函数 detectMultiScale
faces = faceCascade.detectMultiScale(
    gray,
    scaleFactor=1.15,
    minNeighbors=5,
    minSize=(5, 5)
)
print(faces)
# 打印输出的测试结果
print("发现{0}个人脸!".format(len(faces)))  # 逐个标注人脸
for (x, y, w, h) in faces:
    # cv2.rectangle(image,(x,y),(x+w,y+w),(0,255,0),2) #矩形标注
    cv2.circle(image, (int((x + x + w) / 2), int((y + y + h) / 2)), int(w / 2), (0, 255, 0), 2)  # 显示结果
    cv2.imshow("dect", image)
# 保存检测结果 cv2.imwrite("re.jpg",image)
cv2.waitKey(0)

cv2.destroyAllWindows()

您的支持将鼓励我继续创作!