Python 调用USB摄像头识别人脸进行打卡

python 复制代码
import cv2
import pyttsx3
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import datetime

def draw_circle(event,x,y,flasgs,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(frame,(x,y),50,(255,0,0),-1)

# font=cv2.FONT_ITALIC
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
# 初始化语音合成引擎
engine = pyttsx3.init()
# 加载人脸识别模型
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 打开摄像头
cap = cv2.VideoCapture(0)
# 设置园的直径
diameter = 360
# 读取视频流
while True:
    # 逐帧捕获
    ret, frame = cap.read()
    # 在帧上画一个白色的圆
    # 获取圆的宽度和高度
    height,width = frame.shape[:2]
    # 计算圆的半径
    radius = int((diameter / 2)*(width / 640))
    # 计算圆的中心位置
    center = (int(width / 2),int(height / 2 ))
    # 绘制圆圈
    cv2.circle(frame,center,radius,(255,255,255),thickness=5)
    # 获取当前时间并将其显示在窗口中
    now = datetime.datetime.now()
    weekdays = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
    weekday = weekdays[now.weekday()]
    # 将画面转换为灰度图像
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    # 如果检测到人脸
    if len(faces) > 0:
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            # 播放语音提示
            engine.say('打卡成功')
        engine.runAndWait()
        engine.endLoop()
        engine.stop()
    else:
        # 播放语音提示
        engine.say('打卡失败')
        engine.runAndWait()
        # engine.endLoop()
        # engine.stop()
        #
    frame = cv2AddChineseText(frame, now.strftime('%Y-%m-%d %H:%M:%S')+ " "+ weekday,(10,10),(255,255,255),30)
    # 显示画面
    cv2.imshow('frame', frame)

    # 按下'q'键退出循环 = 27
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源
cap.release()
# 关闭所有OpenCV窗口
cv2.destroyAllWindows()

需要的 haarcascade_frontalface_default.xml 文件,下载

https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml

相关推荐
小九九的爸爸8 分钟前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田17 小时前
Pydantic校验配置文件
python
hboot18 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