海康摄像头配合YOLOv8实现人员监控 01

海康摄像头配合YOLOv8实现人员监控 01 rstp

概要

` 本帅哥位于一家小心公司,公司老总经常出差,这给了我一些空余的时间,但是电脑老旧退出游戏风险太高,于是我用特殊手段获得HK的管理员密码在配合YOLOv8 实现监控通过mqtt传回服务器在转发给手机实现全方面立体监控

整体架构流程

  1. RSTP流配合YOLOv8 监控(延迟比较久)
  2. 海康python 驱动实现监控 (实时性好)

技术名词解释

  • 海康
  • python
  • YOLOv8
  • conda

RSTP

海康摄像头开启rstp
conda 安装yolov8 环境
pip install ultralytics

代码实现

import cv2
import queue
import time
import os
from datetime import datetime
import threading
from ultralytics import YOLO

# 创建 'pic' 文件夹,如果不存在
if not os.path.exists('pic'):
    os.makedirs('pic')

# 加载 YOLOv8 模型
model = YOLO('yolov8s.pt')  # 替换为 'yolov8s.pt', 'yolov8m.pt' 等根据需要选择模型

# RTSP 地址
rtsp_url = 'rtsp://admin:[email protected]:554/Streaming/Channels/1'

# 创建队列
q = queue.Queue()

# 控制是否显示检测框和视频流
display_stream = False  # 设置为 True 显示视频流
draw_boxes = False  # 设置为 True 绘制检测框

# 处理帧的间隔
frame_skip = 8  # 每隔5帧处理一次
frame_counter = 0

def receive_stream():
    print("Start Receiving Stream")
    cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)

    if not cap.isOpened():
        print("Error: Unable to open video stream.")
        return

    # 添加短暂延迟以确保流稳定
    time.sleep(2)

    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Unable to read frame.")
            break
        q.put(frame)

    cap.release()
    print("Stopped Receiving Stream")

def detect_and_save():
    global frame_counter
    print("Start Detection and Saving")
    while True:
        if not q.empty():
            frame = q.get()

            # 每隔 frame_skip 帧进行处理
            if frame_counter % frame_skip == 0:
                # 使用 YOLOv8 模型进行检测
                results = model.predict(frame, verbose=False,classes=[0])

                # 遍历检测结果,检查是否有人(类别 0)
                for result in results:
                    for box in result.boxes:
                        if box.cls == 0:  # 类别 0 通常代表 'person'
                            confidence = box.conf[0]

                            # 如果置信度大于 0.6,则保存图片(不绘制框)
                            if confidence > 0.6:
                                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                                output_filename = f'pic/detected_frame_{timestamp}.jpg'
                                cv2.imwrite(output_filename, frame)
                                print(f"Saved {output_filename} at {timestamp}")

                            # 绘制检测框
                            if draw_boxes:
                                x1, y1, x2, y2 = map(int, box.xyxy[0])
                                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
                                cv2.putText(
                                    frame, f'Person {confidence:.2f}',
                                    (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2
                                )

            # 显示帧(如果启用)
            if display_stream:
                cv2.imshow('RTSP Stream', frame)

            frame_counter += 1

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()
    print("Stopped Detection and Saving")

if __name__ == '__main__':
    p1 = threading.Thread(target=receive_stream)
    p2 = threading.Thread(target=detect_and_save)

    p1.start()
    p2.start()

    p1.join()  # 等待接收线程结束
    p2.join()  # 等待检测和保存线程结束

小结

RSTP 具有滞后性 不符合我们需要,第二章我会说海康摄像头驱动

你可能感兴趣的:(python)