院子摄像头的监控

news2024/9/25 3:26:18

院子摄像头的监控和禁止区域入侵检测相比,多了2个功能:1)如果检测到有人入侵,则把截图保存起来,2)如果检测到有人入侵,则向数据库插入一条事件数据。

      打开checkingfence.py,添加如下代码:

# -*- coding: utf-8 -*-

'''
禁止区域检测主程序
摄像头对准围墙那一侧

用法: 
python checkingfence.py
python checkingfence.py --filename tests/yard_01.mp4
'''

# import the necessary packages
from oldcare.track import CentroidTracker
from oldcare.track import TrackableObject
from imutils.video import FPS
import numpy as np
import imutils
import argparse
import time
import dlib
import cv2
import os
import subprocess

# 得到当前时间
current_time = time.strftime('%Y-%m-%d %H:%M:%S',
                             time.localtime(time.time()))
print('[INFO] %s 禁止区域检测程序启动了.'%(current_time))

# 传入参数
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--filename", required=False, default = '',
    help="")
args = vars(ap.parse_args())

# 全局变量
prototxt_file_path='models/mobilenet_ssd/MobileNetSSD_deploy.prototxt'
# Contains the Caffe deep learning model files. 
#We’ll be using a MobileNet Single Shot Detector (SSD), 
#“Single Shot Detectors for object detection”.
model_file_path='models/mobilenet_ssd/MobileNetSSD_deploy.caffemodel' 
output_fence_path = 'supervision/fence'
input_video = args['filename']
skip_frames = 30 # of skip frames between detections
# your python path
python_path = '/home/reed/anaconda3/envs/tensorflow/bin/python' 

# 超参数
# minimum probability to filter weak detections
minimum_confidence = 0.80 


# 物体识别模型能识别的物体(21种)
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
           "bottle", "bus", "car", "cat", "chair", 
           "cow", "diningtable","dog", "horse", "motorbike", 
           "person", "pottedplant", "sheep","sofa", "train", 
           "tvmonitor"]

# if a video path was not supplied, grab a reference to the webcam
if not input_video:
    print("[INFO] starting video stream...")
    vs = cv2.VideoCapture(0)
    time.sleep(2)
else:
    print("[INFO] opening video file...")
    vs = cv2.VideoCapture(input_video)
    
# 加载物体识别模型
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(prototxt_file_path, model_file_path)



# initialize the frame dimensions (we'll set them as soon as we read
# the first frame from the video)
W = None
H = None

# instantiate our centroid tracker, then initialize a list to store
# each of our dlib correlation trackers, followed by a dictionary to
# map each unique object ID to a TrackableObject
ct = CentroidTracker(maxDisappeared=40, maxDistance=50)
trackers = []
trackableObjects = {}

# initialize the total number of frames processed thus far, along
# with the total number of objects that have moved either up or down
totalFrames = 0
totalDown = 0
totalUp = 0

# start the frames per second throughput estimator
fps = FPS().start()

