# Path: dltk/io/augmentation.py
# def add_gaussian_noise(image, sigma=0.05):
#     """
#     Add Gaussian noise to an image
# 
#     Args:
#         image (np.ndarray): image to add noise to
#         sigma (float): stddev of the Gaussian distribution to generate noise
#             from
# 
#     Returns:
#         np.ndarray: same as image but with added offset to each channel
#     """
# 
#     image += np.random.normal(0, sigma, image.shape)
#     return image
# 
# def extract_random_example_array(image_list,
#                                  example_size=[1, 64, 64],
#                                  n_examples=1):
#     """Randomly extract training examples from image (and a corresponding label).
#         Returns an image example array and the corresponding label array.
# 
#     Args:
#         image_list (np.ndarray or list or tuple): image(s) to extract random
#             patches from
#         example_size (list or tuple): shape of the patches to extract
#         n_examples (int): number of patches to extract in total
# 
#     Returns:
#         np.ndarray, np.ndarray: class-balanced patches extracted from full
#         images with the shape [batch, example_size..., image_channels]
#     """
# 
#     assert n_examples > 0
# 
#     was_singular = False
#     if isinstance(image_list, np.ndarray):
#         image_list = [image_list]
#         was_singular = True
# 
#     assert all([i_s >= e_s for i_s, e_s in zip(image_list[0].shape, example_size)]), \
#         'Image must be bigger than example shape'
#     assert (image_list[0].ndim - 1 == len(example_size) or image_list[0].ndim == len(example_size)), \
#         'Example size doesnt fit image size'
# 
#     for i in image_list:
#         if len(image_list) > 1:
#             assert (i.ndim - 1 == image_list[0].ndim or i.ndim == image_list[0].ndim or i.ndim + 1 == image_list[0].ndim),\
#                 'Example size doesnt fit image size'
# 
#             assert all([i0_s == i_s for i0_s, i_s in zip(image_list[0].shape, i.shape)]), \
#                 'Image shapes must match'
# 
#     rank = len(example_size)
# 
#     # Extract random examples from image and label
#     valid_loc_range = [image_list[0].shape[i] - example_size[i] for i in range(rank)]
# 
#     rnd_loc = [np.random.randint(valid_loc_range[dim], size=n_examples)
#                if valid_loc_range[dim] > 0
#                else np.zeros(n_examples, dtype=int) for dim in range(rank)]
# 
#     examples = [[]] * len(image_list)
#     for i in range(n_examples):
#         slicer = [slice(rnd_loc[dim][i], rnd_loc[dim][i] + example_size[dim])
#                   for dim in range(rank)]
# 
#         for j in range(len(image_list)):
#             ex_image = image_list[j][slicer][np.newaxis]
#             # Concatenate and return the examples
#             examples[j] = np.concatenate((examples[j], ex_image), axis=0) \
#                 if (len(examples[j]) != 0) else ex_image
# 
#     if was_singular:
#         return examples[0]
#     return examples
# 
# Path: dltk/io/preprocessing.py
# def whitening(image):
#     """Whitening. Normalises image to zero mean and unit variance."""
# 
#     image = image.astype(np.float32)
# 
#     mean = np.mean(image)
#     std = np.std(image)
# 
#     if std > 0:
#         ret = (image - mean) / std
#     else:
#         ret = image * 0.
#     return ret


