-2

In the below function imcrop_tosquare. Assume i have a image of shape (8,4) ie 8 rows and 4 column. If that is the case. I will be getting extra as 4. Then extra%2 ==0 condition gets satisfied.

crop = img[2:-2,:]

What does 2 to -2 represent? I assume it is from 2nd row to its before row. 1,2,3,4,5,6,7,8 [This will be in loop] so -1 would be 1 and -2 would be 2. Wont the image be damaged if bring the first two rows to end?? Am i interpreting it wrongly? Can anyone guide me in understanding this.

def imcrop_tosquare(img):
"""Make any image a square image.

Parameters
----------
img : np.ndarray
    Input image to crop, assumed at least 2d.

Returns
-------
crop : np.ndarray
    Cropped image.
"""
  if img.shape[0] > img.shape[1]:
    extra = (img.shape[0] - img.shape[1])
    if extra % 2 == 0:
        crop = img[extra // 2:-extra // 2, :]
    else:
        crop = img[max(0, extra // 2 + 1):min(-1, -(extra // 2)), :]
  elif img.shape[1] > img.shape[0]:
    extra = (img.shape[1] - img.shape[0])
    if extra % 2 == 0:
        crop = img[:, extra // 2:-extra // 2]
    else:
        crop = img[:, max(0, extra // 2 + 1):min(-1, -(extra // 2))]
  else:
    print("It is imgae")
    crop = img
  return crop
DYZ
  • 55,249
  • 10
  • 64
  • 93
Tharun
  • 425
  • 5
  • 13
  • 3
    You should read numpy documentation. It has the answers to all your questions. – DYZ Sep 02 '17 at 06:34

1 Answers1

1

according to documentation :

Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension.

so if you have 8 rows in your array, crop = img[2:-2,:] would mean crop = img[2:6,:]

pouyan
  • 3,445
  • 4
  • 26
  • 44