Skip to content

Geometry

API reference for geometry operations on contours and points.

Schemas

POINT_SCHEMA

from polars_cv import POINT_SCHEMA

# Struct({x: Float64, y: Float64})

BBOX_SCHEMA

from polars_cv import BBOX_SCHEMA

# Struct({x: Float64, y: Float64, width: Float64, height: Float64})

CONTOUR_SCHEMA

from polars_cv import CONTOUR_SCHEMA

# Struct({
#     exterior: List({x: Float64, y: Float64}),
#     holes: List(List({x: Float64, y: Float64})),
#     is_closed: Boolean
# })

Helper Functions

from polars_cv.geometry.schemas import contour_from_points

contour = contour_from_points([
    (10, 10), (10, 90), (90, 90), (90, 10)
])

ContourNamespace

Bases: _PluginNamespace

Namespace for geometric operations on contour columns.

Example

df.with_columns( ... area=pl.col("contour").contour.area(), ... bbox=pl.col("contour").contour.bounding_box(), ... )

normalize

normalize(width: int | Expr, height: int | Expr) -> pl.Expr

Convert pixel coordinates to normalized [0,1] range.

Parameters:

Name Type Description Default
width int | Expr

Reference width for normalization.

required
height int | Expr

Reference height for normalization.

required

Returns:

Type Description
Expr

Contour with coordinates in [0,1] range.

Raises:

Type Description
CoordinateRangeError

If any coordinate exceeds ref dimensions.

to_absolute

to_absolute(
    width: int | Expr, height: int | Expr
) -> pl.Expr

Convert normalized coordinates to pixel coordinates.

Parameters:

Name Type Description Default
width int | Expr

Reference width for scaling.

required
height int | Expr

Reference height for scaling.

required

Returns:

Type Description
Expr

Contour with pixel coordinates.

winding

winding() -> pl.Expr

Compute winding direction from point order.

Returns:

Type Description
Expr

String 'ccw' for counter-clockwise, 'cw' for clockwise.

Note

Winding is computed using the Shoelace formula: - Positive signed area = CCW - Negative signed area = CW

area

area(*, signed: bool = False) -> pl.Expr

Compute contour area using the Shoelace formula.

For contours with holes, the hole areas are subtracted.

Parameters:

Name Type Description Default
signed bool

If True, return signed area (negative for CW winding). If False, return absolute area.

False

Returns:

Type Description
Expr

Float64 area value.

Raises:

Type Description
OpenContourError

If contour is not closed.

perimeter

perimeter() -> pl.Expr

Compute contour perimeter (sum of edge lengths).

Returns:

Type Description
Expr

Float64 perimeter value.

centroid

centroid() -> pl.Expr

Compute contour centroid (center of mass).

Returns:

Type Description
Expr

Point struct with x, y coordinates.

bounding_box

bounding_box() -> pl.Expr

Compute axis-aligned bounding box.

Returns:

Type Description
Expr

BBox struct with x, y, width, height.

convex_hull

convex_hull() -> pl.Expr

Compute convex hull of the contour.

Returns:

Type Description
Expr

New contour representing the convex hull.

is_convex

is_convex() -> pl.Expr

Check if contour is convex.

Returns:

Type Description
Expr

Boolean indicating convexity.

flip

flip() -> pl.Expr

Reverse point order (flips winding direction).

Returns:

Type Description
Expr

Contour with reversed point order.

ensure_winding

ensure_winding(direction: Literal['ccw', 'cw']) -> pl.Expr

Ensure contour has specified winding direction.

Flips the contour if needed to match target winding.

Parameters:

Name Type Description Default
direction Literal['ccw', 'cw']

Target winding direction.

required

Returns:

Type Description
Expr

Contour with guaranteed winding direction.

translate

translate(dx: float | Expr, dy: float | Expr) -> pl.Expr

Translate contour by offset.

Parameters:

Name Type Description Default
dx float | Expr

X offset.

required
dy float | Expr

Y offset.

required

Returns:

Type Description
Expr

Translated contour.

scale

scale(
    sx: float | Expr,
    sy: float | Expr,
    *,
    origin: Literal[
        "centroid", "bbox_center", "origin"
    ] = "origin",
) -> pl.Expr

Scale contour relative to specified origin.

Parameters:

Name Type Description Default
sx float | Expr

X scale factor.

required
sy float | Expr

Y scale factor.

required
origin Literal['centroid', 'bbox_center', 'origin']

Point to scale around: - "centroid": Center of mass - "bbox_center": Bounding box center - "origin": Coordinate origin (0, 0)

'origin'

Returns:

Type Description
Expr

Scaled contour.

simplify

