[:, :, ::-1] 在 python 中是什么意思?

what does [:, :, ::-1] mean in python?

我正在 运行 编写一个程序,我有下面的代码。但我不知道 [:, :, ::-1] 到底做了什么。当我 运行 程序时出现以下错误,因此了解 [:, :, ::-1] 的功能将帮助我进行调试。谢谢

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)

错误:

original_img = cv2.imread(img_path)[:, :, ::-1]
TypeError: 'NoneType' object is not subscriptable

假设您的图像具有三个平面 - R、G 和 B。然后命令 [:, :, ::-1] 将颠倒颜色平面的顺序,使它们成为 B、G 和 R。这样做是因为按照惯例,OpenCV 使用 BGR 格式(参见 here)。所以你将 BGR 转换为 RGB 仅仅是因为我们现在喜欢 RGB。

但是,你的错误与对命令的理解无关。问题是 cv2.imread() 命令无法读取图像,它返回 None。有可能是你给错了路径

这是特定于 numpy 的,不适用于大多数 python 对象。 : 表示 "take everything in this dimension" 而 ::-1 表示 "take everything in this dimension but backwards." 您的矩阵具有三个维度:高度、宽度和颜色。在这里,您将颜色从 BGR 翻转为 RGB。这是必要的,因为 OpenCV 具有 BGR (blue/green/red) 顺序的颜色,而大多数其他图像库具有 RGB 顺序的颜色。此代码会将图像从 OpenCV 格式切换为您要显示的任何格式。