Skip to content

LazyPipelineExpr

The LazyPipelineExpr class enables composable, lazy pipeline expressions.

Overview

import polars as pl
from polars_cv import Pipeline

# Create lazy expression
expr = pl.col("image").cv.pipe(Pipeline().source("image_bytes"))

# Chain operations
gray = expr.pipe(Pipeline().grayscale())

# Materialize with sink
result = df.with_columns(output=gray.sink("png"))

Mirrored Pipeline methods

Every operation and policy setter on Pipeline — resize(), grayscale(), on_error(), on_null_param() and the rest — has a generated LazyPipelineExpr counterpart, so it can be chained directly after .pipe(...):

expr = pl.col("image").cv.pipe(pipe).resize(height=pl.col("h")).on_null_param("null")

Those methods are generated from the Pipeline ones and listed in the reference below with the same documentation, alongside the hand-written surface — composition (pipe(), merge_pipe()), sinks, the binary operators, and the few operations that take another LazyPipelineExpr as an operand.

API Reference

LazyPipelineExpr

Bases: _LazyOpsMixin, _LazyForwardersMixin

Lazy pipeline expression for composed operations.

This class represents a deferred computation that can be composed with other expressions. The entire graph is fused and executed when .sink() is called.

Example

preprocess = Pipeline().source("image_bytes").resize(height=100, width=200) img = pl.col("image").cv.pipe(preprocess) expr = img.sink("numpy")

node_id property

node_id: str

Get the unique node ID for this expression.

column property

column: Expr | None

The input column expression; None for a continuation node.

pipeline property

pipeline: 'Pipeline'

Get the pipeline specification.

alias_name property

alias_name: str | None

Get the user-defined alias for this node, if any.

abs

abs() -> LazyPipelineExpr

Absolute value (|x|).

Lazy form of :meth:Pipeline.abs on this expression's output.

add_constant

add_constant(value: FloatOrExpr) -> LazyPipelineExpr

Add a constant to every value (x + value).

Lazy form of :meth:Pipeline.add_constant on this expression's output.

adjust_brightness

adjust_brightness(
    *, factor: FloatOrExpr, preserve_dtype: bool = False
) -> LazyPipelineExpr

Adjust image brightness by scaling pixel values.

Lazy form of :meth:Pipeline.adjust_brightness on this expression's output.

adjust_contrast

adjust_contrast(factor: FloatOrExpr) -> LazyPipelineExpr

Adjust image contrast: (pixel - mean) * factor + mean.

Lazy form of :meth:Pipeline.adjust_contrast on this expression's output.

adjust_gamma

adjust_gamma(gamma: FloatOrExpr) -> LazyPipelineExpr

Apply gamma (power-law) correction: normalize to [0,1], raise to gamma,

Lazy form of :meth:Pipeline.adjust_gamma on this expression's output.

apply_lut

apply_lut(
    table: Sequence[Sequence[FloatOrExpr]],
    *,
    out_dtype: str = "u8",
) -> LazyPipelineExpr

Map each value through a lookup table.

Lazy form of :meth:Pipeline.apply_lut on this expression's output.

area

area(*, signed: BoolOrExpr = False) -> LazyPipelineExpr

Compute the area of the contour using the Shoelace formula.

Lazy form of :meth:Pipeline.area on this expression's output.

assert_shape

assert_shape(
    *,
    dims: Sequence[int | None] | None = None,
    height: IntOrExpr | None = None,
    width: IntOrExpr | None = None,
    channels: IntOrExpr | None = None,
) -> LazyPipelineExpr

Declare a shape the planner cannot work out for itself.

Lazy form of :meth:Pipeline.assert_shape on this expression's output.

blur

blur(sigma: FloatOrExpr) -> LazyPipelineExpr

Apply Gaussian blur.

Lazy form of :meth:Pipeline.blur on this expression's output.

boundary

boundary() -> LazyPipelineExpr

A region's rings as open lines: the exterior, then each hole, each

Lazy form of :meth:Pipeline.boundary on this expression's output.

bounding_box

bounding_box() -> LazyPipelineExpr

Compute the axis-aligned bounding box of the contour.

Lazy form of :meth:Pipeline.bounding_box on this expression's output.

canny

canny(
    *,
    low_threshold: FloatOrExpr = 50.0,
    high_threshold: FloatOrExpr = 150.0,
) -> LazyPipelineExpr

Canny edge detection, as cv2.Canny(image, low, high) computes it:

Lazy form of :meth:Pipeline.canny on this expression's output.

cast

cast(dtype: str) -> LazyPipelineExpr

Cast to a different data type.

Lazy form of :meth:Pipeline.cast on this expression's output.

ceil

ceil() -> LazyPipelineExpr

Round toward positive infinity.

Lazy form of :meth:Pipeline.ceil on this expression's output.

centroid

centroid() -> LazyPipelineExpr

Compute the centroid (center of mass) of the contour.

Lazy form of :meth:Pipeline.centroid on this expression's output.

channel_select

channel_select(
    index: IntOrExpr, *, keepdims: bool = True
) -> LazyPipelineExpr

Extract one channel of a multi-channel image: [H, W, 1] from a

Lazy form of :meth:Pipeline.channel_select on this expression's output.

channel_swap

channel_swap(
    order: Sequence[IntOrExpr],
) -> LazyPipelineExpr

