-
Couldn't load subscription status.
- Fork 6
Convert Tensor images to PIL #105
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
Conversation
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #105 +/- ##
==========================================
+ Coverage 96.64% 97.39% +0.74%
==========================================
Files 23 38 +15
Lines 1818 3681 +1863
==========================================
+ Hits 1757 3585 +1828
- Misses 61 96 +35 ☔ View full report in Codecov by Sentry. |
WalkthroughThe changes primarily enhance the image processing capabilities within the Changes
Possibly related PRs
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
a269f1d to
9d87e44
Compare
d8f1554 to
22c7a96
Compare
22c7a96 to
105e496
Compare
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.
Actionable comments posted: 10
🧹 Outside diff range and nitpick comments (13)
tests/data/test_get_data_chunks.py (3)
Line range hint
111-112: Add tests for different scale valuesWhile the scale parameter is set to 1.0, we should add test cases with different scale values to verify the resizing functionality works as expected.
config.data_config.preprocessing.scale = 1.0 config.data_config.preprocessing.is_rgb = True +# Test with different scale values +scales = [0.5, 2.0] +for scale in scales: + config.data_config.preprocessing.scale = scale + samples = [] + for idx, lf in enumerate(labels): + res = centered_instance_data_chunks( + (lf, idx), + data_config=config.data_config, + anchor_ind=0, + crop_size=(160, 160), + max_instances=2, + max_hw=max_hw, + ) + samples.extend(res) + expected_size = int(226 * scale) + assert transform(samples[0]["instance_image"]).shape == (3, expected_size, expected_size)
Line range hint
209-260: Consider reducing test setup duplicationThe transformation setup and RGB testing pattern is repeated across all test functions. Consider extracting common setup into fixtures or helper functions.
@pytest.fixture def transform(): return T.ToTensor() @pytest.fixture def rgb_config(config): config.data_config.preprocessing.is_rgb = True return config def assert_image_shapes(sample, transform, is_rgb=False): channels = 3 if is_rgb else 1 assert transform(sample["image"]).shape == (channels, 384, 384)
Line range hint
1-260: Consider enhancing test coverage for image transformationsWhile the changes successfully implement PIL image transformations, consider these improvements:
- Add property-based tests to verify transformation behavior across different image sizes and scales
- Add edge cases for extreme scale values
- Consider testing memory usage to verify the PR's objective of reducing memory footprint
sleap_nn/data/instance_cropping.py (1)
50-55: LGTM! Consider consolidating the NaN handling logic.The NaN handling logic is robust and well-implemented. However, the code could be slightly more concise while maintaining readability.
Consider this alternative implementation that reduces repetition:
- diff_x = np.nanmax(pts[:, 0]) - np.nanmin(pts[:, 0]) - diff_x = 0 if np.isnan(diff_x) else diff_x - max_length = np.maximum(max_length, diff_x) - diff_y = np.nanmax(pts[:, 1]) - np.nanmin(pts[:, 1]) - diff_y = 0 if np.isnan(diff_y) else diff_y - max_length = np.maximum(max_length, diff_y) + diffs = [np.nanmax(pts[:, i]) - np.nanmin(pts[:, i]) for i in range(2)] + diffs = [0 if np.isnan(d) else d for d in diffs] + max_length = np.maximum(max_length, max(diffs))tests/data/test_streaming_datasets.py (1)
35-35: LGTM! Consider adding shape calculation comments.The addition of scale parameter and testing multiple scales (0.5 and 1.0) aligns well with the PR objective. The cleanup is properly handled.
Consider adding comments explaining how the output shapes are calculated, e.g.:
# Image shape: (1, 1, 200, 200) # Original 400x400 with scale=0.5 # Confidence maps: (1, 2, 100, 100) # Image/2 due to output_stride=2 # PAFs: (50, 50, 2) # Image/4 due to output_stride=4Also applies to: 64-81
sleap_nn/data/resizing.py (4)
Line range hint
1-152: Document image format requirements and consider PIL conversion handlingGiven the PR's objective to convert between Tensor and PIL formats, consider:
- Documenting the expected input/output image formats in function docstrings
- Adding PIL conversion utilities in this module since it's the central image processing location
- Ensuring
tvf.resizebehavior is consistent with both Tensor and PIL inputsConsider adding these utility functions:
def to_pil_image(image: torch.Tensor) -> "PIL.Image": """Convert a torch tensor to PIL Image for storage efficiency.""" return tvf.to_pil_image(image) def to_tensor(image: "PIL.Image") -> torch.Tensor: """Convert a PIL Image back to torch tensor for processing.""" return tvf.to_tensor(image)
Line range hint
249-286: Standardize error handling in SizeMatcherThe error handling in
SizeMatcher.__iter__usesExceptionwhile similar checks inapply_sizematcheruseValueError. Consider standardizing to useValueErrorconsistently.- raise Exception( + raise ValueError( f"Max height {self.max_height} should be greater than the current image height: {img_height}" ) if pad_width < 0: - raise Exception( + raise ValueError( f"Max width {self.max_width} should be greater than the current image width: {img_width}" )
Line range hint
31-63: Make padding more configurableThe padding functions use hardcoded parameters that could be made configurable:
- Padding mode is always 'constant'
- Padding value is always 0
Consider updating the function signature:
def apply_pad_to_stride( image: torch.Tensor, max_stride: int, + pad_mode: str = "constant", + pad_value: float = 0.0, ) -> torch.Tensor:
Line range hint
89-106: Consider performance optimizationsThe
apply_resizerfunction could be optimized for batch processing:
- Add batch support to process multiple images at once
- Consider in-place operations where possible to reduce memory usage
Example batch implementation:
def apply_resizer_batch( images: torch.Tensor, instances: torch.Tensor, scale: float = 1.0 ) -> Tuple[torch.Tensor, torch.Tensor]: """Batch version of apply_resizer.""" if scale != 1.0: # images shape: (batch_size, channels, height, width) images = resize_image(images, scale) instances = instances * scale return images, instancessleap_nn/data/get_data_chunks.py (2)
7-7: Consider cleaning up unused imports.Since normalization steps have been removed, consider cleaning up any unused imports from the
normalizationmodule to maintain code cleanliness.Also applies to: 17-17
74-82: Document tensor dimension requirements.The code assumes specific tensor dimensions for the image (presence of batch dimension that gets squeezed). Consider documenting the expected input tensor format in the function's docstring to prevent potential runtime errors.
tests/training/test_model_trainer.py (2)
Line range hint
296-301: Fix inconsistent checkpoint file referencesThere are still references to "best.ckpt" in the test cleanup code while the loading code has been updated to use "last.ckpt". This inconsistency should be resolved to maintain test reliability.
Apply this change to all cleanup sections:
-if (Path(centroid_config.trainer_config.save_ckpt_path) / "best.ckpt").exists(): +if (Path(centroid_config.trainer_config.save_ckpt_path) / "last.ckpt").exists(): os.remove( ( - Path(centroid_config.trainer_config.save_ckpt_path) / "best.ckpt" + Path(centroid_config.trainer_config.save_ckpt_path) / "last.ckpt" ).as_posix() )Also applies to: 449-454
Line range hint
1-24: Add test coverage for new image conversion featuresThe PR introduces Tensor-to-PIL image conversion and relocates the resizer function, but there's no test coverage for these changes. Consider adding test cases to verify:
- Correct conversion between Tensor and PIL formats
- Proper functioning of the relocated resizer
Add new test cases like:
def test_image_format_conversion(): """Test conversion between Tensor and PIL image formats.""" # Test tensor to PIL conversion tensor_image = torch.rand(1, 3, 224, 224) pil_image = convert_tensor_to_pil(tensor_image) assert isinstance(pil_image, Image.Image) # Test PIL to tensor conversion tensor_result = convert_pil_to_tensor(pil_image) assert torch.allclose(tensor_image, tensor_result) def test_resizer_in_get_chunks(): """Test the relocated resizer function in get_chunks.""" # Test resizing behavior original_size = (224, 224) target_size = (112, 112) chunks = get_chunks(...) # Add appropriate test data assert chunks[0].size == target_size
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (10)
sleap_nn/data/get_data_chunks.py(14 hunks)sleap_nn/data/instance_cropping.py(1 hunks)sleap_nn/data/resizing.py(1 hunks)sleap_nn/data/streaming_datasets.py(11 hunks)sleap_nn/inference/predictors.py(1 hunks)sleap_nn/training/get_bin_files.py(5 hunks)sleap_nn/training/model_trainer.py(3 hunks)tests/data/test_get_data_chunks.py(10 hunks)tests/data/test_streaming_datasets.py(8 hunks)tests/training/test_model_trainer.py(4 hunks)
🔇 Additional comments (17)
sleap_nn/training/get_bin_files.py (2)
Line range hint 1-150: Verify integration with PIL conversion process.
While the scale parameter addition supports the PR's goal of reducing file sizes, we should verify the integration with the PIL conversion process mentioned in the PR objectives.
Let's check the image processing pipeline:
#!/bin/bash
# Description: Verify PIL conversion integration
# Look for PIL/image conversion logic in the codebase
echo "Searching for PIL conversion logic..."
rg -l "from PIL import|Image.fromarray|torchvision.*transforms" --type python
# Look for image processing in the data loading pipeline
echo "Searching for image processing in data pipeline..."
rg -A 10 "def (load|process|transform).*image" --type python48-48: Verify scale parameter handling in dependent modules.
The scale parameter is being passed to various data chunk functions, but we should verify its proper handling in those modules.
Let's check the implementation of these functions:
Also applies to: 77-77, 104-104, 130-130
✅ Verification successful
Based on the search results, I can now provide a final response regarding the scale parameter handling:
Scale parameter is properly handled throughout the data processing pipeline
The scale parameter is consistently and correctly handled in all dependent modules:
- In data chunk functions (
bottomup_data_chunks,centered_instance_data_chunks,centroid_data_chunks,single_instance_data_chunks), scale is:- Applied to both images and instances using
apply_resizer - Properly cascaded with
eff_scalefromapply_sizematcher
- Applied to both images and instances using
- Scale transformations are properly tested in test files
- Scale parameter flows through the inference pipeline via
input_scalein predictors and model layers - Resizing operations maintain aspect ratios and coordinate transformations
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check how scale parameter is used in data chunk functions
# Look for the data chunk function implementations
echo "Searching for data chunk function implementations..."
rg -A 10 "def (bottomup|centered_instance|centroid|single_instance)_data_chunks" --type python
# Look for image scaling/resizing logic
echo "Searching for image scaling implementation..."
rg -A 5 "scale.*image|resize.*image" --type python
Length of output: 495
Script:
#!/bin/bash
# Let's try a different approach to find scale parameter usage
# Search for scale parameter in function definitions and their implementations
echo "Searching for scale parameter usage..."
rg -A 10 "def.*scale.*:|scale\s*=\s*" --type-add 'python:*.py'
# Search specifically in the data chunks related files
echo "Searching in data chunks related files..."
fd -e py chunks | xargs rg -A 10 "scale"
# Look for image processing related functions
echo "Searching for image processing..."
rg -A 10 "(process|transform).*image" --type-add 'python:*.py'
Length of output: 79132
tests/data/test_get_data_chunks.py (3)
1-2: LGTM: Import changes align with PR objectives
The addition of torchvision.transforms is appropriate for handling the new PIL image conversion workflow.
143-143: LGTM: Consistent transformation handling
The changes maintain consistency with other test functions in handling image transformations and shape assertions.
Also applies to: 171-171, 201-201
16-16: Verify the intended tensor shapes after transformation
The shape assertions have changed significantly:
- Grayscale:
(1,1,384,384)→(1,384,384) - RGB:
(1,3,384,384)→(3,384,384)
These changes indicate the removal of the batch dimension. While this works for testing, we should verify if downstream components expect this tensor shape.
Also applies to: 42-42, 69-69
✅ Verification successful
Let me analyze the shape requirements more broadly to understand the tensor dimension expectations in the codebase.
Let me analyze the tensor transformations and shape expectations in the codebase to better understand if the shape changes are intentional.
Based on the codebase analysis, I can now provide a definitive response about the tensor shape changes:
Shape changes are intentional and correct
The shape changes from (1,1,384,384) → (1,384,384) for grayscale and (1,3,384,384) → (3,384,384) are the expected behavior of ToTensor() transform. This is because:
- The codebase shows consistent use of
PILToTensor()followed byunsqueeze(dim=0)for image processing, indicating batch dimension is handled explicitly ToTensor()is designed to output tensors without the batch dimension, which matches the observed shape changes- The removal of batch dimension is standard practice in PyTorch data transformations, as the batch dimension is typically added later by the DataLoader
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for tensor shape expectations in the codebase
rg -A 2 "\.shape\s*==.*384.*384" --glob '!tests/**'
Length of output: 53
Script:
#!/bin/bash
# Search for shape-related assertions or checks in the main codebase
rg -A 2 "shape|size.*384" --glob '!tests/**'
# Search for tensor operations or model forward passes that might expect specific shapes
ast-grep --pattern 'def forward($$$) { $$$ }'
# Look for any configuration files that might specify expected dimensions
fd -e yaml -e json -e ini -e cfg -x cat {}
Length of output: 103031
Script:
#!/bin/bash
# Search for tensor shape expectations in model forward passes and data processing
rg -A 2 "ToTensor|transform.*tensor" --glob '!tests/**'
# Look for any configuration files that specify input/output tensor shapes
rg -A 2 "shape.*384|384.*shape" --glob '!tests/**'
Length of output: 1199
sleap_nn/data/instance_cropping.py (1)
50-55: Verify NaN handling with PIL image conversion.
Since this PR involves converting images to PIL format, let's verify that the NaN handling in this function remains compatible with the new image processing pipeline.
✅ Verification successful
NaN handling is properly tested and compatible with image processing pipeline
The NaN handling in the find_instance_crop_size function is verified to be working correctly:
- The test file
test_instance_cropping.pyincludes comprehensive tests for instance cropping functionality - The NaN handling code is used only for calculating bounding box dimensions and doesn't interact with PIL/image conversion
- The image cropping is handled separately by
kornia.geometry.transform.crop_and_resizeafter the NaN checks - The test
test_find_instance_crop_sizeverifies the core functionality with real instances that could contain NaN values
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for PIL image conversion code that might interact with this function
rg -l "PIL" . | xargs rg "find_instance_crop_size"
# Search for test files that verify NaN handling
rg -l "test.*instance.*crop" . | xargs rg "nan"
Length of output: 96
Script:
#!/bin/bash
# Let's first find the function definition and its usage
ast-grep --pattern 'def find_instance_crop_size'
# Search for any PIL-related image processing in the same file
rg "PIL|Image" sleap_nn/data/instance_cropping.py
# Find tests related to instance cropping
fd "test.*instance.*crop.*\.py$"
Length of output: 174
Script:
#!/bin/bash
# Let's examine the test file to understand how NaN handling is tested
cat tests/data/test_instance_cropping.py
# Let's also look at the full implementation of instance_cropping.py
cat sleap_nn/data/instance_cropping.py
Length of output: 11743
tests/data/test_streaming_datasets.py (3)
170-170: LGTM! Changes align with PR objectives.
The implementation properly tests both scale values and includes appropriate cleanup. The output shape assertions correctly validate the scaling behavior.
Also applies to: 197-216
Line range hint 1-324: Verify test coverage of PIL conversion and resizing.
The tests provide good coverage of the new scaling functionality, but there are a few areas that could be improved:
- Test that the images are actually converted to PIL format and back
- Verify that the resizing is performed correctly with different aspect ratios
- Add error cases for invalid scale values
Let's check if these aspects are covered in other test files:
#!/bin/bash
# Check for PIL conversion tests
rg -l "PIL|Image\.fromarray|ToTensor" tests/
# Check for aspect ratio tests
rg -l "aspect_ratio|different.*width.*height" tests/
# Check for invalid scale tests
rg -l "invalid.*scale|negative.*scale|zero.*scale" tests/126-126: Consider adding test case with scale=1.0 for consistency.
While the scale parameter is correctly implemented, other test functions include test cases with both scale=0.5 and scale=1.0. Consider adding a similar second test case here for consistency in test coverage.
Let's verify if other files in the test suite follow this pattern:
Also applies to: 144-144
sleap_nn/data/resizing.py (1)
152-152: LGTM: Type consistency improvement
The change from 1 to 1.0 ensures consistent float type returns for the scale ratio, matching the type returned in the resizing branch (eff_scale_ratio).
sleap_nn/data/get_data_chunks.py (2)
Line range hint 1-316: Ensure comprehensive testing of image transformations.
The changes introduce new image transformation logic across multiple functions. Consider:
- Adding tests for various scale factors to verify correct resizing
- Verifying PIL conversion maintains image quality
- Testing memory usage with different image sizes to confirm reduction in
.binfile size - Adding integration tests to verify the entire pipeline works with the new transformations
#!/bin/bash
# Check for existing image-related tests
rg -l "test.*image" tests/161-163: Consider handling dtype conversion consistently.
The explicit conversion to float32 suggests potential dtype compatibility issues. Consider:
- Handling dtype conversion earlier in the pipeline
- Documenting the expected dtype in the function signature
- Adding error handling for unsupported dtypes
✅ Verification successful
Let's search with broader patterns to catch different forms of dtype conversions and documentation.
Dtype conversion is consistently handled across the codebase
The explicit conversion to float32 in get_data_chunks.py aligns with the project's established pattern. The codebase shows:
- Consistent use of
torch.float32for image processing across multiple modules - Explicit dtype assertions in tests confirming
float32expectations - Clear documentation in docstrings specifying
float32requirements
The conversion is appropriate and follows the project's conventions. No changes needed.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for other dtype conversions in the codebase
rg "to\(torch\.float32\)" --type py
Length of output: 122
Script:
#!/bin/bash
# Search for dtype conversions with different patterns
rg "\.to\(.*float" --type py -A 2
# Search for tensor type conversions
rg "\.type\(torch\." --type py -A 2
# Search for float dtype mentions in function signatures and docstrings
rg "dtype.*float|float.*dtype" --type py
Length of output: 15563
sleap_nn/data/streaming_datasets.py (2)
Line range hint 1-355: Verify complete implementation of PIL conversion workflow.
The changes in this file implement the PIL to Tensor conversion as intended. However, to ensure the complete workflow is functioning:
- Verify that images are properly converted to PIL format in
generate_bin_files.py - Confirm that resizing is correctly implemented in
get_chunks() - Ensure the conversion maintains image quality while reducing file size
#!/bin/bash
# Check for PIL usage in generate_bin_files.py
rg "PIL" --type python "generate_bin_files.py"
# Check for resize implementation in get_chunks
rg "get_chunks.*scale" --type python8-8: Verify if resizing imports are still needed.
The apply_resizer import from sleap_nn.data.resizing appears to be unused after the changes, as the resizing functionality has been moved. Consider removing it if it's no longer needed.
Also applies to: 16-16
sleap_nn/training/model_trainer.py (1)
185-186: LGTM: Scale parameter properly integrated
The addition of the scale parameter to the subprocess call is well-implemented and aligns with the PR's objective of supporting image resizing for reduced storage requirements.
sleap_nn/inference/predictors.py (2)
Line range hint 54-55: Addition of max_height and max_width to preprocess_config
The inclusion of max_height and max_width in the preprocess_config dictionary enhances flexibility in image resizing during preprocessing. This allows for better control over the dimensions of input images, which can improve model performance and efficiency.
278-278:
Potential redundant normalization of frame["image"]
The apply_normalization function is applied to frame["image"] here, but normalization may already be performed elsewhere in the preprocessing pipeline, potentially leading to redundancy.
Please run the following script to verify if apply_normalization is called on frame["image"] or ex["image"] elsewhere in the codebase:
Currently, the
binfiles generated by sleap_nn.training.generate_bin_files.py is much larger compared to the source dataset (almost 100 times bigger). Thus, to reduce the disk footprint, we convert the images to PIL before generating the.binfiles and then convert it back totorch.Tensorin theLitdata.StreamingDatasetclasses. We also move the resizer function toget_chunks()so that the.binfiles have resized image (which helps in saving up disk space).Summary by CodeRabbit
Release Notes
New Features
--scalefor specifying scaling factors during data processing.Bug Fixes
Documentation
Tests