编写人脸检测程序

新建一个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()
相关推荐
Shockang2 小时前
AI Slop 治理实战
人工智能
Mr数据杨3 小时前
医学影像分类实战复盘 从 Kaggle 竞赛到可落地建模流程
人工智能·数据分析·kaggle竞赛
顶点多余4 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
AI情绪识别开源4 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
ZGIAI5 小时前
ZGI 迭代节点:批量资料的逐项处理
人工智能·架构
ZGIAI5 小时前
ZGI 知识检索:让业务回答有据可查
人工智能·架构
Asize5 小时前
框架的说明书是写给 AI 看的:我用 Next.js 搭了个博客
人工智能·代码规范·next.js
2601_955662465 小时前
AI 配音工具 7 款实测:短视频、影视解说、小说推文音质横向对比
人工智能·音视频·语音识别·视频
AI创界者5 小时前
PinkCherry-MiniMax-H3 全能AI视频整合包:8G显存开箱即用,支持首尾帧/超分补帧/自动提示词
人工智能·aigc