【OpenCV-Python】38.OpenCV的人脸检测——dlib库

37.OpenCV的人脸和目标的跟踪——dlib库



前言

  dlib库是一个十分好用的机器学习库,其源码均由C++实现,并提供了Python 接口,可广泛适用于很多场景。本实例仅简单示范dlib库中关于人脸检测技术的Python应用。


一、基于dlib库的人脸检测(图片)

  程序可以实现对图片中的人脸进行检测。

import cv2
import dlib
import numpy as np

def plot_rectangle(image, faces):
    for face in faces:
        cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (255,0,0), 4)
    return image

def main():
    
    img = cv2.imread("family.jpg")

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

    detector = dlib.get_frontal_face_detector()
    dets_result = detector(gray, 1) 

    img_result = plot_rectangle(img.copy(), dets_result)

    cv2.imshow("face detection", img_result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

在这里插入图片描述


二、基于dlib库的人脸检测(视频)

  程序可以实现对视频中的人脸进行检测。

import cv2
import dlib

def plot_rectangle(image, faces):
    for face in faces:
        cv2.rectangle(image, (face.left(), face.top()), (face.right(), face.bottom()), (255,0,0), 4)
    return image

def main():
    
    capture = cv2.VideoCapture(0)
    
    if capture.isOpened() is False:
        print("Camera Error !")
    
    while True:
        ret, frame = capture.read()
        if ret:
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # BGR to GRAY

            detector = dlib.get_frontal_face_detector()
            det_result = detector(gray, 1)

            dets_image = plot_rectangle(frame, det_result)

            cv2.imshow("face detection with dlib", dets_image)

            if cv2.waitKey(1) == 27:
                break

    capture.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

三、OpenCV-Python资源下载

OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码


总结

  以上内容简单的介绍了OpenCV-Python的人脸跟踪和目标跟踪,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。

猜你喜欢

转载自blog.csdn.net/weixin_43843069/article/details/122324966