Skip to content

Instantly share code, notes, and snippets.

@joferkington
Created March 3, 2013 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joferkington/5074650 to your computer and use it in GitHub Desktop.
Save joferkington/5074650 to your computer and use it in GitHub Desktop.
Print the largest (by area) contiguous object in an array
import numpy as np
import scipy.ndimage as ndimage
# The array you gave above
data = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
])
# Fill holes to make sure we get nice clusters
filled = ndimage.morphology.binary_fill_holes(data)
# Now separate each group of contiguous ones into a distinct value
# This will be an array of values from 1 - num_objects, with zeros
# outside of any contiguous object
objects, num_objects = ndimage.label(filled)
# Now return a list of slices around each object
# (This is effectively the tuple that you wanted)
object_slices = ndimage.find_objects(objects)
# Find the object with the largest area
areas = [np.product([x.stop - x.start for x in slc]) for slc in object_slices]
largest = object_slices[np.argmax(areas)]
print data[largest]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment