12

I am running a program and I have the code below. But I do not know what does that [:, :, ::-1] do exactly. I get the following error when I run the program so understanding the function of [:, :, ::-1] will help me to debug. Thanks.

while True:
    ix = np.random.choice(np.arange(len(lists)), batch_size)
    imgs = []
    labels = []
    for i in ix:
        # images
        img_path = img_dir + lists.iloc[i, 0] + '.png'
        original_img = cv2.imread(img_path)[:, :, ::-1]
        resized_img = cv2.resize(original_img, dims+[3])
        array_img = img_to_array(resized_img)/255
        imgs.append(array_img)

error:

original_img = cv2.imread(img_path)[:, :, ::-1]
TypeError: 'NoneType' object is not subscriptable
Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
parvaneh
  • 490
  • 2
  • 6
  • 16
  • It's wacky but legal syntax: an object subscripted by a tuple of slices. I guess that's how cv2 does things? But the `TypeError: 'NoneType' object is not subscriptable` error just means that the `imread` function returned `None`. I don't know why it would do that instead of raising an exception, but I imagine it means there was some problem reading the image file? – Daniel Pryden Dec 11 '18 at 02:08
  • 1
    cv2 images are numpy ndarrays, so this slice syntax is not specific to cv2. – Håken Lid Dec 11 '18 at 02:15

2 Answers2

25

This is numpy-specific and will not work for most python objects. The : means "take everything in this dimension" and the ::-1 means "take everything in this dimension but backwards." Your matrix has three dimensions: height, width and color. Here you're flipping the color from BGR to RGB. This is necessary because OpenCV has colors in BGR (blue/green/red) order, while most other imaging libraries have them in RGB order. This code will switch the image from OpenCV format to whatever format you'll display it in.

Aaron Klein
  • 574
  • 5
  • 9
7

Let's say your image has three planes - R, G and B. Then the command [:, :, ::-1] will reverse the order of the color planes, making them B, G and R. This is done because by convention, OpenCV used BGR format (see here). So you are converting BGR to RGB simply because we like RGB nowadays.

However, your error has nothing do with the understanding of the command. The problem is that the cv2.imread() command cannot read the image and it is returning None. It is possible that you have given the wrong path.

Autonomous
  • 8,935
  • 1
  • 38
  • 77