# loop over frames from the video stream
while True:
    # grab the next frame and handle if we are reading from either
    # VideoCapture or VideoStream
    ret, frame = vs.read()

    # if we are viewing a video and we did not grab a frame then we
    # have reached the end of the video
    if input_video and not ret:
        break
    
    if not input_video:
        frame = cv2.flip(frame, 1)
        
    # resize the frame to have a maximum width of 500 pixels (the
    # less data we have, the faster we can process it), then convert
    # the frame from BGR to RGB for dlib
    frame = imutils.resize(frame, width=500)
    rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # if the frame dimensions are empty, set them
    if W is None or H is None:
        (H, W) = frame.shape[:2]

    # initialize the current status along with our list of bounding
    # box rectangles returned by either (1) our object detector or
    # (2) the correlation trackers
    status = "Waiting"
    rects = []

    # check to see if we should run a more computationally expensive
    # object detection method to aid our tracker
    if totalFrames % skip_frames == 0:
        # set the status and initialize our new set of object trackers
        status = "Detecting"
        trackers = []

        # convert the frame to a blob and pass the blob through the
        # network and obtain the detections
        blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)
        net.setInput(blob)
        detections = net.forward()

        # loop over the detections
        for i in np.arange(0, detections.shape[2]):
            # extract the confidence (i.e., probability) associated
            # with the prediction
            confidence = detections[0, 0, i, 2]

            # filter out weak detections by requiring a minimum
            # confidence
            if confidence > minimum_confidence:
                # extract the index of the class label from the
                # detections list
                idx = int(detections[0, 0, i, 1])

                # if the class label is not a person, ignore it
                if CLASSES[idx] != "person":
                    continue

                # compute the (x, y)-coordinates of the bounding box
                # for the object
                box = detections[0, 0, i, 3:7]*np.array([W, H, W, H])
                (startX, startY, endX, endY) = box.astype("int")
                
                # construct a dlib rectangle object from the bounding
                # box coordinates and then start the dlib correlation
                # tracker
                tracker = dlib.correlation_tracker()
                rect = dlib.rectangle(startX, startY, endX, endY)
                tracker.start_track(rgb, rect)

                # add the tracker to our list of trackers so we can
                # utilize it during skip frames
                trackers.append(tracker)

    # otherwise, we should utilize our object *trackers* rather than
    #object *detectors* to obtain a higher frame processing throughput
    else:
        # loop over the trackers
        for tracker in trackers:
            # set the status of our system to be 'tracking' rather
            # than 'waiting' or 'detecting'
            status = "Tracking"

            # update the tracker and grab the updated position
            tracker.update(rgb)
            pos = tracker.get_position()

            # unpack the position object
            startX = int(pos.left())
            startY = int(pos.top())
            endX = int(pos.right())
            endY = int(pos.bottom())
            
            # draw a rectangle around the people
            cv2.rectangle(frame, (startX, startY), (endX, endY),
                (0, 255, 0), 2)
            
            # add the bounding box coordinates to the rectangles list
            rects.append((startX, startY, endX, endY))

    
    
    
    # draw a horizontal line in the center of the frame -- once an
    # object crosses this line we will determine whether they were
    # moving 'up' or 'down'
    cv2.line(frame, (0, H // 2), (W, H // 2), (0, 255, 255), 2)

    # use the centroid tracker to associate the (1) old object
    # centroids with (2) the newly computed object centroids
    objects = ct.update(rects)

    # loop over the tracked objects
    for (objectID, centroid) in objects.items():
        # check to see if a trackable object exists for the current
        # object ID
        to = trackableObjects.get(objectID, None)

        # if there is no existing trackable object, create one
        if to is None:
            to = TrackableObject(objectID, centroid)

        # otherwise, there is a trackable object so we can utilize it
        # to determine direction
        else:
            # the difference between the y-coordinate of the *current*
            # centroid and the mean of *previous* centroids will tell
            # us in which direction the object is moving (negative for
            # 'up' and positive for 'down')
            y = [c[1] for c in to.centroids]
            direction = centroid[1] - np.mean(y)
            to.centroids.append(centroid)

            # check to see if the object has been counted or not
            if not to.counted:
                # if the direction is negative (indicating the object
                # is moving up) AND the centroid is above the center
                # line, count the object
                if direction < 0 and centroid[1] < H // 2:
                    totalUp += 1
                    to.counted = True

                # if the direction is positive (indicating the object
                # is moving down) AND the centroid is below the
                # center line, count the object
                elif direction > 0 and centroid[1] > H // 2:
                    totalDown += 1
                    to.counted = True
                    
                    current_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                         time.localtime(time.time()))
                    event_desc = '有人闯入禁止区域!!!'
                    event_location = '院子'
                    print('[EVENT] %s, 院子, 有人闯入禁止区域!!!' 
                                                      %(current_time))
                    cv2.imwrite(os.path.join(output_fence_path, 
                                                   'snapshot_%s.jpg' 
                           %(time.strftime('%Y%m%d_%H%M%S'))), frame)
                    
                    # insert into database
                    command = '%s inserting.py --event_desc %s 
                           --event_type 4 --event_location %s' 
                           %(python_path, event_desc, event_location)
                    p = subprocess.Popen(command, shell=True)  

        # store the trackable object in our dictionary
        trackableObjects[objectID] = to

        # draw both the ID of the object and the centroid of the
        # object on the output frame
        text = "ID {}".format(objectID)
        cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        cv2.circle(frame, (centroid[0], centroid[1]), 4, 
                   (0, 255, 0), -1)

    # construct a tuple of information we will be displaying on the
    # frame
    info = [
        #("Up", totalUp),
        ("Down", totalDown),
        ("Status", status),
    ]

    # loop over the info tuples and draw them on our frame
    for (i, (k, v)) in enumerate(info):
        text = "{}: {}".format(k, v)
        cv2.putText(frame, text, (10, H - ((i * 20) + 20)),
            cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    # show the output frame
    cv2.imshow("Prohibited Area", frame)
    
    k = cv2.waitKey(1) & 0xff 
    if k == 27:
        break

    # increment the total number of frames processed thus far and
    # then update the FPS counter
    totalFrames += 1
    fps.update()

# stop the timer and display FPS information
fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed())) # 14.19
print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) # 90.43

