Home > database >  Extracting contours multiple times with Python
Extracting contours multiple times with Python

Time:03-05

I'm currently using matplotlib.pyplot.contour to extract certain level plots form a 2D function. This is an example extracted from here, for the sake of the discussion:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcParams['lines.color'] = 'k'
mpl.rcParams['axes.prop_cycle'] = mpl.cycler('color', ['k'])
x = np.linspace(-9, 9, 400)
y = np.linspace(-5, 5, 400)
x, y = np.meshgrid(x, y)
a = .3
plt.contour(x, y, (y**2 - 4*a*x), [0], colors='k')
plt.show()

I'm extracting the data from the contour for later manipulation following the answers to this question.

I need to do this process several times, so I wonder if there is a way to either do it without matplotlib or skipping the plotting stage. Thanks a lot!

CodePudding user response:

If somebody faces the same challenge, I found a suitable solution in one of the answers to this question.

It uses the marching squares method implemented in the scikit-image package. As an example:

import numpy as np
from skimage import measure

# Construct some test data
x, y = np.ogrid[-np.pi:np.pi:100j, -np.pi:np.pi:100j]
r = np.sin(np.exp((np.sin(x)**3   np.cos(y)**2)))

# Find contours at a constant value of 0.8
contours = measure.find_contours(r, 0.8)

There are some caveats discussed in the comments, but now you have another option to matplotlib.pyplot.contour if needed.

  • Related