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

feat: add image cropping preprocessing #119

Merged
merged 71 commits into from
Feb 12, 2025

Conversation

strixy16
Copy link
Collaborator

@strixy16 strixy16 commented Feb 10, 2025

Using crop methods from med-imagetools, setup three crop methods that can be used as preprocessing steps for feature extraction.
Three methods migrated from readii-fmcib = bbox, centroid, cube

Summary by CodeRabbit

  • New Features
    • Refined visualization in the notebook with updated image display settings, including adjusted colormaps and layout.
    • Introduced functionality to crop and resize images and masks using multiple methods and configurable dimensions.
  • Enhancements
    • Improved image slice display with the option to specify a custom display axis.
  • Tests
    • Added comprehensive tests to validate the new image processing and cropping features.
  • Documentation
    • Updated notebook metadata and display settings.

strixy16 and others added 30 commits January 17, 2025 15:53
…for quick checking dimension match between image and centroid/mask/dimensions/etc.
…to centroid, and mask update in crop with pyradiomics
Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Walkthrough

The changes update a Jupyter notebook to modify image display settings and metadata, adjust the execution count, and change colormap and axis tick configurations. The displayImageSlice function in the image processing module now accepts an optional axis parameter and returns its value. A new module for image cropping and resizing is added with accompanying tests to validate various cropping methods and resize dimensions. Additionally, a lint configuration update allows the io module in built-in checks.

Changes

File(s) Change Summary
notebooks/viz_neg_controls.ipynb Modified execution count; updated image output with new colormap parameters and axis ticks; updated notebook metadata (display name, kernel name, and Python version).
src/readii/image_processing.py Updated displayImageSlice to accept an optional ax parameter and return the axis object; modified logic to create a new axis if none is provided.
src/readii/process/images/{__init__.py, crop.py} Introduced new function crop_and_resize_image_and_mask, including type alias CropMethods; implemented cropping and resizing logic with error handling and different crop methods.
tests/process/images/test_crop.py Added test fixtures and functions to validate the cropping and resizing functionality for various methods and resize dimensions.
config/ruff.toml Added a lint configuration section to permit usage of the io module under flake8-builtins.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant DIS as displayImageSlice
    participant PLT as plt.subplots

    Caller->>DIS: call displayImageSlice(image, sliceIdx, ..., ax)
    alt ax provided
        DIS->>DIS: Use provided axis
    else ax is None
        DIS->>PLT: Create new axis using plt.subplots()
    end
    DIS->>DIS: Display image using imshow with specified colormap
    DIS->>Caller: Return the axis object
Loading
sequenceDiagram
    participant Caller as Caller
    participant CropFunc as crop_and_resize_image_and_mask
    participant LabelCheck as LabelShapeStatisticsImageFilter
    participant Processor as Image & Mask Processor

    Caller->>CropFunc: call crop_and_resize_image_and_mask(image, mask, label, crop_method, resize_dimension)
    CropFunc->>LabelCheck: Check if label exists in mask
    alt Label found
        CropFunc->>CropFunc: Determine crop box based on crop_method ("bounding_box", "centroid", "cube")
        CropFunc->>Processor: Crop image and mask accordingly
        alt Resize dimension provided
            Processor->>Processor: Resize image (linear) and mask (nearest neighbor)
        end
        CropFunc->>Caller: Return cropped and resized image, mask
    else Label not found
        CropFunc->>Caller: Raise ValueError (label missing)
    end
Loading

Suggested reviewers

  • jjjermiah

Poem

Oh, I’m a rabbit with a curious hop,
Nibbling on code ‘til bugs all stop.
New functions bloom like carrots in spring,
Cropping and showing images with a zing!
With tests and tweaks, my heart does race,
Celebrating each change with a happy, twitching face!
🥕🐰


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 525c5bc and 1b62c0e.

📒 Files selected for processing (1)
  • src/readii/process/images/crop.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/readii/process/images/crop.py
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Unit-Tests (windows-latest, py312)
  • GitHub Check: Unit-Tests (windows-latest, py310)
  • GitHub Check: Unit-Tests (macos-14, py312)
  • GitHub Check: Unit-Tests (macos-latest, py312)
  • GitHub Check: Unit-Tests (macos-latest, py310)

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.

