1

OpenCV uses numpy arrays in order to store image data. In this question and accepted answer I was told that to access a subregion of interest in an image, I could use the form roi = img[y0:y1, x0:x1].

I am confused because when I create an numpy array in the terminal and test, I don't seem to be getting this behavior. Below I want to get the roi [[6,7], [11,12]], where y0 = index 1, y1 = index 2, and x0 = index 0, x1 = index 1.

enter image description here

Why then do I get what I want only with arr[1:3, 0:2]? I expected to get it with arr[1:2, 0:1].

It seems that when I slice an n-by-n ndarray[a:b, c:d], a and c are the expected range of indicies 0..n-1, but b and d are indicies ranging 1..n.

Community
  • 1
  • 1
user391339
  • 8,355
  • 13
  • 58
  • 71

1 Answers1

10

In your posted example numpy and cv2 are working as expected. Indexing or Slicing in numpy, just as in python in general, is 0 based and of the form [a, b), i.e. not including b.

Recreate your example:

>>> 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]])

So the statement arr[1:2, 0:1] means get the value(s) at row=1 (row 1 up to but not including 2) and column=0 (we expect 6):

>>> arr[1:2, 0:1]
array([[6]])

Similarly for arr[1:3, 0:2] we expect rows 1,2 and columns 0,1:

>>> arr[1:3, 0:2]
array([[ 6,  7],
       [11, 12]])

So if what you want is the region [[a, b], [c, d]] to include b and d, what you really need is:

[[a, b+1], [c, d+1]]

Further examples:

Suppose you need all columns but just rows 0 and 1:

>>> arr[:2, :]
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])

Here arr[:2, :] means all rows up to, but not including 2, followed by all columns :.

Suppose you want every other column, starting at column index 0 (and all rows):

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

where ::2 follows the start:stop:step notation (where stop is not inclusive).

Scott
  • 6,089
  • 4
  • 34
  • 51