simplify(tolerance: float) -> pl.Expr

Simplify contour using Douglas-Peucker algorithm.

Parameters:

Name Type Description Default
tolerance float

Simplification tolerance. Higher = fewer points.

required

Returns:

Type Description
Expr

Simplified contour.

iou

iou(other: Expr) -> pl.Expr

Compute Intersection over Union with another contour.

Parameters:

Name Type Description Default
other Expr

Another contour column to compare with.

required

Returns:

Type Description
Expr

Float64 IoU value in [0, 1].

pairwise_iou

pairwise_iou(other: Expr) -> pl.Expr

Compute full pairwise IoU matrix between contour sets.

Parameters:

Name Type Description Default
other Expr

Ground-truth contour-set expression (List[Contour]).

required

Returns:

Type Description
Expr

A nested list (List[List[Float64]]) representing an N x M IoU matrix.

match_detections

match_detections(
    other: Expr,
    *,
    threshold: float = 0.5,
    scores: Expr | None = None,
    strategy: Literal["greedy"] = "greedy",
) -> pl.Expr

Match prediction contour set against ground truth contour set.

Parameters:

Name Type Description Default
other Expr

Ground-truth contour-set expression (List[Contour]).

required
threshold float

IoU threshold for positive matches.

0.5
scores Expr | None

Optional per-prediction confidence score list used for ordering.

None
strategy Literal['greedy']

Matching strategy. Currently only "greedy" is supported.

'greedy'

Returns:

Type Description
Expr

A struct containing per-prediction match indices, IoUs, and TP/FP/FN counts.

label_reduce

label_reduce(
    image: Expr | None = None,
    *,
    heatmap: Expr | None = None,
    reduction: Literal["max", "mean", "sum"] = "max",
    region_mode: Literal["interior", "bbox"] = "interior",
) -> pl.Expr

Score each contour from an image/array expression with configurable reduction.

Parameters:

Name Type Description Default
image Expr | None

Image/array expression aligned by row with contour sets.

None
heatmap Expr | None

Backward-compatible alias for image.

None
reduction Literal['max', 'mean', 'sum']

Aggregation method over pixels in each contour region.

'max'
region_mode Literal['interior', 'bbox']

Region selector - "interior" or "bbox".

'interior'

Returns:

Type Description
Expr

A list of float scores, aligned to the input contour order.

dice

dice(other: Expr) -> pl.Expr

Compute Dice coefficient with another contour.

Dice = 2 * intersection / (area1 + area2)

Parameters:

Name Type Description Default
other Expr

Another contour column to compare with.

required

Returns:

Type Description
Expr

Float64 Dice coefficient in [0, 1].

hausdorff_distance

hausdorff_distance(other: Expr) -> pl.Expr

Compute Hausdorff distance to another contour.

The Hausdorff distance is the maximum distance from any point on one contour to the nearest point on the other.

Parameters:

Name Type Description Default
other Expr

Another contour column to compare with.

required

Returns:

Type Description
Expr

Float64 Hausdorff distance.

contains_point

contains_point(point: Expr) -> pl.Expr

Test if contour contains a point.

Parameters:

Name Type Description Default
point Expr

Point column to test.

required

Returns:

Type Description
Expr

Boolean indicating if point is inside contour.

PointNamespace

Bases: _PluginNamespace

Operations on point columns.

This namespace provides geometric operations for point data, including coordinate transformations and distance calculations.

The point column must match POINT_SCHEMA or POINT_SET_SCHEMA. Operations automatically handle both single points and sets of points.

Example

df.with_columns( ... normalized=pl.col("keypoint").point.normalize(width=100, height=100), ... shifted=pl.col("keypoint").point.translate(dx=10, dy=20), ... )

normalize

normalize(
    width: int | float, height: int | float
) -> pl.Expr

Convert pixel coordinates to normalized [0,1] range.

Parameters:

Name Type Description Default
width int | float

Reference width for normalization.

required
height int | float

Reference height for normalization.

required

Returns:

Type Description
Expr

Point with coordinates in [0,1] range.

to_absolute

to_absolute(
    width: int | float, height: int | float
) -> pl.Expr

Convert normalized coordinates to pixel coordinates.

Parameters:

Name Type Description Default
width int | float

Reference width for scaling.

required
height int | float

Reference height for scaling.

required

Returns:

Type Description
Expr

Point with pixel coordinates.

translate

translate(dx: float, dy: float) -> pl.Expr

Translate point by offset.

Parameters:

Name Type Description Default
dx float

X offset.

required
dy float

Y offset.

required

Returns:

Type Description
Expr

Translated point.

scale

scale(sx: float, sy: float) -> pl.Expr