@strixy16 strixy16 marked this pull request as ready for review February 11, 2025 21:40
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 (6)
tests/process/images/test_crop.py (3)

2-2: Remove unused import.

The SimpleITK import is not directly used in this file.

-import SimpleITK as sitk
🧰 Tools
🪛 Ruff (0.8.2)

2-2: SimpleITK imported but unused

Remove unused import: SimpleITK

(F401)


9-16: Make test data paths configurable.

Hardcoded test data paths make tests brittle and less maintainable. Consider making these paths configurable through environment variables or test configuration.

Example implementation:

import os

@pytest.fixture
def test_data_dir():
    return os.getenv('TEST_DATA_DIR', 'tests')

@pytest.fixture
def nsclcCT(test_data_dir):
    return os.path.join(test_data_dir, 'NSCLC_Radiogenomics/R01-001/09-06-1990-NA-CT_CHEST_ABD_PELVIS_WITH_CON-98785/3.000000-THORAX_1.0_B45f-95741')

Also applies to: 19-21, 24-26


45-51: Add docstring and explain expected size.

The test function would benefit from a docstring explaining the default behavior being tested and why the expected size is (92, 92, 92).

 def test_default_crop_and_resize_image(lung4D_image, lung4D_mask):
+    """Test the default cropping behavior using the cube method.
+    
+    The default crop method is 'cube', which expands the bounding box to a cube
+    with the maximum dimension. In this case, the maximum dimension is 92 voxels,
+    resulting in a (92, 92, 92) cube.
+    """
     expected_size = (92, 92, 92)
src/readii/process/images/crop.py (2)

67-69: Use 'is' for None comparison.

Replace == with is when comparing with None as per Python style guidelines.

-            if resize_dimension == None:
+            if resize_dimension is None:
🧰 Tools
🪛 Ruff (0.8.2)

67-67: Comparison to None should be cond is None

Replace with cond is None

(E711)


100-126: Consider moving test code to a separate test file.

The main block contains test code with hardcoded paths. Consider moving this code to a proper test file or using configurable paths.

src/readii/image_processing.py (1)

157-212: Use 'is' for None comparisons.

Replace == with is when comparing with None as per Python style guidelines.

-    if dispMin == None:
+    if dispMin is None:
-    if dispMax == None:
+    if dispMax is None:
-    if ax == None:
+    if ax is None:
🧰 Tools
🪛 Ruff (0.8.2)

187-187: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)


193-193: Comparison to None should be cond is None

Replace with cond is None

(E711)


195-195: Comparison to None should be cond is None

Replace with cond is None

(E711)


199-199: Multiple statements on one line (colon)

(E701)


200-200: Multiple statements on one line (colon)

(E701)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a11db1 and 1076261.

