Nizam
Nizam

Reputation: 410

What does the slice operator img[:,:,::-1] with images do?

I am a novice with image processing and came across a blog that demonstrates using the slice operator to flip an image, which I require for a Machine Learning task.

I tried implementing the same, by reading 3 channel images using OpenCV as below, and it doesn't work as expected!

All that the slice operator is doing, is converting a BGR image to an RGB one(No Flipping!).

import cv2
from matplotlib import pyplot as plt
%matplotlib inline

img = cv2.imread('path_to_image')
img = img[:,:,::-1]
plt.imshow(img)
plt.show()

What am I missing over here???

Upvotes: 1

Views: 8119

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51683

You sliced the wrong part of the image array.

Images consist of X,Y and BGR values. By slicing the last index you only inverteded the BGR to RGB.

To mirror the image you need to reverse either the X or the Y cooords wich are the indexes on 0 and 1 of the image - index 2 is RGB:

img = img[:    ,:    ,::-1]  # reverses BGR to RGB, keeps x and y as is

Instead you do

img = img[:    ,::-1 ,:   ]  # reverses the x coords - mirror on x
img = img[::-1 ,:    ,:   ]  # reverses the y coords - mirror on y

etc.

BGR:

BGR

RGB: img1 = img[:, :, ::-1]

RGB

FLIP Y: img1 = img[::-1, :, ::-1]

FLIP Y

FLIP X: img1 = img[:, ::-1, ::-1]

FLIP X

FLIP X,Y: img1 = img[::-1, ::-1, ::-1]

FLIP X+Y

Upvotes: 9

Related Questions