Skip to content

Conversation

@shaneahmed
Copy link
Member

  • Add Nucleus Detection Engine
  • Fix documentation in patch_predictor.py

- Add Nucleus Detection Engine
- Fix documentation in patch_predictor.py
@shaneahmed shaneahmed marked this pull request as draft February 16, 2023 13:18
- Improve structure of init
@shaneahmed shaneahmed self-assigned this Feb 16, 2023
@codecov
Copy link

codecov bot commented Feb 16, 2023

Codecov Report

Merging #538 (6368325) into develop (25f5f3d) will decrease coverage by 0.15%.
The diff coverage is 100.00%.

❗ Current head 6368325 differs from pull request most recent head 7989aa7. Consider uploading reports for the commit 7989aa7 to get more accurate results

@@             Coverage Diff             @@
##           develop     #538      +/-   ##
===========================================
- Coverage    99.77%   99.63%   -0.15%     
===========================================
  Files           64       63       -1     
  Lines         6817     6642     -175     
  Branches      1101     1078      -23     
===========================================
- Hits          6802     6618     -184     
- Misses           7       15       +8     
- Partials         8        9       +1     
Impacted Files Coverage Δ
tiatoolbox/models/engine/__init__.py 100.00% <ø> (ø)
tiatoolbox/models/engine/semantic_segmentor.py 100.00% <ø> (ø)
tiatoolbox/models/engine/nucleus_detector.py 100.00% <100.00%> (ø)
tiatoolbox/models/engine/patch_predictor.py 100.00% <100.00%> (ø)

... and 24 files with indirect coverage changes

📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more

- Add documentation for mapde and sccnn
- Add a test for nucleus detection
- Fix input in patch predictor test
- Fix mpp for cell detection
…-engine

# Conflicts:
#	docs/pretrained.rst
#	tiatoolbox/data/pretrained_model.yaml
- Fix bug with loading NucleusDetector
- Fix bug with loading sccnn
- Fix test bug in test_patch_predictor.py
- Add test for NucleusDetector
@shaneahmed shaneahmed marked this pull request as ready for review February 21, 2023 17:42
- Set GPU

Signed-off-by: Shan E Ahmed Raza <13048456+shaneahmed@users.noreply.github.com>
- Add test to improve coverage
@shaneahmed shaneahmed added the enhancement New feature or request label Feb 22, 2023
Copy link
Collaborator

@mostafajahanifar mostafajahanifar left a comment

Choose a reason for hiding this comment

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

Thanks, Shan for doing this important PR.
I made some comments. As we mentioned before, I believe this engine requires some special consideration in the design, especially for post-processing. However, if we want to have it in its current shape for now, it needs some changes as well as some more rigorous testing. For example, how does the algorithm work on a slightly large WSI on a mediocre system (16-32GB RAM)?
Also, we need to consider the detection class and probability in the outputs as well because there might be some models that predict these parameters too.

)


class IONucleusDetectorConfig(IOSegmentorConfig):
Copy link
Collaborator

Choose a reason for hiding this comment

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

In the current shape, defining this new class seems unnecessary because there is no change to IOSegmentorConfig. I see no reason why we could not use the main class.

Copy link
Member Author

Choose a reason for hiding this comment

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

Agree I can remove this for now.

