perf(detection): count mask pixels with count_nonzero#2361
Open
RubenHaisma wants to merge 1 commit into
Open
Conversation
Mask pixel-area counting used `np.sum` — `np.array([np.sum(m) for m in masks])` in `Detections.area` and `np.sum(mask, axis=(1, 2))` in the metrics `get_mask_size_category`. For boolean masks `np.count_nonzero` (with no axis) dispatches to NumPy's SIMD popcount over the raw byte buffer, whereas every axis-reduction form — `np.sum(..., axis=...)` and even `np.count_nonzero(..., axis=...)` — falls back to a slower generic reduction. So counting per mask with `np.count_nonzero` is several times faster than the "obvious" vectorized sum, while producing bit-identical integer counts. Route both sites through `np.fromiter((np.count_nonzero(m) for m in masks), dtype=np.int64, count=len(masks))`. `dtype=np.int64` preserves the documented `Detections.area` mask-branch dtype on every platform (a bare `np.array([...])` of Python ints would be int32 on Windows). Measured ~5x on 640x640 masks (e.g. `Detections.area`, N=300: ~24ms -> ~4ms), faster across densities. `get_mask_size_category` feeds the size-bucketed F1/Precision/Recall/mAP/mAR metrics, where it is invoked repeatedly per dataset. Counts are integer-exact (verified over 400 randomized trials plus empty / all-true / all-false / 1x1 edge cases). Adds parity tests for `Detections.area` (dense mask) and `get_mask_size_category` against an `np.sum` reference.
Codecov Report✅ All modified and coverable lines are covered by tests. ❌ Your project check has failed because the head coverage (82%) is below the target coverage (95%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## develop #2361 +/- ##
=======================================
Coverage 82% 82%
=======================================
Files 68 68
Lines 9560 9560
=======================================
Hits 7881 7881
Misses 1679 1679 🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
Mask pixel-area counting used
np.sum:np.array([np.sum(m) for m in masks])inDetections.area, andnp.sum(mask, axis=(1, 2))in the metrics helperget_mask_size_category.For boolean masks,
np.count_nonzero(with noaxis) dispatches to NumPy's SIMD popcount over the raw byte buffer, whereas every axis-reduction form —np.sum(..., axis=...)and evennp.count_nonzero(..., axis=...)— falls back to a slower generic reduction. So counting per-mask withnp.count_nonzerois several times faster than the "obvious" vectorized sum, while producing bit-identical integer counts. (The plainmasks.sum(axis=(1, 2))vectorization, by contrast, is only ~1.1x — it's the primitive, not the loop-removal, that matters here.)Both sites now use:
dtype=np.int64preserves the documentedDetections.areamask-branch dtype on every platform (a barenp.array([...])of Python ints is int32 on Windows).Performance
~5x on 640×640 masks, density-independent:
Detections.areaDetections.areaget_mask_size_categoryget_mask_size_categoryfeeds the size-bucketedF1Score/Precision/Recall/MeanAveragePrecision/MeanAverageRecallmetrics, where it runs repeatedly (SMALL/MEDIUM/LARGE × predictions+targets) across a dataset.Correctness
Counting
Truepixels equals summing a bool array exactly (integers, no float error). Verified bit-identical over 400 randomized trials plus empty / all-true / all-false / 1×1 edge cases, with int64 dtype preserved. ExistingDetections.areaand metrics suites pass unchanged.Tests
Adds parity tests for
Detections.area(dense mask) andget_mask_size_category, each against annp.sumreference, plus threshold-boundary coverage.ruff check/formatclean.