编写人脸检测程序

新建一个py文件,命名为facedetectionwithdlib.py。添加如下代码:

【代码 facedetectionwithdlib.py】

python 复制代码
# -*- coding: utf-8 -*-
'''
使用dlib实现人脸检测
'''

import face_recognition
import cv2
import time

# 超参数
detection_method = 'hog' # 参数值为hog/cnn。表示人脸检测使用hog提取特征还是使用cnn提取特征。

# video_path = 'test.mp4'
video_path = ''

# 初始化摄像头
if video_path:
    cap = cv2.VideoCapture(video_path)
else:
    cap = cv2.VideoCapture(0)

cap.set(0,640) # 视频宽度
cap.set(1,480) # 视频高度
time.sleep(2)


while True:# 拍100张图片就结束
    ret, img = cap.read()
    # 人脸检测不依赖色彩,所以先把人脸图像转成灰度图像
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    
    face_locations = face_recognition.face_locations(
                     gray, number_of_times_to_upsample=1, 
                     model = detection_method)
    # 用矩形框框出人脸位置
    for (top, right, bottom, left) in face_locations:
        cv2.rectangle(img, (left, top), (right, bottom), 
                      (0, 0, 255), 2)
        cv2.rectangle(gray, (left, top), (right, bottom), 
                      (0, 0, 255), 2)
    
    cv2.imshow('original image', img)
    cv2.imshow('gray image', gray)
    
    # 按 'ESC' 键终止
    k = cv2.waitKey(100) & 0xff 
    if k == 27:
        break
 
cap.release()
cv2.destroyAllWindows()
相关推荐
用户7196975933582 分钟前
YOLO-World 精读:慢的不是检测器,是文本编码器
人工智能
alonglong2 分钟前
RAG 增量索引实测:把 434.7 秒的全量重建压到 1.35 秒,以及"字节级一致"为什么只属于复用路径
人工智能
康实训4 分钟前
高校中医康复实训室建设规划要点
人工智能·实训室·实训室建设
larance9 分钟前
机器学习的数据分片
人工智能·机器学习
Gu_WenYun9 分钟前
端侧AI规模化落地,算力景气延续,科技基金怎么选?
人工智能·科技·金融
杜 硕13 分钟前
快速排序02
算法·排序算法
u13013015 分钟前
GitHub 热榜项目:日榜(2026-10-12)
人工智能·github
chien01118 分钟前
Agent 需要什么样的运行时?——读阿里云 Agent Sandbox 发布报道
人工智能·语言模型
码流子19 分钟前
事件告警延迟拆解:从摄像头到手机通知,延迟卡在哪六个环节
数据库·人工智能·物联网