How to Find the Locations of Any Constant Contour Value

In some application or research, we may need not only to create the contour plots but also to find out the location of certain contour value. Python package scikit-image is a very useful tool to do all kinds of image processing and manipulation including feature detection, edge finding, filtering and geometrical transformations.
In this recipe, we use skimage.measure.find_contours routine to find constant valued contours in the data array. The skimage routine uses a marching squares method, the array values are linearly interpolated to provide better precision of the output contours. Contours which intersect the image edge are open; all others are closed.
Here is the sample code which uses the MUR L4 dataset file to demonstrate the methodology:
Here is the output plot. The constant contour locations for SST = 298.0K are shown in black lines.
In this recipe, we use skimage.measure.find_contours routine to find constant valued contours in the data array. The skimage routine uses a marching squares method, the array values are linearly interpolated to provide better precision of the output contours. Contours which intersect the image edge are open; all others are closed.
Here is the sample code which uses the MUR L4 dataset file to demonstrate the methodology:
- Code: Select all
from matplotlib import pyplot as plt
import numpy as np
from netCDF4 import Dataset
from skimage import measure
# Load MUR L4 netcdf file
filename = '20170901090000-JPL-L4_GHRSST-SSTfnd-MUR-GLOB-v02.0-fv04.1_subset.nc'
ncin = Dataset(filename, 'r')
sst = ncin.variables['analysed_sst'][:]
sst = sst[0,:,:]
lons = ncin.variables['lon'][:]
lats = ncin.variables['lat'][:]
ncin.close()
# Create Colormap and Contour Levels
cmap=plt.get_cmap("jet")
clevs = np.linspace(290, 305, 21)
cs=plt.contourf(lons, lats, sst, clevs, cmap=cmap)
# Find contours at a constant value of 298.0
contours = measure.find_contours(sst, 298.0)
# Draw the location lines
for n, contour in enumerate(contours):
lons_c = -169.0+contour[:, 1]*0.01
lats_c = -25.01 + contour[:, 0]*0.01
if len(lats_c) > 500:
plt.plot(lons_c, lats_c, color='k', linewidth=2)
# Draw SST colorbar
cb = plt.colorbar(cs)
cb.set_label('SST (K)', fontsize=10)
cb.ax.tick_params(labelsize=8)
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.show()
Here is the output plot. The constant contour locations for SST = 298.0K are shown in black lines.