我在提取以下数据的精确轮廓时遇到了困难:(只需查看数据就可以看到轮廓)
data = np.array( [[ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277]])
如果我将其绘制出来:
plt.imshow(data)
但是,当我尝试使用以下方法提取轮廓时:
plt.contour(data, levels = np.unique(data))
如您所见,轮廓线并未遵循实际数据的尖角。如果我叠加两个图:
完整代码如下:
import numpy as np import matplotlib.pyplot as plt data = np.array([[ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277]]) plt.imshow(data) plt.show() plt.contour(data, levels=np.unique(data), cmap="jet") plt.colorbar()
使用行进平方算法计算轮廓位置来绘制轮廓,它在网格点之间进行插值。
也许您正在寻找离散区域边界:可以像这样检索这些边界:
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl data = np.array([[ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 1. , 1. ], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277], [ 1.46184395, 1.46184395, 1.46184395, 4.24552277, 4.24552277]]) def region_borders(data, value, color, **kwargs): v = np.argwhere(np.diff((data == value).T, axis=0)) vlines = np.array(list(zip(v + [.5, -.5], v + [.5, .5]))) h = np.argwhere(np.diff((data == value).T, axis=1)) hlines = np.array(list(zip(h + [-.5, .5], h + [.5, .5]))) if len(vlines) and len(hlines): lines = np.vstack((vlines, hlines)) elif len(vlines): lines = vlines else: lines = hlines return mpl.collections.LineCollection(lines, colors=color, **kwargs) contours = np.unique(data) fig, ax = plt.subplots(ncols=len(contours)+1, sharex=True, sharey=True, layout='constrained') im = ax[0].matshow(data, cmap='jet', aspect='auto') fig.colorbar(im, ax=ax[-1]