Giter Site home page Giter Site logo

anomalyclip's Introduction

Paper Website

Delving into CLIP latent space for Video Anomaly Recognition

Luca Zanella*, Benedetta Liberatori*, Willi Menapace, Fabio Poiesi, Yiming Wang, Elisa Ricci
* denotes equal contribution


Abstract: We tackle the complex problem of detecting and recognising anomalies in surveillance videos at the frame level, utilising only video-level supervision. We introduce the novel method AnomalyCLIP, the first to combine Large Language and Vision (LLV) models, such as CLIP, with multiple instance learning for joint video anomaly detection and classification. Our approach specifically involves manipulating the latent CLIP feature space to identify the normal event subspace, which in turn allows us to effectively learn text-driven directions for abnormal events. When anomalous frames are projected onto these directions, they exhibit a large feature magnitude if they belong to a particular class. We also introduce a computationally efficient Transformer architecture to model short- and long-term temporal dependencies between frames, ultimately producing the final anomaly score and class prediction probabilities. We compare AnomalyCLIP against state-of-the-art methods considering three major anomaly detection benchmarks, i.e., ShanghaiTech, UCF-Crime, and XD-Violence, and empirically show that it outperforms baselines in recognising video anomalies.

Setup

We recommend the use of a Linux machine with CUDA compatible GPUs. We provide both a Conda environment and a Dockerfile to configure the required libraries.

Clone the repo with:

git clone https://github.com/luca-zanella-dvl/AnomalyCLIP
cd AnomalyCLIP

Conda

The environment can be installed and activated with:

conda create --name anomalyclip python=3.8
conda activate anomalyclip
pip install -r requirements.txt

Docker

Use the Dockerfile to build the docker image:

docker build -t anomalyclip -f docker/Dockerfile .

Run the docker image by mounting the project root to /usr/src/app and the datasets folder to /usr/src/datasets in the docker container:

docker run --gpus '"device=0"' --rm -it -v /path/to/directory/AnomalyCLIP/:/usr/src/app -v /path/to/directory/datasets/:/usr/src/datasets anomalyclip /bin/bash

Preparing Datasets

Pre-extracted Features

We recommend to use pre-extracted features to accelerate training. Please download the extracted Vit-B/16 features for ShanghaiTech, UCF-Crime and XD-Violence datasets from links below:

Dataset Feature Backbone Link
ShanghaiTech ViT-B/16-CLIP Google Drive
UCF-Crime ViT-B/16-CLIP Google Drive
XD-Violence ViT-B/16-CLIP Google Drive

and place them in the /path/to/directory/datasets folder.

Pretrained Models

Pretrained models are available for all the datasets and can be downloaded at the following Google Drive link.

Please place the checkpoints folder under the project root folder.

Training

To train AnomalyCLIP on ShanghaiTech, UCF-Crime and XD-Violence using the pre-extracted features, run the following bash script:

python src/train.py experiment=<dataset_name>

choosing dataset_name from one of shanghaitech, ucfcrime and xdviolence.

To train AnomalyCLIP on ShanghaiTech, UCF-Crime and XD-Violence from frames, run the following bash script:

python src/train.py experiment=<dataset_name> data.load_from_features=False data.frames_root=/path/to/directory/frames/ data.frames_root_val=/path/to/directory/frames/

after extracting frames from video data in the folder /path/to/directory/frames/.

Evaluation

The trained models can be evaluated on the dataset of interest by running the following bash script:

python src/eval.py model=anomaly_clip_<dataset_name> data=<dataset_name> ckpt_path=/path/to/checkpoints/<dataset_name>/last.ckpt

Citation

Please consider citing our paper in your publications if the project helps your research.

@article{zanella2023delving,
  title={Delving into CLIP latent space for Video Anomaly Recognition},
  author={Zanella, Luca and Liberatori, Benedetta and Menapace, Willi and Poiesi, Fabio and Wang, Yiming and Ricci, Elisa},
  journal={arXiv preprint arXiv:2310.02835},
  year={2023}
}

