0

I have an n-dimensional numpy array of boolean values. I want to find the indices to be able to slice into the array with my slice containing all True values and as few False values as possible.

In less math terms, basically I have an image in 3D and I want to be able to autocrop it based on a given function I define (such as only care about sections labeled with green). What would be the best way to do this? n-dimensional solution preferred so I can use for all image types in the future.

cmitch
  • 233
  • 1
  • 10
  • numpy get index where value is true: https://stackoverflow.com/questions/16094563/numpy-get-index-where-value-is-true ; numpy.where() : https://numpy.org/doc/stable/reference/generated/numpy.where.html is it reasonable ? – pippo1980 Jan 26 '21 at 07:27

1 Answers1

1

One possible way would be to use numpy.nonzero to obtain all indices of the True values and then using the minimum and maximum value in each dimension to construct the slices:

def bounding_slices(a):
    indices = np.nonzero(a)
    # indices is an tuple of arrays containing the indices of the non-zero elements
    # (False is interpreted as zero) with each array corresponding to one dimension
    slices = []
    for indices_in_dimension in indices:
      slices.append(slice(
          np.min(indices_in_dimension),  # start slice at lowest index in dimension
          np.max(indices_in_dimension) + 1  # end slice after (+ 1) highest index
      ))
    return slices
felix-eku
  • 2,203
  • 17
  • 20