python-opencv 人脸检测

python-opencv 人脸检测

代码还使用到了dlib 和face_recognition这两个库,需要安装一下,看一下代码:

import face_recognition
import cv2

# 创建视频捕捉对象
video_capture = cv2.VideoCapture(0)
print(video_capture.isOpened())

# video_capture.set(3, 1280)
# video_capture.set(4, 480)

while video_capture.isOpened():
    # ret 表示读取是否成功
    # frame 具体的图像数据
    ret, frame = video_capture.read()

    # 尺寸缩放为原来的 1/4
    # 作用:为了加速人脸检测过程
    small_frame = cv2.resize(frame, None, fx=0.25, fy=0.25)

    # bgr -> rgb
    rgb_frame = small_frame[:, :, ::-1]

    # 拿到人脸坐标
    face_loc = face_recognition.face_locations(rgb_frame)

    for (top, right, bottlm, left), in zip(face_loc):
        top *= 4
        right *= 4
        bottlm *= 4
        left *= 4

        cv2.rectangle(
            frame,
            (left, top),
            (right, bottlm),
            (255, 0, 0),
            2
        )

    cv2.imshow("face detection", frame)

    # 退出条件
    if cv2.waitKey(1) & 0xFF == 27:
        break

video_capture.release()
cv2.destroyAllWindows()

也可以只通过dlib实现:

# 导包
import dlib  # 人脸识别
import numpy as np  # python 科学计算库
import cv2  # opencv 图像处理

# Dlib 检测器,人脸检测器对象
detector = dlib.get_frontal_face_detector()


def face_detection(img):
    cv2.imshow("img_original", img)

    # cv2.waitKey(0)
    # exit()

    # 记录人脸矩阵大小
    height_max = 0
    width_sum = 0

    # Dlib 检测,0 表示原图,eg:1 表示放大 1 倍再检查
    faces = detector(img, 0)  # faces 是坐标数据
    print("faces:\n", faces)
    # exit()

    # 判断是否检测到人脸
    if faces:
        # 计算要生成的图像 img_blank 大小
        # 记录最大的宽度、高度,创建空白图像 img_blank,用于存储提取出的人脸区域
        for k, d in enumerate(faces):

            # 计算人脸矩形框大小
            height = d.bottom() - d.top()
            width = d.right() - d.left()

            # 处理宽度
            width_sum += width

            # 处理高度,处理异常值
            if height > height_max:
                height_max = height
            else:
                height_max = height_max

        # 生成用来显示的人脸图像
        # 3 表示图像是 rgb 彩图,如果是 1 表示图像是灰度图,只有 1 个通道
        img_blank = np.zeros((height_max, width_sum, 3), np.uint8)

        # 记录每次开始写入人脸像素的宽度位置
        blank_start = 0

        # 将人脸填充到 img_blank
        for k, d in enumerate(faces):

            height = d.bottom() - d.top()
            width = d.right() - d.left()

            # 逐像素点填充
            for i in range(height):
                for j in range(width):
                    img_blank[i][blank_start + j] = img[d.top() + i][d.left() + j]
            # 调整图像
            blank_start += width

    cv2.namedWindow("img_faces")  # , 2)
    cv2.imshow("img_faces", img_blank)
    cv2.waitKey(0)


if __name__ == "__main__":
    # 读取图像
    img_path = "./image/lakers.jpeg"  # 相对路径
    img = cv2.imread(img_path)  # 读取图片
    # print(img)  # 图片数组,每个数字表示像素 (0-255)
    # exit()
    face_detection(img)

    # 作业
    # 1、运行成功本案例
    # 2、下载 5 张图片:没有人脸、1 张人脸、多张人脸,并成功运行代码进行检测

看一下效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43327597/article/details/134605284