我在 2D 網格上有布爾資料,想用來matplotlib在資料所在的區域True和False.
然而,這些區域之間的分離在實際資料中并不平滑。給定這些資料,如何計算平滑計數?
這是一個最小的例子:
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()
這會產生以下情節,該情節忠實于資料,但不是我想要的:

如何使用 中給出的資料my_x,my_y并圍繞其中的my_z域構建平滑輪廓?my_zTrue
像這樣的東西:

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. 我為您繪制了一些:

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)
輸出:

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資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418155.html
標籤:
