⚡️ Speed up function _extract_segmentation_annotation by 12%
#44
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 12% (0.12x) speedup for
_extract_segmentation_annotationinultralytics/utils/callbacks/comet.py⏱️ Runtime :
1.74 milliseconds→1.56 milliseconds(best of250runs)📝 Explanation and details
The optimized code achieves an 11% speedup by replacing inefficient list comprehensions with a single explicit loop and using more direct array operations.
Key optimizations applied:
Eliminated double list comprehensions: The original code used two chained list comprehensions that created intermediate arrays and lists. The optimized version uses a single loop that processes each polygon once.
Replaced
np.array().squeeze().ravel()withreshape(-1): The original approach unnecessarily copied data and performed multiple array transformations. Sincecv2.findContoursalready returns numpy arrays,reshape(-1)directly flattens them without copying when possible.Pre-allocated output list: Instead of building intermediate lists through comprehensions, the optimized version directly appends to a pre-allocated result list, reducing memory allocations.
Why this leads to speedup:
reshape(-1)avoids the copy operations inherent innp.array().squeeze().ravel()Performance impact based on test results:
The optimization shows the most significant gains (15-25% speedup) for cases with multiple polygons, such as masks with many small shapes or complex segmentation scenarios. Even simple single-polygon cases see 12-22% improvements. The function is called from
_format_prediction_annotationsduring YOLO prediction processing, where segmentation masks are converted for visualization - making this optimization valuable for real-time inference pipelines processing many segmented objects.Best performance gains observed in:
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_extract_segmentation_annotation-mirackkxand push.