Basically, contour
returns an empty collection if you contour a value outside the range of your data.
Either check that the value you're contouring is inside the bounds of your data or check to see if you get an empty collection.
Also, you're currently assuming that there will be only a single contour at the given value. That's probably a bad assumption. Because you're contouring a single values, you do want to use collections[0]
, but that contour is likely to have more than one path.
If you don't want to plot the results, why not just extract the contour values directly? skimage.measure.find_contours
sounds like a better fit to what you're doing.
For example:
import numpy as np
from skimage.measure import find_contours
data = np.random.random((10,10))
contours = find_contours(data, 0.5)
for xy in contours:
x, y = xy.T
perim = np.hypot(np.diff(x), np.diff(y)).sum()