Home > Blockchain >  How can I randomly apply rotation and flip to arrays in a list of using python?
How can I randomly apply rotation and flip to arrays in a list of using python?

Time:10-24

I have a list of NumPy arrays, I want to apply rot90 and flip function randomly on it. So that in the end, I have a list where some arrays are as it is, and some are modified (with that two fuctions).

I directly pass that list of arrays to numpy.random.choice, it gives me the following error ValueError: a must be 1-dimensional.

thanks in advance.

CodePudding user response:

One approach it to create a population of functions and pick randomly, using random.choice, the one to apply to each image:

import random
import numpy as np

# for reproducibility
random.seed(42)
np.random.seed(42)

# toy data representing the list of images
images = [np.random.randint(255, size=(128, 128)) for _ in range(10)]

functions = [lambda x: x, np.rot90, np.flip]

# pick function at random at apply to image
res = [random.choice(functions)(image) for image in images]

CodePudding user response:

You can just sample indices and apply to the array at the respecting index. So here is an example of the basic idea:

import numpy as np
# generate some random list of arrays
l = [np.random.randint(0,10,(4,4)) for _ in range(10)]

# sample indices and apply rotation and flip
indices = np.random.choice(np.arange(len(l)),int(len(l)/2),replace=False)
new_l = [np.flip(np.rot90(l[i])) if i in indices else l[i] for i in range(len(l))]

CodePudding user response:

Why don't you sample a list of indeces that needs to be modified? In the following example, I have set:

  • A list of functions which could be applied transformations
  • If functions can be applied to the same only once (apply_only_once=True), or multiple applications are permitted (apply_only_once=False)
  • Number of lines which must be modified is n_lines_to_modify. Clearly, if apply_ony_once=True, n_lines_to_modify must be less or equal to the number of rows in the array; note that, if apply_only_once=False, n_lines_to_modify is not constrained, because multiple transformation can be applied to the same line (corner case: all the transformations applied to one line only!)
  • arrays is just a test input

In code:

import random
import numpy as np

transformations = [lambda x: x**2, lambda x: x 2]
apply_only_once = True
n_lines_to_modify = 2
arrays = np.array([np.array([1,2,3]), np.array([1,2,3]), np.array([3,4,5])])

if apply_only_once:
    to_be_modified = random.sample(range(len(arrays)), n_lines_to_modify)
else:
    to_be_modified = [random.choice(range(len(arrays))) for _ in range(n_lines_to_modify)]

for i in to_be_modified:
    arrays[i] = random.choice(transformations)(arrays[i])

print(arrays)
  • Related