Skip to content
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

Updated MIL tracker implementation #8942

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open

Updated MIL tracker implementation #8942

wants to merge 8 commits into from

Conversation

bsekachev
Copy link
Member

@bsekachev bsekachev commented Jan 14, 2025

Motivation and context

Resolved #8894

The patch updates approach we use to run OpenCV MIL tracker.
Now it is run through annotations actions. It allows us to get more memory control, fix some issues related to non-consequent frames in GT jobs and track object on many frames. Tracking in general works faster.

However it removes user's ability to adjust objects during tracking.

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
  • I have updated the documentation accordingly
  • I have added tests to cover my changes
  • I have linked related issues (see GitHub docs)
  • I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Added OpenCV MIL (Minimum Information Loss) tracking algorithm for object tracking
    • Enhanced frame data method to return additional render width and height information
  • Bug Fixes

    • Improved image resizing and scaling for tracking functionality
    • Updated error handling in image processing methods
  • Refactor

    • Simplified annotation action modal initialization
    • Removed unused tracking-related states and methods
    • Updated copyright notices across multiple files
  • Style

    • Minor formatting and code consistency improvements

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request introduces several enhancements across the CVAT (Computer Vision Annotation Tool) codebase, focusing on improving frame data handling, annotation actions, OpenCV tracking capabilities, and overall code quality. The changes include modifications to core functionality in frame data retrieval, updating modal interactions, introducing a new MIL (Minimum Information Loss) tracker implementation, and refining image processing utilities. The updates aim to provide more flexible and robust annotation and tracking features while maintaining the existing architectural design.

Changes

File Change Summary
cvat-core/src/frames.ts Updated data method return type to include renderWidth and renderHeight
cvat-ui/src/components/annotation-page/annotations-actions/annotations-actions-modal.tsx Added defaultAnnotationAction to props, modified modal opening function
cvat-ui/src/components/annotation-page/standard-workspace/controls-side-bar/opencv-control.tsx Removed tracking-related code, updated job instance type
cvat-ui/src/components/annotation-page/standard-workspace/styles.scss Renamed CSS class, added margin-bottom
cvat-ui/src/containers/annotation-page/... Updated openAnnotationsActionModal calls with new parameter structure
cvat-ui/src/utils/opencv-wrapper/annotations-actions/tracker-mil.ts Added new OpenCVTrackerMIL class for object tracking
cvat-ui/src/utils/opencv-wrapper/opencv-wrapper.ts Registered new TrackerMILAction, updated tracking description
cvat-ui/src/utils/opencv-wrapper/tracker-mil.ts Added image resizing and scaling capabilities to tracker

Sequence Diagram

sequenceDiagram
    participant User
    participant AnnotationModal
    participant TrackerMIL
    participant OpenCVWrapper

    User->>AnnotationModal: Open Modal
    AnnotationModal->>OpenCVWrapper: Initialize Tracker
    OpenCVWrapper->>TrackerMIL: Register MIL Tracker
    User->>AnnotationModal: Select Tracking Action
    AnnotationModal->>TrackerMIL: Run Tracking
    TrackerMIL->>TrackerMIL: Process Frames
    TrackerMIL-->>AnnotationModal: Return Tracked Objects
Loading

Poem

🐰 Tracking pixels with grace and might,
OpenCV dances in digital light
Frames resize, annotations take flight
MIL tracker leaps with algorithmic delight
Code evolves, our vision grows bright! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (4)
cvat-ui/src/utils/opencv-wrapper/annotations-actions/tracker-mil.ts (1)

275-279: Ensure default values are correctly set in parameters

The default value for 'Convert rectangle shapes to tracks' may not reflect the initial state if this.#convertRectangleShapesToTracks changes.

Consider using a static default value or initializing this.#convertRectangleShapesToTracks before assigning it as a default:

