栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

dlib-正面人脸检测

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

dlib-正面人脸检测

需要安装dlib,参考:dlib安装参坑记录
本人对于人工智能属于零基础,所以以下内容是在网上查阅的资料并整理出来的。
我想干啥:我想实现人脸识别。
需要做啥:人脸检测、人脸识别
人脸检测怎么做?
查阅到可以使用Haar特征分类器或dlib检测方法。
一开始使用Haar特征分类器时,发现很多方法我都使用不了。不知道是不是版本的原因。

所以换到了dlib检测方法。
大概需要如下几步:
a、灰度处理

gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

b、获得dlib的正面人脸检测器

detector = dlib.get_frontal_face_detector()

c、进行检测

rects = detector(gray_img)

d、在图片中圈出人脸部分

cv2.rectangle(img,(x1,y1),(x2,y2),(0,252,0),2)

e、对步骤d中圈出的框进行文字描述

cv2.putText(img=image, text="Face: {}".format(i + 1), org=(x-10, y-10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(0, 255, 0), thickness=2)

具体代码如下:

# encoding:utf-8

import dlib
import numpy as np
import cv2

def rect_to_bb(rect): # 获得人脸矩形的坐标信息
    x1 = rect.left()
    y1 = rect.top()
    x2 = rect.right()
    y2 = rect.bottom()
    return (x1, y1, x2, y2)
    # x = rect.left()
    # y = rect.top()
    # w = rect.right() - x
    # h = rect.bottom() - y
    # return (x, y, w, h)

# def resize(image, width=1200):  # 将待检测的image进行resize
#     r = width * 1.0 / image.shape[1]
#     dim = (width, int(image.shape[0] * r))
#     resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
#     return resized

def detect_face(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 灰度处理 
    detector = dlib.get_frontal_face_detector() # 获得dlib的正面人脸检测器
    # image = resize(image, width=1200)
    rects = detector(gray,1) # 第一个参数是灰度图像 第二个参数不知道,可能与检测器的识别度有关0的时候只检测除了3张脸,少了三张脸。1,2,3的时候检测到六张脸
    for (i, rect) in enumerate(rects):
        (x, y, x2, y2) = rect_to_bb(rect)
        # cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.rectangle(image, (x, y), (x2, y2), (0, 255, 0), 2) # 参数:图片,左上角坐标,右下角坐标,颜色,边框粗细值
        cv2.putText(img=image, text="Face: {}".format(i + 1), org=(x-10, y-10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(0, 255, 0), thickness=2) 
        # 参数:图片,文字,字体,字号,颜色,文字粗细值

    cv2.imshow("Output", image)
    cv2.waitKey(0)

if __name__ == "__main__":
    # test_img1 = cv2.imread("test_data/test1.jpg")
    # test_img2 = cv2.imread("test_data/test2.jpg")
    # test_img3 = cv2.imread("test_data/test3.jpg")
    # detect_face(test_img1)
    # detect_face(test_img2)
    # detect_face(test_img3)
    test_img5 = cv2.imread("test_data/test5.jpg")
    detect_face(test_img5)


原文参考自:https://blog.csdn.net/liuxiao214/article/details/83411820

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983881.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号