anomalyclip's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

anomalyclip's Issues

Running an error.

Hello, your work is excellent. I have downloaded the code and deployed the environment according to the process you provided. However, I encountered the following error while further trying to utilize the command test dataset:

[2023-11-09 10:46:55,253][__main__][INFO] - Instantiating datamodule <src.data.anomaly_clip_datamodule.AnomalyCLIPDataModule>
[2023-11-09 10:46:55,286][__main__][INFO] - Instantiating model <src.models.anomaly_clip_module.AnomalyCLIPModule>
[2023-11-09 10:46:59,655][src.utils.utils][ERROR] - 
Traceback (most recent call last):
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/utils.py", line 644, in _locate
    obj = getattr(obj, part)
AttributeError: module 'src.models.components' has no attribute 'anomaly_clip'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/utils.py", line 650, in _locate
    obj = import_module(mod)
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 843, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/src/models/components/anomaly_clip.py", line 8, in <module>
    from src.models.components.clip import clip
  File "/remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/src/models/components/clip/__init__.py", line 1, in <module>
    from .clip import *
  File "/remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/src/models/components/clip/clip.py", line 14, in <module>
    from .simple_tokenizer import SimpleTokenizer as _Tokenizer
  File "/remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/src/models/components/clip/simple_tokenizer.py", line 7, in <module>
    import regex as re
