contact

Building Multi Camera Multi Object Tracking

It was not an easy ride

How it started

I was working on the early stages of a product that tracks where each person walks inside a space, so you can see which spots get visited the most and make better use of the space. To get that movement data out of the CCTV cameras that were already installed, we had to build Multi Camera Multi Object Tracking (MCMOT).

Object detection wasn't a big deal since great models like YOLO already exist. Single camera tracking is also easy with DeepSORT or ByteTrack. Multiple cameras were a different story though. I don't have a deep background in computer vision, so this was all new to me, and I had no idea how to even approach it. Usually when I wonder "has someone already built this?", the amazing open source world has a library or a model sitting there waiting for me. Sadly, not this time.

It felt hard enough that we actually sat down to check if we could even finish it in time.

A video that left just one sentence as a hint
A video that left just one sentence as a hint

Then I found a short video where 5 cameras were telling a bunch of people apart without any trouble.

Note that the detection happens separately on each camera and then unified into one since identification process.

That one line was the only thing in the caption. But it told me two things. This is doable, and detection happens on each camera first, then identification happens all at once.

There wasn't a model that did detection and tracking across multiple cameras out of the box, but there were a lot of papers, and it started to look like I could actually pull it off.

So I decided to give it a shot.

Some terms first

Detection

Finding objects and telling what they are. If you want to give each object an ID and follow it around, you need tracking on top of this. Usually detection just gives you what the object is and where it is.

Models like YOLO are already out there and they work really well.

Tracking

Telling individual objects apart, usually by giving each one an ID. In this post I use it to mean Single Camera Multi Object Tracking.

There are models like DeepSORT, StrongSORT and ByteTrack. I'd go with ByteTrack.

Identification

In this post this means the main topic, Multi Camera Multi Object Tracking. People usually call it Re-ID (Re-Identification), and I use Identification and Re-Identification to mean the same thing here.

As of writing this, there's no model made just for Re-ID.

Building it

Finding the answer for multiple cameras

While reading papers on multi camera multi object tracking, I kept seeing the term Re-Identification, so I looked into it. It's the logic that finds the same object across multiple inputs and gives it a new global ID. That was exactly what I needed to match the same person across cameras.

How do you do Re-Identification?

Re-Identification goes like this:

  1. For each camera, extract a vector for every object.
  2. Compare the vectors of objects from different cameras and match the ones that look the most alike. (matching algorithm)

Here's what I had in mind.

// first idea

Detection => Identification?

With a single camera, you run detection, then run tracking on the coordinates of each object, and each one gets an ID.

With multiple cameras you can do the same detection and tracking on each one separately.

Detecting

# Method in the Detector class that runs detection with the YOLO model
def detect(self, img, cls=0):
    # Call the preprocessing method and get the processed image back
    # Handles resizing, color conversion, turning the Numpy array into a Pytorch tensor, etc
    input_image, scale = self.preprocess_image(img, (640, 640))

    # Run the YOLO model
    self.detections = self.model(input_image)

    # Return the top left x,y, bottom right x,y and confidence for each object
    self.detections = [
        [
            int(det.boxes.xyxy.cpu().numpy().tolist()[0][0] / scale[0]),
            int(det.boxes.xyxy.cpu().numpy().tolist()[0][1] / scale[1]),
            int(det.boxes.xyxy.cpu().numpy().tolist()[0][2] / scale[0]),
            int(det.boxes.xyxy.cpu().numpy().tolist()[0][3] / scale[1]),
            round(det.boxes.conf[0].item(), 2),
        ]
        for det in self.detections[0]
        if int(det.boxes.cls[0].item()) == cls
    ]

    # Call the postprocessing method
    # Turns the detections into a Pytorch tensor so ByteTrack can take it as input
    self.processed_detections = self.process_detections()

Tracking

ByteTrack handles tracking really well with high accuracy.

One thing specific to this project: we had to get rid of outliers, like staff standing still or people just walking past without looking at anything. For that, there was some logic that compares each person's position with the previous frame to get how far they moved. I've cut it down here and just pretend there's a function for it. (If you think about it for a bit, it's pretty simple to write.)

# Method in the Tracker class that runs tracking with ByteTrack
def track(self, detections, frame_size):
    # Run ByteTrack
    tracks = self.tracker.update(detections, frame_size, frame_size)

    # There's logic here that compares with the previous frame to get the distance moved in the image,
    # but let's just assume there's a calculate_movement_distance() function and skip it
    for track in tracks:
        self.track_move[track.track_id] += calculate_movement_distance(track)

    # Return the ID and the bounding box coordinates
    return [
        (
            track.track_id,
            int(max(0, track.tlbr[0])),
            int(max(0, track.tlbr[1])),
            int(min(track.tlbr[2], frame_size[0])),
            int(min(track.tlbr[3], frame_size[1])),
        )
        for track in tracks
    ]

Removing outliers

This uses the distance we just got as the main value for each visitor, and treats anyone who moved less than some amount as an outlier and drops them.

I don't know what that threshold should be either.

If you run clustering with different numbers of clusters and calculate the silhouette score for each, the one with the highest score gives you the best number of clusters.

The silhouette score tells you how tight each cluster is and how far it is from the other clusters. Closer to -1 is bad, closer to 1 is good.

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score