Scale point coordinates.

Parameters:

Name Type Description Default
sx float

X scale factor.

required
sy float

Y scale factor.

required

Returns:

Type Description
Expr

Scaled point.

distance

distance(other: Expr) -> pl.Expr

Compute Euclidean distance to another point.

Parameters:

Name Type Description Default
other Expr

Another point column.

required

Returns:

Type Description
Expr

Float64 distance.

manhattan_distance

manhattan_distance(other: Expr) -> pl.Expr

Compute Manhattan (L1) distance to another point.

Parameters:

Name Type Description Default
other Expr

Another point column.

required

Returns:

Type Description
Expr

Float64 distance.

distance_to_contour

distance_to_contour(contour: Expr) -> pl.Expr

Compute minimum distance from point to contour boundary.

This computes the distance to the nearest edge of the contour, considering both the exterior ring and any holes.

Parameters:

Name Type Description Default
contour Expr

A contour column.

required

Returns:

Type Description
Expr

Float64 distance (always non-negative).

Example

df.with_columns( ... dist=pl.col("point").point.distance_to_contour(pl.col("polygon")) ... )

signed_distance_to_contour

signed_distance_to_contour(contour: Expr) -> pl.Expr

Compute signed distance from point to contour boundary.

Returns negative distance if point is inside the contour, positive distance if outside. Zero if on the boundary.

Parameters:

Name Type Description Default
contour Expr

A contour column.

required

Returns:

Type Description
Expr

Float64 signed distance.

Example

df.with_columns( ... sdf=pl.col("point").point.signed_distance_to_contour(pl.col("polygon")) ... )

nearest_point_on_contour

nearest_point_on_contour(contour: Expr) -> pl.Expr

Find the nearest point on a contour boundary.

Returns the point on the contour boundary that is closest to this point.

Parameters:

Name Type Description Default
contour Expr

A contour column.

required

Returns:

Type Description
Expr

Point struct with x, y coordinates of nearest boundary point.

Example

df.with_columns( ... nearest=pl.col("point").point.nearest_point_on_contour(pl.col("polygon")) ... )

angle_to

angle_to(other: Expr) -> pl.Expr

Compute angle from this point to another in radians.

Returns the angle in [-pi, pi] using atan2, where: - 0 radians points to the right (positive x) - pi/2 radians points up (positive y) - pi radians points left (negative x) - -pi/2 radians points down (negative y)

Parameters:

Name Type Description Default
other Expr

Target point column.

required

Returns:

Type Description
Expr

Float64 angle in radians.

Example

df.with_columns( ... angle=pl.col("p1").point.angle_to(pl.col("p2")) ... )

rotate

rotate(
    angle: float, *, origin: Expr | None = None
) -> pl.Expr

Rotate point around an origin by angle (in radians).

Parameters:

Name Type Description Default
angle float

Rotation angle in radians (counter-clockwise positive).

required
origin Expr | None

Center of rotation. If None, rotates around (0, 0).

None

Returns:

Type Description
Expr

Rotated point.

Example

import math df.with_columns( ... rotated=pl.col("point").point.rotate(math.pi / 2) # 90 degrees ... )

midpoint

midpoint(other: Expr) -> pl.Expr

Compute midpoint between this point and another.

Parameters:

Name Type Description Default
other Expr

Another point column.

required

Returns:

Type Description
Expr

Point at the midpoint.

Example

df.with_columns( ... mid=pl.col("p1").point.midpoint(pl.col("p2")) ... )

interpolate

interpolate(other: Expr, t: float = 0.5) -> pl.Expr

Linear interpolation between two points.

Parameters:

Name Type Description Default
other Expr

Target point column.

required
t float

Interpolation parameter (0 = self, 1 = other). Values outside [0, 1] extrapolate beyond the endpoints.

0.5

Returns:

Type Description
Expr

Interpolated point.

Example

df.with_columns( ... quarter=pl.col("p1").point.interpolate(pl.col("p2"), t=0.25) ... )

within_bbox

within_bbox(bbox: Expr) -> pl.Expr

Check if point is within a bounding box.

Parameters:

Name Type Description Default
bbox Expr

Bounding box column with x, y, width, height fields.

required

Returns:

Type Description
Expr

Boolean indicating if point is within the bbox.

Example

df.with_columns( ... inside=pl.col("point").point.within_bbox(pl.col("bbox")) ... )

x

x() -> pl.Expr

Extract X coordinate.

Returns:

Type Description
Expr

Float64 X coordinate.

y

y() -> pl.Expr

Extract Y coordinate.

Returns:

Type Description
Expr

Float64 Y coordinate.