Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
bd25319
feat: implement detection tracking and integrate it into save_results
mohamedelabbas1996 May 27, 2025
e06f79f
used the latest classification features vector instead of the detecti…
mohamedelabbas1996 May 28, 2025
853607d
feat: added tracking stage, per-session logic, optimal detection pairing
mohamedelabbas1996 May 29, 2025
50ce8fc
test: added testing for tracking
mohamedelabbas1996 Jun 2, 2025
0ebbea5
skip sessions with human identifications
mohamedelabbas1996 Jun 3, 2025
3f4acac
added missing migration
mohamedelabbas1996 Jun 9, 2025
a4eeede
restored migrations
mohamedelabbas1996 Jun 9, 2025
8801f89
fixed migration issues
mohamedelabbas1996 Jun 10, 2025
d6d481a
fix: pin minio containers to known working versions
mihow Jun 18, 2025
8991b44
fix: pin minio container versions in CI stack
mihow Jun 18, 2025
ff3d1bb
moved tracking to a separate job
mohamedelabbas1996 Jun 19, 2025
1ea816d
Merge branch 'feat/restore-tracking' of https://github.com/RolnickLab…
mohamedelabbas1996 Jun 19, 2025
c688e68
removed call to tracking from ml job
mohamedelabbas1996 Jun 20, 2025
db5f104
passed tracking cost threshold as a job param
mohamedelabbas1996 Jun 20, 2025
d3a7b8c
fix: assigned occurrence project and deployment
mohamedelabbas1996 Jun 20, 2025
000c247
changed the observed date field in the occurrence list view to show t…
mohamedelabbas1996 Jun 20, 2025
be69807
fixed frontend code formatting
mohamedelabbas1996 Jun 20, 2025
1526cfb
improved logging and job progress tracking
mohamedelabbas1996 Jun 20, 2025
b82f175
fix: use features from the same algo when comparing detections
mihow Jun 25, 2025
9d0fd96
feat: update some type annotations & logging, resolve warnings
mihow Jun 25, 2025
87c91c1
feat: validate tracking parameters, add more parameters
mihow Jun 25, 2025
a194ffd
fix: only assign new occurrences to tracks with >1 detection
mihow Jun 25, 2025
4c4e4c9
feat: log number of occurrences reduced, and other things.
mihow Jun 25, 2025
b7f28ea
feat: skip chains that don't need new occurrences (len 1 or all same)
mihow Jun 25, 2025
30cc279
feat: don't require fully processed sessions for now
mihow Jul 2, 2025
ed35121
Merge branch 'deployments/ood.antenna.insectai.org' into feat/restore…
mihow Aug 21, 2025
785a8f2
Merge branch 'deployments/ood.antenna.insectai.org' into feat/restore…
mihow Aug 22, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions ami/ml/models/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
SourceImageResponse,
)
from ami.ml.tasks import celery_app, create_detection_images
from ami.ml.tracking import assign_occurrences_by_tracking
from ami.utils.requests import create_session

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -881,10 +882,14 @@ def save_results(

# Create a new occurrence for each detection (no tracking yet)
# @TODO remove when we implement tracking!
create_and_update_occurrences_for_detections(
detections=detections,
logger=job_logger,
)
# create_and_update_occurrences_for_detections(
# detections=detections,
# logger=job_logger,
# )
job_logger.info(f"Creating occurrences for {len(detections)} detections ")
job_logger.info("type logger: " + str(type(job_logger)))

assign_occurrences_by_tracking(detections=detections, logger=job_logger)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check if all captures have been processed in a Session before calling assign_occurrences_by_tracking().

Add logging statement to say when a session is complete. But this check should only consider captures that are in the collection (not all captures).


# Update precalculated counts on source images and events
source_images = list(source_images)
Expand Down
131 changes: 131 additions & 0 deletions ami/ml/tracking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import math
from collections import defaultdict
from collections.abc import Iterable

import numpy as np

from ami.main.models import Detection, Occurrence

TRACKING_COST_THRESHOLD = 2


def cosine_similarity(v1: Iterable[float], v2: Iterable[float]) -> float:
v1 = np.array(v1)
v2 = np.array(v2)
sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
return float(np.clip(sim, 0.0, 1.0))


def iou(bb1, bb2):
xA = max(bb1[0], bb2[0])
yA = max(bb1[1], bb2[1])
xB = min(bb1[2], bb2[2])
yB = min(bb1[3], bb2[3])
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
boxAArea = (bb1[2] - bb1[0] + 1) * (bb1[3] - bb1[1] + 1)
boxBArea = (bb2[2] - bb2[0] + 1) * (bb2[3] - bb2[1] + 1)
unionArea = boxAArea + boxBArea - interArea
return interArea / unionArea if unionArea > 0 else 0


def box_ratio(bb1, bb2):
area1 = (bb1[2] - bb1[0] + 1) * (bb1[3] - bb1[1] + 1)
area2 = (bb2[2] - bb2[0] + 1) * (bb2[3] - bb2[1] + 1)
return min(area1, area2) / max(area1, area2)


def distance_ratio(bb1, bb2, img_diag):
cx1 = (bb1[0] + bb1[2]) / 2
cy1 = (bb1[1] + bb1[3]) / 2
cx2 = (bb2[0] + bb2[2]) / 2
cy2 = (bb2[1] + bb2[3]) / 2
dist = math.sqrt((cx2 - cx1) ** 2 + (cy2 - cy1) ** 2)
return dist / img_diag if img_diag > 0 else 1.0


def image_diagonal(width: int, height: int) -> int:
img_diagonal = int(math.ceil(math.sqrt(width**2 + height**2)))
return img_diagonal


def total_cost(f1, f2, bb1, bb2, diag):
return (
(1 - cosine_similarity(f1, f2))
+ (1 - iou(bb1, bb2))
+ (1 - box_ratio(bb1, bb2))
+ distance_ratio(bb1, bb2, diag)
)


def get_latest_feature_vector(detection: Detection):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make sure all detections use the same feature extraction algorithm for both captures. See the most_common_algorithm function in the clustering function.

return (
detection.classifications.filter(features_2048__isnull=False)
.order_by("-timestamp")
.values_list("features_2048", flat=True)
.first()
)


def assign_occurrences_by_tracking(
detections: list[Detection],
logger,
) -> None:
"""
Perform object tracking by assigning detections across multiple source images
to the same Occurrence if they are similar enough, based on the latest classification feature vectors.
"""
logger.info(f"Starting to assign occurrences by tracking. {len(detections)} detections found.")

# Group detections by source image timestamp
image_to_dets = defaultdict(list)
for det in detections:
image_to_dets[det.source_image.timestamp].append(det)
sorted_timestamps = sorted(image_to_dets.keys())
logger.info(f"Found {len(sorted_timestamps)} source images with detections.")

last_detections = []

for timestamp in sorted_timestamps:
current_detections = image_to_dets[timestamp]
logger.info(f"Processing {len(current_detections)} detections at {timestamp}")

for det in current_detections:
det_vec = get_latest_feature_vector(det)
if det_vec is None:
logger.info(f"No features for detection {det.id}, skipping.")
continue

best_match = None
best_cost = float("inf")

for prev in last_detections:
prev_vec = get_latest_feature_vector(prev)
if prev_vec is None:
continue

cost = total_cost(
det_vec,
prev_vec,
det.bbox,
prev.bbox,
image_diagonal(det.source_image.width, det.source_image.height),
)

logger.info(f"Comparing detection {det.id} with previous {prev.id}: cost = {cost:.4f}")
if cost < best_cost:
best_cost = cost
best_match = prev

if best_match and best_cost < TRACKING_COST_THRESHOLD:
det.occurrence = best_match.occurrence
logger.info(f"Assigned detection {det.id} to existing occurrence {best_match.occurrence.pk}")
else:
occurrence = Occurrence.objects.create(event=det.source_image.event)
det.occurrence = occurrence
logger.info(f"Created new occurrence {occurrence.pk} for detection {det.id}")

det.save()

last_detections = current_detections

logger.info("Finished assigning occurrences by tracking.")
Loading