Reorder channels in a multi-channel image.

Lazy form of :meth:Pipeline.channel_swap on this expression's output.

clamp

clamp(
    min_val: FloatOrExpr,
    max_val: FloatOrExpr,
    out_dtype: str | None = None,
    preserve_dtype: bool = False,
) -> LazyPipelineExpr

Clamp values to a range.

Lazy form of :meth:Pipeline.clamp on this expression's output.

clamp_max

clamp_max(value: FloatOrExpr) -> LazyPipelineExpr

Cap values at value (min(x, value)); one-sided clamp.

Lazy form of :meth:Pipeline.clamp_max on this expression's output.

clamp_min

clamp_min(value: FloatOrExpr) -> LazyPipelineExpr

Floor values at value (max(x, value)); one-sided clamp.

Lazy form of :meth:Pipeline.clamp_min on this expression's output.

close

close() -> LazyPipelineExpr

Join an open line's ends into the region it bounds. A line that

Lazy form of :meth:Pipeline.close on this expression's output.

convert_color

convert_color(
    *, from_space: str, to_space: str
) -> LazyPipelineExpr

Convert between color spaces.

Lazy form of :meth:Pipeline.convert_color on this expression's output.

convex_hull

convex_hull() -> LazyPipelineExpr

Compute the convex hull of the contour.

Lazy form of :meth:Pipeline.convex_hull on this expression's output.

convolve2d

convolve2d(
    kernel: Sequence[FloatOrExpr],
    *,
    normalize: BoolOrExpr = False,
    border: str | Expr = "replicate",
) -> LazyPipelineExpr

Apply generic 2D convolution with an arbitrary kernel.

Lazy form of :meth:Pipeline.convolve2d on this expression's output.

coordinate_grid

coordinate_grid(
    *, normalized: BoolOrExpr = False
) -> LazyPipelineExpr

The pixel coordinates of the image: an f32 [H, W, 2] buffer holding

Lazy form of :meth:Pipeline.coordinate_grid on this expression's output.

crop

crop(
    *,
    top: IntOrExpr = 0,
    left: IntOrExpr = 0,
    height: IntOrExpr | None = None,
    width: IntOrExpr | None = None,
) -> LazyPipelineExpr

Extract a rectangular region.

Lazy form of :meth:Pipeline.crop on this expression's output.

densify

densify(
    max_segment_length: FloatOrExpr,
) -> LazyPipelineExpr

Add points so no edge is longer than max_segment_length: each edge is

Lazy form of :meth:Pipeline.densify on this expression's output.

dilate

dilate(
    *,
    ksize: IntOrExpr = 3,
    iterations: IntOrExpr = 1,
    footprint: str | Expr = "square",
) -> LazyPipelineExpr

