code: def crop_coords(img, padding):
      
  
      coords = np.nonzero(img)
      empty_axis_exists = np.any([len(arr) == 0 for arr in coords])
      if empty_axis_exists:
          end_coords = img.shape
          beg_coords = np.zeros((1, img.ndim)).astype(int).flatten()
      else:
          min_coords = np.array([arr.min() for arr in coords])
          max_coords = np.array([arr.max() for arr in coords])
          beg_coords = np.fmax(0, min_coords - padding)
          end_coords = np.fmin(img.shape, max_coords + padding)
  
      return beg_coords, end_coords
docs: Find coordinates describing extent of non-zero portion of image, padded