File size: 1,674 Bytes
377dccd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | # Copyright 2020-present, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Davide Abati, Simone Calderara.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
class Permutation(object):
"""
Defines a fixed permutation for a numpy array.
"""
def __init__(self) -> None:
"""
Initializes the permutation.
"""
self.perm = None
def __call__(self, sample: np.ndarray) -> np.ndarray:
"""
Randomly defines the permutation and applies the transformation.
:param sample: image to be permuted
:return: permuted image
"""
old_shape = sample.shape
if self.perm is None:
self.perm = np.random.permutation(len(sample.flatten()))
return sample.flatten()[self.perm].reshape(old_shape)
class FixedPermutation(object):
"""
Defines a fixed permutation (given the seed) for a numpy array.
"""
def __init__(self, seed: int) -> None:
"""
Defines the seed.
:param seed: seed of the permutation
"""
self.perm = None
self.seed = seed
def __call__(self, sample: np.ndarray) -> np.ndarray:
"""
Defines the permutation and applies the transformation.
:param sample: image to be permuted
:return: permuted image
"""
old_shape = sample.shape
if self.perm is None:
np.random.seed(self.seed)
self.perm = np.random.permutation(len(sample.flatten()))
return sample.flatten()[self.perm].reshape(old_shape)
|