⛔ Files ignored due to path filters (1)
  • pixi.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • notebooks/viz_neg_controls.ipynb (4 hunks)
  • pyproject.toml (1 hunks)
  • src/readii/image_processing.py (3 hunks)
  • src/readii/process/images/__init__.py (1 hunks)
  • src/readii/process/images/crop.py (1 hunks)
  • tests/process/images/test_crop.py (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • src/readii/process/images/init.py
  • pyproject.toml
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/process/images/test_crop.py

2-2: SimpleITK imported but unused

Remove unused import: SimpleITK

(F401)

src/readii/process/images/crop.py

67-67: Comparison to None should be cond is None

Replace with cond is None

(E711)

🔇 Additional comments (5)
notebooks/viz_neg_controls.ipynb (3)

102-103: LGTM! Good visualization improvements.

The addition of the grayscale colormap and axis removal enhances the clarity of the donut image visualization.


106-108: LGTM! Enhanced mask visualization.

Good choice of using the 'Greens' colormap for the mask visualization and removing axis ticks for a cleaner display.


388-390: Verify Python version compatibility.

The notebook is using Python 3.12.8. Let's verify this version is officially released and stable.

Also applies to: 402-402

✅ Verification successful

🌐 Web query:

What is the latest stable version of Python 3.12?

💡 Result:

The latest stable version of Python 3.12 as of February 2025 is Python 3.12.8, released on December 3, 2024[5]. This maintenance release includes over 250 bug fixes, security updates like libexpat upgrades to address CVE-2024-50602[5], and documentation improvements since version 3.12.7.

Key details about the Python 3.12 series:

  • Security focus: Recent versions prioritize patching vulnerabilities (e.g., CVE-2024-7592 fixed in v3.12.6)[3]
  • Performance: Maintains a ~5% speed improvement over Python 3.11 through optimizations like BOLT binary enhancements[1][7]
  • Support lifecycle: Security updates will continue through October 2028[4]

For most users, Python recommends upgrading to the latest stable version (currently v3.12.x) for security and stability benefits while waiting for newer major releases like Python 3.13[6].

Citations:


Python Version Compatibility Confirmed
The web query confirms that Python 3.12.8 is the latest stable release as of February 2025. The notebook's usage of Python 3.12.8 is therefore compliant with the current stable version.

tests/process/images/test_crop.py (1)

53-93: LGTM! Comprehensive test coverage.

The parameterized test is well-structured with good coverage of different cropping methods and resize dimensions. The test cases are clearly documented with comments explaining each scenario.

src/readii/image_processing.py (1)

157-212: LGTM! Good improvement to function reusability.

The addition of the optional ax parameter and returning the axis object improves the function's reusability by allowing it to be used in subplots and custom figure layouts.

🧰 Tools
🪛 Ruff (0.8.2)

187-187: Use is and is not for type comparisons, or isinstance() for isinstance checks

(E721)


193-193: Comparison to None should be cond is None

Replace with cond is None

(E711)


195-195: Comparison to None should be cond is None

Replace with cond is None

(E711)


199-199: Multiple statements on one line (colon)

(E701)


200-200: Multiple statements on one line (colon)

(E701)

src/readii/process/images/crop.py Outdated Show resolved Hide resolved
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 (2)
src/readii/process/images/crop.py (2)

30-31: Fix parameter name in docstring.

The parameter name in the docstring is resize_dimensions but the actual parameter is resize_dimension (singular).

-    resize_dimensions : int, optional
+    resize_dimension : int, optional

106-110: Consider using path constants or configuration for test paths.

The hardcoded test paths could break if files are moved or renamed. Consider:

  1. Moving these paths to a configuration file
  2. Using path constants
  3. Using relative paths from a base test directory
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1076261 and 1b0d4d4.

⛔ Files ignored due to path filters (1)
  • pixi.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • src/readii/process/images/crop.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
src/readii/process/images/crop.py

67-67: Comparison to None should be cond is None

Replace with cond is None

(E711)

🔇 Additional comments (2)
src/readii/process/images/crop.py (2)

1-9: LGTM! Well-organized imports and clear type definitions.

The imports are properly organized and the CropMethods type alias accurately reflects the implemented methods.


12-98: LGTM! Well-implemented cropping functionality.

The implementation is robust with:

  • Comprehensive error handling
  • Clear method-specific logic
  • Proper image and mask resizing with appropriate interpolation methods
🧰 Tools
🪛 Ruff (0.8.2)

67-67: Comparison to None should be cond is None

Replace with cond is None

(E711)

src/readii/process/images/crop.py Outdated Show resolved Hide resolved
Copy link

codecov bot commented Feb 11, 2025

Codecov Report

Attention: Patch coverage is 51.78571% with 27 lines in your changes missing coverage. Please review.

Project coverage is 50.25%. Comparing base (39a6d6b) to head (1b62c0e).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
src/readii/process/images/crop.py 55.10% 22 Missing ⚠️
src/readii/image_processing.py 0.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #119      +/-   ##
==========================================
+ Coverage   48.12%   50.25%   +2.13%     
==========================================
  Files          34       36       +2     
  Lines        1492     1546      +54     
==========================================
+ Hits          718      777      +59     
+ Misses        774      769       -5     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@strixy16 strixy16 requested a review from jjjermiah February 12, 2025 15:03
Copy link
Contributor

@jjjermiah jjjermiah left a comment

Choose a reason for hiding this comment

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

looks solid

@strixy16 strixy16 merged commit 978bdb5 into main Feb 12, 2025
20 checks passed
@strixy16 strixy16 deleted the katys/feature/add-fmcib-cropping-code branch February 14, 2025 15:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

2 participants