def filter_ids_with_low_appear(self):
    # Count how many times each ID shows up
    moves = np.array(list(self.track_move.values())).reshape(-1, 1)

    # Pick the best number of clusters based on the silhouette score
    # Try from 1 up to min(number of people, 10) clusters
    silhouette_scores = []
    K = range(2, min(len(np.unique(moves)), 10))

    for k in K:
        kmeans = KMeans(n_clusters=k, random_state=0).fit(moves) # Run K-means clustering
        score = silhouette_score(moves, kmeans.labels_) # Calculate the silhouette score
        silhouette_scores.append(score) # Save the score

    # The silhouette scores tell us the best number of clusters
    optimal_k = K[silhouette_scores.index(max(silhouette_scores))]
    # Run K-means clustering with that number
    kmeans = KMeans(n_clusters=optimal_k, random_state=0).fit(moves)

    # Use the smallest value in each cluster as a threshold and sort them
    thresholds = sorted([min(moves[kmeans.labels_ == i]) for i in range(optimal_k)])

    # Pick the second smallest threshold, with a length check in case there's only one cluster
    if len(thresholds) > 1:
        selected_threshold = thresholds[1]
    else:
        # Only one cluster, so use the first value
        selected_threshold = thresholds[0]


    # Keep only the IDs of objects that moved at least the threshold
    filtered_ids = [
        id
        for id, move in self.track_move.items()
        if move >= min(selected_threshold)
    ]

    # Print the results
    print("Original moves:", self.track_move)
    print("Optimal number of clusters:", optimal_k)
    print("Thresholds per cluster:", thresholds)
    print("Threshold:", selected_threshold)
    print("Filtered moves (dynamic thresholds):", filtered_ids)

    self.filtered_ids = filtered_ids

Detection, tracking and outlier removal are done. Time for identification.

Identifying

Now every camera angle has its own IDs, and we need to pull the features of each object straight out of the image.

I went with resnet50, which is a CNN model. Once it's trained on images, you can use it for things like:

  • Object detection
  • Image classification, like telling chairs, cars and dogs apart
  • Image segmentation, which splits out the area of each object

But we're going to use it to get vectors, basically the features of an image, and compare them across different angles to find the same person. To be exact, we extract a vector every frame, then take the average at the end to get what that person looks like.

resnet50 model info

- Dataset: msmt17
- Input image size: 256x128 (h,w)
- Epochs: 150
- Learning rate: 0.0015
- Batch size: 64

You can download the model I used here.

Now let's feed images into resnet50.

Below is the Identifier class I wrote. It imports some libraries and a few util functions I made, but it shouldn't be hard to follow.

import torch
import torchvision.transforms as transforms
import torchreid
import cv2
import numpy as np
from analyzer.device import get_device
from PIL import Image


class Identifier:
    # Set up the instance
    def __init__(self) -> None:
        self.device = get_device() # device name
        self.features_by_id = {}
        self.average_features_by_id = {}

        model = torchreid.models.resnet50(num_classes=4101, pretrained=True)

        # Load the weights
        checkpoint = torch.load(
            "models/resnet50_msmt17_combineall_256x128_amsgrad_ep150_stp60_lr0.0015_b64_fb10_softmax_labelsmooth_flip_jitter.pth",
            map_location=self.device,
        )

        new_state_dict = {}  # dict to hold the processed state_dict from the checkpoint

        key_map = {
            "fc.weight": "classifier.weight",
            "fc.bias": "classifier.bias",
        }  # key mapping

        # Remove the "model." prefix from every key in the checkpoint
        for key, value in checkpoint.items():
            key = key.replace("model.", "")  # strip "model."
            if key in key_map:
                new_state_dict[key_map[key]] = value
            else:
                new_state_dict[key] = value

        model.load_state_dict(new_state_dict, strict=False)  # load the fixed state dict

        model = model.to(self.device)  # move to device

        model.eval()  # switch to eval mode

        self.model = model # set the model

    # Preprocess the image
    def preprocess_image(self, img):
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        transform = transforms.Compose(
            [
                transforms.Resize((256, 128)),
                transforms.ToTensor(),
                transforms.Normalize(
                    mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
                ),
            ]
        )
        img = transform(img).unsqueeze(0).to(self.device)
        return img

    # Extract the image vector
    def extract_feature(self, img):
        img = self.preprocess_image(img)
        with torch.no_grad():
            feature = self.model(img)
        return feature.cpu().numpy()

    # Save the extracted vector
    def save_feature(self, id, feature):
        if id not in self.features_by_id:
            self.features_by_id[id] = list()
        self.features_by_id[id].append(feature)

    # Get the average vector for each ID
    # Used at the very end
    def calculate_average_feature(self):
        self.average_features_by_id = {
            id: np.mean(np.stack(features), axis=0)
            for id, features in self.features_by_id.items()
        }
        return self.average_features_by_id

Finding the same person

With the methods in the Identifier class above, you can extract vectors for each camera and get the average vector for each object in each video, which works as that object's main value.

Next we need to group similar vectors across videos, which basically means grouping the objects in each video that are probably the same person. This part isn't too hard. Just run clustering on the vectors. There are lots of clustering methods, so pick one you like. I used K-means for this project. I'll skip the code.

Say each video has the same n people, and for each video you have an array of size n that looks like [(ByteTrack id), (extracted vector)]. All you have to do is match each video's ByteTrack IDs to a global ID (0, 1, 2 ... n) and you're done.

Results

Now that the same people are matched up, a quick visualization shows everyone with their global ID after identification.

Two cameras facing each other, giving the same person the same ID
Two cameras facing each other, giving the same person the same ID

The annoying part is that unless detection and tracking are 100% accurate, you'll miss some frames here and there. But the IDs from tracking in each video stay the same the whole time, so you can still get a lot out of it.

Written up like this it looks quick, but it was a lot of trial and error, learning things, and then turning that into actual knowledge, over and over. This project meant a lot to me.

If you have any questions, shoot me an email here. I'll help however I can.

← blog