深度学习-智能视频监控
深度學習-智能視頻監控
Deep Surveillance with Deep Learning – Intelligent Video Surveillance
原文地址:
https://data-flair.training/blogs/deep-surveillance-with-deep-learning-intelligent-video-surveillance-project/
監視安全是一項非常乏味和耗時的工作。在本文中,將構建一個自動分析視頻監視任務的系統。將實時分析視頻反饋,并識別任何異常活動,如暴力或盜竊。
其中,視頻監控行業正在進行大量的研究,央視視頻的作用已經過大。監控和保安的地方到處都有閉路電視攝像機。
近十年來,用于深度監視的深度學習算法有了很大的發展。這些進展已顯示出深入監視的一個基本趨勢,并有望大幅提高效率。深度監視的典型應用是盜竊識別、暴力檢測和爆炸機會檢測。
Intelligent Video Surveillance with Deep Learning
將使用時空編碼器來識別異常活動。
網絡架構
通常看到用于計算機視覺、圖像分類和目標檢測任務的深層神經網絡。在這個項目中,必須將深度神經網絡擴展到三維,以學習視頻饋送的時空特征。
針對這個視頻監控項目,將介紹一種基于三維卷積網絡的時空自動編碼器。編碼器部分提取空間和時間信息,然后解碼器重構幀。利用重建批次與原始批次之間的歐氏距離計算重建損失,識別異常事件。
視頻監控異常事件檢測數據集 The dataset for abnormal event detection
in video surveillance
以下是用于訓練異常檢測任務模型的綜合數據集。
CUHK Avenue Dataset
這個數據集包含16個訓練和21個測試視頻片段。視頻總共包含30652幀。
訓練視頻包含正常情況下的視頻。測試視頻包含標準和異常事件視頻。
數據集下載鏈接:
http://www.cse.cuhk.edu.hk/leojia/projects/detectabnormal/dataset.html
UCSD pedestrian Dataset
這個數據集包含行人視頻。包括一組走向、離開和平行于攝像機的人。
異常事件包括
非行人實體
異常行人運動模式
數據集下載鏈接:http://www.svcl.ucsd.edu/projects/anomaly/dataset.html
Project Source Code
在繼續之前,請下載在這個深度學習項目中使用的源代碼:視頻監控項目代碼
Video Surveillance – Anomaly Even Detection
Code
視頻監控-異常偶數檢測代碼:
首先,下載上述任何一個數據集并將其放入名為“train”的目錄中。
生成新的python文件train.py并粘貼以下步驟中描述的代碼:
一. Imports
-
from keras.preprocessing.image import
img_to_array,load_img -
import numpy as np
-
import glob
-
import os
-
from scipy.misc import imresize
-
from keras.layers import
Conv3D,ConvLSTM2D,Conv3DTranspose -
from keras.models import Sequential
-
from keras.callbacks import ModelCheckpoint,
EarlyStopping -
import imutils
二. 初始化目錄路徑變量并描述處理和存儲視頻幀的函數Initialize directory path variable and describe a function to process and store video frames:
-
store_image=[]
-
train_path=’./train’
-
fps=5
-
trian_videos=os.listdir(‘train_path’)
-
train_images_path=train_path+’/frames’
-
os.makedir(train_images_path)
-
def store_inarray(image_path)
-
image=load_img(image_path)
-
image=img_to_array(image)
-
image=cv2.resize(image, (227,227), interpolation = cv2.INTER_AREA)
-
gray=0.2989image[:,:,0]+0.5870image[:,:,1]+0.1140*image[:,:,2]
-
store_image.append(gray)
三. Extract frames from video and call store function:
-
from video and call store function
-
for video in train_videos:
-
os.system( ‘ffmpeg -i {}/{} -r 1/{} {}/frames/%03d.jpg’.format(train_path,video,fps,train_path))
-
images=os.listdir(train_images_path)
-
for image in images:
-
image_path=framepath+ ‘/’+ image
-
store_inarray(image_path)
四. Store the store_image list in a numpy file “training.npy”
-
store_image=np.array(store_image)
-
a,b,c=store_image.shape
-
store_image.resize(b,c,a)
-
store_image=(store_image-store_image.mean())/(store_image.std())
-
store_image=np.clip(store_image,0,1)
-
np.save(‘training.npy’,store_image)
五. Create spatial autoencoder architecture
-
stae_model=Sequential()
-
stae_model.add(Conv3D(filters=128,kernel_size=(11,11,1),strides=(4,4,1),padding=‘valid’,input_shape=(227,227,10,1),activation=‘tanh’))
-
stae_model.add(Conv3D(filters=64,kernel_size=(5,5,1),strides=(2,2,1),padding=‘valid’,activation=‘tanh’))
-
stae_model.add(ConvLSTM2D(filters=64,kernel_size=(3,3),strides=1,padding=‘same’,dropout=0.4,recurrent_dropout=0.3,return_sequences=True))
-
stae_model.add(ConvLSTM2D(filters=32,kernel_size=(3,3),strides=1,padding=‘same’,dropout=0.3,return_sequences=True))
-
stae_model.add(ConvLSTM2D(filters=64,kernel_size=(3,3),strides=1,return_sequences=True, padding=‘same’,dropout=0.5))
-
stae_model.add(Conv3DTranspose(filters=128,kernel_size=(5,5,1),strides=(2,2,1),padding=‘valid’,activation=‘tanh’))
-
stae_model.add(Conv3DTranspose(filters=1,kernel_size=(11,11,1),strides=(4,4,1),padding=‘valid’,activation=‘tanh’))
-
stae_model.compile(optimizer=‘adam’,loss=‘mean_squared_error’,metrics=[‘accuracy’])
六. Train the autoencoder on the “training.npy” file and save the model with name “saved_model.h5”
-
training_data=np.load(‘training.npy’)
-
frames=training_data.shape[2]
-
frames=frames-frames%10
-
training_data=training_data[:,:,:frames]
-
training_data=training_data.reshape(-1,227,227,10)
-
training_data=np.expand_dims(training_data,axis=4)
-
target_data=training_data.copy()
-
epochs=5
-
batch_size=1
-
callback_save = ModelCheckpoint(“saved_model.h5”, monitor=“mean_squared_error”, save_best_only=True)
-
callback_early_stopping = EarlyStopping(monitor=‘val_loss’, patience=3)
-
stae_model.fit(training_data,target_data,
batch_size=batch_size, epochs=epochs, callbacks = [callback_save,callback_early_stopping]) -
stae_model.save(“saved_model.h5”)
運行此腳本以訓練并保存自動編碼器模型。
現在制作另一個python文件“train.py“并在任何自定義視頻上觀察異常事件檢測的結果。將下面的代碼粘貼到“train.py”
import cv2
import numpy as np
from keras.models import load_model
import argparse
from PIL import Image
import imutils
def mean_squared_loss(x1,x2):
difference=x1-x2
a,b,c,d,e=difference.shape
n_samples=abcde
sq_difference=difference**2
Sum=sq_difference.sum()
distance=np.sqrt(Sum)
mean_distance=distance/n_samples
return mean_distance
model=load_model(“saved_model.h5”)
cap = cv2.VideoCapture("__path_to_custom_test_video")
print(cap.isOpened())
while cap.isOpened():
imagedump=[]
ret,frame=cap.read()
for i in range(10):
ret,frame=cap.read()
image = imutils.resize(frame,width=700,height=600)
frame=cv2.resize(frame, (227,227), interpolation =
cv2.INTER_AREA)
gray=0.2989frame[:,:,0]+0.5870frame[:,:,1]+0.1140*frame[:,:,2]
gray=(gray-gray.mean())/gray.std()
gray=np.clip(gray,0,1)
imagedump.append(gray)
imagedump=np.array(imagedump)
imagedump.resize(227,227,10)
imagedump=np.expand_dims(imagedump,axis=0)
imagedump=np.expand_dims(imagedump,axis=4)
output=model.predict(imagedump)
loss=mean_squared_loss(imagedump,output)
if frame.any()==None:
print(“none”)
if cv2.waitKey(10) & 0xFF==ord(‘q’):
break
if loss>0.00068:
print(‘Abnormal Event Detected’)
cv2.putText(image,“Abnormal Event”,(100,80),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),4)
cv2.imshow(“video”,image)
cap.release()
cv2.destroyAllWindows()
現在,運行這個腳本并觀察視頻監控的結果,將突出顯示異常事件。
Summary
在這個深度學習項目中,訓練一個異常事件偵測的自動編碼器。在普通視頻上訓練自動編碼器。根據自定義視頻源的歐氏距離和自動編碼器預測的幀來識別異常事件。
為異常事件設置了一個閾值。在這個項目中,是0.0068;可以改變這個閾值來實驗獲得更好的結果。
總結
以上是生活随笔為你收集整理的深度学习-智能视频监控的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GPU上创建目标检测Pipeline管道
- 下一篇: CUDA 8混合精度编程