Search code examples
pythonopencvnumpyimread

Python: opencv (cv2) image slicing not working?


I've got an image loaded in grayscale via img = cv2.imread("myimg.jpg", 0).

Examining the value of img after loading, it's an ndarray that looks like this:

[[53,53,58,...,62,66,70],
 [52,52,57,...,68,68,90],
 ...,
 [80,80,80,...,91,92,91],
 [81,82,80,...,90,91,93]]

Trying to crop out a chunk of it using cropped = img[top:bottom, left:right] where top, bottom, left and right are all integers.

However, cropped is winding up as an empty ndarray.

Why would this be?


Solution

  • You are trying to split your array while supplying top = 337 and bottom = 271. Numpy works the other way around. Try to split it like this: img[bottom:top, left:right] or just invert the values of top and bottom so that you have img[a:b, c:d] with a < b and c < d.