Class GeometryTools

java.lang.Object
qupath.lib.roi.GeometryTools

public class GeometryTools extends Object
Convert between QuPath ROI objects and Java Topology Suite Geometry objects.
  • Constructor Details

    • GeometryTools

      public GeometryTools()
  • Method Details

    • getDefaultFactory

      public static GeometryFactory getDefaultFactory()
      Get the default GeometryFactory to construct Geometries within QuPath.
      Returns:
    • parseTransformMatrix

      public static AffineTransformation parseTransformMatrix(String text) throws ParseException
      Parse the matrix (String) to create and return an AffineTransformation.

      The order of the matrix elements should be the following:

      1. m00 m01 m02

      2. m10 m11 m12

      Parameters:
      text -
      Returns:
      affineTransformation
      Throws:
      ParseException
    • convertTransform

      public static AffineTransform convertTransform(AffineTransformation transform)
      Parameters:
      transform -
      Returns:
    • convertTransform

      public static AffineTransformation convertTransform(AffineTransform transform)
      Parameters:
      transform -
      Returns:
    • shapeToGeometry

      public static Geometry shapeToGeometry(Shape shape)
      Convert a java.awt.Shape to a JTS Geometry.
      Parameters:
      shape -
      Returns:
    • envelopToRegion

      public static ImageRegion envelopToRegion(Envelope env, int z, int t)
      Convert an Envelope to an ImageRegion.
      Parameters:
      env - envelope
      z - z index for the region (default is 0)
      t - timepoint for the region (default is 0)
      Returns:
      the smallest ImageRegion that contains the specified envelop
    • regionToEnvelope

      public static Envelope regionToEnvelope(ImageRegion region)
      Convert an ImageRegion to an Envelope. This will lose z and t information.
      Parameters:
      region - the region = * @return the smallest Envelope that contains the specified region
    • roiToEnvelope

      public static Envelope roiToEnvelope(ROI roi)
      Convert the bounding box of a ROI to an Envelope. This will lose z and t information.
      Parameters:
      roi - the ROI
      Returns:
      the smallest Envelope that contains the specified ROI. Note that this does not involve any use of a precision model.
    • attemptOperation

      public static Geometry attemptOperation(Geometry input, Function<Geometry,Geometry> fun)
      Attempt to apply a function to a geometry, returning the input unchanged if there was an exception.

      The purpose of this is to make it easier to apply non-essential functions that might fail (e.g. with a TopologyException and to recover easily.

      Parameters:
      input - the input geometry
      fun - the function to (attempt) to apply
      Returns:
      the new geometry if the function succeeded, otherwise the original geometry
    • roundCoordinates

      public static Geometry roundCoordinates(Geometry geometry)
      Round coordinates in a Geometry to integer values.
      Parameters:
      geometry - the updated Geometry
      Returns:
    • ensurePrecision

      public static Geometry ensurePrecision(Geometry geometry)
      Update a geometry to have the precision model of the default factory. This can help ensure consistency among geometries used in QuPath.
      Parameters:
      geometry - the input geometry
      Returns:
      the input geometry if it already had the required precision model, or a duplicate geometry after precision reduction.
    • ensurePrecision

      public static Geometry ensurePrecision(Geometry geometry, PrecisionModel precisionModel)
      Update a geometry to have the specified precision model.
      Parameters:
      geometry - the input geometry
      precisionModel - the target precision model
      Returns:
      the input geometry if it already had the required precision model, or a duplicate geometry after precision reduction.
    • constrainToBounds

      public static Geometry constrainToBounds(Geometry geometry, double x, double y, double width, double height)
      Compute the intersection of a Geometry and a specified bounding box. The original Geometry may be returned unchanged if no changes are required to fit within the bounds.
      Parameters:
      geometry - the updated Geometry
      x -
      y -
      width -
      height -
      Returns:
    • iou

      public static double iou(Geometry a, Geometry b)
      Calculate the intersection over union, based on geometry areas.
      Parameters:
      a - first geometry
      b - second geometry
      Returns:
      intersection over union for a and b
    • intersectionArea

      public static double intersectionArea(Geometry a, Geometry b)
      Calculate the intersection area between two polygonal geometries.
      Parameters:
      a - first geometry
      b - second geometry
      Returns:
      the intersection area, or 0 if the geometries do not intersect
    • createRectangle

      public static Polygon createRectangle(double x, double y, double width, double height)
      Create a rectangular Geometry for the specified bounding box.
      Parameters:
      x - x ordinate for the top left of the rectangle bounding box
      y - y ordinate for the top left of the rectangle bounding box
      width - width of the rectangle bounding box
      height - height of the rectangle bounding box
      Returns:
      a polygon representing the rectangle
    • createEllipse

      public static Polygon createEllipse(double x, double y, double width, double height, int nPoints)
      Create a polygonal geometry that approximates an ellipse.
      Parameters:
      x - x ordinate for the top left of the ellipse bounding box
      y - y ordinate for the top left of the ellipse bounding box
      width - width of the ellipse bounding box
      height - height of the ellipse bounding box
      nPoints - number of points to use for the ellipse; more points will approximate the ellipse more closely
      Returns:
      a polygon representing the ellipse
    • createLineString

      public static LineString createLineString(double x1, double y1, double x2, double y2)
      Create a line Geometry for the specified end points.
      Parameters:
      x1 -
      y1 -
      x2 -
      y2 -
      Returns:
      Since:
      v0.6.0
    • createLineString

      public static LineString createLineString(Point2... points)
      Create a line Geometry for the specified array of points.
      Parameters:
      points -
      Returns:
      Since:
      v0.6.0
    • geometryToROI

      public static ROI geometryToROI(Geometry geometry, ImagePlane plane)
      Convert a JTS Geometry to a QuPath ROI.
      Parameters:
      geometry - the geometry from which to create a ROI
      plane - the plane that should contain the ROI
      Returns:
      a new ROI
    • geometryToROI

      public static ROI geometryToROI(Geometry geometry)
      Convert a JTS Geometry to a QuPath ROI on the default image plane.
      Parameters:
      geometry - the geometry from which to create a ROI
      Returns:
      a new ROI
      See Also:
    • roiToGeometry

      public static Geometry roiToGeometry(ROI roi)
      Convert to QuPath ROI to a JTS Geometry.
      Parameters:
      roi -
      Returns:
    • geometryToShape

      public static Shape geometryToShape(Geometry geometry)
      Convert a JTS Geometry to a java.awt.Shape.
      Parameters:
      geometry -
      Returns:
    • regionToGeometry

      public static Geometry regionToGeometry(ImageRegion region)
      Convert an ImageRegion to a rectangular Geometry. The z-position is retained, but timepoint is lost.
      Parameters:
      region -
      Returns:
    • union

      public static Geometry union(Geometry... geometries)
      Calculate the union of multiple Geometry objects.
      Parameters:
      geometries -
      Returns:
      Since:
      v0.6.0
    • union

      public static Geometry union(Collection<? extends Geometry> geometries)
      Calculate the union of multiple Geometry objects.
      Parameters:
      geometries -
      Returns:
      Implementation Note
      since v0.6.0 this uses FastPolygonUnion for merging polygons.
    • ensurePolygonal

      public static Geometry ensurePolygonal(Geometry geometry)
      Strip non-polygonal parts from a GeometryCollection (non-recursive).
      Parameters:
      geometry -
      Returns:
      a Geometry containing only Polygons, which may be the same as the input Geometry or empty
    • homogenizeGeometryCollection

      public static Geometry homogenizeGeometryCollection(Geometry geometry)
      Ensure a GeometryCollection contains only Geometries of the same type (Polygonal, Lineal or Puntal). Other geometries (with lower dimension) are discarded.
      Parameters:
      geometry -
      Returns:
    • removeInteriorRings

      public static Geometry removeInteriorRings(Geometry geometry, double minRingArea)
      Fill all interior rings for the specified geometry that have an area < a specified threshold.

      Note that this assumes that the geometry is valid, and does not contain self-intersections or overlapping pieces. No checks are made to confirm this (for performance reasons).

      Parameters:
      geometry -
      minRingArea -
      Returns:
    • fillHoles

      public static Geometry fillHoles(Geometry geometry)
      Fill all interior rings for the specified geometry.
      Parameters:
      geometry -
      Returns:
    • findLargestPolygon

      public static Polygon findLargestPolygon(Geometry geometry)
      Find the polygon with the largest area in a Geometry.

      If the input is a polygon, then it is returned unchanged.

      Otherwise, polygons are extracted and the one with the largest area is returned - or the first encountered polygon with the largest area in the case of a tie.

      If no polygons are found, then the method returns null.

      Parameters:
      geometry -
      Returns:
    • removeFragments

      public static Geometry removeFragments(Geometry geometry, double minArea)
      Remove fragments smaller than the specified area from a Geometry, ignoring internal rings.
      Parameters:
      geometry - the geometry to refine
      minArea - the minimum area of a fragment to retain. If ≤ 0, the geometry is returned unchanged. Otherwise, polygons will be extracted from the geometry and all that have an external ring area smaller than minArea will be removed.
      Returns:
      the refined Geometry, or an empty polygon if all pieces of the geometry were removed.
    • tryToFixPolygon

      public static Geometry tryToFixPolygon(Polygon polygon)
      Test a polygon for validity, attempting to fix TopologyValidationErrors if possible. This attempts a range of tricks (starting with Geometry.buffer(0)), although none are guaranteed to work. The first that largely preserves the polygon's area is returned.

      The result is guaranteed to be valid, but not necessarily to be a close match to the original polygon; in particular, if everything failed the result will be empty.

      Code that calls this method can test if the output is equal to the input to determine if any changes were made.

      Parameters:
      polygon - input (possibly-invalid) polygon
      Returns:
      the input polygon (if valid), an adjusted polygon (if attempted fixes helped), or an empty polygon if the situation could not be resolved
    • refineAreas

      public static Geometry refineAreas(Geometry geometry, double minSizePixels, double minHoleSizePixels)
      Remove small fragments and fill small interior rings within a Geometry.

      Note that any modifications to the geometry will result in points and lines being stripped away, leaving only polygons.

      Parameters:
      geometry - input geometry to refine
      minSizePixels - minimum area of a fragment to keep (the area of interior rings for polygons will be ignored)
      minHoleSizePixels - minimum size of an interior hole to keep
      Returns:
      the refined geometry (possibly the original unchanged), or empty geometry if the changes resulted in the Geometry disappearing
      See Also:
    • splitGeometryByLineStrings

      public static List<Geometry> splitGeometryByLineStrings(Geometry polygon, Collection<? extends Geometry> splitLines) throws IllegalArgumentException
      Split an input polygonal geometry using a collection of split lines.

      The main input must be polygonal, but the split lines can be any geometry type; their linestrings will be extracted and used for splitting.

      Important! This will also split a MultiPolygon into its constituent Polygon objects as a side effect. This is to ensure consistency and avoid cases where linestrings may span multiple polygons within the same multipolygon. The output may be combined to form a new multipolygon later if required.

      Parameters:
      polygon - the polygonal geometry to split
      splitLines - a collection of geometries, whose union will be used to split the input geometry
      Returns:
      a list of polygons formed by the splitting. This may return the original geometry, or geometries within an original collection, if these do not need to be split.
      Throws:
      IllegalArgumentException - if the input geometry is not polygonal
      Since:
      v0.5.0