# Coordinates in output resolution for the current canvas.
cum_canvas = np.expand_dims(cum_canvas, axis=0)
coordinates_canvas = pd.DataFrame(
self.model.postproc_func(cum_canvas), columns=["x", "y"]
Copy link
Collaborator

@mostafajahanifar mostafajahanifar Mar 9, 2023

Choose a reason for hiding this comment

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

Now that engine is written like this, the post_proc function should be working with all detection models. There are two major things to consider:
1- this part should be compatible with all the detection models
2- this part should also support prediction class and prediction probability of detections (if available)

Therefore, it seems that we either need to update the postproc function of the detection networks to return the results in a predefined structure ([x, y, cls, prob]) and then convert the results properly here.

Copy link
Collaborator

@mostafajahanifar mostafajahanifar Mar 9, 2023

Choose a reason for hiding this comment

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

Also, I wonder if the post-processing works with large WSIs? as it seems that results are saved in high resolution and then the whole canvas is passed to the post-processing.

@shaneahmed shaneahmed added this to the Release v2.0.0 milestone Apr 10, 2023
shaneahmed added 7 commits May 5, 2023 17:39
# Conflicts:
#	tiatoolbox/models/engine/patch_predictor.py
#	tiatoolbox/models/engine/semantic_segmentor.py
- Pin `torch` version
- Pin `torch` version
- Try cuda 11.8 to run the tests as it passes locally.

Signed-off-by: Shan E Ahmed Raza <13048456+shaneahmed@users.noreply.github.com>
@shaneahmed shaneahmed added the stale Old PRs/Issues which are inactive label Jun 29, 2023
@shaneahmed shaneahmed marked this pull request as draft October 4, 2024 11:36
@Jiaqi-Lv Jiaqi-Lv mentioned this pull request Nov 6, 2025
4 tasks
shaneahmed added a commit that referenced this pull request Jan 6, 2026
# 🚀 Summary

This PR introduces a new **`NucleusDetector` engine** to the TIAToolbox framework, enabling detection of nuclei from whole slide images (WSIs) or image patches using models such as **`MapDe`** and **`SCCNN`**. It supersedes PR #538 by leveraging **`dask`** for efficient, parallelized post-processing and result merging. The update also includes:

---

## ✨ Key Features

### **New Engine: `NucleusDetector`**
- Detects nuclei centroids and probabilities from WSIs or patches.  
- Produces a **detection map** aligned with segmentation dimensions.  
- Serializes detections into **detection arrays** (`[[x], [y], [type], [probs]]`).  
- Supports multiple output backends:  
  - **SQLiteStore** (chunked storage for WSI/patch).  
  - **Dictionary** (flat or patch-indexed).  
  - **Zarr** (arrays for coordinates, classes, probabilities).  
- Compatible with nucleus detection models:  
  - **MapDe** (implemented).  
  - **SCCNN** (integration in progress/debugging).  
- Supports both **patch-mode** and **WSI-mode** workflows.  

### Technical Implementation
The detection pipeline operates as follows:
1.  **Segmentation**: A WSI-level segmentation map (dask array) is generated using `SemanticSegmentor.infer_wsi()`.
2.  **Parallel Post-processing**: For WSI inference. Use `dask.array.map_overlap` to apply the model's post-processing function across the entire segmentation map. This allows the function to execute in parallel on chunks, after which the results are automatically merged back into a unified **"detection_map"**, which is saved as zarr in a cache directory for further processing.
3.  **Detection Map**:
    * Maintains the same dimensions as the segmentation map.
    * Nuclei centroids contain the detection probability values (defaults to `1` if the model does not produce probabilities).
4.  **Serialization**: The "detection_map" is converted into **"detection_arrays"** (format: `[[x], [y], [type], [probs]]`) representing the detected nuclei. These records are then saved into `SQLiteStore` (chunk-by-chunk), `zarr`, or a `dict` (patch mode only).

### Output Formats

#### SQLiteStore
* **WSI Mode**: Returns a single `SQLiteStore`.
* **Patch Mode**: Returns one `SQLiteStore` per patch.
* **Format**:
    ```python
    Annotation(Point(x,y), properties={'type': 'nuclei', 'probs': 0.9})
    ```

#### Dictionary
* **WSI Mode**:
    ```python
    {
        'x': [...],
        'y': [...],
        'classes': [...],
        'probs': [...]
    }
    ```
* **Patch Mode** (One sub-dictionary per patch index):
    ```python
    {
        0: {
            'x': [...],
            'y': [...],
            'classes': [...],
            'probs': [...]
        },
        1: { ... }
    }
    ```

#### Zarr
* **WSI Mode**:
    ```python
    {
        'x': [...],
        'y': [...],
        'classes': [...],
        'probs': [...]
    }
    ```
* **Patch Mode**: Each key maps to a list of `da.array` objects, where each array corresponds to a patch.
    ```python
    {
        'x': [[...], ...],
        'y': [[...], ...],
        'classes': [[...], ...],
        'probs': [[...], ...]
    }
    ```
### **Codebase Integration**
- Registers `NucleusDetector` in `tiatoolbox.models` and engine registry.  
- Refactors detection logic from PR #538 into modular components.  
- Updates `MapDe` implementation to use the new engine.  
- Begins integration of `SCCNN` with `NucleusDetector`.  
- Adds utilities for serialization into SQLite, dict, and zarr formats.  
- Introduces unit tests for detection workflows.  
- Removes unused parameters `prediction_shape` and `prediction_dtype` from `post_process_patches()` and `post_process_wsi()` functions in all engines.
- `post_process_patches()` and `post_process_wsi()` now takes `raw_predictions` instead of `raw_predictions["probabilities"]`.

### Tasks
- [x] Port code from PR #538 to supersede and close it.
- [x] Add `NucleusDetector` engine.
- [x] Update existing detection models (`MapDe` implementation complete; `SCCNN` implementation in progress/debugging).
- [x] Add unit tests.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Shan E Ahmed Raza <13048456+shaneahmed@users.noreply.github.com>
Co-authored-by: Jiaqi Lv <jiaqilv@Jiaqis-MacBook-Pro.local>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request stale Old PRs/Issues which are inactive

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants