You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现摄像头检测未戴口罩人员并抓拍存储到本地桌面?

口罩检测抓拍功能实现方案

以下是基于你现有代码修改后的可运行版本,新增了无口罩人员自动抓拍存储到桌面的功能,同时修复了原代码的缩进错误、依赖缺失问题:

关键修改说明

  • 补全了缺失的preprocess_input依赖导入
  • 自动在桌面创建no_mask_captures文件夹用于存储抓拍图片
  • 新增3秒抓拍冷却机制,避免短时间内重复抓拍同一场景
  • 检测到未佩戴口罩人员时自动保存当前画面,文件用时间戳命名避免覆盖
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from imutils.video import VideoStream
import numpy as np
import imutils
import time
import cv2
import os

lowConfidence = 0.75

# 配置无口罩抓拍存储路径(桌面)
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
capture_dir = os.path.join(desktop_path, "no_mask_captures")
os.makedirs(capture_dir, exist_ok=True)
# 抓拍冷却时间(单位秒,可按需调整)
capture_cooldown = 3
last_capture_time = 0

def detectAndPredictMask(frame, faceNet, maskNet):
    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
        (104.0, 177.0, 123.0))

    faceNet.setInput(blob)
    detections = faceNet.forward()

    faces = []
    locs = []
    preds = []

    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        if confidence > lowConfidence:
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            (startX, startY) = (max(0, startX), max(0, startY))
            (endX, endY) = (min(w - 1, endX), min(h - 1, endY))

            face = frame[startY:endY, startX:endX]
            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
            face = cv2.resize(face, (224, 224))
            face = img_to_array(face)
            face = preprocess_input(face)

            faces.append(face)
            locs.append((startX, startY, endX, endY))

    # 原代码缩进错误修复,移到循环外执行预测
    if len(faces) > 0:
        faces = np.array(faces, dtype="float32")
        preds = maskNet.predict(faces, batch_size=32)

    return (locs, preds)

prototxtPath = r"deploy.prototxt"
weightsPath = r"res10_300x300_ssd_iter_140000.caffemodel"
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)

maskNet = load_model("mask_detector.model")

vs = VideoStream(src=0).start()

while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=900)
    # 如需保存无标注原始画面,可在这里复制一份原始frame备用
    # raw_frame = frame.copy()

    (locs, preds) = detectAndPredictMask(frame, faceNet, maskNet)

    for (box, pred) in zip(locs, preds):
        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred

        label = "Mask" if mask > withoutMask else "No Mask"
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
        label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
        
        if label.startswith("Mask"):
            print("MASK DETECTED")
        else: 
            print("MASK NOT DETECTED")
            # 无口罩时触发抓拍逻辑
            current_time = time.time()
            if current_time - last_capture_time >= capture_cooldown:
                file_name = f"no_mask_{time.strftime('%Y%m%d_%H%M%S')}.jpg"
                save_path = os.path.join(capture_dir, file_name)
                # 如需保存原始无标注画面,把frame换成上面定义的raw_frame即可
                cv2.imwrite(save_path, frame)
                print(f"已抓拍无口罩人员,存储路径:{save_path}")
                last_capture_time = current_time

        cv2.putText(frame, label, (startX, startY - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

    cv2.imshow("PROMENADE FACE MASK DETECTOR", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

cv2.destroyAllWindows()
vs.stop()

可调参数说明

  • capture_cooldown:抓拍冷却时间,默认3秒,调整该值可控制抓拍频率
  • 如需保存不带检测框的原始画面,可在读取frame后复制一份原始帧,保存时使用原始帧即可

内容的提问来源于stack exchange,提问作者Rukshan Perera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:24:05