Morphological dilation: the local maximum over a footprint (a

Lazy form of :meth:Pipeline.dilate on this expression's output.

distance_transform

distance_transform(
    *, signed: BoolOrExpr = False
) -> LazyPipelineExpr

Exact Euclidean distance transform of a mask: an f32 image of the same

Lazy form of :meth:Pipeline.distance_transform on this expression's output.

equalize_histogram

equalize_histogram() -> LazyPipelineExpr

Apply histogram equalization for contrast enhancement: map each pixel

Lazy form of :meth:Pipeline.equalize_histogram on this expression's output.

erode

erode(
    *,
    ksize: IntOrExpr = 3,
    iterations: IntOrExpr = 1,
    footprint: str | Expr = "square",
) -> LazyPipelineExpr

Morphological erosion: the local minimum over a footprint (a

Lazy form of :meth:Pipeline.erode on this expression's output.

expand_dims

expand_dims(axis: int) -> LazyPipelineExpr

Insert an axis of size 1: [H, W] to [H, W, 1] with axis=-1. The

Lazy form of :meth:Pipeline.expand_dims on this expression's output.

extract_contours

extract_contours(
    *,
    mode: str | Expr = "external",
    method: str | Expr = "simple",
    min_area: FloatOrExpr | None = None,
    min_area_fraction: FloatOrExpr | None = None,
) -> LazyPipelineExpr

Extract contours from binary mask.

Lazy form of :meth:Pipeline.extract_contours on this expression's output.

extract_shape

extract_shape() -> LazyPipelineExpr

Extract the buffer's shape: one Float64 per dimension, in order

Lazy form of :meth:Pipeline.extract_shape on this expression's output.

flip

flip(axes: Sequence[int]) -> LazyPipelineExpr

Flip along specified axes.

Lazy form of :meth:Pipeline.flip on this expression's output.

flip_h

flip_h() -> LazyPipelineExpr

Flip horizontally (along width axis).

Lazy form of :meth:Pipeline.flip_h on this expression's output.

flip_v

flip_v() -> LazyPipelineExpr

Flip vertically (along height axis).

Lazy form of :meth:Pipeline.flip_v on this expression's output.

floor

floor() -> LazyPipelineExpr

Round toward negative infinity.

Lazy form of :meth:Pipeline.floor on this expression's output.

grayscale

grayscale() -> LazyPipelineExpr

Convert to grayscale (luminance 0.299R + 0.587G + 0.114B).

Lazy form of :meth:Pipeline.grayscale on this expression's output.

histogram

histogram(
    *,
    bins: IntOrExpr | Sequence[float] = 256,
    range: Sequence[FloatOrExpr] | None = None,
    closed: str = "left",
    output: str = "buckets",
) -> LazyPipelineExpr

Compute pixel value histogram.

Lazy form of :meth:Pipeline.histogram on this expression's output.

invert

invert() -> LazyPipelineExpr

Invert values, keeping the dtype: MAX + MIN - x for an integer

Lazy form of :meth:Pipeline.invert on this expression's output.

label_reduce

label_reduce(
    contours: Expr,
    *,
    reduction: str | Expr = "max",
    region_mode: str | Expr = "interior",
) -> LazyPipelineExpr

Score contour regions against the current buffer values.

Lazy form of :meth:Pipeline.label_reduce on this expression's output.

laplacian

laplacian() -> LazyPipelineExpr

Laplacian second-derivative operator.

Lazy form of :meth:Pipeline.laplacian on this expression's output.

largest

largest(*, k: IntOrExpr = 1) -> LazyPipelineExpr

Keep the k largest contours of the set, by area: largest first,

Lazy form of :meth:Pipeline.largest on this expression's output.

letterbox

letterbox(
    *,
    height: IntOrExpr,
    width: IntOrExpr,
    value: FloatOrExpr = 0.0,
    filter: str | Expr = "lanczos3",
) -> LazyPipelineExpr

Resize image maintaining aspect ratio and pad to exact target size: fit

Lazy form of :meth:Pipeline.letterbox on this expression's output.

morphology_close

morphology_close(
    *,
    ksize: IntOrExpr = 3,
    footprint: str | Expr = "square",
) -> LazyPipelineExpr

Morphological closing (dilate then erode).

Lazy form of :meth:Pipeline.morphology_close on this expression's output.

morphology_gradient

morphology_gradient(
    *,
    ksize: IntOrExpr = 3,
    footprint: str | Expr = "square",
) -> LazyPipelineExpr

Morphological gradient (dilate - erode): an edge outline. Requires

Lazy form of :meth:Pipeline.morphology_gradient on this expression's output.

morphology_open

morphology_open(
    *,
    ksize: IntOrExpr = 3,
    footprint: str | Expr = "square",
) -> LazyPipelineExpr

Morphological opening (erode then dilate).

Lazy form of :meth:Pipeline.morphology_open on this expression's output.

neg

neg() -> LazyPipelineExpr

Negate every value (-x).

Lazy form of :meth:Pipeline.neg on this expression's output.

normalize

normalize(
    *,
    method: str = "minmax",
    mean: Sequence[FloatOrExpr] | None = None,
    std: Sequence[FloatOrExpr] | None = None,
    out_dtype: str | None = None,
) -> LazyPipelineExpr

Normalize values to a standard range.

Lazy form of :meth:Pipeline.normalize on this expression's output.

offset

offset(
    distance: FloatOrExpr, *, join: str | Expr = "round"
) -> LazyPipelineExpr

Grow the set's regions by distance (negative: shrink them): every

Lazy form of :meth:Pipeline.offset on this expression's output.

on_error

on_error(policy: str) -> LazyPipelineExpr

Set the per-row error policy for the executed pipeline graph.

Lazy form of :meth:Pipeline.on_error on this expression's output.

on_null_param

on_null_param(policy: str) -> LazyPipelineExpr

Set what a null in a per-row expression parameter means.

Lazy form of :meth:Pipeline.on_null_param on this expression's output.

pad

pad(
    *,
    top: IntOrExpr = 0,
    bottom: IntOrExpr = 0,
    left: IntOrExpr = 0,
    right: IntOrExpr = 0,
    value: FloatOrExpr = 0.0,
    mode: str | Expr = "constant",
) -> LazyPipelineExpr

Add padding to the image.

Lazy form of :meth:Pipeline.pad on this expression's output.

pad_to_size

pad_to_size(
    *,
    height: IntOrExpr,
    width: IntOrExpr,
    position: str | Expr = "center",
    value: FloatOrExpr = 0.0,
) -> LazyPipelineExpr

Pad image to exact target size (computed at runtime). A larger image is

Lazy form of :meth:Pipeline.pad_to_size on this expression's output.

perceptual_hash

perceptual_hash(
    *, algorithm: str = "perceptual", hash_size: int = 64
) -> LazyPipelineExpr

Compute a perceptual hash fingerprint.

Lazy form of :meth:Pipeline.perceptual_hash on this expression's output.

perimeter

perimeter() -> LazyPipelineExpr

Compute the perimeter (arc length) of the contour.

Lazy form of :meth:Pipeline.perimeter on this expression's output.

rasterize

rasterize(
    *,
    width: IntOrExpr | None = None,
    height: IntOrExpr | None = None,
    shape: LazyPipelineExpr | None = None,
    fill_value: IntOrExpr = 255,
    background: IntOrExpr = 0,
    supersample: IntOrExpr = 1,
) -> LazyPipelineExpr

Rasterize contours to a mask: each region filled.

Lazy form of :meth:Pipeline.rasterize on this expression's output.

reciprocal

reciprocal() -> LazyPipelineExpr

Reciprocal (1 / x; ±inf at zero).

Lazy form of :meth:Pipeline.reciprocal on this expression's output.

reduce_argmax

reduce_argmax(axis: int) -> LazyPipelineExpr

Index of the maximum value along an axis.

Lazy form of :meth:Pipeline.reduce_argmax on this expression's output.

reduce_argmin

reduce_argmin(axis: int) -> LazyPipelineExpr

Index of the minimum value along an axis.

Lazy form of :meth:Pipeline.reduce_argmin on this expression's output.

reduce_max

reduce_max(*, axis: int | None = None) -> LazyPipelineExpr

Reduce buffer by computing the maximum value.

Lazy form of :meth:Pipeline.reduce_max on this expression's output.

reduce_mean

reduce_mean(*, axis: int | None = None) -> LazyPipelineExpr

Compute arithmetic mean.

Lazy form of :meth:Pipeline.reduce_mean on this expression's output.

reduce_min

reduce_min(*, axis: int | None = None) -> LazyPipelineExpr

Reduce buffer by computing the minimum value.

Lazy form of :meth:Pipeline.reduce_min on this expression's output.

reduce_percentile

reduce_percentile(q: FloatOrExpr) -> LazyPipelineExpr

Compute the q-th percentile of all values (linear interpolation, as numpy's

Lazy form of :meth:Pipeline.reduce_percentile on this expression's output.

reduce_popcount

reduce_popcount() -> LazyPipelineExpr

Count set bits (1s) in the buffer.

Lazy form of :meth:Pipeline.reduce_popcount on this expression's output.

reduce_std

reduce_std(
    *, axis: int | None = None, ddof: IntOrExpr = 0
) -> LazyPipelineExpr

Reduce buffer by computing the standard deviation.

Lazy form of :meth:Pipeline.reduce_std on this expression's output.

reduce_sum

reduce_sum() -> LazyPipelineExpr

Sum all elements in the buffer.

Lazy form of :meth:Pipeline.reduce_sum on this expression's output.

relu

relu() -> LazyPipelineExpr

Apply ReLU activation (max(0, x)): negative values become zero.

Lazy form of :meth:Pipeline.relu on this expression's output.

reshape

reshape(shape: Sequence[IntOrExpr]) -> LazyPipelineExpr

Reshape array to new dimensions.

Lazy form of :meth:Pipeline.reshape on this expression's output.

resize

resize(
    *,
    height: IntOrExpr,
    width: IntOrExpr,
    filter: str | Expr = "lanczos3",
) -> LazyPipelineExpr

Resize image to specified dimensions.

Lazy form of :meth:Pipeline.resize on this expression's output.

resize_max

resize_max(
    max_size: IntOrExpr, *, filter: str | Expr = "lanczos3"
) -> LazyPipelineExpr

Resize image so the maximum dimension equals target, preserving aspect ratio (200x100 with max_size=50 gives 50x25).

Lazy form of :meth:Pipeline.resize_max on this expression's output.

resize_min

resize_min(
    min_size: IntOrExpr, *, filter: str | Expr = "lanczos3"
) -> LazyPipelineExpr

Resize image so the minimum dimension equals target, preserving aspect ratio (200x100 with min_size=50 gives 100x50).

Lazy form of :meth:Pipeline.resize_min on this expression's output.

resize_scale

resize_scale(
    *,
    scale: FloatOrExpr | None = None,
    scale_x: FloatOrExpr | None = None,
    scale_y: FloatOrExpr | None = None,
    filter: str | Expr = "lanczos3",
) -> LazyPipelineExpr

Resize image by scale factor.

Lazy form of :meth:Pipeline.resize_scale on this expression's output.

resize_to_height

resize_to_height(
    height: IntOrExpr, *, filter: str | Expr = "lanczos3"
) -> LazyPipelineExpr

Resize image to target height, preserving aspect ratio (width is computed at runtime).

Lazy form of :meth:Pipeline.resize_to_height on this expression's output.

resize_to_width

resize_to_width(
    width: IntOrExpr, *, filter: str | Expr = "lanczos3"
) -> LazyPipelineExpr

Resize image to target width, preserving aspect ratio (height is computed at runtime).

Lazy form of :meth:Pipeline.resize_to_width on this expression's output.

rotate

rotate(
    angle: FloatOrExpr,
    *,
    expand: bool = False,
    interpolation: str | Expr = "bilinear",
    border_value: FloatOrExpr = 0.0,
) -> LazyPipelineExpr

Rotate image by specified angle.

Lazy form of :meth:Pipeline.rotate on this expression's output.

rotate_and_scale

rotate_and_scale(
    *,
    angle: FloatOrExpr,
    center: Sequence[FloatOrExpr],
    output_size: Sequence[IntOrExpr],
    scale: FloatOrExpr = 1.0,
) -> LazyPipelineExpr

Combined rotation and scaling around a center point.

Lazy form of :meth:Pipeline.rotate_and_scale on this expression's output.

round

round() -> LazyPipelineExpr

Round to nearest, ties to even (matches Polars/numpy).

Lazy form of :meth:Pipeline.round on this expression's output.

scale

scale(
    factor: FloatOrExpr,
    out_dtype: str | None = None,
    preserve_dtype: bool = False,
) -> LazyPipelineExpr

Multiply all values by a factor.

Lazy form of :meth:Pipeline.scale on this expression's output.

scale_contour

scale_contour(
    *,
    sx: FloatOrExpr,
    sy: FloatOrExpr,
    origin: str | Expr = "centroid",
) -> LazyPipelineExpr

Scale the contour about origin.

Lazy form of :meth:Pipeline.scale_contour on this expression's output.

sharpen

sharpen(*, strength: FloatOrExpr = 1.0) -> LazyPipelineExpr

Sharpen using an unsharp-mask-style kernel.

Lazy form of :meth:Pipeline.sharpen on this expression's output.

shear

shear(
    *,
    sx: FloatOrExpr = 0.0,
    sy: FloatOrExpr = 0.0,
    output_size: tuple[IntOrExpr, IntOrExpr],
) -> LazyPipelineExpr

Apply a shear transformation.

Lazy form of :meth:Pipeline.shear on this expression's output.

sign

sign() -> LazyPipelineExpr

Sign: -1/0/+1 (0 for ±0, NaN for NaN).

Lazy form of :meth:Pipeline.sign on this expression's output.

simplify

simplify(tolerance: FloatOrExpr) -> LazyPipelineExpr

Simplify the contour using the Douglas-Peucker algorithm.

Lazy form of :meth:Pipeline.simplify on this expression's output.

smooth

smooth(*, iterations: IntOrExpr = 1) -> LazyPipelineExpr

Round off corners by Chaikin's corner cutting: each pass replaces every

Lazy form of :meth:Pipeline.smooth on this expression's output.

sobel

sobel(*, axis: str = 'x') -> LazyPipelineExpr

Sobel gradient operator.

Lazy form of :meth:Pipeline.sobel on this expression's output.

sqrt

sqrt() -> LazyPipelineExpr

Square root (sqrt(x); NaN for negative input).

Lazy form of :meth:Pipeline.sqrt on this expression's output.

square

square() -> LazyPipelineExpr

Square (x * x).

Lazy form of :meth:Pipeline.square on this expression's output.

squeeze

squeeze(axis: int) -> LazyPipelineExpr

Remove an axis of size 1: [H, W, 1] to [H, W] with axis=-1. The

Lazy form of :meth:Pipeline.squeeze on this expression's output.

stroke

stroke(
    *,
    width: FloatOrExpr = 1.0,
    cap: str | Expr = "round",
    join: str | Expr = "round",
) -> LazyPipelineExpr

The region the set's paths cover when stroked, as disjoint regions:

Lazy form of :meth:Pipeline.stroke on this expression's output.

subtract_constant

subtract_constant(value: FloatOrExpr) -> LazyPipelineExpr

Subtract a constant from every value (x - value).

Lazy form of :meth:Pipeline.subtract_constant on this expression's output.

threshold

threshold(value: FloatOrExpr) -> LazyPipelineExpr

Apply binary threshold: a U8 mask, 255 where the element exceeds value

Lazy form of :meth:Pipeline.threshold on this expression's output.

to_bgr

to_bgr() -> LazyPipelineExpr

Convert from RGB to BGR channel order.

Lazy form of :meth:Pipeline.to_bgr on this expression's output.

to_hsv

to_hsv() -> LazyPipelineExpr

Convert from RGB to HSV color space.

Lazy form of :meth:Pipeline.to_hsv on this expression's output.

to_lab

to_lab() -> LazyPipelineExpr

Convert from RGB to CIE LAB color space.

Lazy form of :meth:Pipeline.to_lab on this expression's output.

to_ycbcr

to_ycbcr() -> LazyPipelineExpr

Convert from RGB to YCbCr color space.

Lazy form of :meth:Pipeline.to_ycbcr on this expression's output.

translate

translate(
    *, dx: FloatOrExpr, dy: FloatOrExpr
) -> LazyPipelineExpr

Translate the contour by an offset.

Lazy form of :meth:Pipeline.translate on this expression's output.

transpose

transpose(axes: Sequence[int]) -> LazyPipelineExpr

Transpose dimensions.

Lazy form of :meth:Pipeline.transpose on this expression's output.

trunc

trunc() -> LazyPipelineExpr

Round toward zero (drop the fractional part).

Lazy form of :meth:Pipeline.trunc on this expression's output.

union_all

union_all() -> LazyPipelineExpr

The union of the set's regions, as disjoint regions: overlapping

Lazy form of :meth:Pipeline.union_all on this expression's output.

warp_affine

warp_affine(
    *,
    matrix: Sequence[FloatOrExpr],
    output_size: Sequence[IntOrExpr],
    interpolation: str | Expr = "bilinear",
    border_value: FloatOrExpr = 0.0,
) -> LazyPipelineExpr

Apply a 2x3 affine transformation matrix.

Lazy form of :meth:Pipeline.warp_affine on this expression's output.

add

add(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise addition with another array.

For u8/u16: saturating addition (clamps to the maximum, e.g. 255 for u8). For f32/f64: standard addition.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.add(b).sink("numpy")

bitwise_and

bitwise_and(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise bitwise AND: for binary masks (0/255), the intersection.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.bitwise_and(b).sink("numpy")

bitwise_or

bitwise_or(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise bitwise OR: for binary masks (0/255), the union.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.bitwise_or(b).sink("numpy")

bitwise_xor

bitwise_xor(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise bitwise XOR: for binary masks (0/255), the symmetric difference.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.bitwise_xor(b).sink("numpy")

blend

blend(other: LazyPipelineExpr) -> LazyPipelineExpr

Normalized blend (element-wise), for image blending/compositing.

For u8: (a/255) * (b/255) * 255. For u16: (a/65535) * (b/65535) * 65535. For f32/f64: standard multiplication.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.blend(b).sink("numpy")

difference

difference(other: LazyPipelineExpr) -> LazyPipelineExpr

Inside this set and not other: this contour set's regions with other's cut away.

Each side is read as the union of its set (a single contour is a set of one), and the result is disjoint regions — always a set, since combining shapes can split or merge them. An open contour (a line) on either side is refused, and a null on either side nulls the row. One definition for both surfaces: in a pipeline other is another contour-domain expression; .contour.difference takes a contour column and runs this op.

Domain: contour → contour

Parameters:

Name Type Description Default
other LazyPipelineExpr

The other contour set: a contour-domain expression (a contour column, through .contour).

required
Example
>>> a = pl.col("pred").cv.pipe(Pipeline().source("contour"))
>>> b = pl.col("truth").cv.pipe(Pipeline().source("contour"))
>>> result = a.difference(b).sink("native")
>>> same = pl.col("pred").contour.difference(pl.col("truth"))

divide

divide(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise true division, into a float.

The operands promote as NumPy's do and divide in float: f64 when that promotion is f64 or a 32/64-bit integer, else f32. a / b follows IEEE 754, as NumPy's true_divide: x / 0 is inf (-inf for negative x) and 0 / 0 is nan.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.divide(b).sink("numpy")

intersection

intersection(other: LazyPipelineExpr) -> LazyPipelineExpr

Inside both: where this contour set's regions overlap other's.

Each side is read as the union of its set (a single contour is a set of one), and the result is disjoint regions — always a set, since combining shapes can split or merge them. An open contour (a line) on either side is refused, and a null on either side nulls the row. One definition for both surfaces: in a pipeline other is another contour-domain expression; .contour.intersection takes a contour column and runs this op.

Domain: contour → contour

Parameters:

Name Type Description Default
other LazyPipelineExpr

The other contour set: a contour-domain expression (a contour column, through .contour).

required
Example
>>> a = pl.col("pred").cv.pipe(Pipeline().source("contour"))
>>> b = pl.col("truth").cv.pipe(Pipeline().source("contour"))
>>> result = a.intersection(b).sink("native")
>>> same = pl.col("pred").contour.intersection(pl.col("truth"))

maximum

maximum(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise maximum of two arrays, for compositing, clamping and non-linear image processing.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.maximum(b).sink("numpy")

minimum

minimum(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise minimum of two arrays, for compositing, clamping and non-linear image processing.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.minimum(b).sink("numpy")

multiply

multiply(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise multiplication.

For u8/u16: saturating multiplication (clamps to the maximum). For f32/f64: standard multiplication. For normalized image blending (values treated as [0, 1]), use blend instead.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.multiply(b).sink("numpy")

subtract

subtract(other: LazyPipelineExpr) -> LazyPipelineExpr

Element-wise subtraction.

For u8/u16: saturating subtraction (clamps to 0). For f32/f64: standard subtraction.

Domain: buffer → buffer, vector → vector

Parameters:

Name Type Description Default
other LazyPipelineExpr

The expression to combine with, element-wise.

required
Example
>>> a = pl.col("image1").cv.pipe(pipe1)
>>> b = pl.col("image2").cv.pipe(pipe2)
>>> result = a.subtract(b).sink("numpy")

symmetric_difference

symmetric_difference(
    other: LazyPipelineExpr,
) -> LazyPipelineExpr

Inside exactly one: where this contour set's regions and other's do not overlap.

Each side is read as the union of its set (a single contour is a set of one), and the result is disjoint regions — always a set, since combining shapes can split or merge them. An open contour (a line) on either side is refused, and a null on either side nulls the row. One definition for both surfaces: in a pipeline other is another contour-domain expression; .contour.symmetric_difference takes a contour column and runs this op.

Domain: contour → contour

Parameters:

Name Type Description Default
other LazyPipelineExpr

The other contour set: a contour-domain expression (a contour column, through .contour).

required
Example
>>> a = pl.col("pred").cv.pipe(Pipeline().source("contour"))
>>> b = pl.col("truth").cv.pipe(Pipeline().source("contour"))
>>> result = a.symmetric_difference(b).sink("native")
>>> same = pl.col("pred").contour.symmetric_difference(pl.col("truth"))

union

union(other: LazyPipelineExpr) -> LazyPipelineExpr

Inside either: the union of this contour set's regions and other's.

Each side is read as the union of its set (a single contour is a set of one), and the result is disjoint regions — always a set, since combining shapes can split or merge them. An open contour (a line) on either side is refused, and a null on either side nulls the row. One definition for both surfaces: in a pipeline other is another contour-domain expression; .contour.union takes a contour column and runs this op.

Domain: contour → contour

Parameters:

Name Type Description Default
other LazyPipelineExpr

The other contour set: a contour-domain expression (a contour column, through .contour).

required
Example
>>> a = pl.col("pred").cv.pipe(Pipeline().source("contour"))
>>> b = pl.col("truth").cv.pipe(Pipeline().source("contour"))
>>> result = a.union(b).sink("native")
>>> same = pl.col("pred").contour.union(pl.col("truth"))

__init__

__init__(
    column: Expr | None,
    pipeline: "Pipeline",
    node_id: str | None = None,
    upstream: list["LazyPipelineExpr"] | None = None,
    alias: str | None = None,
) -> None

Initialize a LazyPipelineExpr.

Parameters:

Name Type Description Default
column Expr | None

The Polars column expression this pipeline reads from.

required
pipeline 'Pipeline'

The Pipeline instance defining operations.

required
node_id str | None

Unique identifier for this node in the graph.

None
upstream list['LazyPipelineExpr'] | None

List of upstream LazyPipelineExpr dependencies.

None
alias str | None

Optional user-defined name for this node (for multi-output).

None

alias

alias(name: str) -> 'LazyPipelineExpr'

Name this checkpoint for multi-output extraction.

Example

base = pl.col("img").cv.pipe(pipe).alias("base") gray = base.pipe(Pipeline().grayscale()).alias("gray") expr = gray.sink({"base": "numpy", "gray": "png"})

pipe

pipe(pipeline: 'Pipeline') -> 'LazyPipelineExpr'

Chain a Pipeline onto this expression.

Parameters:

Name Type Description Default
pipeline 'Pipeline'

Operations to apply. If no source(), it continues from here.

required

sink

sink(
    format: str
    | dict[str, str | tuple[str, dict[str, Any]]] = ...,
    return_expr: Literal[True] = ...,
    opt_flags: OptFlags | bool | None = ...,
    **kwargs: Any,
) -> pl.Expr
sink(
    format: str
    | dict[str, str | tuple[str, dict[str, Any]]] = ...,
    *,
    return_expr: Literal[False],
    opt_flags: OptFlags | bool | None = ...,
    **kwargs: Any,
) -> PipelineGraph
sink(
    format: str
    | dict[
        str, str | tuple[str, dict[str, Any]]
    ] = "native",
    return_expr: bool = True,
    opt_flags: "OptFlags | bool | None" = None,
    **kwargs: Any,
) -> "pl.Expr | PipelineGraph"

Finalize the pipeline graph and return a Polars expression.

Parameters:

Name Type Description Default
format str | dict[str, str | tuple[str, dict[str, Any]]]

Output format string (e.g., "numpy", "png") or a dict mapping aliases to formats for multi-output. A dict value may be (format, {params}) to give that output its own sink parameters, e.g. {"x": ("array", {"shape": [224, 224, 3]}), "thumb": ("jpeg", {"quality": 85})}. "ndarray" is the "numpy" struct tagged with the polars_cv.ndarray extension type (:class:polars_cv.NdArrayType).

'native'
return_expr bool

If True (default), return a pl.Expr. If False, return the PipelineGraph.

True
opt_flags 'OptFlags | bool | None'

Which plan-time optimizations to apply. None (default) reads the POLARS_CV_OPTIMIZATIONS env var, falling back to all-on; True/False are all/none shorthands; an :class:polars_cv.OptFlags selects passes individually. Every pass is output-preserving, so this only changes the physical graph — see :mod:polars_cv._optimize.

None
kwargs Any

Parameters for the sink. quality for the jpeg sink (the other encoders take none); shape for the array sink; dtype="f16" for the numpy/torch/ndarray sink to downcast the output tensor to half precision at the encode boundary (halving the tensor bytes and H2D transfer). dtype only accepts half precision, as "f16" or "float16" — cast inside the pipeline for other dtypes. compact=True for the numpy/torch/ndarray sink makes each row's data exactly its elements, row-major, at offset 0, instead of the storage a view reads from (zero-copy, but written whole by Parquet/IPC); it copies only a row that is not already compact. A keyword that does not apply to the chosen format is rejected rather than ignored, as is one that is not a sink parameter at all. With a dict format these apply to every output; naming one both here and in an output's own params is refused.

{}

Returns:

Type Description
'pl.Expr | PipelineGraph'

A Polars expression (or PipelineGraph if return_expr=False).

apply_mask

apply_mask(
    mask: "LazyPipelineExpr", *, invert: bool | Expr = False
) -> "LazyPipelineExpr"

Weigh this image by a mask.

The mask's own dtype says its scale, whatever the image's: a u8 mask weighs each pixel by m / 255 (a rasterize or threshold mask: 255 keeps, 0 hides), a float mask by m in [0, 1]. The result keeps the image's dtype. A mask of any other dtype is refused; cast or scale it first. A single-channel mask spreads over the image's channels.

Parameters:

Name Type Description Default
mask 'LazyPipelineExpr'

LazyPipelineExpr producing the mask.

required
invert bool | Expr

If True, invert the mask (keep exterior, zero interior).

False

Returns:

Type Description
'LazyPipelineExpr'

New LazyPipelineExpr with the mask operation composed.

channel_merge

channel_merge(
    *others: "LazyPipelineExpr",
) -> "LazyPipelineExpr"

Join this buffer's channels with the operands', in order.

Each [H, W] operand brings one channel and each [H, W, C] operand its C: an RGB image and an [H, W] mask give RGBA, and single channels stack into a multi-channel image (the inverse of :meth:Pipeline.channel_select). Every operand has this buffer's height, width and dtype.

Parameters:

Name Type Description Default
others 'LazyPipelineExpr'

One or more operands, in channel order after this one.

()

Returns:

Type Description
'LazyPipelineExpr'

New LazyPipelineExpr producing the [H, W, total] image.

Example
>>> photo = pl.col("img").cv.pipe(Pipeline().source("image_bytes"))
>>> alpha = photo.pipe(Pipeline().grayscale())
>>> rgba = photo.channel_merge(alpha)
>>> sel = lambda i: photo.channel_select(i)
>>> bgr = sel(2).channel_merge(sel(1), sel(0))

apply_contour_mask

apply_contour_mask(
    contour: "LazyPipelineExpr",
    *,
    invert: bool | Expr = False,
) -> "LazyPipelineExpr"

Apply a contour as a mask to this image.

The contour is rasterized onto this image's canvas. This is a convenience for: mask = contour.rasterize(shape=img) img.apply_mask(mask)

Parameters:

Name Type Description Default
contour 'LazyPipelineExpr'

LazyPipelineExpr whose pipeline ends in contours (its ops all run), or in rasterize(), whose canvas is replaced by this image's while its fill_value/background are kept.

required
invert bool | Expr

If True, mask exterior instead of interior.

False

Raises:

Type Description
ValueError

If contour ends in neither contours nor rasterize().

Returns:

Type Description
'LazyPipelineExpr'

New LazyPipelineExpr with the contour mask applied.

merge_pipe

merge_pipe(
    *others: "LazyPipelineExpr",
) -> "LazyPipelineExpr"

Merge multiple pipeline branches into a single terminal node.

This creates a node that depends on self and all others, making them all reachable for multi-output sinking. The merged node outputs the same as self (the first/primary branch).

Use this when you have branching pipelines that share a backbone and want to sink multiple branches in a single expression.

Parameters:

Name Type Description Default
others 'LazyPipelineExpr'

Other LazyPipelineExpr nodes to include in the graph.

()

Returns:

Type Description
'LazyPipelineExpr'

New LazyPipelineExpr with all branches as upstream dependencies.

Example
>>> gray = pl.col("image").cv.pipe(gray_pipe).alias("gray")
>>> contours = gray.extract_contours().alias("contours")
>>> blurred = gray.blur(5).alias("blurred")
>>>
>>> # Merge branches for multi-output
>>> result = contours.merge_pipe(blurred)
>>> expr = result.sink({
...     "gray": "png",
...     "contours": "native",
...     "blurred": "numpy"
... })

Note: - Safe to merge nodes that are already upstream (deduplication handled) - Can merge pipelines from different source columns (multi-source graph) - The merged node's output is the same as self (first argument)

statistics

statistics(include: list[str] | None = None) -> pl.Expr

Compute multiple statistics from the buffer in a single pass.

Returns a Struct column with named fields for each statistic. By default includes: mean, std, min, max.

This is a convenience method that creates branching reduction pipelines and merges them into a single multi-output expression.

Parameters:

Name Type Description Default
include list[str] | None

List of statistics to compute. Valid options: - "mean": Arithmetic mean - "std": Standard deviation - "min": Minimum value - "max": Maximum value - "sum": Sum of all values If None, defaults to ["mean", "std", "min", "max"].

None

Returns:

Type Description
Expr

A Polars expression that returns a Struct column with the

Expr

requested statistics as fields.

Example
>>> # Get statistics for processed images
>>> pipe = Pipeline().source("image_bytes").grayscale()
>>> img = pl.col("image").cv.pipe(pipe)
>>> stats_expr = img.statistics()
>>> df.with_columns(stats=stats_expr)
>>> # Access: df["stats"].struct.field("mean")
>>>
>>> # Only compute specific stats
>>> stats_expr = img.statistics(include=["min", "max"])

statistics_lazy

statistics_lazy(
    include: list[str] | None = None,
) -> "LazyPipelineExpr"

Create a lazy pipeline for computing multiple statistics.

Unlike statistics() which returns a finalized pl.Expr, this method returns a LazyPipelineExpr that can be merged with other pipelines for multi-output composition.

When sunk, each statistic becomes a separate field in the output struct. The stat nodes are aliased with prefixed names: "stat_mean", "stat_std", etc.

Parameters:

Name Type Description Default
include list[str] | None

List of statistics to compute. Valid options: - "mean": Arithmetic mean - "std": Standard deviation - "min": Minimum value - "max": Maximum value - "sum": Sum of all values If None, defaults to ["mean", "std", "min", "max"].

None

Returns:

Type Description
'LazyPipelineExpr'

A LazyPipelineExpr representing the merged statistics pipelines.

'LazyPipelineExpr'

Can be composed with other pipelines using merge_pipe().

Example
>>> # Compose stats with other outputs
>>> pipe = Pipeline().source("image_bytes")
>>> img = pl.col("image").cv.pipe(pipe).alias("img")
>>> gray = img.pipe(Pipeline().grayscale()).alias("gray")
>>> stats = gray.statistics_lazy()  # Creates stat_mean, stat_std, etc.
>>>
>>> # Merge and sink together
>>> result = img.merge_pipe(gray, stats)
>>> expr = result.sink({
...     "img": "numpy",
...     "gray": "numpy",
...     "stat_mean": "native",
...     "stat_std": "native",
...     "stat_min": "native",
...     "stat_max": "native",
... })

__repr__

__repr__() -> str

Return string representation with guidance.

__str__

__str__() -> str

Return string representation.