# close any open windows
vs.release()
cv2.destroyAllWindows()

执行下行命令即可运行程序:

python checkingfence.py --filename tests/yard_01.mp4

      同学们如果可以把摄像头挂在高处,也可以通过摄像头捕捉画面。程序运行方式如下:

python checkingfence.py

      程序运行结果如下图:

 

image.png

图1 程序运行效果

image.png

图2 程序运行控制台的输出

      supervision/fence目录下出现了入侵的截图。

image.png

图3 入侵截图被保存

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1539399.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2024阿里云学生服务器免费领取申请(2024新版教程)

阿里云学生服务器免费申请&#xff0c;之前是云翼计划学生服务器9元/月&#xff0c;现在是高校计划&#xff0c;学生服务器可以免费申请&#xff0c;先完成学生认证即可免费领取一台云服务器ECS&#xff0c;配置为2核2G、1M带宽、40G系统盘&#xff0c;在云服务器ECS实例过期之…

大学期末考试搜题软件?这4款足够解决问题 #知识分享#笔记#职场发展

当代大学生面临着繁重的学业压力和海量的知识点&#xff0c;如何高效地进行学习和搜题成了他们关注的焦点。幸运的是&#xff0c;随着科技的不断进步&#xff0c;我们有越来越多的日常搜题和学习软件可以帮助我们更好地应对这些挑战。在本文中&#xff0c;我将为大家介绍10款备…

软考复习笔记day3(计算机体系结构和指令系统基础)(精简版)

计算机体系结构分类 处理机数量分类&#xff1a; 单处理&#xff08;一个处理单元&#xff09;并行处理系统&#xff08;两个以上处理机互联&#xff09;.分布式处理系统 Flynn分类&#xff1a;&#xff08;常考&#xff09; 以指令流和数据流进行区别 指令流由控制部分进…

day03_mysql_课后练习 - 参考答案

文章目录 day03_mysql_课后练习mysql练习题第1题第2题第3题第4题第5题 day03_mysql_课后练习 mysql练习题 第1题 案例&#xff1a; 1、创建一个数据库&#xff1a;day03_test01_school 2、创建如下表格 表1 Department表的定义 字段名字段描述数据类型主键外键非空唯一D…

算法 之 排序算法

&#x1f389;欢迎大家观看AUGENSTERN_dc的文章(o゜▽゜)o☆✨✨ &#x1f389;感谢各位读者在百忙之中抽出时间来垂阅我的文章&#xff0c;我会尽我所能向的大家分享我的知识和经验&#x1f4d6; &#x1f389;希望我们在一篇篇的文章中能够共同进步&#xff01;&#xff01;&…

总结 | vue3项目初始化(附相应链接)

如何运行 vue 项目&#xff1a;vscode运行vue项目_vscode启动vue项目命令-CSDN博客 vue3项目搭建 目录管理 git管理&#xff1a;vue3项目搭建并git管理_git 新建vue3项目-CSDN博客 目录调整&#xff1a;vue3项目 - 目录调整-CSDN博客 vscode中快速生成vue3模板&#xff1a…

12 Games101 - 笔记 - 几何(网格处理)、阴影图

12 几何&#xff08;网格处理&#xff09;、阴影图 曲面细分 曲面细分是指将一个模型的面合理的分成更多小的面&#xff0c;从而提升模型精度&#xff0c;使模型越来越光滑&#xff0c;提高渲染效果。 Loop细分 Loop细分是指Loop提出来的细分规则&#xff0c;只能针对于三角…

中等职业学校大数据课程建设方案

大数据产业是以数据及数据所蕴含的信息价值为核心生产要素&#xff0c;通过数据技术、数据产品、数据服务等形式&#xff0c;使数据与信息价值在各行业经济活动中得到充分释放的赋能型产业。 大数据产业定义一般分为核心业态、关联业态、衍生业态三大业态。 一、专…

【Entity Framework】 EF中DbContext类详解

【Entity Framework】 EF中DbContext类详解 一、概述 DbContext类是实体框架的重要组成部分。它是应用域或实例类与数据库交互的桥梁。 从上图可以看出DbContext是负责与数据交互作为对象的主要类。DbContext负责以下活动&#xff1a; EntitySet&#xff1a;DbContext包含…

golang sync.Map之如何设计一个并发安全的读写分离结构?

