0

I am going through the following lines of code but I didn't understand image[...,list()]. What do the three dots mean?

self.probability = 0.5
self.indices = list(permutations(range(3), 3))
if random.random() < self.probability:
            image = np.asarray(image)
            image = Image.fromarray(image[...,list(self.indices[random.randint(0, len(self.indices) - 1)])])   

What exactly is happening in the above lines?

I have understood that the list() part is taking random channels from image? Am I correct?

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
avsr
  • 143
  • 3
  • 15
  • Does this answer your question? [What does "three dots" in Python mean when indexing what looks like a number?](https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number) – Thomas Schillaci Jun 25 '20 at 11:30

2 Answers2

1

list(permutations(range(3), 3)) generates all permutations of the intergers 0,1,2.

from itertools import permutations
list(permutations(range(3), 3))
# [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]

So the following chooses among these tuples of permutations:

list(self.indices[random.randint(0, len(self.indices) - 1)])]

In any case you'll have a permutation over the last axis of image which is usually the image channels RGB (note that with the ellipsis (...) here image[...,ixs] we are taking full slices over all axes except for the last. So this is performing a shuffling of the image channels.

An example run -

indices = list(permutations(range(3), 3))
indices[np.random.randint(0, len(indices) - 1)]
# (2, 0, 1)

Here's an example, note that this does not change the shape, we are using integer array indexing to index on the last axis only:

a = np.random.randint(0,5,(5,5,3))
a[...,(0,2,1)].shape
# (5, 5, 3)
yatu
  • 86,083
  • 12
  • 84
  • 139
  • You said except for the last axis, but indices[np.random---] produces three values right? So how does it work then? – avsr Jun 25 '20 at 11:55
  • So if the last dimension is three then those three values for an image are shuffled? Am I correct? – avsr Jun 25 '20 at 11:59
  • Take a look at the example. Here `...` basically says "ignore the first 2 axes", and with `(0,2,1)` we are indexing on the last axis (channels) on those indices. So the channels would now be ordered as `RBG` in this example @VenkataSaiReddyAvuluri – yatu Jun 25 '20 at 12:03
1

It is an object in Python called Ellipsis (for example, as a placeholder for something missing).

x = np.random.rand(3,3,3,3,3)
elem = x[:, :, :, :, 0]
elem = x[..., 0]  # same as above

This should be helpful if you want to access a specific element in a multi-dimensional array in NumPy.