Coverage for tcvx21/analysis/contour_finding_m.py: 100%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2Implementation of a contour finding routine for 2D data
3"""
4import numpy as np
5from skimage import measure
8def find_contours(x_vals, y_vals, array, level: float) -> list:
9 """
10 Uses skimage.measure.find_contours to find the contours of an array at a given level
12 skimage uses pixel units, so we need to convert back to real units
13 """
14 x_vals, y_vals, array = np.asarray(
15 x_vals), np.asarray(y_vals), np.asarray(array)
17 assert x_vals.size == array.shape[-1]
18 assert y_vals.size == array.shape[-2]
20 x_spacing, y_spacing = np.mean(np.diff(x_vals)), np.mean(np.diff(y_vals))
21 assert np.allclose(np.diff(x_vals), x_spacing) and np.allclose(
22 np.diff(y_vals), y_spacing), "Error: basis vectors are not equally spaced."
24 contours = measure.find_contours(array, level)
25 # Contours is a list of numpy arrays, where the numpy arrays have the
26 # shape (n, 2)
28 for i, contour in enumerate(contours):
29 # For each contour level found, switch the x and y elements, and then
30 # convert to grid units
32 x_contour, y_contour = contour[:, 1], contour[:, 0]
33 x_contour, y_contour = x_contour * x_spacing + \
34 x_vals.min(), y_contour * y_spacing + y_vals.min()
35 contours[i] = np.column_stack((x_contour, y_contour))
37 return contours