Isa*_*and 37 python polygon scipy sage point-in-polygon
我需要使用标准的Python包创建一个numpy 2D数组,它表示多边形的二进制掩码.
(更大的上下文:我想使用scipy.ndimage.morphology.distance_transform_edt获取此多边形的距离变换.)
谁能告诉我怎么做?
Isa*_*and 64
答案结果很简单:
import numpy
from PIL import Image, ImageDraw
# polygon = [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]
# width = ?
# height = ?
img = Image.new('L', (width, height), 0)
ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1)
mask = numpy.array(img)
Run Code Online (Sandbox Code Playgroud)
Joe*_*ton 25
作为@Anil答案的一个更直接的替代品,matplotlib matplotlib.nxutils.points_inside_poly可以用来快速栅格化任意多边形.例如
import numpy as np
from matplotlib.nxutils import points_inside_poly
nx, ny = 10, 10
poly_verts = [(1,1), (5,1), (5,9),(3,2),(1,1)]
# Create vertex coordinates for each grid cell...
# (<0,0> is at the top left of the grid in this system)
x, y = np.meshgrid(np.arange(nx), np.arange(ny))
x, y = x.flatten(), y.flatten()
points = np.vstack((x,y)).T
grid = points_inside_poly(points, poly_verts)
grid = grid.reshape((ny,nx))
print grid
Run Code Online (Sandbox Code Playgroud)
产生(布尔numpy数组):
[[False False False False False False False False False False]
[False True True True True False False False False False]
[False False False True True False False False False False]
[False False False False True False False False False False]
[False False False False True False False False False False]
[False False False False True False False False False False]
[False False False False False False False False False False]
[False False False False False False False False False False]
[False False False False False False False False False False]
[False False False False False False False False False False]]
Run Code Online (Sandbox Code Playgroud)
你应该能够grid很好地传递给任何scipy.ndimage.morphology函数.
小智 13
Joe的评论更新.自评论发布以来,Matplotlib API已发生变化,现在您需要使用子模块提供的方法matplotlib.path.
工作代码如下.
import numpy as np
from matplotlib.path import Path
nx, ny = 10, 10
poly_verts = [(1,1), (5,1), (5,9),(3,2),(1,1)]
# Create vertex coordinates for each grid cell...
# (<0,0> is at the top left of the grid in this system)
x, y = np.meshgrid(np.arange(nx), np.arange(ny))
x, y = x.flatten(), y.flatten()
points = np.vstack((x,y)).T
path = Path(poly_verts)
grid = path.contains_points(points)
grid = grid.reshape((ny,nx))
print grid
Run Code Online (Sandbox Code Playgroud)
小智 11
作为@Yusuke N.答案的一个轻微替代方案,请考虑使用matplotlib.path,它与 one by 一样有效from PIL import Image, ImageDraw(无需安装Pillow,无需考虑integer或float。对我有用吗?)
工作代码如下:
import pylab as plt
import numpy as np
from matplotlib.path import Path
width, height=2000, 2000
polygon=[(0.1*width, 0.1*height), (0.15*width, 0.7*height), (0.8*width, 0.75*height), (0.72*width, 0.15*height)]
poly_path=Path(polygon)
x, y = np.mgrid[:height, :width]
coors=np.hstack((x.reshape(-1, 1), y.reshape(-1,1))) # coors.shape is (4000000,2)
mask = poly_path.contains_points(coors)
plt.imshow(mask.reshape(height, width))
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30234 次 |
| 最近记录: |