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

Testing OpenCV TrackerMIL 'Tracking error' on high resolution #8934

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

Conversation

archibald1418
Copy link
Contributor

@archibald1418 archibald1418 commented Jan 13, 2025

This contributes a regression test reproducing a bug from #8894

Motivation and context

A 'Tracking error' message notification popping up when tracking shapes with OpenCV's TrackerMIL.
Its cause was shown to be memory issues when using an OpenCV tracker on frames with high resolution (ca. 5000x5000)

How has this been tested?

  • Generate 3 pics 5000x5000 each containing an object to be tracked
  • Open task job and load OpenCV library
  • Go to the 2nd frame
  • Create a shape with TrackerMIL, assert that UI state is correct
  • Go to next frame
  • Assert that no 'Tracking error' notification message popsup

The test is marked as skipped for now since the fix is still to be implemented.

WARN: Cypress crashes if this test is enabled (this is expected for now)

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.

Copy link
Contributor

coderabbitai bot commented Jan 13, 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 configuration and testing enhancements across multiple files. The changes primarily focus on debugging configurations in VS Code, improving image generation capabilities for Cypress tests, and adding error handling in the OpenCV tracker implementation. The modifications span across development tools, testing utilities, and utility functions, with a particular emphasis on supporting more complex testing scenarios, especially for high-resolution image tracking.

Changes

File Change Summary
.vscode/launch.json - Updated Chrome debugger type from pwa-chrome to chrome
- Added specific Cypress test file arguments for ui.js: test
.vscode/settings.json - Added JavaScript-specific settings
- Set max tokenization line length to 2500
- Configured ESLint to automatically fix issues on save
.vscode/tasks.json - Modified endsPattern from "Compiled" to "compiled"
cvat-ui/src/utils/opencv-wrapper/tracker-mil.ts - Added error handling in init method
- Ensured memory cleanup with finally block
tests/cypress/e2e/issues_prs2/issue_8894_OpenCV_TrackerMIL_tracking_error_with_big_resolution.js - Added new skipped Cypress test for TrackerMIL tracking
- Implemented test setup for high-resolution image scenarios
tests/cypress/plugins/imageGenerator/addPlugin.js - Added imageGeneratorManyObjects function
- Expanded image generation capabilities
tests/cypress/plugins/imageGenerator/imageGeneratorCommand.js - Added new imageGeneratorManyObjects Cypress command
tests/cypress/plugins/index.js - Registered new imageGeneratorManyObjects task
tests/cypress/support/commands_canvas3d.js - Added logging for customScreenshot command

Poem

🐰 In the realm of code, a rabbit's delight,
Debugging configs now shine so bright!
Cypress tests dance, OpenCV takes flight,
With images generated, pixel-perfect and tight.
Tracking errors fade, our code takes might! 🚀


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: 3

🧹 Nitpick comments (4)
tests/cypress/plugins/imageGenerator/imageGeneratorCommand.js (1)

18-29: LGTM with minor naming suggestion

The new command follows good patterns from the existing implementation. Consider renaming posXs and posYs to positions and accepting an array of {x, y} objects for better maintainability.

tests/cypress/e2e/issues_prs2/issue_8894_OpenCV_TrackerMIL_tracking_error_with_big_resolution.js (2)

28-35: Consider adding test cases with varying shape sizes.

While the current test case is valid, consider adding variations of shape sizes to ensure the tracking error isn't size-dependent. This would provide better coverage of potential failure scenarios.


45-74: Enhance test assertions and error handling.

While the test correctly verifies the absence of tracking errors, consider:

  1. Adding assertions for shape position/size after tracking
  2. Implementing error handling for potential OpenCV initialization failures
  3. Adding timeout handling for high-resolution operations

Example assertion addition:

 cy.get(`#cvat_canvas_shape_${shapeNumber}`)
     .then(() => {
         cy.get('.cvat-tracking-notice').should('not.exist');
         cy.get(`#cvat-objects-sidebar-state-item-${shapeNumber}`)
             .should('contain', 'RECTANGLE TRACK');
+        // Verify shape position after tracking
+        cy.get(`#cvat_canvas_shape_${shapeNumber}`)
+            .should('have.attr', 'x')
+            .and('not.equal', '0');
     });
.vscode/settings.json (1)

52-58: Remove incomplete comment.

