_polygon2mask.py 2.4 KB

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