院子摄像头的监控

院子摄像头的监控和禁止区域入侵检测相比,多了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 入侵截图被保存

 

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

“AI与程序员的共存之路:全球首位AI程序员Devin的诞生及其深远意义“

全球首位AI程序员Devin诞生的深远影响 随着全球首位AI程序员Devin的亮相&#xff0c;一个关于未来技术与人类劳动力关系的讨论再次被推到风口浪尖。AI是否会成为程序员的"同行"&#xff0c;甚至"对手"&#xff0c;引起了业界广泛的关注和讨论。本文将从四个…

基于springboot+vue的个人云盘管理系统

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、阿里云专家博主、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战&#xff0c;欢迎高校老师\讲师\同行交流合作 ​主要内容&#xff1a;毕业设计(Javaweb项目|小程序|Pyt…

基础:TCP四次挥手做了什么,为什么要挥手?

1. TCP 四次挥手在做些什么 1. 第一次挥手 &#xff1a; 1&#xff09;挥手作用&#xff1a;主机1发送指令告诉主机2&#xff0c;我没有数据发送给你了。 2&#xff09;数据处理&#xff1a;主机1&#xff08;可以是客户端&#xff0c;也可以是服务端&#xff09;&#xff0c…

题目:笨笨机器人(蓝桥OJ 3262)

问题描述&#xff1a; 解题思路&#xff1a; 用n位二进制数每位来表示每一步的状态&#xff0c;2的n次幂即使全部可能。遍历计算全部符合题意总数&#xff0c;再用cnt/(2的n次幂&#xff09;即答案。 需要注意的是&#xff0c;四舍五入后四位的方法&#xff1a;round(),可以四舍…

RN导航路由配置

tabbar底部导航栏 安装依赖包 需要安装四个依赖包&#xff08;自己找适配自己RN的导航版本&#xff0c;我这里RN下面的依赖目前都是最新的&#xff0c;如下图所示&#xff09;react-navigation/native 网站 yarn add react-navigation/native yarn add react-navigation/botto…

C++进阶之路---C++11相关特性 | 左值引用 | 右值引用 | 完美转发

顾得泉&#xff1a;个人主页 个人专栏&#xff1a;《Linux操作系统》 《C从入门到精通》 《LeedCode刷题》 键盘敲烂&#xff0c;年薪百万&#xff01; 一、C11简介 在2003年C标准委员会曾经提交了一份技术勘误表(简称TC1)&#xff0c;使得C03这个名字已经取代了C98称为C11之…

网络工程师之路由交换试题篇

网络工程师之路由交换试题篇 试题练习知识点练习方案设计案例一 试题练习 知识点练习 1.局域网和广域网的特点。 2.常见的网络拓扑类型有哪些&#xff0c;简述特点。 3.常见的传输介质有哪些&#xff0c;光纤连接器种类有哪些&#xff0c; 4.VRP系统视图中&#xff0c;用户访…

pcl 凸包ConvexHull

pcl 凸包ConvexHull 头文件等 #include <pcl/surface/convex_hull.h>typedef pcl::PointXYZ PointT; typedef pcl::PointCloud<PointT> CloudT; typedef CloudT::Ptr CP 代码 CP PSO::tubao(CP cloud) {pcl::ConvexHull<PointT> hull;hull.setInputCloud…

Redis入门到实战-第三弹

Redis入门到实战 Redis数据类型官网地址Redis概述Redis数据类型介绍更新计划 Redis数据类型 官网地址 声明: 由于操作系统, 版本更新等原因, 文章所列内容不一定100%复现, 还要以官方信息为准 https://redis.io/Redis概述 Redis是一个开源的&#xff08;采用BSD许可证&#…

【Mysql数据库基础03】分组函数(聚合函数)、分组查询

