百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

利用神经网络模型检测摄像头上的可疑行为

ztj100 2024-12-12 16:14 12 浏览 0 评论

您可能想知道如何检测网络摄像头视频Feed中的可疑行为?我们将使用您计算机的网络摄像头作为视频源,用于训练数据和测试您的神经网络模型。这种方法是使用迁移学习的监督学习。

你需要遵循什么

您应该可以访问安装了以下组件的计算机。

  • Python 3
  • Keras/Tensorflow
  • Pillow (PIL)
  • NumPy
  • CV2

他们都可以通过pip和conda。

虽然,我已经在Mac上测试了这段Python代码,但它应该适用于任何系统。给出的文字转语音是唯一的例外,我以前用它subprocess.call()来调用Mac OS X say命令。您的操作系统上可能有一个等效的命令。

导入Python库

# Create training videos
import cv2
import numpy as np
from time import sleep
import glob
import os
import sys
from PIL import Image
import subprocess
NUM_FRAMES = 100
TAKES_PER = 2
CLASSES = ['SAFE', 'DANGER']
NEG_IDX = 0
POS_IDX = 1
HIDDEN_SIZE = 256
MODEL_PATH='model.h5'
TRAIN_MODEL = True
EPOCHS = 10
HIDDEN_SIZE = 16

准备数据

首先,我们需要一些训练数据来学习。我们需要“可疑”和“安全”行为的视频,因此请准备好行动!为了更容易训练我们的模型,您可以抓住玩具枪或其他可识别的物品来处理“可疑”场景。这样,在没有大量训练数据的情况下,您的模型将更容易分离两个案例。

这是一段Python代码片段,可从计算机的网络摄像头中捕获四个视频(两个可疑和两个安全),并将它们存储在一个data目录中供以后处理。

def capture(num_frames, path='out.avi'):
 
 # Create a VideoCapture object
 cap = cv2.VideoCapture(0)
 # Check if camera opened successfully
 if (cap.isOpened() == False): 
 print("Unable to read camera feed")
 # Default resolutions of the frame are obtained.The default resolutions are system dependent.
 # We convert the resolutions from float to integer.
 frame_width = int(cap.get(3))
 frame_height = int(cap.get(4))
 # Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
 out = cv2.VideoWriter(path, cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
 print('Recording started')
 for i in range(num_frames):
 ret, frame = cap.read()
 if ret == True: 
 # Write the frame into the file 'output.avi'
 out.write(frame)
 # When everything done, release the video capture and video write objects
 cap.release()
 out.release()
 
for take in range(VIDEOS_PER_CLASS):
 for cla in CLASSES:
 path = 'data/{}{}.avi'.format(cla, take)
 print('Get ready to act:', cla)
 # Only works on Mac
 subprocess.call(['say', 'get ready to act {}'.format(cla)])
 capture(FRAMES_PER_VIDEO, path=path)

看看data目录中的视频。你视频根据类别命名,例如SAFE1.avi用于安全视频。

使用预训练的模型从视频中提取特征

接下来,您需要将这些视频转换为机器学习算法可以训练的内容。为此,我们将重新利用经过预训练的VGG16网络,该神经网络已在ImageNet上接受过训练。Python实现如下:

# Create X, y series
from keras.preprocessing import image
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
import numpy as np
class VGGFramePreprocessor():
 
 def __init__(self, vgg_model):
 self.vgg_model = vgg_model
 
 def process(self, frame):
 img_data = cv2.resize(frame,(224,224))
 img_data = np.expand_dims(img_data, axis=0)
 img_data = preprocess_input(img_data)
 x = self.vgg_model.predict(img_data).flatten()
 x = np.expand_dims(x, axis=0)
 return x
def get_video_frames(video_path):
 vidcap = cv2.VideoCapture(video_path)
 success, frame = vidcap.read()
 while success:
 yield frame
 success,frame = vidcap.read()
 vidcap.release()
frame_preprocessor = VGGFramePreprocessor(VGG16(weights='imagenet', include_top=False))
 
if TRAIN_MODEL:
 # Load movies and transform frames to features
 movies = []
 X = []
 y = []
 for video_path in glob.glob('data/*.avi'):
 print('preprocessing', video_path)
 positive = CLASSES[POS_IDX] in video_path
 _X = np.concatenate([frame_preprocessor.process(frame) for frame in get_video_frames(video_path)])
 _y = np.array(_X.shape[0] * [[int(not positive), int(positive)]])
 X.append(_X)
 y.append(_y)
 X = np.concatenate(X)
 y = np.concatenate(y)
 print(X.shape)
 print(y.shape)

训练分类器

现在我们有了X和Y序列,现在是时候训练神经网络模型来区分可疑行为和安全行为了!在此示例中,我们将使用深度神经网络。你可以根据需要进行调整。Python代码如下:

from keras.models import Sequential, load_model
from keras.layers import Dense, Activation, Dropout
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
MODEL_PATH='model.h5'
EPOCHS = 10
HIDDEN_SIZE = 16
if TRAIN_MODEL:
 model = Sequential()
 model.add(Dense(HIDDEN_SIZE, input_shape=(X.shape[1],)))
 model.add(Dense(HIDDEN_SIZE))
 model.add(Dropout(0.2))
 model.add(Dense(len(CLASSES), activation='softmax'))
 model.compile(loss='categorical_crossentropy',
 optimizer='rmsprop',
 metrics=['accuracy'])
 x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=42)
 model.fit(x_train, y_train,
 batch_size=10, epochs=EPOCHS,
 validation_split=0.1)
 model.save(MODEL_PATH)
 y_true = [np.argmax(y) for y in y_test]
 y_pred = [np.argmax(pred) for pred in model.predict(x_test)]
 score = f1_score(y_true, y_pred)
 print('F1:', score) 
