当从numpy数组(opencv图像)获得ROI时,为什么img [y0:y1,x0:x1]似乎使用不一致的指标范围?

use*_*339 1 python opencv numpy

OpenCV使用numpy数组来存储图像数据.在这个问题和接受的答案中,我被告知要访问图像中感兴趣的子区域,我可以使用该表格roi = img[y0:y1, x0:x1].

我很困惑,因为当我在终端中创建一个numpy数组并进行测试时,我似乎没有得到这种行为.下面我想得到roi [[6,7], [11,12]],在哪里y0 = index 1, y1 = index 2,和x0 = index 0, x1 = index 1.

在此输入图像描述

为什么我得到我想要的东西arr[1:3, 0:2]呢?我期望得到它arr[1:2, 0:1].

似乎当我切割n-by-n ndarray [a:b,c:d]时,a和c是预期的指标范围0..n-1,但b和d是指数范围1..n .

Sco*_*ott 8

在您发布的示例中,numpy和cv2正在按预期工作. numpy中的索引或切片,就像在python中一样,基于0和形式[a, b),即不包括b.

重新创建您的示例:

>>> import numpy as np
>>> arr = np.arange(1,26).reshape(5,5)
>>> arr
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])
Run Code Online (Sandbox Code Playgroud)

所以声明arr[1:2, 0:1]意味着得到row=1(第1行但不包括2)和column=0(我们期望6)的值:

>>> arr[1:2, 0:1]
array([[6]])
Run Code Online (Sandbox Code Playgroud)

类似地,arr[1:3, 0:2]我们期望行1,2和列0,1:

>>> arr[1:3, 0:2]
array([[ 6,  7],
       [11, 12]])
Run Code Online (Sandbox Code Playgroud)

因此,如果你想要的是[[a, b], [c, d]]包含b和d 的区域,你真正需要的是:

[[a, b+1], [c, d+1]]
Run Code Online (Sandbox Code Playgroud)

更多例子:

假设您需要所有列,但只需要行0和1:

>>> arr[:2, :]
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
Run Code Online (Sandbox Code Playgroud)

这里arr[:2, :]表示所有行,但不包括2,后跟所有列:.

假设您希望每个其他列,从列索引0(和所有行)开始:

>>> arr[:, ::2]
array([[ 1,  3,  5],
       [ 6,  8, 10],
       [11, 13, 15],
       [16, 18, 20],
       [21, 23, 25]])
Run Code Online (Sandbox Code Playgroud)

这里::2遵循start:stop:step符号(其中站是不包括在内).