1

I have a cropping method, that works for (N, M) array, and I want it to work for (T, N, M) - see below things I've tried and don't work (hint - couldn't get np.vectorize to work)

This is the method

def crop(image: np.ndarray) -> np.ndarray:
    """
    Crop a single image
    """
    image_cropped = image[~np.all(image == 0, axis=1)]
    image_cropped = image_cropped[:, ~np.all(image_cropped == 0, axis=0)]

    return image_cropped

What I tried

  • np.vectorize(crop)(sequence_of_images) leads to this error: numpy.AxisError: axis 1 is out of bounds for array of dimension 0
  • np.apply_along_axis(crop, 0, sequence_of_images) leads to this error: numpy.AxisError: axis 1 is out of bounds for array of dimension 1

How can I get this to work without using a loop? (It can be assumed that for each image over time dimension, the size will be equal after cropping, though the images cropping mask is not the same)

1 Answer 1

2

For 2D image, the chained indexing could be replicated with an outer mask of rows and cols.

Thus,

m1 = ~np.all(image == 0, axis=1)
m2 =  ~np.all(image_cropped == 0, axis=0)

image_cropped = image[m1, :]
image_cropped = image_cropped[:, m2]

would be same as :

image_cropped = image_cropped[outer_mask(m1, m2)]

We will transfer this knowledge to 3D case. Also, that outer mask for 3D could be easily constructed off the two maks with keepdims=True for the ALL reductions and finally using elementwise multiplication that takes care of the outer operation.

Thus, we will end up with :

mask_0s = image_nd == 0
mask1 = ~np.all(mask_0s, axis=2, keepdims=True)
mask2 = ~np.all(mask_0s, axis=1, keepdims=True)
out = image_nd[mask1 & mask2]

Finally to have 3D array output :

out = out.reshape(image_nd.shape[0],-1,mask2[0].sum())
2
  • Beautiful! Can you elaborate on each step please so I can understand the logic here? Jul 31, 2020 at 10:45
  • @bluesummers Added some explanation.
    – Divakar
    Jul 31, 2020 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.