利用神经网络模型检测摄像头上的可疑行为
bigegpt 2024-09-29 09:22 3 浏览
您可能想知道如何检测网络摄像头视频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。
相关推荐
- 有些人能留在你的心里,但不能留在你生活里。
-
有时候,你必须要明白,有些人能留在你的心里,但不能留在你生活里。Sometimes,youhavetorealize,Somepeoplecanstayinyourheart,...
- Python学不会来打我(34)python函数爬取百度图片_附源码
-
随着人工智能和大数据的发展,图像数据的获取变得越来越重要。作为Python初学者,掌握如何从网页中抓取图片并保存到本地是一项非常实用的技能。本文将手把手教你使用Python函数编写一个简单的百度图片...
- 软网推荐:图像变变变 一“软”见分晓
-
当我们仅需要改变一些图片的分辨率、裁减尺寸、添加水印、标注文本、更改图片颜色,或将一种图片转换为另一种格式时,总比较讨厌使用一些大型的图像处理软件,尤其是当尚未安装此类软件时,更是如此。实际上,只需一...
- 首款WP8.1图片搜索应用,搜照片得资料
-
首款WP8.1图片搜索应用,搜照片得资料出处:IT之家原创(天际)2014-11-1114:32:15评论WP之家报道,《反向图片搜索》(ReverseImageSearch)是Window...
- 盗墓笔记电视剧精美海报 盗墓笔记电视剧全集高清种子下载
-
出身“老九门”世家的吴邪,因身为考古学家的父母在某次保护国家文物行动时被国外盗墓团伙杀害,吴家为保护吴邪安全将他送去德国读书,因而吴邪对“考古”事业有着与生俱来的兴趣。在一次护宝过程中他偶然获得一张...
- 微软调整Win11 24H2装机策略:6月起36款预装应用改为完整版
-
IT之家7月16日消息,微软公司今天(7月16日)发布公告,表示自今年6月更新开始,已默认更新Windows1124H2和WindowsServer2025系统中预装...
- 谷歌手把手教你成为谣言终结者 | 域外
-
刺猬公社出品,必属原创,严禁转载。合作事宜,请联系微信号:yunlugongby贾宸琰编译、整理11月23日,由谷歌新闻实验室(GoogleNewsLab)联合Bellingcat、DigD...
- NAS 部署网盘资源搜索神器:全网资源一键搜,免费看剧听歌超爽!
-
还在为找不到想看的电影、电视剧、音乐而烦恼?还在各个网盘之间来回切换,浪费大量时间?今天就教你如何在NAS上部署aipan-netdisk-search,一款强大的网盘资源搜索神器,让你全网资源...
- 使用 Docker Compose 简化 INFINI Console 与 Easysearch 环境搭建
-
前言回顾在上一篇文章《搭建持久化的INFINIConsole与Easysearch容器环境》中,我们详细介绍了如何使用基础的dockerrun命令,手动启动和配置INFINICon...
- 为庆祝杜特尔特到访,这个国家宣布全国放假?
-
(观察者网讯)近日,一篇流传甚广的脸书推文称,为庆祝杜特尔特去年访问印度,印度宣布全国放假,并举办了街头集会以示欢迎。菲媒对此做出澄清,这则消息其实是“假新闻”。据《菲律宾世界日报》2日报道,该贴子...
- 一课译词:毛骨悚然(毛骨悚然的意思是?)
-
PhotobyMoosePhotosfromPexels“毛骨悚然”,汉语成语,意思是毛发竖起,脊梁骨发冷;形容恐惧惊骇的样子(withone'shairstandingonend...
- Bing Overtakes Google in China's PC Search Market, Fueled by AI and Microsoft Ecosystem
-
ScreenshotofBingChinahomepageTMTPOST--Inastunningturnintheglobalsearchenginerace,Mic...
- 找图不求人!6个以图搜图的识图网站推荐
-
【本文由小黑盒作者@crystalz于03月08日发布,转载请标明出处!】前言以图搜图,专业说法叫“反向图片搜索引擎”,是专门用来搜索相似图片、原始图片或图片来源的方法。常用来寻找现有图片的原始发布出...
- 浏览器功能和“油管”有什么关联?为什么要下载
-
现在有没有一款插件可以实现全部的功能,同时占用又小呢,主题主要是网站的一个外观,而且插件则主要是实现wordpress网站的一些功能,它不仅仅可以定制网站的外观,还可以实现很多插件的功能,搭载chro...
- 一周热门
- 最近发表
- 标签列表
-
- mybatiscollection (79)
- mqtt服务器 (88)
- keyerror (78)
- c#map (65)
- xftp6 (83)
- bt搜索 (75)
- c#var (76)
- xcode-select (66)
- mysql授权 (74)
- 下载测试 (70)
- linuxlink (65)
- pythonwget (67)
- androidinclude (65)
- libcrypto.so (74)
- linux安装minio (74)
- ubuntuunzip (67)
- vscode使用技巧 (83)
- secure-file-priv (67)
- vue阻止冒泡 (67)
- jquery跨域 (68)
- php写入文件 (73)
- kafkatools (66)
- mysql导出数据库 (66)
- jquery鼠标移入移出 (71)
- 取小数点后两位的函数 (73)