ucf_crime / ucf_crime.py
jinmang2's picture
size Mb -> Kb
2e26f27
import os
import datasets
_HOMEPAGE = "https://www.crcv.ucf.edu/projects/real-world/"
_CITATION = """
@InProceedings{Sultani_2018_CVPR,
author={Sultani, Waqas and Chen, Chen and Shah, Mubarak},
title={Real-World Anomaly Detection in Surveillance Videos},
booktitle={The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
month={June},
year={2018},
}
"""
_LICENSE = "CC0"
_DESCRIPTION = """
# Real-world Anomaly Detection in Surveillance Videos
Surveillance videos are able to capture a variety of realistic anomalies. In this paper, we propose to learn anomalies by exploiting both normal and anomalous videos. To avoid annotating the anomalous segments or clips in training videos, which is very time consuming, we propose to learn anomaly through the deep multiple instance ranking framework by leveraging weakly labeled training videos, i.e. the training labels (anomalous or normal) are at video-level instead of clip-level. In our approach, we consider normal and anomalous videos as bags and video segments as instances in multiple instance learning (MIL), and automatically learn a deep anomaly ranking model that predicts high anomaly scores for anomalous video segments. Furthermore, we introduce sparsity and temporal smoothness constraints in the ranking loss function to better localize anomaly during training.
We also introduce a new large-scale first of its kind dataset of 128 hours of videos. It consists of 1900 long and untrimmed real-world surveillance videos, with 13 realistic anomalies such as fighting, road accident, burglary, robbery, etc. as well as normal activities. This dataset can be used for two tasks. First, general anomaly detection considering all anomalies in one group and all normal activities in another group. Second, for recognizing each of 13 anomalous activities. Our experimental results show that our MIL method for anomaly detection achieves significant improvement on anomaly detection performance as compared to the state-of-the-art approaches. We provide the results of several recent deep learning baselines on anomalous activity recognition. The low recognition performance of these baselines reveals that our dataset is very challenging and opens more opportunities for future work.
# Problem & Motivation
One critical task in video surveillance is detecting anomalous events such as traffic accidents, crimes or illegal activities. Generally, anomalous events rarely occur as compared to normal activities. Therefore, to alleviate the waste of labor and time, developing intelligent computer vision algorithms for automatic video anomaly detection is a pressing need. The goal of a practical anomaly detection system is to timely signal an activity that deviates normal patterns and identify the time window of the occurring anomaly. Therefore, anomaly detection can be considered as coarse level video understanding, which filters out anomalies from normal patterns. Once an anomaly is detected, it can further be categorized into one of the specific activities using classification techniques.
In this work, we propose an anomaly detection algorithm using weakly labeled training videos. That is we only know the video-level labels, i.e. a video is normal or contains anomaly somewhere, but we do not know where. This is intriguing because we can easily annotate a large number of videos by only assigning video-level labels. To formulate a weakly-supervised learning approach, we resort to multiple instance learning. Specifically, we propose to learn anomaly through a deep MIL framework by treating normal and anomalous surveillance videos as bags and short segments/clips of each video as instances in a bag. Based on training videos, we automatically learn an anomaly ranking model that predicts high anomaly scores for anomalous segments in a video. During testing, a longuntrimmed video is divided into segments and fed into our deep network which assigns anomaly score for each video segment such that an anomaly can be detected.
# Method
Our proposed approach (summarized in Figure 1) begins with dividing surveillance videos into a fixed number of segments during training. These segments make instances in a bag. Using both positive (anomalous) and negative (normal) bags, we train the anomaly detection model using the proposed deep MIL ranking loss.
https://www.crcv.ucf.edu/projects/real-world/method.png
# UCF-Crime Dataset
We construct a new large-scale dataset, called UCF-Crime, to evaluate our method. It consists of long untrimmed surveillance videos which cover 13 realworld anomalies, including Abuse, Arrest, Arson, Assault, Road Accident, Burglary, Explosion, Fighting, Robbery, Shooting, Stealing, Shoplifting, and Vandalism. These anomalies are selected because they have a significant impact on public safety. We compare our dataset with previous anomaly detection datasets in Table 1. For more details about the UCF-Crime dataset, please refer to our paper. A short description of each anomalous event is given below.
Abuse: This event contains videos which show bad, cruel or violent behavior against children, old people, animals, and women.
Burglary: This event contains videos that show people (thieves) entering into a building or house with the intention to commit theft. It does not include use of force against people.
Robbery: This event contains videos showing thieves taking money unlawfully by force or threat of force. These videos do not include shootings.
Stealing: This event contains videos showing people taking property or money without permission. They do not include shoplifting.
Shooting: This event contains videos showing act of shooting someone with a gun.
Shoplifting: This event contains videos showing people stealing goods from a shop while posing as a shopper.
Assault: This event contains videos showing a sudden or violent physical attack on someone. Note that in these videos the person who is assaulted does not fight back.
Fighting: This event contains videos displaying two are more people attacking one another.
Arson: This event contains videos showing people deliberately setting fire to property.
Explosion: This event contains videos showing destructive event of something blowing apart. This event does not include videos where a person intentionally sets a fire or sets off an explosion.
Arrest: This event contains videos showing police arresting individuals.
Road Accident: This event contains videos showing traffic accidents involving vehicles, pedestrians or cyclists.
Vandalism: This event contains videos showing action involving deliberate destruction of or damage to public or private property. The term includes property damage, such as graffiti and defacement directed towards any property without permission of the owner.
Normal Event: This event contains videos where no crime occurred. These videos include both indoor (such as a shopping mall) and outdoor scenes as well as day and night-time scenes.
https://www.crcv.ucf.edu/projects/real-world/dataset_table.png
https://www.crcv.ucf.edu/projects/real-world/method.png
"""
_DATA_URLS = {
"anomaly-part1": "Anomaly-Videos-Part-1.zip",
"anomaly-part2": "Anomaly-Videos-Part-2.zip",
"anomaly-part3": "Anomaly-Videos-Part-3.zip",
"anomaly-part4": "Anomaly-Videos-Part-4.zip",
"normal-test": "Testing_Normal_Videos.zip",
"normal-train-part1": "Training-Normal-Videos-Part-1.zip",
"normal-train-part2": "Training-Normal-Videos-Part-2.zip",
"normal-event-recognition": "Normal_Videos_for_Event_Recognition.zip",
# 5 Videos for test load
# --> Abuse001_x264.mp4, Arrest002_x264.mp4, Arson003_x264.mp4
# --> Assault004_x264.mp4, Normal_Videos_050_x264.mp4
"test": "test.zip",
}
_SPLIT_PATH = "UCF_Crimes-Train-Test-Split/"
_SPLIT_FILES = {
"event_recognition": {
"train": {
f"event{i}": _SPLIT_PATH + f"Action_Recognition_splits/train_{i:03}.txt"
for i in range(1, 5)
},
"test": {
f"event{i}": _SPLIT_PATH + f"Action_Recognition_splits/test_{i:03}.txt"
for i in range(1, 5)
},
},
"anomaly_detection": {
"train": {"anomaly": _SPLIT_PATH + "Anomaly_Detection_splits/Anomaly_Train.txt"},
"test": {"anomaly": _SPLIT_PATH + "Anomaly_Detection_splits/Anomaly_Test.txt"},
},
"temporal_anomaly": {
"train": [_SPLIT_PATH + "Temporal_Anomaly_Annotation_for_Testing_Videos.txt"],
},
}
_NAMES = [
"Normal",
"Abuse", "Arrest", "Arson", "Assault",
"Burglary", "Explosion", "Fighting",
"RoadAccidents", "Robbery", "Shooting",
"Shoplifting", "Stealing", "Vandalism",
]
_ANOMALIES = ["Normal", "Abnormal"]
video_frames = datasets.Features(
{
"video_path": datasets.Value("string"),
"event": datasets.features.ClassLabel(names=_NAMES),
"anomaly": datasets.features.ClassLabel(names=_ANOMALIES),
"size": datasets.features.Value("uint32"),
}
)
class UCFCrimeConfig(datasets.BuilderConfig):
def __init__(
self,
data_urls: str = _DATA_URLS,
split_files: str = _SPLIT_FILES,
**kwargs,
):
super().__init__(**kwargs)
self.data_urls = data_urls
self.split_files = split_files
self.features = video_frames
class UCFCrime(datasets.GeneratorBasedBuilder):
DEFAULT_CONFIG_NAME = "all"
BUILDER_CONFIG_CLASS = UCFCrimeConfig
BUILDER_CONFIGS = [
UCFCrimeConfig(name="all"),
UCFCrimeConfig(name="anomaly"),
*[UCFCrimeConfig(name=f"event{i}") for i in range(1, 5)],
UCFCrimeConfig(name="test"), # For speed-loading
]
def _info(self):
return datasets.DatasetInfo(
features=self.config.features,
description=_DESCRIPTION,
citation=_CITATION,
homepage=_HOMEPAGE,
license=_LICENSE,
)
def _split_generators(self, dl_manager):
"""Return SplitGenerators."""
data_urls = self.config.data_urls
split_url = None
if self.config.name != "test":
data_urls.pop("test")
if "event" in self.config.name:
data_urls.pop("normal-train-part1")
data_urls.pop("normal-train-part2")
data_urls.pop("normal-test")
split_url = _SPLIT_FILES["event_recognition"]
elif "anomaly" == self.config.name:
data_urls.pop("normal-event-recognition")
split_url = _SPLIT_FILES["anomaly_detection"]
data_urls = data_urls
else:
data_urls = {"test": data_urls["test"]}
path = dl_manager.download(data_urls)
if split_url is not None:
split_path = dl_manager.download(split_url)
if self.config.name in ("all", "test"):
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"extracted": dl_manager.extract(path),
"split_path": split_url,
},
),
]
elif self.config.name in ("anomaly", *[f"event{i}" for i in range(1, 5)]):
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"extracted": dl_manager.extract(path),
"split_path": split_path["train"][self.config.name],
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"extracted": dl_manager.extract(path),
"split_path": split_path["test"][self.config.name],
},
),
]
def _generate_examples(self, extracted: str, split_path: dict):
"""Yields example."""
idx = 0
split_files = []
if split_path is not None:
with open(split_path, "r") as f:
split_files = [line.strip().split(os.sep)[-1] for line in f.readlines()]
for extracted_path in extracted.values():
for root, _, files in os.walk(extracted_path, topdown=False):
for name in files:
if name.endswith(".mp4"):
absolute_file_path = os.path.join(root, name)
if split_path and name not in split_files:
continue
label = root.split(os.sep)[-1]
if "normal" in label.lower():
label = "Normal"
yield idx, {
"video_path": absolute_file_path,
"event": label,
"anomaly": "Abnormal" if label != "Normal" else label,
"size": os.path.getsize(absolute_file_path) // 1024,
}
idx += 1