Repository navigation
feat(transforms): add ultrasound speckle noise and depth-gain augmentation (#8172) #9319
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
base: dev
Are you sure you want to change the base?
Changes from 3 commits
26c120a
3fb09e3
3cfe834
342169d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -44,6 +44,8 @@ | |
| __all__ = [ | ||
| "RandGaussianNoise", | ||
| "RandRicianNoise", | ||
| "RandSpeckleNoise", | ||
| "RandUltrasoundDepthGain", | ||
| "ShiftIntensity", | ||
| "RandShiftIntensity", | ||
| "StdShiftIntensity", | ||
|
|
@@ -231,6 +233,218 @@ def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTen | |
| return img | ||
|
|
||
|
|
||
| class RandSpeckleNoise(RandomizableTransform): | ||
| """ | ||
| Add multiplicative speckle noise to image, simulating the speckle pattern | ||
| characteristic of B-mode ultrasound images. | ||
|
|
||
| Fully developed speckle is commonly modelled as multiplicative noise: the | ||
| backscattered intensity follows a Gamma distribution, see for example | ||
| `Statistics of speckle in ultrasound B-scans | ||
| <https://doi.org/10.1109/TSU.1983.31404>`_. The noise factor has unit mean, | ||
| so the mean image intensity is unchanged in expectation, while the | ||
| variance of the factor is controlled by `std`. With `std` fixed, the | ||
| Gamma shape is ``1 / std ** 2`` (the number of looks) and the scale is | ||
| ``std ** 2``. | ||
|
|
||
| Args: | ||
| prob: Probability to add speckle noise. | ||
| std: relative standard deviation of the multiplicative speckle factor. | ||
| Must be non-negative. A larger value produces stronger speckle. | ||
| sample_std: If True, sample the relative standard deviation uniformly | ||
| from 0 to `std` on each call. | ||
| dtype: output data type, if None, same as input image. defaults to float32. | ||
|
|
||
| """ | ||
|
|
||
| backend = [TransformBackends.TORCH, TransformBackends.NUMPY] | ||
|
|
||
| def __init__( | ||
| self, prob: float = 0.1, std: float = 0.5, sample_std: bool = True, dtype: DtypeLike = np.float32 | ||
| ) -> None: | ||
| """ | ||
| Args: | ||
| prob: probability to add speckle noise. | ||
| std: relative standard deviation of the multiplicative speckle factor. Must be non-negative. | ||
| sample_std: if True, sample the relative standard deviation uniformly from 0 to `std` on each call. | ||
| dtype: output data type, if None, same as input image. | ||
|
|
||
| Raises: | ||
| ValueError: if `std` is negative. | ||
| """ | ||
| RandomizableTransform.__init__(self, prob) | ||
| if std < 0: | ||
| raise ValueError(f"`std` must be non-negative, got {std}.") | ||
| self.std = std | ||
| self.sample_std = sample_std | ||
| self.dtype = dtype | ||
| self.speckle: np.ndarray | None = None | ||
|
|
||
| def randomize(self, img: NdarrayOrTensor) -> None: | ||
| """ | ||
| Randomize the speckle factor for the given image. | ||
|
|
||
| Args: | ||
| img: image the speckle factor is sampled for, only its shape is used. | ||
| The sampled factor is stored in `self.speckle` and reused when | ||
| `__call__` is invoked with `randomize=False`. | ||
| """ | ||
| super().randomize(None) | ||
| if not self._do_transform: | ||
| return None | ||
| std = self.R.uniform(0, self.std) if self.sample_std else self.std | ||
| if std <= 0: | ||
| self.speckle = np.ones(img.shape, dtype=self.dtype) | ||
| return None | ||
| # Gamma with mean 1 and variance std ** 2: shape = 1 / std ** 2, scale = std ** 2 | ||
| self.speckle, *_ = convert_data_type(self.R.gamma(1.0 / std**2, std**2, size=img.shape), dtype=self.dtype) | ||
|
|
||
| def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor: | ||
| """ | ||
| Apply the transform to `img`. | ||
|
|
||
| Args: | ||
| img: input image. | ||
| randomize: if True, sample a fresh speckle factor, otherwise reuse the | ||
| factor stored by a previous `randomize` call. | ||
|
|
||
| Returns: | ||
| image multiplied by the speckle factor, converted to `dtype` (or the input dtype if `dtype` is None). | ||
|
|
||
| Raises: | ||
| RuntimeError: if `randomize` is False and no speckle factor was sampled yet. | ||
| """ | ||
| img = convert_to_tensor(img, track_meta=get_track_meta()) | ||
| if randomize: | ||
| self.randomize(img=img) | ||
|
|
||
| if not self._do_transform: | ||
| return img | ||
|
|
||
| if self.speckle is None: | ||
| raise RuntimeError("please call the `randomize()` function first.") | ||
| # Multiply in floating point, then convert to the requested output dtype, | ||
| # so fractional factors are not truncated for integer inputs when `dtype` is None. | ||
| out_dtype = self.dtype if self.dtype is not None else img.dtype | ||
| img_f, *_ = convert_data_type(img, dtype=np.float64) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use a computation dtype supported by the input device. With a float32 MPS image and Use float32 computation on MPS. Keep multiplication in floating point before the final output cast. Add device-specific regression coverage. Also applies to: 441-441
|
||
| speckle, *_ = convert_to_dst_type(self.speckle, img_f) | ||
| out = img_f * speckle | ||
| out, *_ = convert_data_type(out, dtype=out_dtype) | ||
| return out | ||
|
|
||
|
|
||
| class RandUltrasoundDepthGain(RandomizableTransform): | ||
| """ | ||
| Apply a smooth depth-dependent gain to a B-mode ultrasound image, | ||
| simulating time-gain compensation (TGC) adjustments and depth attenuation. | ||
|
|
||
| Ultrasound signal attenuates with imaging depth, and scanners compensate | ||
| with a depth-dependent (TGC) gain. Varying that gain is a natural | ||
| augmentation for ultrasound models, making them robust to transducer | ||
| settings at deployment time. The gain profile is log-linear along the | ||
| depth axis: ``gain(t) = exp(slope * (t - 0.5))`` for ``t`` in ``[0, 1]`` | ||
| from the shallow to the deep end of the image. A negative slope darkens | ||
| the image with depth (attenuation / shadowing), a positive slope | ||
| brightens it with depth (TGC over-compensation). The slope is sampled | ||
| uniformly from `gain_range` on each call. | ||
|
|
||
| Args: | ||
| prob: Probability to apply the depth gain. | ||
| gain_range: (minimum, maximum) log-gain slope sampled uniformly. | ||
| A slope of 0 leaves the image unchanged. | ||
| depth_axis: axis of the image along which depth increases. Defaults to 1, | ||
| the first spatial axis for channel-first images, where depth | ||
| typically increases downwards in a B-mode frame. | ||
| dtype: output data type, if None, same as input image. defaults to float32. | ||
|
|
||
| """ | ||
|
|
||
| backend = [TransformBackends.TORCH, TransformBackends.NUMPY] | ||
|
|
||
| def __init__( | ||
| self, | ||
| prob: float = 0.1, | ||
| gain_range: tuple[float, float] = (-1.0, 1.0), | ||
| depth_axis: int = 1, | ||
| dtype: DtypeLike = np.float32, | ||
| ) -> None: | ||
| """ | ||
| Args: | ||
| prob: probability to apply the depth gain. | ||
| gain_range: (minimum, maximum) log-gain slope sampled uniformly. | ||
| depth_axis: axis of the image along which depth increases. | ||
| dtype: output data type, if None, same as input image. | ||
|
|
||
| Raises: | ||
| ValueError: if `gain_range` does not contain exactly two values. | ||
| """ | ||
| RandomizableTransform.__init__(self, prob) | ||
| if len(gain_range) != 2: | ||
| raise ValueError(f"`gain_range` must be a (min, max) tuple, got {gain_range}.") | ||
| self.gain_range = gain_range | ||
| self.depth_axis = depth_axis | ||
| self.dtype = dtype | ||
| self.slope: float | None = None | ||
|
|
||
| def randomize(self, img: NdarrayOrTensor | None = None) -> None: | ||
| """ | ||
| Randomize the gain slope. | ||
|
|
||
| Args: | ||
| img: unused, accepted for a uniform `randomize` signature across transforms. | ||
| The sampled slope is stored in `self.slope` and reused when | ||
| `__call__` is invoked with `randomize=False`. | ||
| """ | ||
| super().randomize(None) | ||
| if not self._do_transform: | ||
| return None | ||
| self.slope = float(self.R.uniform(self.gain_range[0], self.gain_range[1])) | ||
|
|
||
| def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor: | ||
| """ | ||
| Apply the transform to `img`. | ||
|
|
||
| Args: | ||
| img: input image. | ||
| randomize: if True, sample a fresh slope, otherwise reuse the slope | ||
| stored by a previous `randomize` call. | ||
|
|
||
| Returns: | ||
| image multiplied by the depth-gain profile, converted to `dtype` | ||
| (or the input dtype if `dtype` is None). | ||
|
|
||
| Raises: | ||
| RuntimeError: if `randomize` is False and no slope was sampled yet. | ||
| ValueError: if `depth_axis` is out of range for the image. | ||
| """ | ||
| img = convert_to_tensor(img, track_meta=get_track_meta()) | ||
| if randomize: | ||
| self.randomize(img=img) | ||
|
|
||
| if not self._do_transform: | ||
| return img | ||
|
|
||
| if self.slope is None: | ||
| raise RuntimeError("please call the `randomize()` function first.") | ||
| depth_axis = self.depth_axis if self.depth_axis >= 0 else img.ndim + self.depth_axis | ||
| if depth_axis < 0 or depth_axis >= img.ndim: | ||
| raise ValueError(f"`depth_axis` {self.depth_axis} is out of range for image with {img.ndim} dims.") | ||
| n = img.shape[depth_axis] | ||
| t = np.linspace(0.0, 1.0, n) | ||
| profile = np.exp(self.slope * (t - 0.5)) | ||
| gain_shape = [1] * img.ndim | ||
| gain_shape[depth_axis] = n | ||
| profile = profile.reshape(gain_shape) | ||
| # Multiply in floating point, then convert to the requested output dtype, | ||
| # so fractional gains are not truncated for integer inputs when `dtype` is None. | ||
| out_dtype = self.dtype if self.dtype is not None else img.dtype | ||
| img_f, *_ = convert_data_type(img, dtype=np.float64) | ||
| gain, *_ = convert_to_dst_type(profile, img_f) | ||
| out = img_f * gain | ||
| out, *_ = convert_data_type(out, dtype=out_dtype) | ||
| return out | ||
|
|
||
|
|
||
| class ShiftIntensity(Transform): | ||
| """ | ||
| Shift intensity uniformly for the entire image with specified `offset`. | ||
|
|
||
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.
Add Google-style docstrings to the new transform methods.
RandSpeckleNoise.__init__(line 262),RandSpeckleNoise.randomize(line 273),RandUltrasoundDepthGain.__init__(line 330), andRandUltrasoundDepthGain.randomize(line 345) have no docstrings. The__call__docstrings at lines 284-287 and 351-354 state only "Apply the transform toimg."The Python path rule requires docstrings for all definitions. Each docstring must document its arguments, return value, and raised exceptions in Google-style sections.
__call__: documentimg,randomize, and the returned tensor. DocumentRuntimeErrorforrandomize=Falsewithout prior randomization. ForRandUltrasoundDepthGain, also documentValueErrorfor an out-of-rangedepth_axis.randomize: document the stored state (speckleorslope). Note thatrandomize=Falsereuses this state and requires a prior call.__init__: document each argument. ForRandUltrasoundDepthGain, document theValueErrorraised whengain_rangedoes not contain exactly two values.