-
Notifications
You must be signed in to change notification settings - Fork 5
Add support for occurrence tracking #863
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mohamedelabbas1996
wants to merge
27
commits into
deployments/ood.antenna.insectai.org
Choose a base branch
from
feat/restore-tracking
base: deployments/ood.antenna.insectai.org
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 e06f79f
used the latest classification features vector instead of the detecti…
mohamedelabbas1996 853607d
feat: added tracking stage, per-session logic, optimal detection pairing
mohamedelabbas1996 50ce8fc
test: added testing for tracking
mohamedelabbas1996 0ebbea5
skip sessions with human identifications
mohamedelabbas1996 3f4acac
added missing migration
mohamedelabbas1996 a4eeede
restored migrations
mohamedelabbas1996 8801f89
fixed migration issues
mohamedelabbas1996 d6d481a
fix: pin minio containers to known working versions
mihow 8991b44
fix: pin minio container versions in CI stack
mihow ff3d1bb
moved tracking to a separate job
mohamedelabbas1996 1ea816d
Merge branch 'feat/restore-tracking' of https://github.com/RolnickLab…
mohamedelabbas1996 c688e68
removed call to tracking from ml job
mohamedelabbas1996 db5f104
passed tracking cost threshold as a job param
mohamedelabbas1996 d3a7b8c
fix: assigned occurrence project and deployment
mohamedelabbas1996 000c247
changed the observed date field in the occurrence list view to show t…
mohamedelabbas1996 be69807
fixed frontend code formatting
mohamedelabbas1996 1526cfb
improved logging and job progress tracking
mohamedelabbas1996 b82f175
fix: use features from the same algo when comparing detections
mihow 9d0fd96
feat: update some type annotations & logging, resolve warnings
mihow 87c91c1
feat: validate tracking parameters, add more parameters
mihow a194ffd
fix: only assign new occurrences to tracks with >1 detection
mihow 4c4e4c9
feat: log number of occurrences reduced, and other things.
mihow b7f28ea
feat: skip chains that don't need new occurrences (len 1 or all same)
mihow 30cc279
feat: don't require fully processed sessions for now
mihow ed35121
Merge branch 'deployments/ood.antenna.insectai.org' into feat/restore…
mihow 785a8f2
Merge branch 'deployments/ood.antenna.insectai.org' into feat/restore…
mihow File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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): | ||
|
||
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.") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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).