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

fix grayscale segmentation regression + RGB masks recoloring issue #5266

Merged
merged 4 commits into from
Dec 13, 2024

Conversation

sashankaryal
Copy link
Contributor

@sashankaryal sashankaryal commented Dec 12, 2024

What changes are proposed in this pull request?

Use a heuristic to detect if mask is grayscale. This is unfortunately a limitation of using canvas decoding method (introduced by #5089), which always outputs an RGBA bitmap.

Also fixes recoloring issue with RGB mask targets

How is this patch tested? If it is not, please explain why.

Locally. Use following code:

import fiftyone as fo
import fiftyone.zoo as foz
import fiftyone.utils.labels as foul

dataset = foz.load_zoo_dataset(
    "coco-2017",
    split="validation",
    label_types="segmentations",
    classes=["person", "cat", "dog"],
    label_field="instances",
    max_samples=50,
    only_matching=True,
)

dataset.name = "coco-2017-gray-seg"
dataset.persistent = True

# Mask targets DO NOT appear in App tooltip
int_mask_targets = {1: "person", 2: "cat", 3: "dog"}

# Mask targets DO appear in App tooltip
rgb_mask_targets = {"#ff6d04": "person", "#499cef": "cat", "#6d04ff": "dog"}

mask_targets = int_mask_targets

dataset.default_mask_targets = mask_targets

foul.objects_to_segmentations(
    dataset,
    "instances",
    "segmentations",
    mask_targets=mask_targets,
    output_dir="/tmp/segmentations",
)

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • New Features

    • Introduced a new function to determine if an image is grayscale based on pixel data.
    • Updated image decoding logic to optimize data handling for grayscale images.
  • Bug Fixes

    • Enhanced robustness of mask handling in the segmentation process by adding guard conditions.
  • Tests

    • Added a comprehensive test suite for the grayscale detection functionality, covering various edge cases.

Copy link
Contributor

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes introduce a new function isGrayscale in the canvas-decoder module, which determines if pixel data represents a grayscale image by sampling pixels and checking their color values and alpha channel. The decodeWithCanvas function is modified to use isGrayscale for determining the number of channels in the image data. Additionally, a new test suite for isGrayscale is added using the Vitest framework, covering various scenarios to ensure accurate functionality.

Changes

File Path Change Summary
app/packages/looker/src/worker/canvas-decoder.ts - Added isGrayscale function to check if pixel data is grayscale.
- Modified decodeWithCanvas to utilize isGrayscale for channel determination and updated return object.
app/packages/looker/src/worker/canvas-decoder.test.ts - Introduced a test suite for isGrayscale with four test cases covering various grayscale scenarios.
app/packages/looker/src/worker/painter.ts - Added a guard condition in the Segmentation method of PainterFactory to optimize RGBA mask handling.

Possibly related PRs

  • performance: use offscreen canvas to decode on-disk masks #5089: This PR introduces the decodeWithCanvas function in canvas-decoder.ts, which is directly related to the main PR's changes that also modify the decodeWithCanvas function to utilize the new isGrayscale function.
  • improve overlay rendering performance #5156: This PR enhances the performance of overlay rendering, which includes optimizations related to mask decoding and fetching, directly connecting to the functionality of the isGrayscale function in the context of image processing and overlay management.

Suggested labels

bug, app

Suggested reviewers

  • benjaminpkane

Poem

In a world of colors, bright and bold,
A grayscale tale begins to unfold.
With pixels checked, both near and far,
Our isGrayscale shines like a star.
So let’s decode with joy and cheer,
For clarity in images is finally here! 🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5307d57 and d83c00a.

📒 Files selected for processing (1)
  • app/packages/looker/src/worker/painter.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/looker/src/worker/painter.ts

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. (Experiment)
  • @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.

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.

@sashankaryal sashankaryal requested review from a team, benjaminpkane and brimoor December 12, 2024 23:57
@sashankaryal sashankaryal self-assigned this Dec 12, 2024
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

🧹 Outside diff range and nitpick comments (5)
app/packages/looker/src/lookers/utils.ts (1)

3-7: LGTM! Consider adding JSDoc documentation.

The implementation is clean and efficient. Consider adding JSDoc documentation to describe the parameters and return value, especially since this is a utility function that will be used across the codebase.

+/**
+ * Checks if a frame number exists within any of the buffer ranges
+ * @param buffers - Array of buffer ranges [start, end]
+ * @param frameNumber - Frame number to check
+ * @returns boolean indicating if the frame exists in any buffer range
+ */
 export const hasFrame = (buffers: Buffers, frameNumber: number) => {
app/packages/looker/src/lookers/utils.test.ts (1)

5-19: Consider adding more edge cases to the test suite.

The current test coverage is good but could be enhanced by adding these scenarios:

  • Empty buffers array
  • Single-frame buffer (where start equals end)
  • Adjacent buffers (e.g., [1,3], [4,6])
 describe("looker utilities", () => {
+  it("handles empty buffers", () => {
+    const EMPTY_BUFFERS: Buffers = [];
+    expect(hasFrame(EMPTY_BUFFERS, 1)).toBe(false);
+  });
+
+  it("handles single-frame buffers", () => {
+    const SINGLE_FRAME: Buffers = [[5, 5]];
+    expect(hasFrame(SINGLE_FRAME, 5)).toBe(true);
+    expect(hasFrame(SINGLE_FRAME, 4)).toBe(false);
+  });
+
   it("determines frame availability given a buffer list", () => {
app/packages/looker/src/worker/canvas-decoder.test.ts (2)

17-25: Consider adding more alpha value edge cases

The test effectively checks for non-255 alpha values, but consider adding tests for alpha = 0 and other boundary values.

it("should handle various alpha values", () => {
  const alphaTests = [
    [100, 100, 100, 0],   // fully transparent
    [100, 100, 100, 1],   // nearly transparent
    [100, 100, 100, 254], // nearly opaque
  ];
  for (const pixel of alphaTests) {
    const data = createData([pixel, ...Array(99).fill([100, 100, 100, 255])]);
    expect(isGrayscale(data)).toBe(false);
  }
});

27-35: Consider adding more color channel variation tests

While the test effectively checks for non-grayscale pixels, consider adding tests for variations in red and blue channels as well.

it("should detect various non-grayscale patterns", () => {
  const colorTests = [
    [101, 100, 100, 255], // red variation
    [100, 100, 101, 255], // blue variation
    [0, 255, 0, 255],     // extreme difference
  ];
  for (const pixel of colorTests) {
    const data = createData([pixel, ...Array(99).fill([100, 100, 100, 255])]);
    expect(isGrayscale(data)).toBe(false);
  }
});
app/packages/looker/src/worker/canvas-decoder.ts (1)

41-48: Consider preserving original imageData

The current implementation modifies the original imageData. Consider creating a new buffer instead.

   if (channels === 1) {
     // get rid of the G, B, and A channels, new buffer will be 1/4 the size
     const data = new Uint8ClampedArray(width * height);
     for (let i = 0; i < data.length; i++) {
       data[i] = imageData.data[i * 4];
     }
-    imageData.data.set(data);
+    return {
+      buffer: data.buffer,
+      channels,
+      arrayType: "Uint8ClampedArray",
+      shape: [height, width],
+    } as OverlayMask;
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4df037 and b0388a2.

📒 Files selected for processing (5)
  • app/packages/looker/src/lookers/utils.test.ts (1 hunks)
  • app/packages/looker/src/lookers/utils.ts (1 hunks)
  • app/packages/looker/src/lookers/video.ts (2 hunks)
  • app/packages/looker/src/worker/canvas-decoder.test.ts (1 hunks)
  • app/packages/looker/src/worker/canvas-decoder.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
app/packages/looker/src/lookers/utils.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/utils.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.test.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

app/packages/looker/src/lookers/video.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (4)
app/packages/looker/src/lookers/video.ts (1)

398-398: LGTM! Clean refactor of hasFrame method.

The change simplifies the implementation by delegating to the new utility function while maintaining the same behavior. This improves code maintainability and reduces duplication.

app/packages/looker/src/worker/canvas-decoder.test.ts (2)

4-8: LGTM: Helper function is well-implemented

The createData utility function is well-typed and correctly converts pixel tuples to the required Uint8ClampedArray format.


11-15: LGTM: Good test coverage for basic grayscale case

The test effectively verifies the basic grayscale detection with sufficient sample size.

app/packages/looker/src/worker/canvas-decoder.ts (1)

51-54: LGTM: Return object structure is correct

The OverlayMask object is properly constructed with all required fields.

app/packages/looker/src/worker/canvas-decoder.ts Outdated Show resolved Hide resolved
@sashankaryal sashankaryal changed the base branch from develop to release/v1.2.0 December 13, 2024 00:01
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

🧹 Outside diff range and nitpick comments (2)
app/packages/looker/src/worker/canvas-decoder.ts (2)

3-8: Enhance function documentation

While the current documentation explains the sampling strategy well, consider adding:

  • @param tag describing the data parameter
  • @returns tag explaining the boolean return value
  • @example showing typical usage
 /**
  * Checks if the given pixel data is grayscale by sampling a subset of pixels.
  * The function will check at least 500 pixels or 1% of all pixels, whichever is larger.
  * If the image is grayscale, the R, G, and B channels will be equal for all sampled pixels,
  * and the alpha channel will always be 255.
+ * 
+ * @param data - Uint8ClampedArray containing RGBA pixel data
+ * @returns boolean - true if the image is grayscale, false otherwise
+ * @example
+ * const imageData = ctx.getImageData(0, 0, width, height);
+ * const isGray = isGrayscale(imageData.data);
  */

39-48: Improve memory management and error handling

The grayscale optimization is good, but consider these improvements:

  1. Use TypedArray.transfer() for better memory efficiency
  2. Add error handling for buffer allocation
   const channels = isGrayscale(imageData.data) ? 1 : 4;

   if (channels === 1) {
-    // get rid of the G, B, and A channels, new buffer will be 1/4 the size
-    const data = new Uint8ClampedArray(width * height);
+    try {
+      // Preallocate with correct size
+      const data = new Uint8ClampedArray(new ArrayBuffer(width * height));
+      
+      // Use typed array methods for better performance
+      for (let i = 0; i < data.length; i++) {
+        data[i] = imageData.data[i * 4];
+      }
+      
+      // Transfer the buffer to avoid memory copy
+      imageData.data = new Uint8ClampedArray(data.buffer);
+    } catch (error) {
+      console.error("Failed to optimize grayscale buffer:", error);
+      // Fallback to RGBA
+      return {
+        buffer: imageData.data.buffer,
+        channels: 4,
+        arrayType: "Uint8ClampedArray",
+        shape: [height, width],
+      } as OverlayMask;
+    }
-    for (let i = 0; i < data.length; i++) {
-      data[i] = imageData.data[i * 4];
-    }
-    imageData.data.set(data);
   }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0388a2 and d570937.

📒 Files selected for processing (2)
  • app/packages/looker/src/worker/canvas-decoder.test.ts (1 hunks)
  • app/packages/looker/src/worker/canvas-decoder.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/packages/looker/src/worker/canvas-decoder.test.ts
🧰 Additional context used
📓 Path-based instructions (1)
app/packages/looker/src/worker/canvas-decoder.ts (1)

Pattern **/*.{ts,tsx}: Review the Typescript and React code for conformity with best practices in React, Recoil, Graphql, and Typescript. Highlight any deviations.

🔇 Additional comments (1)
app/packages/looker/src/worker/canvas-decoder.ts (1)

51-54: Verify type compatibility and memory management

Let's verify the impact of these changes on the codebase.

✅ Verification successful

Type compatibility and memory management are properly handled

Based on the verification results:

  1. The OverlayMask interface in numpy.ts correctly defines the expected type structure with buffer: ArrayBuffer, matching the implementation.
  2. Memory management is properly handled:
    • The buffer is part of the ImageData object which is managed by the browser
    • Canvas cleanup is implemented in overlay classes via cleanup() methods
    • Video and bitmap resources are properly released through close() and release() methods

The changes are type-safe and follow the established memory management patterns in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check OverlayMask type usage and potential memory issues

# Find all uses of OverlayMask type
echo "Checking OverlayMask usage..."
ast-grep --pattern 'type $_ = OverlayMask'

# Look for memory management patterns
echo "Checking memory management patterns..."
rg -l 'imageData\.data\.buffer' --type ts

# Check for existing memory leak reports
echo "Checking for memory leak reports..."
rg -i 'memory\s+leak.*canvas' --type ts

Length of output: 416


Script:

#!/bin/bash
# Let's check more thoroughly

# Find type definitions and interfaces related to canvas data
echo "Checking type definitions..."
rg "interface.*Mask" --type ts -A 5
rg "type.*Mask\s*=" --type ts -A 5

# Check buffer usage patterns in the codebase
echo "Checking buffer usage..."
rg "\.buffer" --type ts -A 2

# Look for canvas cleanup or disposal patterns
echo "Checking cleanup patterns..."
rg "dispose|cleanup|release|free" --type ts -A 3

# Check for ArrayBuffer or TypedArray related patterns
echo "Checking array buffer patterns..."
rg "Uint8ClampedArray|ArrayBuffer" --type ts -A 2

Length of output: 51601

tom-vx51
tom-vx51 previously approved these changes Dec 13, 2024
@sashankaryal sashankaryal force-pushed the fix/grayscale-segmentations branch from 5307d57 to d83c00a Compare December 13, 2024 01:44
@sashankaryal sashankaryal changed the title fix grayscale segmentation regression fix grayscale segmentation regression + RGB masks recoloring issue Dec 13, 2024
@sashankaryal sashankaryal merged commit 568da8a into release/v1.2.0 Dec 13, 2024
12 checks passed
@sashankaryal sashankaryal deleted the fix/grayscale-segmentations branch December 13, 2024 17:31
This was referenced Dec 13, 2024
@coderabbitai coderabbitai bot mentioned this pull request Jan 3, 2025
7 tasks
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.

2 participants