else:
 model = load_model(MODEL_PATH)

准备测试!

现在到了有趣的部分。现在我们将使用我们构建的所有部分。是时候将计算机的网络摄像头变成现场CCTV行为检测器了!

# Infer on live video
from math import ceil
import subprocess
TEST_FRAMES = 500
# Initialize camera
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if (cap.isOpened() == False): 
 print("Unable to read camera feed")
 test_frames = 0
# Start processing video
for i in range(TEST_FRAMES):
 ret, frame = cap.read()
 if not ret: continue
 x_pred = frame_preprocessor.process(frame)
 y_pred = model.predict(x_pred)[0]
 conf_negative = y_pred[NEG_IDX]
 conf_positive = y_pred[POS_IDX]
 cla = CLASSES[np.argmax(y_pred)]
 if cla == CLASSES[POS_IDX]:
 subprocess.call(['say', CLASSES[POS_IDX]])
 progress = int(100 * (i / TEST_FRAMES))
 message = 'testing {}% conf_neg = {:.02f} conf_pos = {:.02f} class = {} \r'.format(progress, conf_negative, conf_positive, cla)
 sys.stdout.write(message)
 sys.stdout.flush()
cap.release()

结论

我希望你喜欢这个关于检测CCTV视频中可疑行为的教程。

一个明显的选择是在单一帧或帧序列上训练。为了简单起见,我为这个示例选择了单个帧,因为我们可以跳过一些正交任务,例如缓冲图像和排序训练数据。如果你想训练序列,你可以使用LSTM。

相关推荐

使用Python编写Ping监测程序(python 测验)

Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...

批量ping!有了这个小工具,python再也香不了一点

号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...

python之ping主机(python获取ping结果)

#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...

网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南

太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...

Vue开发中使用iframe(vue 使用iframe)

内容:iframe全屏显示...

Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)

本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...

Vue基础四——Vue-router配置子路由

我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...

Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)

作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...

swiper在vue中正确的使用方法(vue中如何使用swiper)

swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...

Vue怎么实现权限管理?控制到按钮级别的权限怎么做?

在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...

【Vue3】保姆级毫无废话的进阶到实战教程 - 01

作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...

Vue3开发极简入门(13):编程式导航路由

前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...

vue路由同页面重定向(vue路由重定向到外部url)

在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...

那个 Vue 的路由,路由是干什么用的?

在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...

Vue3项目投屏功能开发!(vue投票功能)

最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...

取消回复欢迎 发表评论: