2

Given X is a Numpy Array X.shape =(1, 96, 96, 3), Basically an Image read from CV2 . I am looking for simpler articulation of a augment operation.

Could you please explain what the following lines of code does

b=X[:, ::-1, :, :]
c=X[:, ::-1, ::-1, :]
d=X[:, :, ::-1, :]

1 Answer 1

2

X[::-1] indexing applies: indices of X from first to last in steps of -1.

  • b=X[:, ::-1, :, :] - Reverse image up/down.
  • c=X[:, ::-1, ::-1, :] - Reverse image up/down and left/right.
  • d=X[:, :, ::-1, :] - Reverse image left/right.

Remark:
:: is not an operator, it's actually two : operators one after the other.
X[::-1] is the same as X[ : : -1].
Refer to Indexing documentation.

The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step.

If i is not given it defaults to 0

If j is not given it defaults to n

Writing [: : -1], omits i and j, and sets k to -1.
The syntax means: "from index 0, take all elements, with step -1", that gives all elements in reverse order (all elements along this axis).


Example:

import cv2
import numpy as np

# Build input:
im = cv2.imread('chelsea.png')
im = cv2.resize(im, (96, 96))
X = np.empty((1, im.shape[0], im.shape[1], im.shape[2])).astype(np.uint8)
X[0, :, :, :] = im

b = X[:, ::-1, :, :]
c = X[:, ::-1, ::-1, :]
d = X[:, :, ::-1, :]

Result:

im:
enter image description here

b:
enter image description here

c:
enter image description here

d:
enter image description here


Note:
I kind of ignored the fist index because the dimension is 1.
In case of multiple frames, it's common for the fist index to apply the number of frames.

Sign up to request clarification or add additional context in comments.

4 Comments

Got the output, could you please elaborate with respect to What Happens in the multi dimensional array. Trying to WhiteBox it
It's the same as in 1D array, but each dimension has separate indexing. In case X is 2D, X[:, :] equals X, X[::-1, :] reverse the first dimension, and keep second as is, X[:, ::-1] reverse the second dimension and keep the first as is, X[::-1, ::-1] reverses first and second dimension.
In case X shape is (10, 10), you can also write X[10:0:-1, 10:0:-1]
To clarify it further, :: is not an operator, it's actually two : operators one after the other. I edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.