【问题标题】:Extract coordinates enclosed by a matplotlib patch.提取由 matplotlib 补丁包围的坐标。
【发布时间】:2014-08-05 18:32:04
【问题描述】:

我使用 matplotlib.patches.ellipse 创建了一个椭圆,如下所示:

patch = mpatches.Ellipse(center, major_ax, minor_ax, angle_deg, fc='none', ls='solid', ec='g', lw='3.')

我想要的是这个补丁中包含的所有整数坐标的列表。 IE。如果我要绘制这个椭圆以及同一个网格上的每个整数点,那么有多少个点包含在椭圆中?

我试过看看我是否可以提取椭圆的方程,这样我就可以遍历每个点,看看它是否落在直线内,但我似乎找不到明显的方法来做到这一点,它变得更加复杂因为椭圆的长轴可以任意角度定向。执行此操作的信息必须存储在某个地方的补丁中,但我似乎无法找到它。

对此的任何建议将不胜感激。

【问题讨论】:

标签: python matplotlib patch ellipse


【解决方案1】:

Ellipse 对象有一个 contains_point 方法,如果该点在椭圆中,则返回 1,否则返回 0。

窃取@DrV 的答案:

import matplotlib.pyplot as plt
import matplotlib.patches
import numpy as np

# create an ellipse
el = matplotlib.patches.Ellipse((50,-23), 10, 13.7, 30, facecolor=(1,0,0,.2), edgecolor='none')

# calculate the x and y points possibly within the ellipse
y_int = np.arange(-30, -15)
x_int = np.arange(40, 60)

# create a list of possible coordinates
g = np.meshgrid(x_int, y_int)
coords = list(zip(*(c.flat for c in g)))

# create the list of valid coordinates (from untransformed)
ellipsepoints = np.vstack([p for p in coords if el.contains_point(p, radius=0)])

# just to see if this works
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_artist(el)
ep = np.array(ellipsepoints)
ax.plot(ellipsepoints[:,0], ellipsepoints[:,1], 'ko')
plt.show()

这将为您提供如下结果:

【讨论】:

  • 如何从一维对象(如 FancyArrowPatch)中提取 XY 坐标?他们没有实现此方法的内部区域:(
【解决方案2】:

如果你真的想使用matplotlib提供的方法,那么:

import matplotlib.pyplot as plt
import matplotlib.patches
import numpy as np

# create an ellipse
el = matplotlib.patches.Ellipse((50,-23), 10, 13.7, 30, facecolor=(1,0,0,.2), edgecolor='none')

# find the bounding box of the ellipse
bb = el.get_window_extent()

# calculate the x and y points possibly within the ellipse
x_int = np.arange(np.ceil(bb.x0), np.floor(bb.x1) + 1, dtype='int')
y_int = np.arange(np.ceil(bb.y0), np.floor(bb.y1) + 1, dtype='int')

# create a list of possible coordinates
g = np.meshgrid(x_int, y_int)
coords = np.array(zip(*(c.flat for c in g)))

# create a list of transformed points (transformed so that the ellipse is a unit circle)
transcoords = el.get_transform().inverted().transform(coords)

# find the transformed coordinates which are within a unit circle
validcoords = transcoords[:,0]**2 + transcoords[:,1]**2 < 1.0

# create the list of valid coordinates (from untransformed)
ellipsepoints = coords[validcoords]

# just to see if this works
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_artist(el)
ep = np.array(ellipsepoints)
ax.plot(ellipsepoints[:,0], ellipsepoints[:,1], 'ko')

似乎有效:

(放大显示,即使是挂在边缘的点也在里面。)

这里的重点是matplotlib 将椭圆处理为变换的圆(平移、旋转、缩放、任何仿射)。如果反向应用变换,则结果是原点处的单位圆,并且很容易检查一个点是否在该单位圆内。

提醒一句:get_window_extent 可能不是非常可靠,因为它似乎使用了圆的样条逼近。另请参阅 tcaswell 对渲染器依赖项的评论。

为了找到更可靠的边界框,您可以:

  • 在绘图坐标中创建一个水平和垂直向量(它们的位置并不重要,([0,0],[1,0]) 和 ([0,0], [0,1])会的)

  • 将这些向量转换成椭圆坐标(get_transform等)

  • 在椭圆坐标系(即椭圆以原点为单位圆的系统)中求圆的四个切线平行于这两个向量

  • 找到向量的交点(4个交点,但2个对角线就足够了)

  • 将交点转换回绘图坐标

这将给出一个准确(但当然受数值精度限制)的方形边界框。

但是,您可以使用简单的近似值:

  • 所有可能的点都在一个圆内,圆心与椭圆相同,直径与椭圆长轴相同

换句话说,所有可能的点都在一个正方形边界框内,该边界框介于 x0+-m/2, y0+-m/2 之间,其中 (x0, y0) 是椭圆的中心,m 是长轴。

【讨论】:

  • get_window_extent 的另一个问题是它取决于所使用的渲染器。如果您重新调整图形的大小(通过更改大小、更改 dpi、使用紧密边界框等),这可能会导致问题,因为来自 get_window_extent 的返回值不会更新它的自身并且可能无效。
  • @tcaswell:好点子!这真的不是一个非常漂亮的方法。我将更新答案以概述更好的方法。
  • 我发现这种变换坐标方法比 contains_point() 方法快得多,有时快 2 个数量级。我认为对于像椭圆这样的规则形状contains_point() 有点矫枉过正。
【解决方案3】:

我想提供另一个使用Path 对象的contains_points() 方法而不是contains_point() 的解决方案:

先获取椭圆的坐标,做成Path对象:

elpath=Path(el.get_verts())

(请注意,el.get_paths() 由于某种原因无法使用。)

然后调用路径的contains_points():

validcoords=elpath.contains_points(coords)

下面我比较了@tacaswell 的解决方案(方法 1)、@Drv 的(方法 2)和我自己的(方法 3)(我将椭圆放大了约 5 倍):

import numpy
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.path import Path
import time

#----------------Create an ellipse----------------
el=Ellipse((50,-23),50,70,30,facecolor=(1,0,0,.2), edgecolor='none')

#---------------------Method 1---------------------
t1=time.time()

for ii in range(50):
    y=numpy.arange(-100,50)
    x=numpy.arange(-30,130)
    g=numpy.meshgrid(x,y)
    coords=numpy.array(zip(*(c.flat for c in g)))

    ellipsepoints = numpy.vstack([p for p in coords if el.contains_point(p, radius=0)])

t2=time.time()
print 'time of method 1',t2-t1

#---------------------Method 2---------------------
t2=time.time()

for ii in range(50):
    y=numpy.arange(-100,50)
    x=numpy.arange(-30,130)
    g=numpy.meshgrid(x,y)
    coords=numpy.array(zip(*(c.flat for c in g)))

    invtrans=el.get_transform().inverted()
    transcoords=invtrans.transform(coords)
    validcoords=transcoords[:,0]**2+transcoords[:,1]**2<=1.0
    ellipsepoints=coords[validcoords]

t3=time.time()
print 'time of method 2',t3-t2

#---------------------Method 3---------------------
t3=time.time()

for ii in range(50):
    y=numpy.arange(-100,50)
    x=numpy.arange(-30,130)
    g=numpy.meshgrid(x,y)
    coords=numpy.array(zip(*(c.flat for c in g)))

    #------Create a path from ellipse's vertices------
    elpath=Path(el.get_verts())
    # call contains_points()
    validcoords=elpath.contains_points(coords)
    ellipsepoints=coords[validcoords]

t4=time.time()
print 'time of method 3',t4-t3

#---------------------Plot it ---------------------
fig,ax=plt.subplots()
ax.add_artist(el)
ep=numpy.array(ellipsepoints)
ax.plot(ellipsepoints[:,0],ellipsepoints[:,1],'ko')
plt.show(block=False)

我得到了这些执行时间:

time of method 1 62.2502269745
time of method 2 0.488734006882
time of method 3 0.588987112045

所以contains_point() 方法要慢得多。坐标变换方法比我的要快,但是当你得到不规则形状的轮廓/多边形时,这种方法仍然有效。

终于出结果图了:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2019-04-20
    相关资源
    最近更新 更多