The commented-out partial word "eslin" appears to be an incomplete or leftover comment.

     "[javascript]": {
         "editor.maxTokenizationLineLength": 2500,
         "editor.codeActionsOnSave": {
-            "source.fixAll.eslint": "always",
-            // "eslin"
+            "source.fixAll.eslint": "always"
         }
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8880e11 and 4799bea.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (9)
  • .vscode/launch.json (2 hunks)
  • .vscode/settings.json (1 hunks)
  • .vscode/tasks.json (1 hunks)
  • cvat-ui/src/utils/opencv-wrapper/tracker-mil.ts (1 hunks)
  • tests/cypress/e2e/issues_prs2/issue_8894_OpenCV_TrackerMIL_tracking_error_with_big_resolution.js (1 hunks)
  • tests/cypress/plugins/imageGenerator/addPlugin.js (2 hunks)
  • tests/cypress/plugins/imageGenerator/imageGeneratorCommand.js (1 hunks)
  • tests/cypress/plugins/index.js (2 hunks)
  • tests/cypress/support/commands_canvas3d.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .vscode/tasks.json
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build
  • GitHub Check: testing
  • GitHub Check: generate_github_pages
  • GitHub Check: Analyze (python)
  • GitHub Check: Linter
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (6)
tests/cypress/plugins/index.js (1)

10-10: LGTM!

Clean integration of the new task following existing patterns.

Also applies to: 19-19

tests/cypress/support/commands_canvas3d.js (1)

39-42: Verify if debug logging should be permanent

The added logging statements appear to be for debugging purposes. Consider:

  1. Making them conditional based on a debug flag
  2. Removing them if they were only meant for temporary debugging
  3. Adding more context to the log messages if they should be permanent
tests/cypress/e2e/issues_prs2/issue_8894_OpenCV_TrackerMIL_tracking_error_with_big_resolution.js (2)

1-26: LGTM! Test setup is well-structured.

The constants and configuration are appropriate for testing high-resolution tracking, with proper image dimensions (5000x5000) and spacing for object positions.


37-43: LGTM! Helper function is well-implemented.

The function properly handles OpenCV initialization and ensures loading is complete before proceeding.

tests/cypress/plugins/imageGenerator/addPlugin.js (1)

Line range hint 1-10: LGTM! Export structure is clean.

The new export follows the existing pattern and maintains consistency.

.vscode/launch.json (1)

Line range hint 129-158: LGTM! Debug configuration is properly updated.

The changes correctly update the Chrome debugger type and add the specific test file pattern for the new test.

Comment on lines 45 to 47
} catch (error) {
// eslint-disable-next-line
const test = error;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Improve error handling in tracker initialization

The current implementation silently swallows errors during tracker initialization, which:

  1. Makes it difficult to diagnose issues
  2. Could hide critical problems from users
  3. May complicate debugging of high-resolution tracking errors (issue "Tracking error" in OpenCV TrackerMIL tracker when tracking many concurrently moving objects #8894)

Consider this improvement:

         try {
             matImage = this.cv.matFromImageData(src);
             const rect = new this.cv.Rect(x1, y1, width, height);
             this.trackerMIL.init(matImage, rect);
-        } catch (error) {
-            // eslint-disable-next-line
-            const test = error;
+        } catch (error: unknown) {
+            const errorMessage = error instanceof Error ? error.message : 'Unknown error during tracker initialization';
+            throw new Error(`Failed to initialize TrackerMIL: ${errorMessage}`);
         } finally {
📝 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
} catch (error) {
// eslint-disable-next-line
const test = error;
try {
matImage = this.cv.matFromImageData(src);
const rect = new this.cv.Rect(x1, y1, width, height);
this.trackerMIL.init(matImage, rect);
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error during tracker initialization';
throw new Error(`Failed to initialize TrackerMIL: ${errorMessage}`);
} finally {

Comment on lines 54 to 62
// FIXME: try invoking assertions from here
// function validateArrays(a, b) {
// assert(Array.isArray(a), `${a} should be an array`);
// assert(Array.isArray(b), `${b} should be an array`);

// assert(a.length === b.length, 'arrays should have same length');
// }

// validateArrays(posXs, posYs);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement the commented array validation logic.

The commented validation code is essential for ensuring proper input handling. Without it, the function might fail silently with mismatched arrays.

Uncomment and implement the validation:

-    // FIXME: try invoking assertions from here
-    // function validateArrays(a, b) {
-    //     assert(Array.isArray(a), `${a} should be an array`);
-    //     assert(Array.isArray(b), `${b} should be an array`);
-
-    //     assert(a.length === b.length, 'arrays should have same length');
-    // }
-
-    // validateArrays(posXs, posYs);
+    function validateArrays(a, b) {
+        if (!Array.isArray(a) || !Array.isArray(b)) {
+            throw new Error('Inputs must be arrays');
+        }
+        if (a.length !== b.length) {
+            throw new Error('Arrays must have the same length');
+        }
+    }
+
+    validateArrays(posXs, posYs);
📝 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
// FIXME: try invoking assertions from here
// function validateArrays(a, b) {
// assert(Array.isArray(a), `${a} should be an array`);
// assert(Array.isArray(b), `${b} should be an array`);
// assert(a.length === b.length, 'arrays should have same length');
// }
// validateArrays(posXs, posYs);
function validateArrays(a, b) {
if (!Array.isArray(a) || !Array.isArray(b)) {
throw new Error('Inputs must be arrays');
}
if (a.length !== b.length) {
throw new Error('Arrays must have the same length');
}
}
validateArrays(posXs, posYs);

Comment on lines 69 to 80
try {
const arraysLength = posXs.length;
for (let i = 1; i <= imagesCount; i++) {
let image = await createImage(width, height, color);
for (let j = 0; j < arraysLength; j++) {
image = await appendText(image, posXs[j], posYs[j], message, j + 1);
// ws.push(image);
}
await image.write(`${file}.${extension}`); // NOTE: where this line should be?
}
// eslint-disable-next-line no-empty
} catch (e) {}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add proper error handling.

The empty catch block silently suppresses errors, which could hide important issues during image generation.

Implement proper error handling:

     try {
         const arraysLength = posXs.length;
         for (let i = 1; i <= imagesCount; i++) {
             let image = await createImage(width, height, color);
             for (let j = 0; j < arraysLength; j++) {
                 image = await appendText(image, posXs[j], posYs[j], message, j + 1);
             }
             await image.write(`${file}.${extension}`);
         }
-    // eslint-disable-next-line no-empty
-    } catch (e) {}
+    } catch (e) {
+        console.error('Failed to generate images:', e);
+        throw e;
+    }
📝 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
try {
const arraysLength = posXs.length;
for (let i = 1; i <= imagesCount; i++) {
let image = await createImage(width, height, color);
for (let j = 0; j < arraysLength; j++) {
image = await appendText(image, posXs[j], posYs[j], message, j + 1);
// ws.push(image);
}
await image.write(`${file}.${extension}`); // NOTE: where this line should be?
}
// eslint-disable-next-line no-empty
} catch (e) {}
try {
const arraysLength = posXs.length;
for (let i = 1; i <= imagesCount; i++) {
let image = await createImage(width, height, color);
for (let j = 0; j < arraysLength; j++) {
image = await appendText(image, posXs[j], posYs[j], message, j + 1);
// ws.push(image);
}
await image.write(`${file}.${extension}`); // NOTE: where this line should be?
}
} catch (e) {
console.error('Failed to generate images:', e);
throw e;
}

@codecov-commenter
Copy link

codecov-commenter commented Jan 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 73.84%. Comparing base (3c8b22d) to head (7d43505).
Report is 3 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #8934   +/-   ##
========================================
  Coverage    73.84%   73.84%           
========================================
  Files          412      412           
  Lines        44261    44262    +1     
  Branches      3993     3993           
========================================
+ Hits         32684    32687    +3     
+ Misses       11577    11575    -2     
Components Coverage Δ
cvat-ui 78.41% <ø> (+<0.01%) ⬆️
cvat-server 69.97% <100.00%> (+<0.01%) ⬆️

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Here the pattern didn't work - the vscode task would go into an endless loop

Copy link

@archibald1418 archibald1418 requested a review from klakhov January 14, 2025 11:01
@bsekachev
Copy link
Member

The test will not be relevant after the fix #8942.
It needs to be updated slightly.

But anyway, my general comment is that we do not need two tests doing basically the same thing (but with different resolution).
I will recommend just to update existing test to use high resolution images there.

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.

3 participants