分组函数(聚合函数&#xff09;、分组查询 0 该博客所要用的数据库表的属性1 分组函数1.1 简单的使用1.2 是否忽略null值1.3 和关键字搭配使用1.4 count函数的详细介绍1.5 练习 2 分组查询Group by2.1 简单的分组查询2.2 练习 3 格式投票:yum: 0 该博客所要用的数据库表的属性 …

树,二叉树与堆

这里写目录标题 树树的概念树的相关概念树的表示 二叉树二叉树的概念满二叉树与完全二叉树二叉树的重要性质二叉树的存储结构 堆二叉树的顺序存储堆的概念堆的实现堆插入和删除数据 树 树的概念 树的概念&#xff1a; 树是一种非线性的数据结构&#xff0c;它是由n&#xff08…

Teable——强大的在线数据电子表格

公众号&#xff1a;【可乐前端】&#xff0c;每天3分钟学习一个优秀的开源项目&#xff0c;分享web面试与实战知识&#xff0c;也有全栈交流学习摸鱼群&#xff0c;期待您的关注! 每天3分钟开源 hi&#xff0c;这里是每天3分钟开源&#xff0c;很高兴又跟大家见面了&#xff0…

在线获取文本列表并集计算器

具体请前往&#xff1a;在线文本并集计算工具

基于STC12C5A60S2系列1T 8051单片机可编程计数阵列CCP/PCA/PWM模块的捕获模式(外部中断)应用

基于STC12C5A60S2系列1T 8051单片机可编程计数阵列CCP/PCA/PWM模块的捕获模式(外部中断)应用 STC12C5A60S2系列1T 8051单片机管脚图STC12C5A60S2系列1T 8051单片机I/O口各种不同工作模式及配置STC12C5A60S2系列1T 8051单片机I/O口各种不同工作模式介绍STC12C5A60S2系列1T 805…

学历提升外贸函电试题及答案,分享几个实用搜题和学习工具 #学习方法#笔记#微信

随着信息技术的快速发展&#xff0c;搜题软件应运而生&#xff0c;为大学生提供了便捷的问题解答方式。 1.九超查题 这个公众号比较有趣&#xff0c;它也是可以搜网课题目&#xff0c;复制题目到窗口即可。 题目解析很详细&#xff0c;题库丰富&#xff0c;有较多的学习资料…

docker desktop 登录不上账号

配置走代理&#xff08;系统全局&#xff09;也没用 解决方法 参考博文&#xff1a; https://blog.csdn.net/weixin_37477009/article/details/135797296 https://adoyle.me/Today-I-Learned/docker/docker-desktop.html 下载 Proxifiler 配置 Proxifiler

掌握这6大工具,自媒体ai写作之路畅通无阻! #知识分享#媒体#科技

从事自媒体运营光靠自己手动操作效率是非常低的&#xff0c;想要提高运营效率就必须要学会合理的使用一些辅助工具。下面小编就跟大家分享一些自媒体常用的辅助工具&#xff0c;觉得有用的朋友可以收藏分享。 1.元芳写作 这是一个微信公众号 面向专业写作领域的ai写作工具&am…

爬虫(七)

1.批量爬取知网数据 lxml:是 Python 的一个功能强大且易用的 XML 和 HTML 处理库。它提供了简单又轻巧的 API,使得解析、构建和操作 XML 和 HTML 文档变得非常方便。lxml 库通常用于处理 XML 和 HTML 文档,例如解析网页、处理配置文件等。openpyxl:是 Python 中用于操作 Ex…

uniapp开发:vue3 中vuex的使用

开发工具HbuilderX3.98 在根目录下创建store目录&#xff0c;并在该目录下创建index.js文件 index.js 文件 /*index.js 文件*/// #ifndef VUE3 import Vue from vue import Vuex from vuex import audio from "/store/modules/audio.js" Vue.use(Vuex) const store…

软件测试-概念

衡量软件测试结果的依据--需求 需求的概念 满足用户期望或正式规定文档(合同, 规范, 标准)所具备的条件或权能, 包含用户需求和软件需求. IEEE:定义: 软件需求是(1)用户解决问题或达到目标所需的条件或权能. (2)系统或系统部件要满足合同, 标准, 规范或其它正式规定文档所具备…