gpt4 book ai didi

python - 如何比较两条轮廓路径在视觉上是否相似 - Python/Matplotlib

转载 作者:行者123 更新时间:2023-11-28 16:36:04 25 4
gpt4 key购买 nike

我想知道如何比较轮廓的两条路径是否重叠,是否相似。

更具体地说,我有一组 n 实现,每个实现都有其轮廓级别。我需要在 l 级别验证每个轮廓的稳定性。为此,我必须计算它在整体中发生了多少次。

到目前为止,我正在处理这段代码:

def iso_contours(scalar_fields):

#TODO : access the paths by level (0, 1, 2 ...)
default = 0
contours = {}
contours_number = 0
for scalar_field in scalar_fields:
cs = plt.contour(scalar_field)
for collection in cs.collections:
paths = collection.get_paths()
for path in paths:
num = contours.get(path, default)
contours[path] = num + 1
contours_number += 1

contours.update((x, y/float(contours_number)) for x, y in contours.items())
return contours

然而,即使有两条相同的路径,它们也被视为不同。

所以,我想知道如何在给定两条路径的情况下确定它们在视觉上是否相似。正如@unutbu 提醒我的那样,我不能只比较顶点,因为顶点可能以不同的顺序出现,或者一条路径中可能有 1000 个顶点,而另一条路径中可能有 100 个顶点......

最佳答案

首先,我在这里假设您知道您的等高线是按相同的比例绘制的并且没有平移,所以这与其说是图像匹配的问题,不如说是试图找出两个笨拙形状之间的差异。

有几种方法可以做到这一点,这两种方法应该会产生大致相同的结果。最准确的方法是取两条曲线之间的内积,但这需要曲线对齐并描述为相同的分辨率。例如,这可以使用插值来完成,但这是一个很大的麻烦。

我在这里尝试的方法是一个捷径,但它应该给出一个合理的估计,即绘制两条曲线之间的面积并从图中求和这个面积。面积越小,曲线越相似。 (也就是说,总而言之,对于曲线,您将使用内积,对于图像,您将使用差异区域)。

例如,从这些轮廓开始:

enter image description here

我们以这个情节结束,不同之处在于标题中的总和:

enter image description here

这是代码(它有点复杂,因为我不认为有一种方法可以简单地在两个任意参数化曲线之间进行填充,所以我取而代之的是从每个填充的单个轮廓制作图像,然后将它们相减):

import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import numpy as np
import io
import Image

xmin, xmax, ymin, ymax = -3, 6, -2, 3
delta = 0.025
x = np.arange(xmin, xmax, delta)
y = np.arange(ymin, ymax, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)

def f(a, b):
return 10.*(a*Z2 - b*Z1)

def fill_contour(cs):
v = cs.collections[0].get_paths()[0].vertices
fig = plt.figure()
ax = fig.add_subplot(111)
ax.fill(v[:,0], v[:,1], 'k')
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
buf = io.BytesIO()
fig.savefig(buf, format = 'png')
buf.seek(0)
im = Image.open(buf).convert('L')
r = np.asarray(im).astype(np.int)
r/=max(r.flat)
return r

figc = plt.figure()
axc = figc.add_subplot(111)
c0 = .07
cs1 = axc.contour(X, Y, f(.6 ,.7), [c0], colors='r')
cs2 = axc.contour(X, Y, f(.8, 1.2), [c0], colors='g')


figd = plt.figure()
axd = figd.add_subplot(111)
d1 = fill_contour(cs1)
d2 = fill_contour(cs2)
d = abs(d1-d2)
im = axd.imshow(d, cmap=cm.gray)
figd.colorbar(im)
axd.set_title( "sum = %i" % np.sum(d.flat))

figc.show()
figd.show()

关于python - 如何比较两条轮廓路径在视觉上是否相似 - Python/Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com