编写人脸检测程序

新建一个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()
相关推荐
AI新兵4 分钟前
深度学习基础:从原理到实践——第二章神经网络(中)
人工智能·深度学习·神经网络
pearbing11 分钟前
B站排名优化:知识、娱乐、生活类内容的差异化实操策略
人工智能·微信·小程序·生活·娱乐
leijiwen12 分钟前
AI × RWA 本地生活品牌数字资产管理与增长平台
人工智能·web3·区块链
却道天凉_好个秋21 分钟前
卷积神经网络CNN(四):池化技术
人工智能·神经网络·cnn·池化
少许极端30 分钟前
算法奇妙屋(五)-链表
数据结构·算法·链表
ARM+FPGA+AI工业主板定制专家34 分钟前
基于Jetson+FPGA+GMSL+AI的自动驾驶数据采集解决方案
人工智能·机器学习·自动驾驶
XISHI_TIANLAN1 小时前
【多模态学习】Q&A6: 什么是MOE架构?Router Z Loss函数是指什么?负载均衡损失(Load Balancing Loss)又是什么?
学习·算法·语言模型
木子.李3471 小时前
数据结构-算法C++(额外问题汇总)
数据结构·c++·算法
聊聊MES那点事1 小时前
汽车零部件MES系统实施案例介绍
人工智能·信息可视化·汽车·数据可视化
花心蝴蝶.1 小时前
API签名认证算法全解析
算法