-
Notifications
You must be signed in to change notification settings - Fork 101
🆕 Add GrandQC tissue detection model #965
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
Draft
Jiaqi-Lv
wants to merge
6
commits into
dev-define-engines-abc
Choose a base branch
from
dev-add-grandQC
base: dev-define-engines-abc
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Unit test package for GrandQC Tissue Model.""" | ||
|
|
||
| import numpy as np | ||
| import torch | ||
|
|
||
| from tiatoolbox.models.architecture import ( | ||
| fetch_pretrained_weights, | ||
| get_pretrained_model, | ||
| ) | ||
| from tiatoolbox.models.architecture.grandqc import TissueDetectionModel | ||
| from tiatoolbox.models.engine.io_config import IOSegmentorConfig | ||
| from tiatoolbox.utils.misc import select_device | ||
| from tiatoolbox.wsicore.wsireader import VirtualWSIReader | ||
|
|
||
| ON_GPU = False | ||
|
|
||
|
|
||
| def test_functional_grandqc() -> None: | ||
| """Test for GrandQC model.""" | ||
| # test fetch pretrained weights | ||
| pretrained_weights = fetch_pretrained_weights("grandqc_tissue_detection_mpp10") | ||
| assert pretrained_weights is not None | ||
|
|
||
| # test creation | ||
| model = TissueDetectionModel(num_input_channels=3, num_output_channels=2) | ||
| assert model is not None | ||
|
|
||
| # load pretrained weights | ||
| pretrained = torch.load(pretrained_weights, map_location="cpu") | ||
| model.load_state_dict(pretrained) | ||
|
|
||
| # test get pretrained model | ||
| model, ioconfig = get_pretrained_model("grandqc_tissue_detection_mpp10") | ||
| assert isinstance(model, TissueDetectionModel) | ||
| assert isinstance(ioconfig, IOSegmentorConfig) | ||
| assert model.num_input_channels == 3 | ||
| assert model.num_output_channels == 2 | ||
|
|
||
| # test inference | ||
| generator = np.random.default_rng(1337) | ||
| test_image = generator.integers(0, 256, size=(2048, 2048, 3), dtype=np.uint8) | ||
| reader = VirtualWSIReader.open(test_image) | ||
| read_kwargs = {"resolution": 0, "units": "level", "coord_space": "resolution"} | ||
| batch = np.array( | ||
| [ | ||
| reader.read_bounds((0, 0, 512, 512), **read_kwargs), | ||
| reader.read_bounds((512, 512, 1024, 1024), **read_kwargs), | ||
| ], | ||
| ) | ||
| batch = torch.from_numpy(batch) | ||
| output = model.infer_batch(model, batch, device=select_device(on_gpu=ON_GPU)) | ||
| assert output.shape == (2, 512, 512, 2) | ||
|
|
||
|
|
||
| def test_grandqc_preproc_postproc() -> None: | ||
| """Test GrandQC preproc and postproc functions.""" | ||
| model = TissueDetectionModel(num_input_channels=3, num_output_channels=2) | ||
|
|
||
| generator = np.random.default_rng(1337) | ||
| # test preproc | ||
| dummy_image = generator.integers(0, 256, size=(512, 512, 3), dtype=np.uint8) | ||
| preproc_image = model.preproc(dummy_image) | ||
| assert preproc_image.shape == dummy_image.shape | ||
| assert preproc_image.dtype == np.float64 | ||
|
|
||
| # test postproc | ||
| dummy_output = generator.random(size=(512, 512, 2), dtype=np.float32) | ||
| postproc_image = model.postproc(dummy_output) | ||
| assert postproc_image.shape == (512, 512) | ||
| assert postproc_image.dtype == np.int64 |
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
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
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,128 @@ | ||||||||||||||||||||||||||
| """Define GrandQC Tissue Detection Model architecture.""" | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| from __future__ import annotations | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| from typing import TYPE_CHECKING, Any | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| if TYPE_CHECKING: # pragma: no cover | ||||||||||||||||||||||||||
| from collections.abc import Mapping | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| import cv2 | ||||||||||||||||||||||||||
| import numpy as np | ||||||||||||||||||||||||||
| import segmentation_models_pytorch as smp | ||||||||||||||||||||||||||
| import torch | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| from tiatoolbox.models.models_abc import ModelABC | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| class TissueDetectionModel(ModelABC): | ||||||||||||||||||||||||||
| """GrandQC Tissue Detection Model. | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| Example: | ||||||||||||||||||||||||||
| >>> from tiatoolbox.models.engine.semantic_segmentor import SemanticSegmentor | ||||||||||||||||||||||||||
| >>> semantic_segmentor = SemanticSegmentor( | ||||||||||||||||||||||||||
| ... model="grandqc_tissue_detection_mpp10", | ||||||||||||||||||||||||||
| ... ) | ||||||||||||||||||||||||||
| >>> results = semantic_segmentor.run( | ||||||||||||||||||||||||||
| ... ["/example_wsi.svs"], | ||||||||||||||||||||||||||
| ... masks=None, | ||||||||||||||||||||||||||
| ... auto_get_mask=False, | ||||||||||||||||||||||||||
| ... patch_mode=False, | ||||||||||||||||||||||||||
| ... save_dir=Path("/tissue_mask/"), | ||||||||||||||||||||||||||
| ... output_type="annotationstore", | ||||||||||||||||||||||||||
| ... ) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| def __init__( | ||||||||||||||||||||||||||
| self: TissueDetectionModel, num_input_channels: int, num_output_channels: int | ||||||||||||||||||||||||||
| ) -> None: | ||||||||||||||||||||||||||
| """Initialize TissueDetectionModel.""" | ||||||||||||||||||||||||||
| super().__init__() | ||||||||||||||||||||||||||
| self.num_input_channels = num_input_channels | ||||||||||||||||||||||||||
| self.num_output_channels = num_output_channels | ||||||||||||||||||||||||||
| self._postproc = self.postproc | ||||||||||||||||||||||||||
| self._preproc = self.preproc | ||||||||||||||||||||||||||
| self.tissue_detection_model = smp.UnetPlusPlus( | ||||||||||||||||||||||||||
| encoder_name="timm-efficientnet-b0", | ||||||||||||||||||||||||||
| encoder_weights=None, | ||||||||||||||||||||||||||
| in_channels=self.num_input_channels, | ||||||||||||||||||||||||||
| classes=self.num_output_channels, | ||||||||||||||||||||||||||
| activation=None, | ||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| @staticmethod | ||||||||||||||||||||||||||
| def preproc(image: np.ndarray) -> np.ndarray: | ||||||||||||||||||||||||||
| """Apply jpg compression then ImageNet normalise.""" | ||||||||||||||||||||||||||
|
||||||||||||||||||||||||||
| """Apply jpg compression then ImageNet normalise.""" | |
| """Apply JPEG compression and ImageNet normalization to the input image. | |
| Args: | |
| image (np.ndarray): | |
| Input image as a NumPy array (H, W, C) in uint8 format. | |
| Returns: | |
| np.ndarray: | |
| The preprocessed image as a float32 NumPy array, normalized using ImageNet mean and std. | |
| """ |
Jiaqi-Lv marked this conversation as resolved.
Show resolved
Hide resolved
Jiaqi-Lv marked this conversation as resolved.
Show resolved
Hide resolved
Oops, something went wrong.
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.
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.
Corrected spelling of 'normalise' to 'normalize' for consistency with American English spelling used elsewhere in the codebase.