matplotlib.path.contains_points不一致的行为

bz4sfanl  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(108)

我一直在使用matplotlib.path.contains_points()方法,没有任何图形或绘图。我得到的结果不一致,这取决于路径。在下面的例子中,一个简单的方形路径可以工作,但椭圆的较长路径则不行:

import numpy as np
from skimage.draw import ellipse_perimeter
from matplotlib.path import Path
import matplotlib.pyplot as plt

s = 100
squarepath = Path([(0,0), (0, s), (s,s), (s, 0)])
print(squarepath.contains_points([(s/2, s/2)]))

(xv,yv) = ellipse_perimeter(200,360,260,360)
xyverts =  np.stack((xv,yv),axis=1)
ellipsepath = Path(xyverts)
pt = (213,300)
print(ellipsepath.contains_points([pt]))

fig,ax = plt.subplots()
plt.scatter(ellipsepath.vertices[:,0],ellipsepath.vertices[:,1])
plt.scatter(pt[0],pt[1])
plt.show()

字符串
我在绘制任何东西之前使用contains_points(),所以不应该有任何数据与显示坐标的问题,就像在其他关于contains_points()的类似问题中讨论的那样。

ioekq8ef

ioekq8ef1#

问题是ellipse_perimeter以一种没有定义路径的顺序返回椭圆周长的点。然后在椭圆上的点之间创建顶点。您可以通过将路径绘制为补丁而不是使用scatter来检查:

from matplotlib.patches import PathPatch
ax.add_patch(PathPatch(ellipsepath, facecolor='yellow', lw=1)) # instead of scatter(ellipsepath...)

字符串
输出(不对代码做任何修改):


的数据
正如您所看到的,我们只看到了线(连接整个周长上的点),而不是看到facecolor指定的黄色椭圆。
我想解决这个问题最简单的方法是使用patches.Ellipse并调用get_path()
但是,如果你坚持使用skimage,你必须在创建路径之前对你的点进行排序:

import numpy as np
from skimage.draw import ellipse_perimeter
from matplotlib.path import Path
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch

(xv,yv) = ellipse_perimeter(200,360,260,360)
xyverts =  list(zip(xv, yv))
pt_top = sorted([(x,y) for x,y in xyverts if y >= 360], key=lambda c: c[0])
pt_bottom = sorted([(x,y) for x,y in xyverts if y < 360], key=lambda c: -c[0])

xyverts = pt_top + pt_bottom

ellipsepath = Path(xyverts)
pt = (213,300)
print(ellipsepath.contains_points([pt]))

fig,ax = plt.subplots()
ax.add_patch(PathPatch(ellipsepath, facecolor='yellow', lw=1))
plt.scatter(pt[0],pt[1])
plt.show()


输出量:


相关问题