在 golang中&#xff0c;想要并发安全的操作map&#xff0c;可以使用sync.Map结构&#xff0c;sync.Map 是一个适合读多写少的数据结构&#xff0c;今天我们来看看它的设计思想&#xff0c;来看看为什么说它适合读多写少的场景。 如下&#xff0c;是golang 中sync.Map的数据结构…

Oracle数据库如果出现乱码,需要查看是否时字符集不一致导致乱码,这样解决

1、如果出现乱码&#xff0c;需要查看是否时字符集不一致导致乱码 以修改为ZHS16GBK字符集为例&#xff0c;具体字符集需要sql查询。 Oracle查看字符集 SELECT * FROM NLS_DATABASE_PARAMETERS p where p.PARAMETERNLS_CHARACTERSET; SELECT USERENV(language) FROM DUAL; 1.…

机器人路径规划:基于斑翠鸟优化算法(Pied Kingfisher Optimizer ,PKO)的机器人路径规划(提供MATLAB代码)

一、机器人路径规划介绍 移动机器人&#xff08;Mobile robot&#xff0c;MR&#xff09;的路径规划是 移动机器人研究的重要分支之&#xff0c;是对其进行控制的基础。根据环境信息的已知程度不同&#xff0c;路径规划分为基于环境信息已知的全局路径规划和基于环境信息未知或…

视频素材库哪个好?这8个短视频相关的优质素材网推荐看看

在这个数字化时代&#xff0c;视频内容的创作变得前所未有地重要。无论是短视频的快速制作&#xff0c;还是专业影片的精心编辑&#xff0c;找到合适的素材资源是每个视频创作者的基本需求。从高清视频片段、无水印的图片&#xff0c;到富有情感的音效&#xff0c;以下精选的网…

Java应用常见log框架介绍以及 如何用好Log

前言 合理使用日志对于Java应用程序的开发、部署和维护都至关重要。通过采用良好的日志记录实践,可以更好地监控应用程序的运行状况、排查问题并优化性能 日志系统与日志框架 日志系统 直接负责打印输出日志&#xff0c;提供完整的日志输出能力&#xff1a; JUL java.uti…

栅格地图路径规划:4种最新算法(小龙虾优化算法COA、螳螂搜索算法MSA、红尾鹰算法RTH、霸王龙优化算法TROA)求解机器人路径规划(提供MATLAB代码)

一、机器人路径规划介绍 移动机器人&#xff08;Mobile robot&#xff0c;MR&#xff09;的路径规划是 移动机器人研究的重要分支之&#xff0c;是对其进行控制的基础。根据环境信息的已知程度不同&#xff0c;路径规划分为基于环境信息已知的全局路径规划和基于环境信息未知或…

RIPGeo代码理解(七)test.py(加载检查点,然后测试)

​代码链接:RIPGeo代码实现 ├── preprocess.py # 预处理数据集并为模型运行执行IP聚类 ├── main.py # 运行模型进行训练和测试 ├── test.py #加载检查点,然后测试 一、导入各种模块和数据库 import torch.nnfrom lib.utils import * import argparse import…

paddlepaddle框架构建数据集进行分类问题的时候,会发现数据集在构建的过程中不会构建标签(花分类)

问题描述 在做一个paddlepaddle项目的时候&#xff0c;需要使用神经网络对他进行分类&#xff0c;数据集的结构如下图&#xff0c;这时候我们可以使用常用dataset方法对数据集进行构建。 这时候我们就会发现一个问题&#xff0c;就是这个矿建不是构建标签&#xff0c;也就是说…

IM系统设计之websocket消息转发

Websocket消息转发 项目地址&#xff1a;gitgithub.com:muyixiaoxi/Link.git 上周面试被面试官问到&#xff1a;“在分布式IM系统中&#xff0c;如何实现多个websocket集群之间的通信”。 我在思考了良久后回答&#xff1a;“不会”。 随着我的回答&#xff0c;我和面试官的…

【C++航海王:追寻罗杰的编程之路】stack

目录 1 -> stack的介绍和使用 1.1 -> stack的介绍 1.2 -> stack的使用 1.3 -> stack的模拟实现 1 -> stack的介绍和使用 1.1 -> stack的介绍 stack的文档介绍 1. stack是一种容器适配器&#xff0c;专门用在具有后进先出操作的上下文环境中&#xff0c…

React【Day1】

B站视频链接 一、React介绍 React由Meta公司开发&#xff0c;是一个用于 构建Web和原生交互界面的库 React的优势 相较于传统基于DOM开发的优势 组件化的开发方式不错的性能 相较于其它前端框架的优势 丰富的生态跨平台支持 React的市场情况 全球最流行&#xff0c;大…