scikit-image
74 строки · 2.4 Кб
1import numpy as np
2
3from . import draw
4
5
6def polygon2mask(image_shape, polygon):
7"""Create a binary mask from a polygon.
8
9Parameters
10----------
11image_shape : tuple of size 2
12The shape of the mask.
13polygon : (N, 2) array_like
14The polygon coordinates of shape (N, 2) where N is
15the number of points. The coordinates are (row, column).
16
17Returns
18-------
19mask : 2-D ndarray of type 'bool'
20The binary mask that corresponds to the input polygon.
21
22See Also
23--------
24polygon:
25Generate coordinates of pixels inside a polygon.
26
27Notes
28-----
29This function does not do any border checking. Parts of the polygon that
30are outside the coordinate space defined by `image_shape` are not drawn.
31
32Examples
33--------
34>>> import skimage as ski
35>>> image_shape = (10, 10)
36>>> polygon = np.array([[1, 1], [2, 7], [8, 4]])
37>>> mask = ski.draw.polygon2mask(image_shape, polygon)
38>>> mask.astype(int)
39array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
40[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
41[0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
42[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
43[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
44[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
45[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
46[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
47[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
48[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
49
50If vertices / points of the `polygon` are outside the coordinate space
51defined by `image_shape`, only a part (or none at all) of the polygon is
52drawn in the mask.
53
54>>> offset = np.array([[2, -4]])
55>>> ski.draw.polygon2mask(image_shape, polygon - offset).astype(int)
56array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
57[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
58[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
59[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
60[0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
61[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
62[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
63[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
64[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
65[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
66"""
67polygon = np.asarray(polygon)
68vertex_row_coords, vertex_col_coords = polygon.T
69fill_row_coords, fill_col_coords = draw.polygon(
70vertex_row_coords, vertex_col_coords, image_shape
71)
72mask = np.zeros(image_shape, dtype=bool)
73mask[fill_row_coords, fill_col_coords] = True
74return mask
75