import SimpleITK as sitk
import tensorflow as tf
import os
import numpy as np
from dltk.io.augmentation import add_gaussian_noise, extract_random_example_array
from dltk.io.preprocessing import whitening
        mode (str): One of the tf.estimator.ModeKeys strings: TRAIN, EVAL or
            PREDICT.
        params (dict, optional): A dictionary to parametrise read_fn outputs
            (e.g. reader_params = {'n_examples': 10, 'example_size':
            [64, 64, 64], 'extract_examples': True}, etc.).

    Yields:
        dict: A dictionary of reader outputs for dltk.io.abstract_reader.
    """

    def _augment(img):
        """An image augmentation function"""
        return add_gaussian_noise(img, sigma=0.1)

    for f in file_references:
        subject_id = f[0]

        data_path = '../../../data/IXI_HH/1mm'

        # Read the image nii with sitk
        t1_fn = os.path.join(data_path, '{}/T1_1mm.nii.gz'.format(subject_id))
        t2_fn = os.path.join(data_path, '{}/T2_1mm.nii.gz'.format(subject_id))
        pd_fn = os.path.join(data_path, '{}/PD_1mm.nii.gz'.format(subject_id))

        t1 = sitk.GetArrayFromImage(sitk.ReadImage(str(t1_fn)))
        t2 = sitk.GetArrayFromImage(sitk.ReadImage(str(t2_fn)))
        pd = sitk.GetArrayFromImage(sitk.ReadImage(str(pd_fn)))

        # Normalise volume images
        t1 = whitening(t1)

# Path: dltk/io/augmentation.py
# def add_gaussian_noise(image, sigma=0.05):
#     """
#     Add Gaussian noise to an image
# 
#     Args:
#         image (np.ndarray): image to add noise to
#         sigma (float): stddev of the Gaussian distribution to generate noise
#             from
# 
#     Returns:
#         np.ndarray: same as image but with added offset to each channel
#     """
# 
#     image += np.random.normal(0, sigma, image.shape)
#     return image
# 
# def extract_random_example_array(image_list,
#                                  example_size=[1, 64, 64],
#                                  n_examples=1):
#     """Randomly extract training examples from image (and a corresponding label).
#         Returns an image example array and the corresponding label array.
# 
#     Args:
#         image_list (np.ndarray or list or tuple): image(s) to extract random
#             patches from
#         example_size (list or tuple): shape of the patches to extract
#         n_examples (int): number of patches to extract in total
# 
#     Returns:
#         np.ndarray, np.ndarray: class-balanced patches extracted from full
#         images with the shape [batch, example_size..., image_channels]
#     """
# 
#     assert n_examples > 0
# 
#     was_singular = False
#     if isinstance(image_list, np.ndarray):
#         image_list = [image_list]
#         was_singular = True
# 
#     assert all([i_s >= e_s for i_s, e_s in zip(image_list[0].shape, example_size)]), \
#         'Image must be bigger than example shape'
#     assert (image_list[0].ndim - 1 == len(example_size) or image_list[0].ndim == len(example_size)), \
#         'Example size doesnt fit image size'
# 
#     for i in image_list:
#         if len(image_list) > 1:
#             assert (i.ndim - 1 == image_list[0].ndim or i.ndim == image_list[0].ndim or i.ndim + 1 == image_list[0].ndim),\
#                 'Example size doesnt fit image size'
# 
#             assert all([i0_s == i_s for i0_s, i_s in zip(image_list[0].shape, i.shape)]), \
#                 'Image shapes must match'
# 
#     rank = len(example_size)
# 
#     # Extract random examples from image and label
#     valid_loc_range = [image_list[0].shape[i] - example_size[i] for i in range(rank)]
# 
#     rnd_loc = [np.random.randint(valid_loc_range[dim], size=n_examples)
#                if valid_loc_range[dim] > 0
#                else np.zeros(n_examples, dtype=int) for dim in range(rank)]
# 
#     examples = [[]] * len(image_list)
#     for i in range(n_examples):
#         slicer = [slice(rnd_loc[dim][i], rnd_loc[dim][i] + example_size[dim])
#                   for dim in range(rank)]
# 
#         for j in range(len(image_list)):
#             ex_image = image_list[j][slicer][np.newaxis]
#             # Concatenate and return the examples
#             examples[j] = np.concatenate((examples[j], ex_image), axis=0) \
#                 if (len(examples[j]) != 0) else ex_image
# 
#     if was_singular:
#         return examples[0]
#     return examples
# 
# Path: dltk/io/preprocessing.py
# def whitening(image):
#     """Whitening. Normalises image to zero mean and unit variance."""
# 
#     image = image.astype(np.float32)
# 
#     mean = np.mean(image)
#     std = np.std(image)
# 
#     if std > 0:
#         ret = (image - mean) / std
#     else:
#         ret = image * 0.
#     return ret


# Path: examples/applications/IXI_HH_representation_learning_cae/reader.py
import SimpleITK as sitk
import tensorflow as tf
import os
import numpy as np
from dltk.io.augmentation import add_gaussian_noise, extract_random_example_array
from dltk.io.preprocessing import whitening

        mode (str): One of the tf.estimator.ModeKeys strings: TRAIN, EVAL or
            PREDICT.
        params (dict, optional): A dictionary to parametrise read_fn outputs
            (e.g. reader_params = {'n_examples': 10, 'example_size':
            [64, 64, 64], 'extract_examples': True}, etc.).

    Yields:
        dict: A dictionary of reader outputs for dltk.io.abstract_reader.
    """

    def _augment(img):
        """An image augmentation function"""
        return add_gaussian_noise(img, sigma=0.1)

    for f in file_references:
        subject_id = f[0]

        data_path = '../../../data/IXI_HH/1mm'

        # Read the image nii with sitk
        t1_fn = os.path.join(data_path, '{}/T1_1mm.nii.gz'.format(subject_id))
        t2_fn = os.path.join(data_path, '{}/T2_1mm.nii.gz'.format(subject_id))
        pd_fn = os.path.join(data_path, '{}/PD_1mm.nii.gz'.format(subject_id))

        t1 = sitk.GetArrayFromImage(sitk.ReadImage(str(t1_fn)))
        t2 = sitk.GetArrayFromImage(sitk.ReadImage(str(t2_fn)))
        pd = sitk.GetArrayFromImage(sitk.ReadImage(str(pd_fn)))

        # Normalise volume images
        t1 = whitening(t1)

        t2 = whitening(t2)