wsi-patching 0.5.4__tar.gz → 0.5.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/.github/workflows/integration_tests.yaml +1 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/.github/workflows/unit_tests.yaml +1 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/PKG-INFO +6 -6
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/README.md +2 -2
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/concepts.md +5 -3
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/extending.md +4 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/installation.md +1 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/reference.md +4 -3
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/pyproject.toml +2 -2
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/backends/fastslide.py +19 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/chunking_and_batching.py +6 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/pipeline.py +17 -15
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/types/types.py +4 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/types/util_types.py +11 -2
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/wsi_grid.py +18 -7
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/cellvit_tissue_classifier_filter.py +2 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/low_contrast_background_filter.py +5 -2
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/otsu_filter.py +12 -6
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/pen_artifact_filter.py +10 -3
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/remove_edge_tiles.py +3 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/transforms/macenko_normalizer.py +3 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/transforms/reinhard_normalizer.py +5 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/stream_writer_base.py +21 -2
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/conftest.py +13 -0
- wsi_patching-0.5.6/tests/integration/test_empty_slide.py +58 -0
- wsi_patching-0.5.6/tests/integration/test_level0_scale.py +38 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/test_resample_pipeline.py +5 -2
- wsi_patching-0.5.6/tests/integration/test_slide_end_hook.py +38 -0
- wsi_patching-0.5.6/tests/integration/test_slide_failed.py +49 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_fastslide.py +105 -4
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_chunking_and_batching.py +22 -1
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_wsi_grid.py +17 -2
- wsi_patching-0.5.6/tests/unit/src/wsi_patching/test_empty_batches.py +89 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_stream_writer_base.py +47 -1
- wsi_patching-0.5.6/uv.lock +2081 -0
- wsi_patching-0.5.4/uv.lock +0 -2020
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/.github/workflows/docs.yml +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/.github/workflows/publish.yaml +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/.gitignore +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/LICENSE +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/auditing.md +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/index.md +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/docs/quickstart.md +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/examples/audit_and_visualize_demo.ipynb +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/examples/numpy_stream_writer_demo.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/examples/torch_stream_writer_demo.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/examples/webdataset_materialize_writer_demo.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/mkdocs.yml +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/annotations/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/annotations/add_annotation_from_geojson.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/annotations/add_cell_annotation_from_csv.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/backends/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/backends/cupy_numpy.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/backends/torch_device.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/core/types/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/custom_component/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/encoders/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/encoders/pngencoder.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/filtering/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/py.typed +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/attach_rois.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/roi_providers.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/rois.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/transforms/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/audit.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/logging_config.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/meta_typing.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/profiling.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/utils/wsi_thumbnail_visualization.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/materialize_writer_base.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/__init__.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/numpy_stream_writer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/torch_stream_writer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/benchmarks/conftest.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_png_encoding.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_tile_planning.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/test_audit_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/test_materialize_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/test_roi_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/integration/test_streaming_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/.gitkeep +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/annotations/test_add_annotation_from_geojson.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/annotations/test_add_cell_annotation_from_csv.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_cupy_numpy.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_torch_device.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_pipeline.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_cellvit_tissue_classifier_filter.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_low_contrast_background_filter.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_otsu_filter.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_pen_artifact_filter.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_remove_edge_tiles.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_attach_rois.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_roi_providers.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_rois.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/transforms/test_macenko_normalizer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/transforms/test_reinhard_normalizer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_audit.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_logging_config.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_meta_typing.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_profiling.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/test_materialize_writer_base.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/webdataset/test_webdataset_loader.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/webdataset/test_webdataset_writer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_numpy_stream_writer.py +0 -0
- {wsi_patching-0.5.4 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_torch_stream_writer.py +0 -0
|
@@ -18,7 +18,7 @@ jobs:
|
|
|
18
18
|
runs-on: ubuntu-latest
|
|
19
19
|
strategy:
|
|
20
20
|
matrix:
|
|
21
|
-
python-version: ${{ fromJson( ((github.ref == 'refs/heads/main') || startsWith(github.ref, 'refs/tags/')) && '["3.
|
|
21
|
+
python-version: ${{ fromJson( ((github.ref == 'refs/heads/main') || startsWith(github.ref, 'refs/tags/')) && '["3.11","3.12","3.13","3.14"]' || '["3.11","3.14"]' ) }}
|
|
22
22
|
|
|
23
23
|
steps:
|
|
24
24
|
- name: Checkout
|
|
@@ -18,7 +18,7 @@ jobs:
|
|
|
18
18
|
runs-on: ubuntu-latest
|
|
19
19
|
strategy:
|
|
20
20
|
matrix:
|
|
21
|
-
python-version: ${{ fromJson( ((github.ref == 'refs/heads/main') || startsWith(github.ref, 'refs/tags/')) && '["3.
|
|
21
|
+
python-version: ${{ fromJson( ((github.ref == 'refs/heads/main') || startsWith(github.ref, 'refs/tags/')) && '["3.11","3.12","3.13","3.14"]' || '["3.11","3.14"]' ) }}
|
|
22
22
|
|
|
23
23
|
steps:
|
|
24
24
|
- name: Checkout
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: wsi-patching
|
|
3
|
-
Version: 0.5.
|
|
3
|
+
Version: 0.5.6
|
|
4
4
|
Summary: A High Performance Patching Library for Digital Pathology AI dataset creation.
|
|
5
5
|
Project-URL: Homepage, https://github.com/amspath/wsi-patching-pipeline
|
|
6
6
|
Project-URL: Repository, https://github.com/amspath/wsi-patching-pipeline
|
|
@@ -33,13 +33,13 @@ Classifier: Intended Audience :: Science/Research
|
|
|
33
33
|
Classifier: License :: OSI Approved :: MIT License
|
|
34
34
|
Classifier: Operating System :: OS Independent
|
|
35
35
|
Classifier: Programming Language :: Python :: 3
|
|
36
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
37
36
|
Classifier: Programming Language :: Python :: 3.11
|
|
38
37
|
Classifier: Programming Language :: Python :: 3.12
|
|
39
38
|
Classifier: Programming Language :: Python :: 3.13
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
40
40
|
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
41
41
|
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
42
|
-
Requires-Python:
|
|
42
|
+
Requires-Python: >=3.11
|
|
43
43
|
Requires-Dist: fastslide>=0.7.5
|
|
44
44
|
Requires-Dist: numpy>=1.24
|
|
45
45
|
Requires-Dist: opencv-python-headless>=4.8
|
|
@@ -78,7 +78,7 @@ A pragmatic pipeline for streaming whole-slide image (WSI) patches with region p
|
|
|
78
78
|
|
|
79
79
|
## 1) Library install
|
|
80
80
|
|
|
81
|
-
Python ≥3.
|
|
81
|
+
Python ≥3.11 is supported, and 3.11 through 3.14 are tested in CI.
|
|
82
82
|
```
|
|
83
83
|
# CPU install
|
|
84
84
|
pip install wsi-patching
|
|
@@ -261,7 +261,7 @@ PNGEncoder.isolated 640 1.440s 2.412ms
|
|
|
261
261
|
|
|
262
262
|
## 5) Development install
|
|
263
263
|
|
|
264
|
-
Python ≥3.
|
|
264
|
+
Python ≥3.11 is recommended. UV is also recommended as the package manager
|
|
265
265
|
```
|
|
266
266
|
git clone https://github.com/amspath/wsi-patching-pipeline.git
|
|
267
267
|
cd wsi-patching-pipeline
|
|
@@ -15,7 +15,7 @@ A pragmatic pipeline for streaming whole-slide image (WSI) patches with region p
|
|
|
15
15
|
|
|
16
16
|
## 1) Library install
|
|
17
17
|
|
|
18
|
-
Python ≥3.
|
|
18
|
+
Python ≥3.11 is supported, and 3.11 through 3.14 are tested in CI.
|
|
19
19
|
```
|
|
20
20
|
# CPU install
|
|
21
21
|
pip install wsi-patching
|
|
@@ -198,7 +198,7 @@ PNGEncoder.isolated 640 1.440s 2.412ms
|
|
|
198
198
|
|
|
199
199
|
## 5) Development install
|
|
200
200
|
|
|
201
|
-
Python ≥3.
|
|
201
|
+
Python ≥3.11 is recommended. UV is also recommended as the package manager
|
|
202
202
|
```
|
|
203
203
|
git clone https://github.com/amspath/wsi-patching-pipeline.git
|
|
204
204
|
cd wsi-patching-pipeline
|
|
@@ -46,7 +46,7 @@ Running a pipeline spawns three categories of threads:
|
|
|
46
46
|
└─────────────────────┘
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
- **Producer threads** each run an independent copy of the full stage chain for one slide. When a producer finishes a slide it puts an `EndOfStream` sentinel on the queue to signal the slide boundary. The supervisor then spawns a new producer for the next pending slide.
|
|
49
|
+
- **Producer threads** each run an independent copy of the full stage chain for one slide. When a producer finishes a slide it puts an `EndOfStream(wsi_id)` sentinel on the queue to signal the slide boundary. Stream writers receive it through `on_slide_end(wsi_id)`. If the producer fails, it puts a `SlideFailed(wsi_id, error)` instead, which stream writers receive through `on_slide_failed(wsi_id, error)`. The supervisor then spawns a new producer for the next pending slide.
|
|
50
50
|
- **The queue** is bounded (`maxsize = writer_prefetch_factor × num_workers`, default 8). This provides natural backpressure: producers block when the writer is slow rather than accumulating unbounded memory.
|
|
51
51
|
- **`EndOfQueue`** is put onto the queue once all slides are done, signalling the writer to stop.
|
|
52
52
|
- In **`.stream()` mode** the writer runs as a generator in the caller's thread — each iteration of `for wsi_id, images, ... in p.stream()` drives the writer forward.
|
|
@@ -90,12 +90,14 @@ If the slide does not have an exact match for the requested resolution, `fallbac
|
|
|
90
90
|
|
|
91
91
|
| `fallback_mode` | Behaviour |
|
|
92
92
|
|---|---|
|
|
93
|
-
| `"error"`
|
|
94
|
-
| `"nearest"` | Picks the closest available level |
|
|
93
|
+
| `"error"` | Raises an error if no exact match |
|
|
94
|
+
| `"nearest"` *(default)* | Picks the closest available level, provided it is within `max_relative_deviation` of the request |
|
|
95
95
|
| `"floor"` | Picks the highest resolution level that is ≤ the request |
|
|
96
96
|
| `"ceil"` | Picks the lowest resolution level that is ≥ the request |
|
|
97
97
|
| `"resample"` | Reads from a finer level, then downsamples with `cv2.resize` to hit the exact target. Not valid with `unit="level"`. |
|
|
98
98
|
|
|
99
|
+
`max_relative_deviation` guards `fallback_mode="nearest"`: if the closest level deviates from the requested resolution by more than this fraction (default `0.05`, i.e. 5%), an error is raised instead of silently patching at the wrong resolution. Pass `None` to disable the check. The other fallback modes ignore it.
|
|
100
|
+
|
|
99
101
|
`resample_interpolation` controls the interpolation method when `fallback_mode="resample"` (default `"lanczos"`; options: `"nearest"`, `"linear"`, `"cubic"`, `"area"`, `"lanczos"`).
|
|
100
102
|
|
|
101
103
|
---
|
|
@@ -78,6 +78,10 @@ class MyStreamWriter(StreamWriterBase):
|
|
|
78
78
|
|
|
79
79
|
`stream()` is called once per queue item. The pipeline handles threading and queue management; you only need to focus on the transformation.
|
|
80
80
|
|
|
81
|
+
Override `on_slide_end(wsi_id)` to act when a slide is done. It is called once per slide, after that slide's last batch, and anything it yields is streamed like `stream()` output. The default does nothing.
|
|
82
|
+
|
|
83
|
+
Override `on_slide_failed(wsi_id, error)` to act when a producer fails on a slide. It is called instead of `on_slide_end` for that slide. Batches of that slide that were already streamed stay streamed. With `gracefully_handle_producer_errors=True` the other slides keep going. The default does nothing.
|
|
84
|
+
|
|
81
85
|
---
|
|
82
86
|
|
|
83
87
|
## Custom MaterializeWriter
|
|
@@ -17,11 +17,12 @@ from wsi_patching import WSIGrid
|
|
|
17
17
|
| Parameter | Type | Default | Description |
|
|
18
18
|
|---|---|---|---|
|
|
19
19
|
| `slides` | `List[str]` | — | Paths to WSI files |
|
|
20
|
-
| `resolution` | `float` |
|
|
21
|
-
| `unit` | `"level" \| "mpp" \| "downsample"` |
|
|
20
|
+
| `resolution` | `float` | `0.25` | Desired resolution value |
|
|
21
|
+
| `unit` | `"level" \| "mpp" \| "downsample"` | `"mpp"` | Unit of `resolution` |
|
|
22
22
|
| `use_gpu` | `bool` | `False` | Enable GPU-accelerated backends (CuPy) |
|
|
23
|
-
| `fallback_mode` | `"nearest" \| "floor" \| "ceil" \| "error" \| "resample"` | `"
|
|
23
|
+
| `fallback_mode` | `"nearest" \| "floor" \| "ceil" \| "error" \| "resample"` | `"nearest"` | What to do when the exact resolution is unavailable |
|
|
24
24
|
| `resample_interpolation` | `"nearest" \| "linear" \| "cubic" \| "area" \| "lanczos"` | `"lanczos"` | Interpolation used when `fallback_mode="resample"` |
|
|
25
|
+
| `max_relative_deviation` | `float \| None` | `0.05` | Max relative deviation between the request and the selected level for `fallback_mode="nearest"`; `None` disables the check |
|
|
25
26
|
|
|
26
27
|
---
|
|
27
28
|
|
|
@@ -8,7 +8,7 @@ dynamic = ["version"]
|
|
|
8
8
|
description = "A High Performance Patching Library for Digital Pathology AI dataset creation."
|
|
9
9
|
readme = {file = "README.md", content-type = "text/markdown"}
|
|
10
10
|
license = {file = "LICENSE"}
|
|
11
|
-
requires-python = ">=3.
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
12
|
authors = [{ name = "Robin van Hoorn", email = "r.d.vanhoorn@amsterdamumc.nl" }]
|
|
13
13
|
keywords = ["digital pathology", "whole slide image", "WSI", "patching", "deep learning", "medical imaging"]
|
|
14
14
|
classifiers = [
|
|
@@ -17,10 +17,10 @@ classifiers = [
|
|
|
17
17
|
"Topic :: Scientific/Engineering :: Medical Science Apps.",
|
|
18
18
|
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
19
19
|
"Programming Language :: Python :: 3",
|
|
20
|
-
"Programming Language :: Python :: 3.10",
|
|
21
20
|
"Programming Language :: Python :: 3.11",
|
|
22
21
|
"Programming Language :: Python :: 3.12",
|
|
23
22
|
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
24
|
"License :: OSI Approved :: MIT License",
|
|
25
25
|
"Operating System :: OS Independent",
|
|
26
26
|
]
|
|
@@ -140,6 +140,7 @@ def get_level_for_resolution(
|
|
|
140
140
|
resolution: float,
|
|
141
141
|
unit: Literal["level", "mpp", "downsample"],
|
|
142
142
|
fallback_mode: Literal["nearest", "floor", "ceil", "error", "resample"],
|
|
143
|
+
max_relative_deviation: float | None = None,
|
|
143
144
|
) -> int:
|
|
144
145
|
"""
|
|
145
146
|
Determine which pyramid level to use for a given resolution specification.
|
|
@@ -152,7 +153,8 @@ def get_level_for_resolution(
|
|
|
152
153
|
- If unit == "downsample": Downsample factor relative to level 0.
|
|
153
154
|
unit: Resolution unit ("level", "mpp", or "downsample").
|
|
154
155
|
fallback_mode:
|
|
155
|
-
- "nearest": pick level whose value is closest to 'resolution'
|
|
156
|
+
- "nearest": pick level whose value is closest to 'resolution';
|
|
157
|
+
see 'max_relative_deviation'.
|
|
156
158
|
- "floor": pick coarsest level with value >= 'resolution'
|
|
157
159
|
(if none, use coarsest level).
|
|
158
160
|
- "ceil": pick finest level with value <= 'resolution'
|
|
@@ -160,6 +162,9 @@ def get_level_for_resolution(
|
|
|
160
162
|
- "resample": same selection as "ceil"; caller must then resample
|
|
161
163
|
the read pixels to the exact requested resolution.
|
|
162
164
|
Raises ValueError when unit == "level".
|
|
165
|
+
max_relative_deviation: Maximum allowed |level_value - resolution| / resolution
|
|
166
|
+
for fallback_mode="nearest". Raises ValueError when the closest level lies
|
|
167
|
+
outside that band. None disables the check. Ignored by the other modes.
|
|
163
168
|
|
|
164
169
|
Returns:
|
|
165
170
|
level_idx: int
|
|
@@ -169,6 +174,9 @@ def get_level_for_resolution(
|
|
|
169
174
|
if fallback_mode == "resample" and unit == "level":
|
|
170
175
|
raise ValueError("fallback_mode='resample' is not meaningful for unit='level'.")
|
|
171
176
|
|
|
177
|
+
if max_relative_deviation is not None and max_relative_deviation < 0:
|
|
178
|
+
raise ValueError(f"max_relative_deviation must be non-negative, got {max_relative_deviation}.")
|
|
179
|
+
|
|
172
180
|
# --- Trivial case: unit == "level" ---------------------------------
|
|
173
181
|
if unit == "level":
|
|
174
182
|
if not float(resolution).is_integer():
|
|
@@ -240,4 +248,14 @@ def get_level_for_resolution(
|
|
|
240
248
|
else:
|
|
241
249
|
raise ValueError(f"Unknown fallback_mode: {fallback_mode}")
|
|
242
250
|
|
|
251
|
+
if fallback_mode == "nearest" and max_relative_deviation is not None:
|
|
252
|
+
deviation = abs(values[level_idx] - requested) / requested
|
|
253
|
+
if deviation > max_relative_deviation:
|
|
254
|
+
raise ValueError(
|
|
255
|
+
f"Nearest level {level_idx} has {unit} {values[level_idx]}, deviating "
|
|
256
|
+
f"{deviation:.2%} from the requested {requested} "
|
|
257
|
+
f"(max_relative_deviation={max_relative_deviation:.2%}). "
|
|
258
|
+
f"Available values: {values}. Widen max_relative_deviation, or pass None to disable."
|
|
259
|
+
)
|
|
260
|
+
|
|
243
261
|
return level_idx
|
|
@@ -415,7 +415,12 @@ class RegionReadAndBatch(Stage):
|
|
|
415
415
|
coords_out = coords_slice.copy()
|
|
416
416
|
patches_xp = xp.asarray(batch_slice.copy(), dtype=self.dtype)
|
|
417
417
|
cpb = CollatedPatchBatch(
|
|
418
|
-
task.wsi_id,
|
|
418
|
+
task.wsi_id,
|
|
419
|
+
coords_out,
|
|
420
|
+
patches_xp,
|
|
421
|
+
use_gpu=self.ctx["use_gpu"],
|
|
422
|
+
wsi_dims=task.wsi_dims,
|
|
423
|
+
level0_scale=task.downsample,
|
|
419
424
|
)
|
|
420
425
|
for k, v in task.meta.items():
|
|
421
426
|
cpb.add_meta_column(k, np.array([v] * len(coords_out)))
|
|
@@ -11,7 +11,7 @@ import numpy as np
|
|
|
11
11
|
|
|
12
12
|
from wsi_patching.backends.fastslide import close_cached_slides
|
|
13
13
|
from wsi_patching.core.types.types import EncodedCollatedPatchBatch
|
|
14
|
-
from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
|
|
14
|
+
from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream, SlideFailed
|
|
15
15
|
from wsi_patching.utils.audit import AuditRecorder, PipelineAuditAggregator, get_current_audit, set_current_audit
|
|
16
16
|
from wsi_patching.utils.logging_config import LogLevel, init_logging
|
|
17
17
|
from wsi_patching.utils.meta_typing import ContextAware, PipelineContext, StageMeta
|
|
@@ -724,8 +724,9 @@ def _producer_worker(
|
|
|
724
724
|
init_logging(verbosity_level)
|
|
725
725
|
profiler: Optional[Profiler] = None
|
|
726
726
|
recorder: Optional[AuditRecorder] = None
|
|
727
|
+
error: Optional[str] = None
|
|
728
|
+
slide_id = Path(slide_path).stem
|
|
727
729
|
try:
|
|
728
|
-
slide_id = Path(slide_path).stem
|
|
729
730
|
profiler = Profiler(enabled=profile, slide_id=slide_id)
|
|
730
731
|
set_current_profiler(profiler)
|
|
731
732
|
recorder = AuditRecorder(enabled=audit, slide_id=slide_id)
|
|
@@ -742,17 +743,10 @@ def _producer_worker(
|
|
|
742
743
|
for out in pipe(iter(())):
|
|
743
744
|
if stop_event is not None and stop_event.is_set():
|
|
744
745
|
break
|
|
745
|
-
|
|
746
|
-
while True:
|
|
747
|
-
try:
|
|
748
|
-
producer_queue.put(out, block=True, timeout=0.5)
|
|
749
|
-
break
|
|
750
|
-
except Full:
|
|
751
|
-
if stop_event is not None and stop_event.is_set():
|
|
752
|
-
break
|
|
753
|
-
continue
|
|
746
|
+
_put_until_stopped(producer_queue, out, stop_event)
|
|
754
747
|
|
|
755
748
|
except Exception as e:
|
|
749
|
+
error = f"{type(e).__name__}: {e}"
|
|
756
750
|
if not gracefully_handle_producer_errors:
|
|
757
751
|
logging.exception(f"Producer error: {e}", exc_info=True)
|
|
758
752
|
if fail_box is not None:
|
|
@@ -772,8 +766,16 @@ def _producer_worker(
|
|
|
772
766
|
set_current_profiler(None)
|
|
773
767
|
set_current_audit(None)
|
|
774
768
|
|
|
775
|
-
|
|
769
|
+
end = EndOfStream(wsi_id=slide_id) if error is None else SlideFailed(wsi_id=slide_id, error=error)
|
|
770
|
+
_put_until_stopped(producer_queue, end, stop_event)
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _put_until_stopped(queue: Queue, item: Any, stop_event: Optional[Event]) -> None:
|
|
774
|
+
"""Block until `item` is on `queue`, giving up only once `stop_event` is set."""
|
|
775
|
+
while True:
|
|
776
776
|
try:
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
777
|
+
queue.put(item, block=True, timeout=0.5)
|
|
778
|
+
return
|
|
779
|
+
except Full:
|
|
780
|
+
if stop_event is not None and stop_event.is_set():
|
|
781
|
+
return
|
|
@@ -67,6 +67,7 @@ class CollatedPatchBatch:
|
|
|
67
67
|
patches: Union[np.ndarray, "cp.ndarray"] # (N, ...)
|
|
68
68
|
metadata: MetaColStorage
|
|
69
69
|
wsi_dims: Tuple[int, int] # (W, H) of the whole slide at patched resolution
|
|
70
|
+
level0_scale: float # coords * level0_scale = level-0 pixels (read downsample * resample factor)
|
|
70
71
|
|
|
71
72
|
def __init__(
|
|
72
73
|
self,
|
|
@@ -76,11 +77,13 @@ class CollatedPatchBatch:
|
|
|
76
77
|
use_gpu: bool,
|
|
77
78
|
wsi_dims: Tuple[int, int],
|
|
78
79
|
metadata: Optional[MetaColStorage] = None,
|
|
80
|
+
level0_scale: float = 1.0,
|
|
79
81
|
):
|
|
80
82
|
self.wsi_id = wsi_id
|
|
81
83
|
self.coords = coords
|
|
82
84
|
self.patches = patches
|
|
83
85
|
self.wsi_dims = wsi_dims
|
|
86
|
+
self.level0_scale = level0_scale
|
|
84
87
|
|
|
85
88
|
if metadata is not None:
|
|
86
89
|
self.metadata = metadata
|
|
@@ -151,6 +154,7 @@ class EncodedCollatedPatchBatch(CollatedPatchBatch):
|
|
|
151
154
|
use_gpu=is_cupy(batch.patches),
|
|
152
155
|
wsi_dims=batch.wsi_dims,
|
|
153
156
|
metadata=batch.metadata,
|
|
157
|
+
level0_scale=batch.level0_scale,
|
|
154
158
|
)
|
|
155
159
|
obj.encoding = encoding
|
|
156
160
|
obj.encoded_patches = encoded_patches
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from dataclasses import dataclass
|
|
2
|
-
from typing import Any, Dict, List, Union
|
|
2
|
+
from typing import Any, Dict, List, Optional, Union
|
|
3
3
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
|
|
@@ -85,7 +85,16 @@ class MetaColStorage:
|
|
|
85
85
|
|
|
86
86
|
@dataclass(frozen=True)
|
|
87
87
|
class EndOfStream:
|
|
88
|
-
|
|
88
|
+
"""A producer finished a slide. `wsi_id` names the slide, or is None for a bare stream boundary."""
|
|
89
|
+
|
|
90
|
+
wsi_id: Optional[str] = None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class SlideFailed(EndOfStream):
|
|
95
|
+
"""A producer failed on slide `wsi_id` and ends its stream early. `error` describes the failure."""
|
|
96
|
+
|
|
97
|
+
error: str = ""
|
|
89
98
|
|
|
90
99
|
|
|
91
100
|
@dataclass(frozen=True)
|
|
@@ -21,11 +21,12 @@ class WSIGrid(Stage):
|
|
|
21
21
|
def __init__(
|
|
22
22
|
self,
|
|
23
23
|
slides: List[str],
|
|
24
|
-
resolution: float,
|
|
25
|
-
unit: Literal["level", "mpp", "downsample"],
|
|
24
|
+
resolution: float = 0.25,
|
|
25
|
+
unit: Literal["level", "mpp", "downsample"] = "mpp",
|
|
26
26
|
use_gpu: bool = False,
|
|
27
|
-
fallback_mode: Literal["nearest", "floor", "ceil", "error", "resample"] = "
|
|
27
|
+
fallback_mode: Literal["nearest", "floor", "ceil", "error", "resample"] = "nearest",
|
|
28
28
|
resample_interpolation: Literal["nearest", "linear", "cubic", "area", "lanczos"] = "lanczos",
|
|
29
|
+
max_relative_deviation: float | None = 0.05,
|
|
29
30
|
):
|
|
30
31
|
"""
|
|
31
32
|
Initializes the WSIGrid stage, the starting point of a WSI patching pipeline.
|
|
@@ -33,14 +34,18 @@ class WSIGrid(Stage):
|
|
|
33
34
|
Args:
|
|
34
35
|
slides: List of file paths to whole slide images (WSIs).
|
|
35
36
|
use_gpu: Whether to use GPU-accelerated backends when possible (e.g., cuCIM, CuPy).
|
|
36
|
-
resolution: Desired resolution for patch extraction.
|
|
37
|
-
unit: Unit of the resolution ("level", "mpp", or "downsample").
|
|
38
|
-
fallback_mode: Strategy for selecting resolution if exact match is unavailable (default is "
|
|
37
|
+
resolution: Desired resolution for patch extraction (default is 0.25).
|
|
38
|
+
unit: Unit of the resolution ("level", "mpp", or "downsample"). Default is "mpp".
|
|
39
|
+
fallback_mode: Strategy for selecting resolution if exact match is unavailable (default is "nearest").
|
|
39
40
|
Options are ("nearest", "floor", "ceil", "error", "resample").
|
|
40
41
|
- "resample": selects the finest level with resolution <= requested, reads extra pixels,
|
|
41
42
|
then downsamples to the exact target resolution using cv2.resize. Not valid for unit="level".
|
|
42
43
|
resample_interpolation: Interpolation method used when fallback_mode="resample".
|
|
43
44
|
Options are ("nearest", "linear", "cubic", "area", "lanczos"). Default is "lanczos".
|
|
45
|
+
max_relative_deviation: Maximum allowed relative deviation between the requested
|
|
46
|
+
resolution and the selected level when fallback_mode="nearest" (default is 0.05,
|
|
47
|
+
i.e. 5%). Raises if the closest level lies outside that band. Pass None to disable.
|
|
48
|
+
Ignored by the other fallback modes.
|
|
44
49
|
"""
|
|
45
50
|
self.slides = list(slides)
|
|
46
51
|
self.use_gpu = use_gpu
|
|
@@ -48,6 +53,7 @@ class WSIGrid(Stage):
|
|
|
48
53
|
self.unit = unit
|
|
49
54
|
self.fallback_mode = fallback_mode
|
|
50
55
|
self.resample_interpolation = resample_interpolation
|
|
56
|
+
self.max_relative_deviation = max_relative_deviation
|
|
51
57
|
|
|
52
58
|
def export_context(self, ctx: "PipelineContext") -> None:
|
|
53
59
|
# Seed/override global grid parameters for other stages to read.
|
|
@@ -56,6 +62,7 @@ class WSIGrid(Stage):
|
|
|
56
62
|
ctx["fallback_mode"] = self.fallback_mode
|
|
57
63
|
ctx["use_gpu"] = self.use_gpu
|
|
58
64
|
ctx["resample_interpolation"] = self.resample_interpolation
|
|
65
|
+
ctx["max_relative_deviation"] = self.max_relative_deviation
|
|
59
66
|
|
|
60
67
|
def validate(self) -> None:
|
|
61
68
|
validate_xp_backend(self.use_gpu)
|
|
@@ -68,6 +75,7 @@ class WSIGrid(Stage):
|
|
|
68
75
|
unit=self.unit,
|
|
69
76
|
fallback_mode=self.fallback_mode,
|
|
70
77
|
resample_interpolation=self.resample_interpolation,
|
|
78
|
+
max_relative_deviation=self.max_relative_deviation,
|
|
71
79
|
)
|
|
72
80
|
|
|
73
81
|
def __call__(self, it: Iterable[Any]) -> Iterable[Slide]:
|
|
@@ -77,7 +85,9 @@ class WSIGrid(Stage):
|
|
|
77
85
|
raise FileNotFoundError(f"Slide path does not exist: {path}")
|
|
78
86
|
|
|
79
87
|
wsi_id = Path(path).stem
|
|
80
|
-
selected_level = get_level_for_resolution(
|
|
88
|
+
selected_level = get_level_for_resolution(
|
|
89
|
+
path, self.resolution, self.unit, self.fallback_mode, max_relative_deviation=self.max_relative_deviation
|
|
90
|
+
)
|
|
81
91
|
W, H = get_dimensions_for_level(path, selected_level)
|
|
82
92
|
level_downsamples = get_level_downsamples(path)
|
|
83
93
|
downsample = level_downsamples[selected_level]
|
|
@@ -110,6 +120,7 @@ class WSIGrid(Stage):
|
|
|
110
120
|
"slide.requested_resolution": self.resolution,
|
|
111
121
|
"slide.requested_unit": self.unit,
|
|
112
122
|
"slide.requested_fallback_mode": self.fallback_mode,
|
|
123
|
+
"slide.requested_max_relative_deviation": self.max_relative_deviation,
|
|
113
124
|
"slide.selected_level": selected_level,
|
|
114
125
|
"slide.downsample": slide_downsample,
|
|
115
126
|
"slide.path": path,
|
|
@@ -66,14 +66,17 @@ class LowContrastBackgroundFilter(Stage):
|
|
|
66
66
|
thr = xp.asarray(self.range_threshold, dtype=xp.float32 if self.float_precision == "float32" else xp.float64)
|
|
67
67
|
|
|
68
68
|
for collated_patch_batch in it:
|
|
69
|
+
if len(collated_patch_batch.patches) == 0:
|
|
70
|
+
continue
|
|
71
|
+
|
|
69
72
|
patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
|
|
70
73
|
|
|
71
74
|
# 1) RGB/RGBA -> grayscale in [0,1]
|
|
72
75
|
gray = self._rgb_to_gray_xp(patches, xp)
|
|
73
76
|
|
|
74
77
|
# 2) Per-patch min/max and dynamic range
|
|
75
|
-
B = gray.shape
|
|
76
|
-
gray_flat = gray.reshape(B,
|
|
78
|
+
B, H, W = gray.shape
|
|
79
|
+
gray_flat = gray.reshape(B, H * W)
|
|
77
80
|
g_min = gray_flat.min(axis=1) # (B,)
|
|
78
81
|
g_max = gray_flat.max(axis=1) # (B,)
|
|
79
82
|
g_range = (g_max - g_min).astype(gray.dtype) # (B,)
|
|
@@ -84,6 +84,8 @@ class OtsuFilter(Stage):
|
|
|
84
84
|
|
|
85
85
|
for collated_patch_batch in it:
|
|
86
86
|
in_sz = len(collated_patch_batch.patches)
|
|
87
|
+
if in_sz == 0:
|
|
88
|
+
continue
|
|
87
89
|
|
|
88
90
|
patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
|
|
89
91
|
|
|
@@ -100,9 +102,9 @@ class OtsuFilter(Stage):
|
|
|
100
102
|
tissue_mask = gray >= thresholds[:, None, None]
|
|
101
103
|
|
|
102
104
|
# 4) Coverage stats per patch
|
|
103
|
-
B = tissue_mask.shape
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
B, H, W = tissue_mask.shape
|
|
106
|
+
total_pixels = H * W
|
|
107
|
+
tissue_pixel_count = tissue_mask.reshape(B, total_pixels).sum(axis=1)
|
|
106
108
|
tissue_fraction = tissue_pixel_count.astype(xp.float32) / float(total_pixels)
|
|
107
109
|
|
|
108
110
|
# Optional filtering
|
|
@@ -123,6 +125,10 @@ class OtsuFilter(Stage):
|
|
|
123
125
|
f"(tissue_is_darker={self.tissue_is_darker}, num_bins={self.num_bins}, "
|
|
124
126
|
f"float_precision={self.float_precision}, min_tissue_fraction={self.min_tissue_fraction})"
|
|
125
127
|
)
|
|
128
|
+
|
|
129
|
+
if len(collated_patch_batch.patches) == 0:
|
|
130
|
+
continue
|
|
131
|
+
|
|
126
132
|
yield collated_patch_batch
|
|
127
133
|
|
|
128
134
|
# ---- helpers (xp-native) ----
|
|
@@ -168,8 +174,8 @@ class OtsuFilter(Stage):
|
|
|
168
174
|
-------
|
|
169
175
|
thresholds : (B,) same dtype as `gray`, each in [0,1] (gray domain)
|
|
170
176
|
"""
|
|
171
|
-
B,
|
|
172
|
-
gray_flat = gray.reshape(B,
|
|
177
|
+
B, H, W = gray.shape
|
|
178
|
+
gray_flat = gray.reshape(B, H * W)
|
|
173
179
|
|
|
174
180
|
# Per-image normalization to [0,1] (robust to constants)
|
|
175
181
|
g_min = gray_flat.min(axis=1)
|
|
@@ -187,7 +193,7 @@ class OtsuFilter(Stage):
|
|
|
187
193
|
xp.clip(bin_idx, 0, num_bins - 1, out=bin_idx)
|
|
188
194
|
|
|
189
195
|
# Batched histograms via offset bincount
|
|
190
|
-
bin_idx_flat = bin_idx.reshape(B,
|
|
196
|
+
bin_idx_flat = bin_idx.reshape(B, H * W).astype(xp.int64, copy=False)
|
|
191
197
|
offsets = (num_bins * xp.arange(B, dtype=xp.int64))[:, None]
|
|
192
198
|
keys = (bin_idx_flat + offsets).ravel()
|
|
193
199
|
counts_flat = xp.bincount(keys, minlength=B * num_bins)
|
|
@@ -97,6 +97,7 @@ class PenArtifactFilter(Stage):
|
|
|
97
97
|
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
|
|
98
98
|
"""
|
|
99
99
|
For each batch:
|
|
100
|
+
- Skip batches with no patches (e.g. an earlier filter dropped them all).
|
|
100
101
|
- Ensure dtype uint8 (accept float32 in [0,255] and cast).
|
|
101
102
|
- Compute per-pixel keep mask from LUTs + darkness guard.
|
|
102
103
|
- Derive per-patch pen_fraction; drop patches exceeding `max_pen_fraction`.
|
|
@@ -108,6 +109,8 @@ class PenArtifactFilter(Stage):
|
|
|
108
109
|
|
|
109
110
|
for collated_patch_batch in it:
|
|
110
111
|
in_sz = len(collated_patch_batch.patches)
|
|
112
|
+
if in_sz == 0:
|
|
113
|
+
continue
|
|
111
114
|
|
|
112
115
|
# Normalize dtype: prefer uint8 for LUT indexing
|
|
113
116
|
if collated_patch_batch.patches.dtype != xp.uint8:
|
|
@@ -133,9 +136,9 @@ class PenArtifactFilter(Stage):
|
|
|
133
136
|
pen = xp.logical_not(keep_final) # [B,H,W] bool
|
|
134
137
|
|
|
135
138
|
# Per-patch stats
|
|
136
|
-
Bsz = pen.shape
|
|
137
|
-
|
|
138
|
-
|
|
139
|
+
Bsz, H, W = pen.shape
|
|
140
|
+
total_pixels = H * W
|
|
141
|
+
pen_pixel_count = pen.reshape(Bsz, total_pixels).sum(axis=1) # xp integer (per patch)
|
|
139
142
|
pen_fraction = pen_pixel_count.astype(xp.float32) / float(total_pixels)
|
|
140
143
|
|
|
141
144
|
# Drop patches with too much pen content
|
|
@@ -150,6 +153,10 @@ class PenArtifactFilter(Stage):
|
|
|
150
153
|
f"batch_in={in_sz} batch_out={len(collated_patch_batch.patches)} "
|
|
151
154
|
f"(max_pen_fraction={self.max_pen_fraction})"
|
|
152
155
|
)
|
|
156
|
+
|
|
157
|
+
if len(collated_patch_batch.patches) == 0:
|
|
158
|
+
continue
|
|
159
|
+
|
|
153
160
|
yield collated_patch_batch
|
|
154
161
|
|
|
155
162
|
# -------- helpers (xp-native) --------
|
|
@@ -62,6 +62,9 @@ class RemoveEdgeTiles(Stage):
|
|
|
62
62
|
tile_size = int(self.ctx["tile_size"])
|
|
63
63
|
|
|
64
64
|
for batch in it:
|
|
65
|
+
if len(batch.patches) == 0:
|
|
66
|
+
continue
|
|
67
|
+
|
|
65
68
|
# Attach the metric for every row (the audit needs it even at depth=0).
|
|
66
69
|
edge_distance = _edge_distance(batch.coords, batch.wsi_dims, tile_size)
|
|
67
70
|
batch.add_meta_column("edge_distance", edge_distance)
|
{wsi_patching-0.5.4 → wsi_patching-0.5.6}/src/wsi_patching/transforms/reinhard_normalizer.py
RENAMED
|
@@ -199,6 +199,9 @@ class ReinhardNormalizer(Stage):
|
|
|
199
199
|
Same batches with ``batch.patches`` replaced by the normalized NHWC uint8 array.
|
|
200
200
|
"""
|
|
201
201
|
for batch in it:
|
|
202
|
+
if len(batch.patches) == 0:
|
|
203
|
+
continue
|
|
204
|
+
|
|
202
205
|
if self._xp is None:
|
|
203
206
|
self._xp = get_xp_backend(self.ctx["use_gpu"])
|
|
204
207
|
self._ref_mean = self._xp.asarray(self.lab_reference_mean, dtype=self._xp.float32)
|
|
@@ -225,7 +228,8 @@ class ReinhardNormalizer(Stage):
|
|
|
225
228
|
lab = _rgb_to_lab(rgb_float, self._xp, rgb2xyz=self._rgb2xyz, white=self._white) # (N, H, W, 3)
|
|
226
229
|
|
|
227
230
|
# Compute per‑patch mean and std over spatial axes (H,W)
|
|
228
|
-
|
|
231
|
+
N, H, W, _ = lab.shape
|
|
232
|
+
lab_flat = lab.reshape(N, H * W, 3)
|
|
229
233
|
mean_lab = lab_flat.mean(axis=1) # (N,3)
|
|
230
234
|
std_lab = lab_flat.std(axis=1, ddof=1) # (N,3)
|
|
231
235
|
|