pnpoly.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from ._pnpoly import _grid_points_in_poly, _points_in_poly
  2. def grid_points_in_poly(shape, verts, binarize=True):
  3. """Test whether points on a specified grid are inside a polygon.
  4. For each ``(r, c)`` coordinate on a grid, i.e. ``(0, 0)``, ``(0, 1)`` etc.,
  5. test whether that point lies inside a polygon.
  6. You can control the output type with the `binarize` flag. Please refer to its
  7. documentation for further details.
  8. Parameters
  9. ----------
  10. shape : tuple (M, N)
  11. Shape of the grid.
  12. verts : (V, 2) array
  13. Specify the V vertices of the polygon, sorted either clockwise
  14. or anti-clockwise. The first point may (but does not need to be)
  15. duplicated.
  16. binarize : bool
  17. If `True`, the output of the function is a boolean mask.
  18. Otherwise, it is a labeled array. The labels are:
  19. O - outside, 1 - inside, 2 - vertex, 3 - edge.
  20. See Also
  21. --------
  22. points_in_poly
  23. Returns
  24. -------
  25. mask : (M, N) ndarray
  26. If `binarize` is True, the output is a boolean mask. True means the
  27. corresponding pixel falls inside the polygon.
  28. If `binarize` is False, the output is a labeled array, with pixels
  29. having a label between 0 and 3. The meaning of the values is:
  30. O - outside, 1 - inside, 2 - vertex, 3 - edge.
  31. """
  32. output = _grid_points_in_poly(shape, verts)
  33. if binarize:
  34. output = output.astype(bool)
  35. return output
  36. def points_in_poly(points, verts):
  37. """Test whether points lie inside a polygon.
  38. Parameters
  39. ----------
  40. points : (K, 2) array
  41. Input points, ``(x, y)``.
  42. verts : (L, 2) array
  43. Vertices of the polygon, sorted either clockwise or anti-clockwise.
  44. The first point may (but does not need to be) duplicated.
  45. See Also
  46. --------
  47. grid_points_in_poly
  48. Returns
  49. -------
  50. mask : (K,) array of bool
  51. True if corresponding point is inside the polygon.
  52. """
  53. return _points_in_poly(points, verts)