Repository navigation
Add display normalization module and test. #45
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8f10837
Add display normalization module and test. Then hook up display norma…
wli51 8952cfc
Fix test relying on renderer backed canvas which may not be present i…
wli51 b71a45f
Tighten visualization backend and add tests for copying behavior
wli51 7f4c3a6
Add tests for new scaling options in visualization behavior.
wli51 45b8166
Additionally tighten tensor creation to avoid modifying original inpu…
wli51 f540bd5
Refactor type hints in display normalization and visualization module…
wli51 b3fafe0
Specify matplotlib version range in dependencies for compatibility
wli51 cf0f807
Refactor image batch handling in extract_samples_from_dataset for dty…
wli51 6759e02
raise the project's declared Python minimum to 3.10
wli51 c60bf10
Enhance _finite_range to consider additional input for display limits…
wli51 d448207
Update changelog for visualization normalization enhancements
wli51 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
105 changes: 105 additions & 0 deletions
105
src/virtual_stain_flow/evaluation/display_normalization.py
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,105 @@ | ||
| """Display-only intensity scaling; never modifies image or metric data.""" | ||
|
|
||
| from typing import List, Optional, Sequence, Tuple, Union, Literal | ||
|
|
||
| import numpy as np | ||
| from matplotlib.colors import Normalize | ||
|
|
||
| DisplayLimits = Union[Tuple[float, float], Sequence[Tuple[float, float]]] | ||
|
|
||
|
|
||
| class _ClippedNormalize(Normalize): | ||
|
wli51 marked this conversation as resolved.
|
||
| """Handle a constant reference without hiding brighter predictions. | ||
|
|
||
| For a zero-width range, equal values are middle gray, lower values are | ||
| black and higher values are white (with the gray colormap). | ||
| """ | ||
|
|
||
| def __call__(self, value, clip=None): | ||
| if self.vmin != self.vmax: | ||
| return super().__call__(value, clip=clip) | ||
| result, is_scalar = self.process_value(value) | ||
| normalized = np.ma.array( | ||
| np.where(result.data < self.vmin, 0.0, | ||
| np.where(result.data > self.vmax, 1.0, 0.5)), | ||
| mask=np.ma.getmaskarray(result) | np.isnan(result.data), | ||
| ) | ||
| return normalized[0] if is_scalar else normalized | ||
|
|
||
|
|
||
| def _fixed_limits(limits: Optional[DisplayLimits], channels: int, name: str) -> np.ndarray: | ||
| """Validate a common pair or one pair per *displayed* channel.""" | ||
| try: | ||
| values = np.asarray(limits, dtype=float) | ||
| except (TypeError, ValueError) as error: | ||
| raise ValueError(f"{name} must be a (min, max) pair or one pair per displayed channel.") from error | ||
| if values.shape == (2,): | ||
| values = np.tile(values, (channels, 1)) | ||
| if values.shape != (channels, 2) or not np.all(np.isfinite(values)): | ||
| raise ValueError(f"{name} must contain finite (min, max) pairs for {channels} displayed channels.") | ||
| if np.any(values[:, 0] >= values[:, 1]): | ||
| raise ValueError(f"{name} requires min < max.") | ||
| return values | ||
|
|
||
|
|
||
| def _finite_range(images: np.ndarray, other: Optional[np.ndarray] = None) -> Tuple[float, float]: | ||
| finite = images[np.isfinite(images)] | ||
| other_finite = other[np.isfinite(other)] if other is not None else np.array([]) | ||
| if not finite.size: | ||
| finite = other_finite | ||
| other_finite = np.array([]) | ||
| if not finite.size: | ||
| raise ValueError("Cannot determine display limits from an image/channel with no finite values.") | ||
| lower, upper = float(finite.min()), float(finite.max()) | ||
| if other_finite.size: | ||
| lower = min(lower, float(other_finite.min())) | ||
| upper = max(upper, float(other_finite.max())) | ||
| return lower, upper | ||
|
|
||
|
|
||
| def image_norms( | ||
| images: np.ndarray, | ||
| *, | ||
| scope: Literal["image", "channel"] = "image", | ||
| limits: Optional[DisplayLimits] = None, | ||
| other: Optional[np.ndarray] = None, | ||
| legacy: bool = False, | ||
| ) -> List[List[Normalize]]: | ||
| """Construct per-row/channel norms, optionally pooling another image stack.""" | ||
| if scope not in ("image", "channel"): | ||
| raise ValueError("Display scale scope must be 'image' or 'channel'.") | ||
| fixed = _fixed_limits(limits, images.shape[1], "Display limits") if limits is not None else None | ||
| rows: List[List[Normalize]] = [] | ||
| for row in range(images.shape[0]): | ||
| if row and (scope == "channel" or fixed is not None): | ||
| rows.append(rows[0]) | ||
| continue | ||
| norms = [] | ||
| for channel in range(images.shape[1]): | ||
| if fixed is not None: | ||
| lower, upper = fixed[channel] | ||
| else: | ||
| reference = images[:, channel] if scope == "channel" else images[row, channel] | ||
| if other is not None: | ||
| comparison = other[:, channel] if scope == "channel" else other[row, channel] | ||
| lower, upper = _finite_range(reference, comparison) | ||
| else: | ||
| lower, upper = _finite_range(reference) | ||
| norm_type = Normalize if legacy else _ClippedNormalize | ||
| norms.append(norm_type(vmin=lower, vmax=upper, clip=True)) | ||
| rows.append(norms) | ||
| return rows | ||
|
|
||
|
|
||
| def unpaired_norms( | ||
| images: np.ndarray, scaling: Literal["independent", "channel", "fixed"], limits: Optional[DisplayLimits], name: str | ||
| ) -> List[List[Normalize]]: | ||
| """Input/raw panels have their own independent, channel-shared or fixed scale.""" | ||
| if scaling not in ("independent", "channel", "fixed"): | ||
| raise ValueError(f"{name}_scaling must be 'independent', 'channel', or 'fixed'.") | ||
| if (scaling == "fixed") != (limits is not None): | ||
| raise ValueError(f"{name}_limits must be provided if and only if {name}_scaling='fixed'.") | ||
| return image_norms( | ||
| images, scope="channel" if scaling == "channel" else "image", | ||
| limits=limits, legacy=scaling == "independent", | ||
| ) | ||
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.