fig, axs = plt.subplots(1, 2, figsize=(12, 6), subplot_kw={'xticks': [],
    'yticks': [], 'frameon': False})
axs[0].set_title('Standard contour plot')
im = axs[0].imshow(Z, cmap=plt.cm.Greys_r)
cs = axs[0].contour(Z, np.arange(-3, 4, 0.5), linewidths=2, colors='red',
    linestyles='solid')
verts = cs.collections[7].get_paths()[0]
axs[0].add_patch(patches.PathPatch(verts, facecolor='none', ec='yellow', lw
    =2, zorder=50))
mask = verts.contains_points(list(np.ndindex(Z.shape)))
mask = mask.reshape(Z.shape).T
axs[1].set_title('Mask of everything within one contour line')
axs[1].imshow(mask, cmap=plt.cm.Greys_r, interpolation='none')
print(np.ma.MaskedArray(Z, mask=~mask).sum())
Как перейти от контура к маске изображения с помощью Matplotlib