2013-06-26 96 views
1

在matplotlib中,只要您事先定義了頂點,就可以使用matplotlib.nxutils.points_inside_poly獲取多邊形內的像素。獲取補丁內的像素

如何獲得補丁內的點數一個橢圓?

問題:如果你定義了一個matplotlib橢圓,它有一個.get_verts()方法,但是這會返回圖(而不是數據)單位的頂點。

一個可以這樣做:

# there has to be a better way to do this, 
# but this gets xy into the form used by points_inside_poly 
xy = np.array([(x,y) for x,y in zip(pts[0].ravel(),pts[1].ravel())]) 
inds = np.array([E.contains_point((x,y)) for x,y in xy], dtype='bool') 

然而,這是非常緩慢的,因爲它的循環在Python,而不是C.

使用 ax.transData.transform()
+0

我認爲,您可以使用變換將單位更改爲數據,而不是使用多邊形。 – tacaswell

+0

@tcaswell - 我認爲這是事實。在這種情況下,該問題應解釋爲「如何使用變換來轉換垂直...」 – keflavich

+1

我沒有時間寫出正確的答案(對不起),但是這個http://matplotlib.org /users/transforms_tutorial.html應該讓你找到答案的大部分路徑。 – tacaswell

回答

2

改造你的觀點,然後用points_inside_poly()

import pylab as pl 
import matplotlib.patches as mpatches 
from matplotlib.nxutils import points_inside_poly 
import numpy as np 

fig, ax = pl.subplots(1, 1) 
ax.set_aspect("equal") 
e = mpatches.Ellipse((1, 2), 3, 1.5, alpha=0.5) 
ax.add_patch(e) 
ax.relim() 
ax.autoscale() 

p = e.get_path() 
points = np.random.normal(size=(1000, 2)) 
polygon = e.get_verts() 
tpoints = ax.transData.transform(points) 
inpoints = points[points_inside_poly(tpoints, polygon)] 
sx, sy = inpoints.T 
ax.scatter(sx, sy) 

結果:

enter image description here