ModuleNotFoundError: No module named 'regex'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 134, in _resolve_target
    target = _locate(target)
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/utils.py", line 653, in _locate
    raise ImportError(
ImportError: Error loading 'src.models.components.anomaly_clip.AnomalyCLIP':
ModuleNotFoundError("No module named 'regex'")
Are you sure that 'anomaly_clip' is importable from module 'src.models.components'?

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/src/utils/utils.py", line 65, in wrap
    metric_dict, object_dict = task_func(cfg=cfg)
  File "src/eval.py", line 52, in evaluate
    model: LightningModule = hydra.utils.instantiate(cfg.model)
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 226, in instantiate
    return instantiate_node(
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 342, in instantiate_node
    value = instantiate_node(
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 333, in instantiate_node
    _target_ = _resolve_target(node.get(_Keys.TARGET), full_key)
  File "/root/anaconda3/envs/anomalyclip/lib/python3.8/site-packages/hydra/_internal/instantiate/_instantiate2.py", line 139, in _resolve_target
    raise InstantiationException(msg) from e
hydra.errors.InstantiationException: Error locating target 'src.models.components.anomaly_clip.AnomalyCLIP', set env var HYDRA_FULL_ERROR=1 to see chained exception.
full_key: model.net
[2023-11-09 10:46:59,671][src.utils.utils][INFO] - Output dir: /remote-home/share/dmb_nas/wy/docker/coding/big_VAD/AnomalyCLIP-main/logs/eval/runs/2023-11-09_10-46-54
Error executing job with overrides: ['model=anomaly_clip_shanghaitech', 'data=shanghaitech', 'ckpt_path=ckpt/checkpoints/shanghaitech/last.ckpt']
Error locating target 'src.models.components.anomaly_clip.AnomalyCLIP', set env var HYDRA_FULL_ERROR=1 to see chained exception.
full_key: model.net

Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.

I am unable to resolve it and have no clue, I would like to hear from you.

ShanghaiTech anomaly labels

Hello! Great work.
I am wondering, how did you generate label files for ShanghaiTech dataset, as in original dataset only normal/anomaly labels are available for test split. I saw in this reply that you are planning to release the code, but it's still not available. Thanks!

Question regarding the preprocessing of image

Good work! May I know what's the preprocessing step to get feature that you've provided?
The following are the snippet of the code that I've used to extract the features, but I realized that the features extracted by the clip is not the same as what you've uploaded.

I've compared the features encoded by the clip and your uploaded feature but it's not the same.
provided_feat.txt
clip_extracted.txt

from src.models.components.anomaly_clip import AnomalyCLIP
import yaml
import torch
from PIL import Image
from src.utils.augmentations import get_augmentations
import glob
import math
import numpy as np
import imageio
from PIL import Image, ImageDraw

def round_to_nearest(number: float, X: int) -> int:
    """Rounds a number to the smallest upper integer that is divisible by a given integer X.

    Args:
    number: A float or integer to be rounded to the nearest multiple of X.
    X: An integer that the rounded number should be divisible by.

    Returns:
    The smallest upper integer that is divisible by X and is closest to the input number.
    """
    return math.ceil(number / X) * X

def load_yaml(path):
    with open(path, 'r') as yaml_file:
        config = yaml.full_load(yaml_file)
    config["net"]["load_from_features"]= False
    config["net"]["stride"] = 1
    config["net"]["ncrops"] = 1
    config["net"]["labels_file"] = "data/sht_labels.csv"
    config["net"]["normal_id"] = 8
    return config["net"]

def load_model(config):
    model = AnomalyCLIP(**config)
    state_dict = torch.load("checkpoints/shanghaitech/last.ckpt")["state_dict"]
    state_dict = {key.replace('net.', ''): value for key, value in state_dict.items()}

    model.load_state_dict(state_dict,strict=False)
    model.cuda()
    for p in model.image_encoder.parameters():
        p.requires_grad = False
    for p in model.text_encoder.parameters():
        p.requires_grad = False
    model.text_encoder.text_projection.requires_grad = True
    for p in model.token_embedding.parameters():
        p.requires_grad = False
    return model

if __name__ == "__main__":
    config = load_yaml("configs/model/anomaly_clip_shanghaitech.yaml")
    model = load_model(config)
    ncentroid = torch.load("logs/train/runs/shanghaitech/ncentroid.pt")

    images = []
    files_list = sorted(glob.glob("../DMAD/DMAD-PDM/data/shanghai/training/frames/01_001/*"), key=lambda x: int(x.split('/')[-1].split(".")[0]))
    num_segments = 32
    frames_per_segment = 16
    stride = 1
    end_frame = round_to_nearest(
        len(files_list),
        num_segments * frames_per_segment * stride,
    )
    start_indices = np.arange(end_frame / (frames_per_segment * stride)) * (
        frames_per_segment * stride
    )        
    for start_index in start_indices:
        for i in range(frames_per_segment):
            frame_index = (int(start_index) + i * stride) % len(files_list)
            frame_index += 0  # make sure to start from the correct frame
            images.append(Image.open(files_list[frame_index]).convert("RGB"))

    test_transform = get_augmentations(224, 1)
    images_feat = test_transform(images)
    images_feat = images_feat.cuda().unsqueeze(0)
    labels = torch.tensor([8]*512).cuda()

    # Forward pass
    similarity, abnormal_scores = model(
        images_feat,
        labels,
        ncentroid,
        1,
        test_mode=True,
    )

Inference on a single video

Thanks to you work! Can you tell me how to inference on a single video and output an anomaly score curve.

Wrong train/test split for the ShanghaiTech dataset

Hello,
I found that on the split of the ShanghaiTech dataset, there are a few classes that have data on the test set but not on the train set and vice versa. For example, there's a total of 4 videos that contain the "Fall" class but all of them are located in the test set only. Since it is important to have data for all classes on each train and test set to have a VAR model, I'm not sure it is a valid dataset to evaluate the VAR task, and assuming your paper's result on such classes is an invalid or unfair evaluation.

CSV files for labels

It looks like to be able to run the evaluation it is required any of these files:

  • sht_labels.csv
  • ucf_labels.csv
  • xd_labels.csv

I didn't find them in the data folder. Is there a place to download them?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.