'Convert rectangle shapes to tracks': {
    type: ActionParameterType.CHECKBOX,
    values: ['true', 'false'],
-   defaultValue: String(this.#convertRectangleShapesToTracks),
+   defaultValue: 'false',
},
cvat-ui/src/utils/opencv-wrapper/histogram-equalization.ts (1)

13-13: Consistent formatting of type annotations

Adding spaces after colons in type annotations enhances readability and maintains a consistent coding style.

-private cv:any;
+private cv: any;

-public processImage(src: ImageData, frameNumber: number): ImageData {
+public processImage(src: ImageData, frameNumber: number): ImageData {

Also applies to: 20-20

cvat-ui/src/utils/opencv-wrapper/opencv-wrapper.ts (1)

128-129: Review the initialization order

The registration of TrackerMILAction is added after the initialization flag is set to true. Consider moving the initialization flag setting after all initialization steps are complete to ensure atomic initialization.

-        this.initialized = true;
         await core.actions.register(new TrackerMILAction(this));
+        this.initialized = true;
cvat-ui/src/components/annotation-page/annotations-actions/annotations-actions-modal.tsx (1)

327-335: Add error handling for invalid default action

The code silently ignores cases where the default action is invalid. Consider adding error notification for better user feedback.

 if (defaultAnnotationAction) {
     const defaultAction = list.find((action) => action.name === defaultAnnotationAction);
+    if (!defaultAction) {
+        notification.warning({
+            message: 'Invalid default action',
+            description: `Action "${defaultAnnotationAction}" not found`,
+        });
+    }
     if (
         defaultAction &&
         (!defaultTargetObjectState || defaultAction.isApplicableForObject(defaultTargetObjectState))
     ) {
         dispatch(reducerActions.setActiveAnnotationsAction(defaultAction));
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e276295 and 0734098.

📒 Files selected for processing (10)
  • cvat-core/src/frames.ts (3 hunks)
  • cvat-ui/src/components/annotation-page/annotations-actions/annotations-actions-modal.tsx (5 hunks)
  • cvat-ui/src/components/annotation-page/standard-workspace/controls-side-bar/opencv-control.tsx (10 hunks)
  • cvat-ui/src/components/annotation-page/standard-workspace/styles.scss (2 hunks)
  • cvat-ui/src/containers/annotation-page/standard-workspace/objects-side-bar/object-item.tsx (2 hunks)
  • cvat-ui/src/containers/annotation-page/standard-workspace/objects-side-bar/objects-list.tsx (2 hunks)
  • cvat-ui/src/utils/opencv-wrapper/annotations-actions/tracker-mil.ts (1 hunks)
  • cvat-ui/src/utils/opencv-wrapper/histogram-equalization.ts (3 hunks)
  • cvat-ui/src/utils/opencv-wrapper/opencv-wrapper.ts (4 hunks)
  • cvat-ui/src/utils/opencv-wrapper/tracker-mil.ts (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • cvat-ui/src/containers/annotation-page/standard-workspace/objects-side-bar/object-item.tsx
  • cvat-ui/src/components/annotation-page/standard-workspace/styles.scss
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: testing
  • GitHub Check: generate_github_pages
🔇 Additional comments (16)
cvat-ui/src/utils/opencv-wrapper/annotations-actions/tracker-mil.ts (2)

223-234: Handle deletion of shapes cautiously

When deleting shapes, ensure that only the intended shapes are removed. Currently, all rectangle shapes are deleted if this.#convertRectangleShapesToTracks is true, which might affect shapes not involved in tracking.

Please verify that this deletion logic does not unintentionally remove unrelated rectangle shapes. If necessary, adjust the deletion criteria to target only the converted shapes.


1-297: Overall implementation is well-structured

The OpenCVTrackerMIL class is thoughtfully designed, with clear logic and appropriate asynchronous handling. The integration with OpenCV's MIL tracker is well-executed, and the code follows best practices.

cvat-ui/src/utils/opencv-wrapper/histogram-equalization.ts (2)

51-52: Improved error handling in catch block

Refining the error handling by specifying the error type as unknown and rethrowing using type checking ensures that unexpected errors are properly propagated.


54-61: Enhanced readability in the finally block

Adding braces around the if statements in the finally block improves code clarity and maintainability.

cvat-ui/src/utils/opencv-wrapper/tracker-mil.ts (4)

16-17: Introduced maxSize and imageScale properties

Adding maxSize and imageScale properties helps manage large images by scaling them appropriately, improving performance and preventing potential issues with high-resolution images.


28-59: Implemented optResize method for image scaling

The optResize method effectively resizes images that exceed maxSize, maintaining the aspect ratio. This enhances performance and resource management when processing large images.


115-120: Added resolution consistency check in update method

Ensuring that the current image has the same resolution as the initial image enhances robustness by preventing errors due to mismatched image sizes.


61-96: Adjusted bounding box coordinates based on scaling factor

Modifying the bounding box coordinates to account for image scaling ensures accurate tracking results after resizing, which is crucial for the tracker’s precision.

cvat-ui/src/utils/opencv-wrapper/opencv-wrapper.ts (1)

314-314: LGTM: Improved description clarity

The updated description better reflects the nature of the tracking functionality.

cvat-ui/src/containers/annotation-page/standard-workspace/objects-side-bar/objects-list.tsx (1)

602-602: LGTM: Improved API usage

The update to use an object parameter for openAnnotationsActionModal improves code clarity and maintainability by making the parameter purpose explicit.

cvat-ui/src/components/annotation-page/standard-workspace/controls-side-bar/opencv-control.tsx (3)

48-48: LGTM: Improved type safety

Replacing any with the proper Job type improves type safety and code maintainability.


417-418: LGTM: Enhanced user guidance

Added help message improves user experience by clearly explaining the tracker's functionality.


447-452: Verify tracker initialization

The code opens the annotations action modal with the tracker name but doesn't verify if the tracker is properly initialized.

cvat-ui/src/components/annotation-page/annotations-actions/annotations-actions-modal.tsx (2)

305-305: LGTM: Enhanced modal configuration

Added defaultAnnotationAction prop improves the modal's flexibility by allowing pre-selection of actions.

Also applies to: 309-309


635-641: LGTM: Improved function signature

The updated openAnnotationsActionModal signature with optional named parameters improves code readability and maintainability.

cvat-core/src/frames.ts (1)

303-307: LGTM! Enhanced type safety in the return type.

The updated method signature provides better type safety and clearer separation of concerns by explicitly returning render dimensions alongside the image data.

Let's verify the impact on API consumers:

✅ Verification successful

Verified: The changes to FrameData.data() are backward compatible

The codebase analysis shows that existing consumers already handle the structured return type with imageData property, and the addition of renderWidth and renderHeight properties is non-breaking. All current usages in tracker-mil.ts, canvas-wrapper.tsx, and other files will continue to work as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to FrameData.data() that might need updates
rg -g '*.{ts,tsx}' -A 2 'data\(\s*\).*\b(ImageBitmap|Blob)\b'

Length of output: 63


Script:

#!/bin/bash
# Search for calls to data() method and frame-related patterns
rg -g '*.{ts,tsx}' -B 2 -A 2 '\.data\(\s*[^)]*\)'

# Search for frame-related type definitions and interfaces
ast-grep --pattern 'interface $_ {
  $$$
  data($$$): $$$
  $$$
}'

Length of output: 4170

Comment on lines +41 to +42
this.#targetFrame = +parameters['Target frame'];
this.#convertRectangleShapesToTracks = parameters['Convert rectangle shapes to tracks'] === 'true';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add parameter validation in the init method

The init method assigns values from the parameters object without validation. If the expected parameters are missing or invalid, this could lead to runtime errors.

Consider adding validation to ensure that 'Target frame' and 'Convert rectangle shapes to tracks' exist and are of the correct type:

public async init(instance: Job | Task, parameters: Record<string, string>): Promise<void> {
    this.#instance = instance;
+   if (!parameters['Target frame'] || isNaN(Number(parameters['Target frame']))) {
+       throw new Error('Invalid or missing parameter: Target frame must be a valid number');
+   }
    this.#targetFrame = +parameters['Target frame'];
+   if (parameters['Convert rectangle shapes to tracks'] !== 'true' && parameters['Convert rectangle shapes to tracks'] !== 'false') {
+       throw new Error('Invalid or missing parameter: Convert rectangle shapes to tracks must be "true" or "false"');
+   }
    this.#convertRectangleShapesToTracks = parameters['Convert rectangle shapes to tracks'] === 'true';
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
this.#targetFrame = +parameters['Target frame'];
this.#convertRectangleShapesToTracks = parameters['Convert rectangle shapes to tracks'] === 'true';
public async init(instance: Job | Task, parameters: Record<string, string>): Promise<void> {
this.#instance = instance;
if (!parameters['Target frame'] || isNaN(Number(parameters['Target frame']))) {
throw new Error('Invalid or missing parameter: Target frame must be a valid number');
}
this.#targetFrame = +parameters['Target frame'];
if (parameters['Convert rectangle shapes to tracks'] !== 'true' && parameters['Convert rectangle shapes to tracks'] !== 'false') {
throw new Error('Invalid or missing parameter: Convert rectangle shapes to tracks must be "true" or "false"');
}
this.#convertRectangleShapesToTracks = parameters['Convert rectangle shapes to tracks'] === 'true';
}

@bsekachev bsekachev requested a review from azhavoro as a code owner January 15, 2025 10:55
@bsekachev bsekachev requested a review from nmanovic as a code owner January 15, 2025 10:59
@codecov-commenter
Copy link

codecov-commenter commented Jan 15, 2025

Codecov Report

Attention: Patch coverage is 77.15736% with 45 lines in your changes missing coverage. Please review.

Project coverage is 73.82%. Comparing base (f215090) to head (a1f55db).
Report is 2 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8942      +/-   ##
===========================================
- Coverage    73.86%   73.82%   -0.04%     
===========================================
  Files          416      417       +1     
  Lines        44413    44578     +165     
  Branches      3993     4025      +32     
===========================================
+ Hits         32804    32909     +105     
- Misses       11609    11669      +60     
Components Coverage Δ
cvat-ui 78.25% <77.15%> (-0.12%) ⬇️
cvat-server 70.06% <ø> (ø)

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
3.4% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

"Tracking error" in OpenCV TrackerMIL tracker when tracking many concurrently moving objects
2 participants