拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 如何在给定非平滑基础资料的情况下在matplotlib中获得平滑的轮廓线

如何在给定非平滑基础资料的情况下在matplotlib中获得平滑的轮廓线

白鹭 - 2022-01-23 1974 0 0

我在 2D 网格上有布尔资料,想用来matplotlib在资料所在的区域TrueFalse.

然而,这些区域之间的分离在实际资料中并不平滑。给定这些资料,如何计算平滑计数?

这是一个最小的例子:

import numpy as np
import matplotlib.pyplot as plt

# generate some non-smooth example data
MESHSIZE = 10
REFINEMENT = 4*MESHSIZE
x = np.linspace(-MESHSIZE, MESHSIZE, REFINEMENT)
xv, yv = np.meshgrid(x, x)
xvf = xv.reshape(-1)
yvf = yv.reshape(-1)


def choppy_circle(x, y):
    inner = x.astype(int)**2 y.astype(int)**2 < 10.0
    return inner


# consider this the *actual* data given to me as-is
my_x = xvf
my_y = yvf
my_z = choppy_circle(xvf, yvf)

# need to visualize the contour that separates areas where
# my_z is True/False
plt.tricontour(my_x, my_y, my_z, levels=np.array([1.0-1e-3]))
plt.scatter(xv, yv, s=0.1)
plt.show()

这会产生以下情节,该情节忠实于资料,但不是我想要的:

如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线

如何使用 中给出的资料my_xmy_y并围绕其中my_z域构建平滑轮廓my_zTrue

像这样的东西:

如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线

uj5u.com热心网友回复:

您可以将样条曲线拟合到轮廓。并通过选择样条曲线的平滑自变量使其尽可能平滑。

首先,您获得边界点

import functools
import itertools

mask = my_z.reshape(40,40)
mask &= functools.reduce(np.logical_or,[~np.roll(np.roll(mask, shift_x, 0),shift_y,1) 
                                            for shift_x,shift_y in itertools.product((-1,0,1),repeat=2)])
x,y = my_x[mask.reshape(-1)],my_y[mask.reshape(-1)]
plt.scatter(x,y)

现在我们通过相应复数的自变量对您的点进行排序。如果您不知道我的意思是该点与原点和点 (1,0) 形成的角度。并为其拟合样条。

import scipy.interpolate as interpolate
import matplotlib.pyplot as plt

arr = np.array(sorted(zip(x,y), key=lambda x: cmath.phase(x[0] 1j*x[1])))
s=1

tck, u = interpolate.splprep([arr[:,0],arr[:,1]],per=1, s=s)
x_i, y_i = interpolate.splev(np.linspace(0, 1, 10**4), tck)
ax = plt.gca()
ax.plot(x_i, y_i)
ax.scatter(arr[:,0],arr[:,1])
ax.set_title(f"{s=}")
ax.set_aspect('equal')

结果看起来会有所不同,具体取决于s. 我为您绘制了一些: 如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线 如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线 如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线

uj5u.com热心网友回复:

您可以使用shapely获取任意形状的质心和边界框,然后绘制一个圆:

# […] same as previously

# get points
cs = plt.tricontour(my_x, my_y, my_z, levels=np.array([1.0-1e-3]))
v = cs.collections[0].get_paths()[0].vertices

from shapely.geometry import Polygon

# find centroid coordinates and bounding box
p = Polygon(v)
x,y =p.centroid.coords[0]
minx, miny, maxx, maxy = p.bounds

# plot circle
# depending on the data, one could also plot an ellipse or rectangle
r = max((maxx-minx)/2, (maxy-miny)/2)
circle = plt.Circle((x, y), r, color='r', fill=False)
plt.gca().add_patch(circle)

输出:

如何在给定非平滑基础资料的情况下在 matplotlib 中获得平滑的轮廓线

uj5u.com热心网友回复:

提取答案中提出的轮廓资料并使用@user2640045 提出的样条插值允许对任意轮廓执行此操作:

# my_x, my_y, my_z as above...

# get contour data
cs = plt.tricontour(my_x, my_y, my_z, levels=np.array([1.0-1e-3]))
print(type(cs))

# process each contour
for contour in cs.collections[0].get_paths():
    vert = contour.vertices
    vert_x = vert[:, 0]
    vert_y = vert[:, 1]

    # plot contour
    plt.plot(vert_x, vert_y)

    # interpolate contour points
    s = 20
    tck, u = interpolate.splprep([vert_x, vert_y], per=1, s=s)
    x_interp, y_interp = interpolate.splev(np.linspace(0, 1, 10**3), tck)

    # plot interpolated contour
    plt.plot(x_interp, y_interp)

# plot grid
plt.scatter(xv, yv, s=0.1)

# display plot
plt.show()

重要的一点是回圈头

for contour in cs.collections[0].get_paths():

其中得到每条等高线的xy资料。

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *