我需要使用标准Python包创建一个代表多边形的二进制掩码的numpy 2D数组。
(较大的上下文:我想使用scipy.ndimage.morphology.distance_transform_edt获得该多边形的距离变换。]
谁能告诉我该怎么做?
答案很简单:
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)
作为@Anil答案的更直接替代,matplotlib具有matplotlib.nxutils.points_inside_poly
,可用于快速栅格化任意多边形。例如:
matplotlib.nxutils.points_inside_poly
哪个会产生(布尔numpy数组):
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
您应该能够很好地将[[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]]
传递给任何scipy.ndimage.morphology函数。
有关乔的评论的最新动态。自发表评论以来,Matplotlib API已更改,现在您需要使用子模块grid
提供的方法。
下面是工作代码。
matplotlib.path
作为@ Yusuke N.'s答案的一种替代方法,请考虑使用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
,它的效率与matplotlib.path
相同(无需安装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()
,亮区是False
。True