一个Python监控系统的实现思路及代码示例

以下是一个满足你需求的Python监控系统的实现思路及代码示例。这个系统会使用OpenCV库来处理摄像头的视频流,进行人员检测和跟踪,同时使用uuid库为每个进入监控区域的人分配唯一ID,使用datetime库来记录每个人的停留时间。由于打印机的操作会因打印机型号和操作系统而异,这里假设使用win32print库(仅适用于Windows系统)来模拟打印功能。

import cv2
import uuid
import datetime
import time
import win32print
import win32ui
from PIL import Image, ImageWin

# 初始化摄像头
cap = cv2.VideoCapture(0)

# 初始化人员跟踪器
trackers = {}
person_ids = {}
entry_times = {}

# 加载人员检测模型(这里使用Haar级联分类器作为示例)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

def print_info(person_id, entry_time, exit_time):
    # 计算停留时间
    duration = exit_time - entry_time
    duration_str = str(duration).split('.')[0]

    # 模拟打印信息到预设模板
    template_text = f"Person ID: {person_id}\nEntry Time: {entry_time}\nExit Time: {exit_time}\nDuration: {duration_str}"
    print(template_text)

    # 使用win32print打印信息(仅适用于Windows)
    printer_name = win32print.GetDefaultPrinter()
    hDC = win32ui.CreateDC()
    hDC.CreatePrinterDC(printer_name)
    printable_area = hDC.GetDeviceCaps(8), hDC.GetDeviceCaps(10), hDC.GetDeviceCaps(11), hDC.GetDeviceCaps(9)
    printer_size = printable_area[2], printable_area[3]
    printer_margins = hDC.GetDeviceCaps(42), hDC.GetDeviceCaps(43)

    bmp = Image.new("RGB", printer_size, "white")
    d = ImageDraw.Draw(bmp)
    d.text((100, 100), template_text, fill="black")

    hDC.StartDoc("Test doc")
    hDC.StartPage()

    dib = ImageWin.Dib(bmp)
    dib.draw(hDC.GetHandleOutput(), (printer_margins[0], printer_margins[1], printer_size[0], printer_size[1]))

    hDC.EndPage()
    hDC.EndDoc()
    hDC.DeleteDC()


while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 转换为灰度图像以进行人脸检测
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

    detected_ids = []

    for (x, y, w, h) in faces:
        found = False
        for person_id, tracker in trackers.items():
            success, bbox = tracker.update(frame)
            if success:
                (x_t, y_t, w_t, h_t) = [int(v) for v in bbox]
                if abs(x - x_t) < 50 and abs(y - y_t) < 50:
                    # 匹配到已有的人员
                    cv2.rectangle(frame, (x_t, y_t), (x_t + w_t, y_t + h_t), (0, 255, 0), 2)
                    cv2.putText(frame, f"ID: {person_id}", (x_t, y_t - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
                    detected_ids.append(person_id)
                    found = True
                    break

        if not found:
            # 发现新的人员
            person_id = str(uuid.uuid4())
            tracker = cv2.TrackerCSRT_create()
            tracker.init(frame, (x, y, w, h))
            trackers[person_id] = tracker
            entry_times[person_id] = datetime.datetime.now()
            detected_ids.append(person_id)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cv2.putText(frame, f"ID: {person_id}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)

    # 检查是否有人离开监控区域
    for person_id in list(trackers.keys()):
        if person_id not in detected_ids:
            exit_time = datetime.datetime.now()
            entry_time = entry_times[person_id]
            print_info(person_id, entry_time, exit_time)
            del trackers[person_id]
            del entry_times[person_id]

    # 显示帧
    cv2.imshow('Monitoring System', frame)

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

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

代码说明:

  1. 摄像头初始化:使用cv2.VideoCapture(0)初始化笔记本电脑的内置摄像头。
  2. 人员检测:使用Haar级联分类器进行人脸检测,作为人员检测的简单示例。
  3. 人员跟踪:使用OpenCV的cv2.TrackerCSRT_create()创建跟踪器,为每个进入监控区域的人分配唯一ID,并记录其进入时间。
  4. 停留时间计算:当人员离开监控区域时,计算其停留时间。
  5. 信息打印:使用win32print库将人员的ID、进入时间、离开时间和停留时间打印到预设模板上。

注意事项:

  • 此代码中的人脸检测方法仅为示例,实际应用中可能需要更精确的人员检测模型,如基于深度学习的目标检测模型(如YOLO、Faster R-CNN等)。
  • 打印机操作部分仅适用于Windows系统,如果你使用的是其他操作系统,需要相应地调整打印代码。
  • 运行代码前,请确保已经安装了所需的库,如OpenCV、Pillow等。可以使用以下命令进行安装:
pip install opencv-python pillow pywin32

你可能感兴趣的:(算法,网络,算法,python)