2

I know how to slice a list in python. But I have a confusion when I see the following codes:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

img = Image.open('test.jpg')
img = np.array(img)
print(img.shape) # (204,204,3)
plt.imshow(img)
plt.imshow(img[:,:,::-1])

Both the last two lines can display the image correctly. But I wonder why img[:,:,::-1] as the img itself can display correctly. Is it just for fun or intentionally?

Thanks in advance!

Victor. L
  • 145
  • 2
  • 9
  • You are selecting everything from the first two dimensions and then reversing the order of the colors so switching RGB to BGR or visa versa. – Zev Jul 24 '18 at 03:35
  • 3
    While this has been marked as duplicate, there is a little more nuance here than just python slice notation. For one, normal python arrays cannot accept a tuple as a slice, that is part of numpy. Secondly it's not clear if it's the slice notation itself which is the question or if it's why the last axis has been reversed. I imagine the image you're plotting is in greyscale, if you try it with a color image you will find the red and blue color channels have been reversed. – Turksarama Jul 24 '18 at 03:37
  • You are amazing! @Zev Thanks, now I understand! – Victor. L Jul 24 '18 at 03:46

0 Answers0