Skip to content
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

113-gaussian-noise #139

Merged
merged 3 commits into from
Mar 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions monai/transforms/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,24 @@ def __call__(self, img):
return rescale_array(img, self.minv, self.maxv, self.dtype)


@export
class GaussianNoise(Randomizable):
"""Add gaussian noise to image.

Args:
mean (float or array of floats): Mean or “centre” of the distribution.
scale (float): Standard deviation (spread) of distribution.
size (int or tuple of ints): Output shape. Default: None (single value is returned).
"""

def __init__(self, mean=0.0, std=0.1):
self.mean = mean
self.std = std

def __call__(self, img):
return img + self.R.normal(self.mean, self.R.uniform(0, self.std), size=img.shape)


@export
class Flip:
"""Reverses the order of elements along the given axis. Preserves shape.
Expand Down
38 changes: 38 additions & 0 deletions tests/test_gaussian_noise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
import numpy as np

from parameterized import parameterized

from monai.transforms import GaussianNoise
from tests.utils import NumpyImageTestCase2D


class GaussianNoiseTest(NumpyImageTestCase2D):

@parameterized.expand([
("test_zero_mean", 0, 0.1),
("test_non_zero_mean", 1, 0.5)
])
def test_correct_results(self, _, mean, std):
seed = 42
gaussian_fn = GaussianNoise(mean=mean, std=std)
gaussian_fn.set_random_state(seed)
noised = gaussian_fn(self.imt)
np.random.seed(seed)
expected = self.imt + np.random.normal(mean, np.random.uniform(0, std), size=self.imt.shape)
assert np.allclose(expected, noised)


if __name__ == '__main__':
unittest.main()