编写人脸检测程序

新建一个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()
相关推荐
kyle~29 分钟前
模型预测控制(MPC)
算法·机器人·控制·传感器
Be for thing43 分钟前
Pytorch【12】transforms进阶|图像数据增强实战,提升模型泛化能力
人工智能·pytorch·机器学习
十有八七1 小时前
手搓 Agent(一):先有大脑——大模型只会做一件事
前端·人工智能·后端
锋行天下1 小时前
「踩坑实录」给 LangGraph Agent 接两个 FastMCP,我被 langchain 偷偷改了工具名
前端·人工智能·后端
阿里云大数据AI技术1 小时前
穹彻智能 × MaxCompute:具身智能 UMI 数据产线的全模态计算实践
人工智能
联犀1 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
飞Link1 小时前
灵巧手是什么?从机械结构、驱动方式到控制原理,认识机器人的精细操作能力
人工智能·python·机器人
阿里云大数据AI技术1 小时前
从“扫文件”到“找数据行”:EMR Serverless StarRocks 支持 Paimon Global Index
人工智能
武子康2 小时前
AI通关了,游戏就算通过测试了吗?
人工智能·游戏·机器学习
Seiran2 小时前
CPU 突然打满,罪魁祸首是条用了三年的正则
人工智能