Skip to content

API reference

All functions and constants below are available directly on the package, e.g. cv.rotateEx. The modules mirror OpenCV's modules (see Design principles).

core

Geometry

rotateEx

rotateEx(src: ndarray, angle: float, scale: float = 1.0, flags: int = cv2.INTER_LINEAR, borderMode: int = cv2.BORDER_CONSTANT, borderValue: float | Sequence[float] = 0) -> np.ndarray

Rotate an image around its center without cropping the corners.

cv.rotate only rotates by multiples of 90°, and cv.warpAffine with cv.getRotationMatrix2D keeps the input size, so the corners are cut off. Here the output canvas is enlarged so the whole rotated (and scaled) image fits.

Parameters:

Name Type Description Default
src ndarray

Image to rotate.

required
angle float

Rotation in degrees, counter-clockwise (as for cv.getRotationMatrix2D).

required
scale float

Isotropic scale factor applied with the rotation.

1.0
flags int

Interpolation, as for cv.warpAffine.

INTER_LINEAR
borderMode int

How to fill the corners uncovered by the rotation, as for cv.warpAffine.

BORDER_CONSTANT
borderValue float | Sequence[float]

Fill color for cv.BORDER_CONSTANT.

0

Returns:

Type Description
ndarray

The rotated image; its size is the bounding box of the rotated input.

Raises:

Type Description
ValueError

If src is empty, angle is not finite, or scale is not a positive finite number.

centerPoint

centerPoint(contour: ArrayLike) -> tuple[float, float]

Return the centroid (x, y) of a contour from its image moments.

The m10 / m00, m01 / m00 arithmetic after cv.moments. :func:contourStats returns the same point as center together with the other measurements (and falls back to the box center for zero-area contours).

Parameters:

Name Type Description Default
contour ArrayLike

Contour of shape (N, 1, 2) or (N, 2), as from cv.findContours.

required

Raises:

Type Description
ValueError

If the contour has no points, is not finite, or has zero area (the centroid is undefined).

isInside

isInside(p: Sequence[float], polygon: ArrayLike) -> bool

Return whether point p lies inside polygon (even-odd ray casting).

polygon may be an OpenCV contour of shape (N, 1, 2) or an array of shape (N, 2).

cartesianToPolar

cartesianToPolar(x: ArrayLike, y: ArrayLike, angleInDegrees: bool = False) -> tuple[Any, Any]

Convert Cartesian coordinates to polar coordinates.

Unlike cv.cartToPolar, this accepts scalars as well as arrays of any shape, returns the angle first ((theta, rho)), and the angle is in [-pi, pi] ([-180, 180] in degrees) instead of [0, 2*pi).

Parameters:

Name Type Description Default
x ArrayLike

x coordinate(s).

required
y ArrayLike

y coordinate(s).

required
angleInDegrees bool

Return the angle in degrees instead of radians (same name as in OpenCV).

False

Returns:

Type Description
tuple[Any, Any]

(theta, rho): the angle and the distance from the origin.

polarToCartesian

polarToCartesian(theta: ArrayLike, rho: ArrayLike, angleInDegrees: bool = False) -> tuple[Any, Any]

Convert polar coordinates (theta, rho) to Cartesian (x, y).

The inverse of :func:cartesianToPolar. Unlike cv.polarToCart, this accepts scalars as well as arrays, and takes the angle first.

Parameters:

Name Type Description Default
theta ArrayLike

Angle(s), in radians unless angleInDegrees is true.

required
rho ArrayLike

Distance(s) from the origin.

required
angleInDegrees bool

theta is in degrees (same name as in OpenCV).

False

Creating images

imcolor

imcolor(size: tuple[int, int], color: float | Sequence[float], channels: int = 3, dtype: DTypeLike = np.uint8) -> np.ndarray

Create an image of size filled with color (a BGR uint8 image by default).

Parameters:

Name Type Description Default
size tuple[int, int]

Image size as (width, height), like cv.resize.

required
color float | Sequence[float]

A scalar, or one value per channel (BGR, or BGRA for channels=4).

required
channels int

3 (BGR, default), 4 (BGRA) or 1 for a grayscale image of shape (height, width).

3
dtype DTypeLike

Pixel type.

uint8

Raises:

Type Description
ValueError

If size is not positive, channels is not 1, 3 or 4, or color is not finite, does not match the channel count, or is outside the range of dtype.

imcolorLike

imcolorLike(src: ndarray, color: float | Sequence[float], dtype: DTypeLike | None = None) -> np.ndarray

Create an image with the same shape (and, by default, dtype) as src filled with color.

Parameters:

Name Type Description Default
src ndarray

Image whose shape (and dtype) to copy.

required
color float | Sequence[float]

A scalar, or one value per channel of src.

required
dtype DTypeLike | None

Pixel type of the result; by default that of src.

None

Raises:

Type Description
ValueError

If color is not finite, does not match the channels of src, or is outside the range of the result dtype.

makeGradient

makeGradient(size: tuple[int, int], start: float | Sequence[float], end: float | Sequence[float], direction: GradientDirection = 'horizontal', channels: int = 3) -> np.ndarray

Create an 8-bit image filled with a linear gradient from start to end.

Parameters:

Name Type Description Default
size tuple[int, int]

Image size as (width, height), like cv.resize.

required
start float | Sequence[float]

Start value. A scalar, or one value per channel (BGR).

required
end float | Sequence[float]

End value. A scalar, or one value per channel (BGR).

required
direction GradientDirection

"horizontal" (left to right), "vertical" (top to bottom), or "raster" (through every pixel in reading order, row by row).

'horizontal'
channels int

3 for a BGR image (default) or 1 for a grayscale image of shape (height, width).

3

Returns:

Type Description
ndarray

A uint8 image of shape (height, width, 3), or (height, width) for channels=1.

Raises:

Type Description
ValueError

If size is not positive, channels is not 1 or 3, a value is outside [0, 255] or does not match the channel count, or direction is unknown.

Layout

padToMultiple

padToMultiple(src: ndarray, multiple: int, color: Color = 0) -> np.ndarray

Pad the right and bottom so that the width and height become multiples of multiple.

Typical for neural networks that need sizes divisible by 32. The original pixels stay at the top-left, so coordinates do not change; crop the result back with dst[:h, :w].

Parameters:

Name Type Description Default
src ndarray

Image to pad.

required
multiple int

The width and height of the result are multiples of this.

required
color Color

Padding color: a scalar, or one value per channel.

0

Raises:

Type Description
ValueError

If src is empty, multiple is not positive, or color is not finite or outside the range of the image dtype.

padToSize

padToSize(src: ndarray, size: tuple[int, int], color: Color = 0, *, center: bool = True) -> np.ndarray

Pad an image to exactly size without scaling it (use :func:letterbox to also scale).

Parameters:

Name Type Description Default
src ndarray

Image to pad.

required
size tuple[int, int]

Output size as (width, height); it must not be smaller than the image.

required
color Color

Padding color: a scalar, or one value per channel.

0
center bool

Center the image; otherwise it stays at the top-left.

True

Raises:

Type Description
ValueError

If src is empty, size is smaller than the image, or color is not finite or outside the range of the image dtype.

splitTiles

splitTiles(src: ndarray, tileSize: tuple[int, int], overlap: int = 0) -> list[tuple[np.ndarray, tuple[int, int]]]

Split a large image into tiles, e.g. to run a model with a fixed input size over a big image.

Every tile has exactly tileSize (unless the image itself is smaller): the last row and column of tiles are shifted inside the image instead of being cut off, so they overlap their neighbors a little more.

Parameters:

Name Type Description Default
src ndarray

Image to split.

required
tileSize tuple[int, int]

Tile size as (width, height).

required
overlap int

Pixels shared by neighboring tiles, to avoid artifacts at tile borders.

0

Returns:

Type Description
list[tuple[ndarray, tuple[int, int]]]

(tile, (x, y)) pairs in row-major order, where (x, y) is the tile's top-left corner in src.

list[tuple[ndarray, tuple[int, int]]]

Tiles are views of src; use :func:mergeTiles to put processed tiles back together.

Raises:

Type Description
ValueError

If src is empty, tileSize is not positive, or overlap is not smaller than the tile.

mergeTiles

mergeTiles(tiles: Sequence[tuple[ndarray, tuple[int, int]]], size: tuple[int, int]) -> np.ndarray

Assemble tiles from :func:splitTiles (possibly processed) into one image; overlaps are averaged.

Parameters:

Name Type Description Default
tiles Sequence[tuple[ndarray, tuple[int, int]]]

(tile, (x, y)) pairs. Tiles may have any channel count, as long as all are the same.

required
size tuple[int, int]

Output size as (width, height), normally the size of the original image.

required

Returns:

Type Description
ndarray

The assembled image, with the dtype of the tiles. Pixels covered by no tile are 0.

Raises:

Type Description
ValueError

If tiles is empty or size is not positive.

mapTiles

mapTiles(src: ndarray, tileSize: tuple[int, int], func: Callable[[ndarray], ndarray], overlap: int = 0, progress: Callable[[int, int], None] | None = None) -> np.ndarray

Run a function over an image tile by tile and merge the results (split, func each tile, merge).

The usual way to apply a model with a fixed input size, or a memory-hungry filter, to an image that is too large for it. func gets each tile (a view of src) and must return an image of the same width and height; it may change the channel count and dtype, so a BGR image can be mapped to a one-channel mask or a float heat map.

Parameters:

Name Type Description Default
src ndarray

Image to process.

required
tileSize tuple[int, int]

Tile size as (width, height).

required
func Callable[[ndarray], ndarray]

Called once per tile with the tile; returns the processed tile.

required
overlap int

Pixels shared by neighboring tiles; the overlaps are averaged when merging, which hides tile seams.

0
progress Callable[[int, int], None] | None

Optional callback progress(done, total) called after each tile.

None

Returns:

Type Description
ndarray

The processed image, the size of src, with the channels and dtype func returned.

Raises:

Type Description
ValueError

If src is empty, tileSize or overlap is invalid (see :func:splitTiles), or func returns a tile of a different size.

Regions

cropRect

cropRect(src: ndarray, rect: tuple[int, int, int, int], margin: int = 0, fill: float | Sequence[float] | None = None) -> np.ndarray

Crop rect from src safely, even when the box extends outside the image.

Plain slicing (src[y:y+h, x:x+w]) silently returns the wrong region for negative coordinates, which is common with boxes from detectors.

Parameters:

Name Type Description Default
src ndarray

Image to crop.

required
rect tuple[int, int, int, int]

The box as (x, y, width, height), e.g. from cv.boundingRect or a detector.

required
margin int

Grow the box by this many pixels on every side (negative values shrink it).

0
fill float | Sequence[float] | None

None (default) clips the box to the image, so the result may be smaller than rect. Otherwise the result has exactly the box size, and the parts outside the image are filled with this color.

None

Returns:

Type Description
ndarray

A new array (not a view of src).

Raises:

Type Description
ValueError

If src is empty, rect is not finite, the box (after margin) has no area, or the box lies entirely outside the image.

cropCenter

cropCenter(src: ndarray, size: tuple[int, int] | int, fill: float | Sequence[float] | None = None) -> np.ndarray

Crop size (width, height) from the middle of the image (the usual square crop for a classifier).

Parameters:

Name Type Description Default
src ndarray

Image to crop.

required
size tuple[int, int] | int

(width, height), or one number for a square.

required
fill float | Sequence[float] | None

None (default) clips the box to the image when it is larger than the image, so the result may be smaller than size. Otherwise the result has exactly size and the outside is filled with this color.

None

Returns:

Type Description
ndarray

A new array.

Raises:

Type Description
ValueError

If size is not positive or src is empty.

cropToContent

cropToContent(src: ndarray, background: float | Sequence[float] | None = None, tolerance: float = 0, margin: int = 0) -> np.ndarray

Crop away a uniform border, e.g. the white margin around a scan or the black bars around a video frame.

Parameters:

Name Type Description Default
src ndarray

Image to trim.

required
background float | Sequence[float] | None

Border color. By default the color of the top-left pixel.

None
tolerance float

Pixels whose every channel differs from background by at most this much count as border, which absorbs JPEG noise.

0
margin int

Keep this many pixels of border around the content (limited by the image size).

0

Returns:

Type Description
ndarray

A new array with the content. If the whole image is border, a copy of src is returned unchanged.

Raises:

Type Description
ValueError

If src is empty, tolerance or margin is negative, or background is not finite.

inRangeEx

inRangeEx(src: ndarray, lowerb: Sequence[float], upperb: Sequence[float]) -> np.ndarray

cv.inRange for HSV images where the hue range may wrap around (e.g. red: hue 170 to 10).

Hue is circular, so a range like red crosses the end of the scale. With cv.inRange, lowerb[0] > upperb[0] silently selects nothing; here it selects the hues >= lowerb[0] or <= upperb[0]. Otherwise this is exactly cv.inRange. Works with cv.COLOR_BGR2HSV (hue 0-179) and cv.COLOR_BGR2HSV_FULL (hue 0-255).

Parameters:

Name Type Description Default
src ndarray

3-channel HSV image.

required
lowerb Sequence[float]

Lower bound (h, s, v).

required
upperb Sequence[float]

Upper bound (h, s, v).

required

Returns:

Type Description
ndarray

Single-channel mask (0 or 255).

Raises:

Type Description
ValueError

If src does not have 3 channels or is empty, the bounds do not have 3 values, or a bound is not finite.

boxIoU

boxIoU(boxesA: ArrayLike, boxesB: ArrayLike) -> np.ndarray

Intersection over union of every box in boxesA with every box in boxesB.

The standard overlap measure for matching detections to ground truth or tracking boxes between frames. OpenCV only uses it inside cv.dnn.NMSBoxes.

Parameters:

Name Type Description Default
boxesA ArrayLike

One box (x, y, width, height) or an array of shape (N, 4).

required
boxesB ArrayLike

One box or an array of shape (M, 4).

required

Returns:

Type Description
ndarray

A float64 array of shape (N, M) with values from 0 (no overlap) to 1 (identical boxes);

ndarray

float(boxIoU(a, b)[0, 0]) for two single boxes.

Raises:

Type Description
ValueError

If the boxes do not have 4 values.

nms

nms(boxes: ArrayLike, scores: ArrayLike, iouThreshold: float = 0.5, scoreThreshold: float = 0.0, maxCount: int | None = None) -> np.ndarray

Non-maximum suppression: the indices of the boxes to keep, best score first.

cv.dnn.NMSBoxes does the same, but wants Python lists of a specific type, returns an empty tuple instead of an empty array when nothing survives, and has no size limit.

Parameters:

Name Type Description Default
boxes ArrayLike

Boxes (x, y, width, height), shape (N, 4).

required
scores ArrayLike

One score per box.

required
iouThreshold float

Boxes overlapping a kept box by more than this IoU are dropped.

0.5
scoreThreshold float

Boxes scoring below this are dropped first.

0.0
maxCount int | None

Keep at most this many boxes.

None

Returns:

Type Description
ndarray

An int64 array of indices into boxes, in descending score order (empty if none survive).

Raises:

Type Description
ValueError

If boxes and scores disagree in length, iouThreshold is outside [0, 1], scoreThreshold is not finite, or maxCount is negative.

xywhToXyxy

xywhToXyxy(boxes: ArrayLike) -> np.ndarray

Convert boxes from (x, y, width, height) to corners (x1, y1, x2, y2).

OpenCV (cv.boundingRect, cv.rectangle with a rect, cv.dnn.NMSBoxes) uses (x, y, w, h); most detector APIs and slicing code want corners. The input shape and dtype are kept.

Raises:

Type Description
ValueError

If the last dimension of boxes does not have 4 values.

xyxyToXywh

xyxyToXywh(boxes: ArrayLike) -> np.ndarray

Convert boxes from corners (x1, y1, x2, y2) to (x, y, width, height) (inverse of :func:xywhToXyxy).

Raises:

Type Description
ValueError

If the last dimension of boxes does not have 4 values.

clipBoxes

clipBoxes(boxes: ArrayLike, size: tuple[int, int]) -> np.ndarray

Clip boxes (x, y, width, height) to an image of size (width, height).

Boxes that lie completely outside become zero-sized at the border. Useful before :func:cropRect or :func:drawLabel on detections near the edge.

Returns:

Type Description
ndarray

A float64 array of shape (N, 4), or (4,) for a single input box.

Raises:

Type Description
ValueError

If size is smaller than 1x1, or the boxes do not have 4 finite values each.

scaleBoxes

scaleBoxes(boxes: ArrayLike, scale: float | tuple[float, float], offset: tuple[float, float] = (0, 0), *, inverse: bool = False) -> np.ndarray

Scale (and shift) boxes, e.g. to map detections on a resized or letterboxed image back to the original.

With scale and offset from :func:letterbox, scaleBoxes(boxes, scale, offset, inverse=True) returns the boxes in the coordinates of the original image. Without inverse, the boxes are mapped the other way: x * scale + offset.

Parameters:

Name Type Description Default
boxes ArrayLike

Boxes (x, y, width, height).

required
scale float | tuple[float, float]

One factor, or (sx, sy).

required
offset tuple[float, float]

(dx, dy) added after scaling (the padding of a letterbox).

(0, 0)
inverse bool

Undo the transform instead: (x - offset) / scale.

False

Returns:

Type Description
ndarray

A float64 array of shape (N, 4), or (4,) for a single input box.

Raises:

Type Description
ValueError

If a factor is not positive and finite.

expandBoxes

expandBoxes(boxes: ArrayLike, ratio: float = 0.0, margin: float = 0.0, size: tuple[int, int] | None = None) -> np.ndarray

Grow (or shrink) boxes around their center, e.g. to add context before cropping a face or an object.

Parameters:

Name Type Description Default
boxes ArrayLike

Boxes (x, y, width, height).

required
ratio float

Fraction of the width and height to add on each side (0.1 adds 10% left and right, 10% top and bottom). Negative values shrink.

0.0
margin float

Fixed number of pixels to add on each side, after ratio (as margin in :func:cropRect).

0.0
size tuple[int, int] | None

(width, height) of the image; when given, the result is clipped to it.

None

Returns:

Type Description
ndarray

A float64 array of shape (N, 4), or (4,) for a single input box. Widths and heights never go

ndarray

below 0.

Raises:

Type Description
ValueError

If ratio or margin is not finite, or the boxes do not have 4 finite values each.

Combining images

hconcatEx

hconcatEx(images: Sequence[ndarray], color: float | Sequence[float] = 0, gap: int = 0) -> np.ndarray

Place images side by side, like cv.hconcat but for images of different sizes and channels.

Shorter images are padded at the bottom with color. Grayscale and color images can be mixed: all images are converted to the largest channel count (gray to BGR, BGR to BGRA).

Parameters:

Name Type Description Default
images Sequence[ndarray]

Images with the same dtype.

required
color float | Sequence[float]

Color of the padding and the gaps: a scalar, or one value per channel (BGR, or BGRA).

0
gap int

Space in pixels between the images.

0

Raises:

Type Description
ValueError

If images is empty, the dtypes differ, an image has an unsupported channel count, or color does not match the channel count.

vconcatEx

vconcatEx(images: Sequence[ndarray], color: float | Sequence[float] = 0, gap: int = 0) -> np.ndarray

Stack images vertically, like cv.vconcat but for images of different sizes and channels.

Narrower images are padded on the right with color. See :func:hconcatEx for the details.

Raises:

Type Description
ValueError

If images is empty, the dtypes differ, an image has an unsupported channel count, or color does not match the channel count.

montage

montage(images: Sequence[ndarray], cols: int | None = None, gap: int = 0, color: float | Sequence[float] = 0, cellSize: tuple[int, int] | None = None) -> np.ndarray

Arrange images in a grid, e.g. to compare many results at once.

Parameters:

Name Type Description Default
images Sequence[ndarray]

Images with the same dtype; sizes and channel counts may differ (see :func:hconcatEx).

required
cols int | None

Number of columns. By default the grid is as square as possible.

None
gap int

Space in pixels between the cells.

0
color float | Sequence[float]

Color of the gaps and padding.

0
cellSize tuple[int, int] | None

If given, every image is fitted into (width, height) with :func:letterbox first, so all cells have the same size.

None

Raises:

Type Description
ValueError

If images is empty or cols is not positive (and see :func:hconcatEx).

overlayImage

overlayImage(src: ndarray, overlay: ndarray, org: tuple[int, int] = (0, 0), alpha: float = 1.0) -> np.ndarray

Draw overlay on top of src at org, using the overlay's alpha channel if it has one.

Typical use: putting a transparent PNG (read with cv.IMREAD_UNCHANGED) such as a logo onto a photo. Parts of overlay outside src are clipped, so org may also be negative.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image. It is not modified.

required
overlay ndarray

8-bit grayscale, BGR or BGRA image. Its alpha channel (if any) controls the blending per pixel.

required
org tuple[int, int]

Position of the overlay's top-left corner in src, as (x, y).

(0, 0)
alpha float

Overall opacity from 0 (invisible) to 1, multiplied with the overlay's alpha channel (the same name as in :func:overlayMask and cv.addWeighted).

1.0

Returns:

Type Description
ndarray

A new image with the same shape as src.

Raises:

Type Description
ValueError

If an image is not 8-bit, is empty or has an unsupported channel count, or alpha is outside [0, 1].

Pixel operations

gammaCorrection

gammaCorrection(src: ndarray, gamma: float = 1.0) -> np.ndarray

Apply gamma correction to an 8-bit image using a lookup table.

Each value v becomes 255 * (v / 255) ** (1 / gamma): gamma > 1 brightens the image, gamma < 1 darkens it, and gamma == 1 leaves it unchanged.

Parameters:

Name Type Description Default
src ndarray

8-bit image with any number of channels.

required
gamma float

Gamma value; 1 leaves the image unchanged.

1.0

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, or gamma is not a positive finite number.

boldEdges

boldEdges(src: ndarray) -> np.ndarray

Bold, high-contrast edge map for drawings and logos.

The 3x3 morphological gradient (cv.morphologyEx(src, cv.MORPH_GRADIENT, ...)) is sharpened and then contrast-stretched, so edges come out as thick white lines on black. cv.Canny gives thin, binary edges instead.

Parameters:

Name Type Description Default
src ndarray

8-bit image with 1 or 3 channels. Color images are processed per channel.

required

Returns:

Type Description
ndarray

An 8-bit image with the shape of src.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty.

Clustering

peakColors (cv2u's own method), kmeansColors, dominantColors and colorQuantize need nothing else. meanShiftColors, dbscanColors and clusterPoints require the cluster extra: pip install "python-opencv-utils[cluster]".

Clusters

Bases: NamedTuple

The result of :func:kmeansColors, :func:meanShiftColors, :func:peakColors and :func:dbscanColors.

maps instance-attribute

maps: ndarray

Label image of shape src.shape[:2] (int32): the cluster of every pixel, 0 .. len(centers) - 1 (-1 for the noise pixels of :func:dbscanColors).

centers instance-attribute

centers: ndarray

The color of every cluster as uint8, shape (k, channels) (BGR, or gray for grayscale input).

dominantColors

dominantColors(src: ndarray, k: int = 5, sampleSize: int = 20000, seed: int = 0) -> list[tuple[tuple[int, ...], float]]

Find the k most common colors of an image (a color palette), most common first.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale or BGR image.

required
k int

Number of colors to find.

5
sampleSize int

Number of pixels used to fit the colors (see :func:kmeansColors).

20000
seed int

Seed, for reproducible results.

0

Returns:

Type Description
list[tuple[tuple[int, ...], float]]

A list of (color, ratio) pairs sorted by ratio, where color is a BGR tuple (or a 1-tuple for

list[tuple[tuple[int, ...], float]]

grayscale) and ratio is the share of pixels, summing to 1. Colors that no pixel ends up with are omitted.

Raises:

Type Description
ValueError

As for :func:kmeansColors.

colorQuantize

colorQuantize(src: ndarray, k: int, sampleSize: int = 20000, seed: int = 0) -> np.ndarray

Reduce an image to k colors (posterize), using the colors found by :func:kmeansColors.

Raises:

Type Description
ValueError

As for :func:kmeansColors.

peakColors

peakColors(src: ndarray, bins: int = 32, sigma: float = 0.75, minShare: float = 0.01, minRegion: int = 0) -> Clusters

Cluster the pixel colors at the peaks of the color histogram, finding the number of colors by itself.

cv2u's own method (see the module documentation for the algorithm). Compared with the other color clusterings:

  • like :func:meanShiftColors, the number of colors is found automatically, but no extra is needed;
  • unlike :func:kmeansColors and :func:meanShiftColors, every pixel is used (no sampling) and the result is fully deterministic, while the run time stays linear in the image size.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR image.

required
bins int

Histogram cells per Lab axis. More bins separate similar colors; fewer bins merge them.

32
sigma float

Histogram smoothing, in cells. Larger values give fewer, broader colors.

0.75
minShare float

Peaks with less than this fraction of the pixels are merged into the nearest stronger color.

0.01
minRegion int

If positive, connected regions smaller than this many pixels take the label of the surrounding region. This removes speckles and gives cleaner segments, but also removes small details such as thin text.

0

Returns:

Type Description
Clusters

class:Clusters (maps, centers) as for :func:kmeansColors: maps holds labels 0 .. n-1,

Clusters

ordered from the most to the least common color, and centers the mean BGR color of each cluster.

Raises:

Type Description
ValueError

If src is not an 8-bit BGR image or is empty, or a parameter is out of range.

kmeansColors

kmeansColors(src: ndarray, k: int, sampleSize: int = 20000, seed: int = 0, maxIter: int = 30) -> Clusters

Cluster the pixel colors of an image into k groups with k-means (cv.kmeans).

Takes care of the cv.kmeans boilerplate (reshaping, float conversion, criteria), clusters in the Lab color space so that groups match perceived colors, and is deterministic: the result depends only on seed, without changing OpenCV's global random state. Large images are fitted on a random sample of pixels, then every pixel is assigned to the nearest center.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale or BGR image.

required
k int

Number of colors.

required
sampleSize int

Number of pixels used to fit the centers.

20000
seed int

Seed for the initial centers and the sampling.

0
maxIter int

Maximum number of k-means iterations.

30

Returns:

Type Description
Clusters

class:Clusters (maps, centers): maps has shape src.shape[:2] with labels 0 .. k-1;

Clusters

centers has shape (k, channels) and holds the colors (BGR, or gray) as uint8.

Raises:

Type Description
ValueError

If src is not an 8-bit grayscale or BGR image or is empty, k is not between 1 and the pixel count, sampleSize is below k, or maxIter is below 1.

meanShiftColors

meanShiftColors(src: ndarray, bandwidth: float | None = None, quantile: float = 0.2, sampleSize: int = 2000, seed: int = 0) -> Clusters

Cluster the pixel colors with mean shift, which finds the number of colors by itself.

The counterpart of :func:kmeansColors when you do not know k: same result format, clustering in the Lab color space, deterministic for a given seed. The centers are fitted on a sample of pixels, so large images are fast. Requires the cluster extra.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR image.

required
bandwidth float | None

Kernel size in Lab units; larger values merge more colors. By default it is estimated from the image with sklearn.cluster.estimate_bandwidth.

None
quantile float

Used to estimate bandwidth when it is not given; larger values give fewer colors.

0.2
sampleSize int

Number of pixels used to fit the centers.

2000
seed int

Seed for the sampling.

0

Returns:

Type Description
Clusters

class:Clusters (maps, centers) as for :func:kmeansColors; len(centers) is the number of

Clusters

colors found.

Raises:

Type Description
ImportError

If scikit-learn is not installed.

ValueError

If src is not an 8-bit BGR image or is empty, bandwidth is not positive, or quantile is outside (0, 1].

dbscanColors

dbscanColors(src: ndarray, eps: float, minSamples: int = 4) -> Clusters

Cluster the pixel colors of a BGR image with DBSCAN (in the Lab color space), noise included.

Requires the cluster extra: pip install "python-opencv-utils[cluster]". Unlike :func:kmeansColors, the number of colors is found by DBSCAN itself, and pixels that belong to no dense color group are reported as noise instead of being forced into a cluster.

Every pixel is a sample, so time and memory grow quickly with the image size. Downscale large images first (e.g. cv.resizeEx(src, width=200)) and upscale maps with cv.INTER_NEAREST if needed.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR image.

required
eps float

Maximum Lab color distance between two pixels in the same neighborhood.

required
minSamples int

Minimum number of pixels in a neighborhood for a core point.

4

Returns:

Type Description
Clusters

class:Clusters (maps, centers) as for :func:kmeansColors: maps holds the labels

Clusters

0 .. len(centers) - 1 and -1 for noise pixels; centers holds the mean BGR color of every

Clusters

cluster. Paint the result with :func:drawClusters.

Raises:

Type Description
ImportError

If scikit-learn is not installed.

ValueError

If src is not an 8-bit BGR image or is empty, eps is not positive, or minSamples is below 1.

drawClusters

drawClusters(src: ndarray, maps: ndarray) -> np.ndarray

Paint every cluster of maps with its mean color in src, as a new image.

For looking at the result of :func:dbscanColors, :func:meanShiftColors, :func:peakColors or :func:kmeansColors. Noise pixels (label -1) keep their original color. To posterize an image with k-means in one call, use :func:colorQuantize instead.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale or BGR image, the one that was clustered.

required
maps ndarray

Label image of shape src.shape[:2], as returned in :class:Clusters.

required

Returns:

Type Description
ndarray

A new image with the shape and dtype of src; src is not modified.

Raises:

Type Description
ValueError

If src is not an 8-bit grayscale or BGR image or is empty, or maps has another shape.

clusterPoints

clusterPoints(points: ArrayLike, eps: float, minSamples: int = 2) -> np.ndarray

Group nearby points with DBSCAN, e.g. keypoints, blob centers or detected text boxes.

Requires the cluster extra.

Parameters:

Name Type Description Default
points ArrayLike

Points as an array of shape (N, 2) (or (N, d)), or an OpenCV contour of shape (N, 1, 2).

required
eps float

Maximum distance between two points of the same group.

required
minSamples int

Minimum number of points that forms a group; 1 puts every point in some group.

2

Returns:

Type Description
ndarray

Labels of shape (N,) (int32): 0, 1, ... for the groups and -1 for noise (points in no

ndarray

group), as in :func:dbscanColors and scikit-learn.

Raises:

Type Description
ImportError

If scikit-learn is not installed.

ValueError

If points is empty or not finite, eps is not positive, or minSamples is below 1.

Point sets

rotatePoints

rotatePoints(points: ArrayLike, angle: float, center: tuple[float, float] = (0, 0), scale: float = 1.0) -> np.ndarray

Rotate points around center by angle degrees, with the convention of cv.getRotationMatrix2D.

Positive angles turn counter-clockwise on screen (image y points down), so points rotated with the same angle and center as cv.warpAffine(img, cv.getRotationMatrix2D(center, angle, scale), ...) land on the rotated image.

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2).

required
angle float

Rotation in degrees.

required
center tuple[float, float]

Center of rotation (x, y); the origin by default.

(0, 0)
scale float

Isotropic scale applied with the rotation.

1.0

Returns:

Type Description
ndarray

The rotated points as float64, in the shape of points.

Raises:

Type Description
ValueError

If a value is not finite or scale is not positive.

scalePoints

scalePoints(points: ArrayLike, scale: float | tuple[float, float], center: tuple[float, float] = (0, 0)) -> np.ndarray

Scale points about center, e.g. to map keypoints onto a resized image.

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2).

required
scale float | tuple[float, float]

One factor, or (sx, sy) for different factors per axis (new_w / old_w, new_h / old_h).

required
center tuple[float, float]

Fixed point (x, y); the origin by default.

(0, 0)

Returns:

Type Description
ndarray

The scaled points as float64, in the shape of points.

Raises:

Type Description
ValueError

If a value is not finite.

translatePoints

translatePoints(points: ArrayLike, dx: float, dy: float) -> np.ndarray

Shift points by (dx, dy), e.g. to move keypoints from a crop back into the full image.

Returns:

Type Description
ndarray

The shifted points as float64, in the shape of points.

Raises:

Type Description
ValueError

If a value is not finite.

flipPoints

flipPoints(points: ArrayLike, size: tuple[int, int], flipCode: int) -> np.ndarray

Flip points like cv.flip flips an image of size, so landmarks stay on the flipped image.

Pixel x maps to width - 1 - x (and y to height - 1 - y), the pixel-center convention of cv.flip. Note that a horizontal flip swaps left / right landmarks (e.g. the eyes) in meaning, which is up to the caller.

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2).

required
size tuple[int, int]

Image size as (width, height).

required
flipCode int

As for cv.flip: 0 vertical, positive horizontal, negative both.

required

Returns:

Type Description
ndarray

The flipped points as float64, in the shape of points.

Raises:

Type Description
ValueError

If size is not positive.

normalizePoints

normalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray

Divide pixel coordinates by the image size, giving [0, 1] coordinates independent of the resolution.

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2) in pixels.

required
size tuple[int, int]

Image size as (width, height).

required

Returns:

Type Description
ndarray

The normalized points as float64, in the shape of points. Points outside the image fall outside [0, 1].

Raises:

Type Description
ValueError

If size is not positive.

denormalizePoints

denormalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray

Multiply [0, 1] coordinates by the image size; the inverse of :func:normalizePoints.

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2) in [0, 1].

required
size tuple[int, int]

Image size as (width, height).

required

Returns:

Type Description
ndarray

The pixel coordinates as float64, in the shape of points.

Raises:

Type Description
ValueError

If size is not positive.

clipPoints

clipPoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray

Clamp points into an image of size: x to [0, width - 1] and y to [0, height - 1].

Parameters:

Name Type Description Default
points ArrayLike

One point, (N, 2) or (N, 1, 2).

required
size tuple[int, int]

Image size as (width, height).

required

Returns:

Type Description
ndarray

The clipped points as float64, in the shape of points.

Raises:

Type Description
ValueError

If size is not positive.

pointsBoundingBox

pointsBoundingBox(points: ArrayLike) -> tuple[int, int, int, int]

Integer bounding box (x, y, width, height) of points, like cv.boundingRect but for float input too.

The box starts at the floor of the minimum and ends at the ceiling of the maximum, so every point lies on a pixel inside it; for integer points this equals cv.boundingRect.

Raises:

Type Description
ValueError

If points is empty or not finite.

distancePoints

distancePoints(a: ArrayLike, b: ArrayLike) -> np.ndarray

Euclidean distance from every point in a to every point in b.

Parameters:

Name Type Description Default
a ArrayLike

One point, (N, 2) or (N, 1, 2).

required
b ArrayLike

One point, (M, 2) or (M, 1, 2).

required

Returns:

Type Description
ndarray

A float64 array of shape (N, M); float(distancePoints(p, q)[0, 0]) for two single points.

nearestPoints

nearestPoints(a: ArrayLike, b: ArrayLike) -> tuple[np.ndarray, np.ndarray]

For every point in a, the index of the closest point in b and the distance to it.

Simple matching of detections between frames or of landmarks to a template.

Parameters:

Name Type Description Default
a ArrayLike

One point, (N, 2) or (N, 1, 2).

required
b ArrayLike

(M, 2) or (M, 1, 2), with at least one point.

required

Returns:

Type Description
tuple[ndarray, ndarray]

(indices, distances): an int64 array and a float64 array, both of length N.

Raises:

Type Description
ValueError

If b is empty.

orderPoints

orderPoints(points: ArrayLike) -> np.ndarray

Order 4 corner points as top-left, top-right, bottom-right, bottom-left (clockwise on screen).

cv.approxPolyDP and cv.minAreaRect give the corners of a quadrilateral in an arbitrary starting order; cv.getPerspectiveTransform needs them matched to the output corners. This is the ordering :func:fourPointTransform uses.

Parameters:

Name Type Description Default
points ArrayLike

4 points as (4, 2) or a contour of shape (4, 1, 2).

required

Returns:

Type Description
ndarray

A float64 array of shape (4, 2).

Raises:

Type Description
ValueError

If there are not exactly 4 points.

polygonCentroid

polygonCentroid(points: ArrayLike) -> tuple[float, float]

Area centroid (x, y) of a polygon given by its vertices in order, like cv.moments on a contour.

For a polygon with no area (fewer than 3 points, or collinear ones) the mean of the points is returned instead of failing, so it also works for a line or a single point.

Raises:

Type Description
ValueError

If points is empty or not finite.

angleBetween

angleBetween(p1: ArrayLike, p2: ArrayLike, degrees: bool = True) -> float

Direction of the vector from p1 to p2, as cv.getRotationMatrix2D or :func:rotateEx expect it.

Zero points right; because image y points down, positive angles turn clockwise on screen, so rotateEx(img, angleBetween(p1, p2)) makes the p1-p2 line horizontal (e.g. the eye line for face alignment).

Parameters:

Name Type Description Default
p1 ArrayLike

Start point (x, y).

required
p2 ArrayLike

End point (x, y).

required
degrees bool

Return degrees ((-180, 180]) instead of radians.

True

Raises:

Type Description
ValueError

If a point is not one finite (x, y) pair.

lineIntersection

lineIntersection(line1: Line, line2: Line) -> tuple[float, float] | None

Intersection of two infinite lines, each given by two points ((x1, y1), (x2, y2)).

Extends the segments, so it also finds the corner where two edges from cv.HoughLinesP would meet.

Returns:

Type Description
tuple[float, float] | None

The point (x, y), or None if the lines are parallel (including coincident).

Raises:

Type Description
ValueError

If a line is not two finite points, or its two points coincide.

pointLineDistance

pointLineDistance(point: ArrayLike, line: Line, segment: bool = False) -> float

Distance from a point to an infinite line (or, with segment, to the segment between its two points).

Parameters:

Name Type Description Default
point ArrayLike

The point (x, y).

required
line Line

Two points ((x1, y1), (x2, y2)) on the line.

required
segment bool

Measure to the segment: beyond its ends, the distance to the nearer end point.

False

Raises:

Type Description
ValueError

If the point or line is not finite, or the line's two points coincide.

Annotation formats

maskToPolygons

maskToPolygons(mask: ndarray, epsilon: float = 0.0, minArea: float = 0) -> list[np.ndarray]

Outer contours of a binary mask as (N, 2) polygons, optionally simplified (COCO-style segmentation).

cv.findContours wants an 8-bit single-channel image, returns (N, 1, 2) arrays and keeps one-pixel specks that no annotation format can store. Here any mask works (nonzero is foreground), polygons with fewer than 3 points are dropped, and epsilon simplifies each polygon like :func:approxContour.

Parameters:

Name Type Description Default
mask ndarray

Binary mask; nonzero (or True) pixels are foreground (color masks count any nonzero channel).

required
epsilon float

Simplification tolerance as a fraction of each polygon's perimeter (0.01 = 1%); 0 keeps every contour point.

0.0
minArea float

Drop polygons whose cv.contourArea is smaller than this.

0

Returns:

Type Description
list[ndarray]

A list of int32 arrays of shape (N, 2), largest area first. The inverse is :func:polygonsToMask.

Raises:

Type Description
ValueError

If mask is not a 2-D array or an image, is empty, or epsilon/minArea is negative.

polygonsToMask

polygonsToMask(polygons: Sequence[ArrayLike] | ndarray, size: tuple[int, int], value: int = 255) -> np.ndarray

Rasterize polygons into a new uint8 mask of size (the inverse of :func:maskToPolygons).

cv.fillPoly needs a pre-allocated image and int32 (N, 1, 2) arrays; this takes point lists and float coordinates (rounded) and returns the mask.

Parameters:

Name Type Description Default
polygons Sequence[ArrayLike] | ndarray

One polygon (N, 2) or a sequence of polygons (an empty sequence gives an all-zero mask).

required
size tuple[int, int]

(width, height) of the mask.

required
value int

Value of the polygon pixels, 1 to 255.

255

Returns:

Type Description
ndarray

uint8 mask with values 0 and value.

Raises:

Type Description
ValueError

If size is not positive, value is outside [1, 255] or a polygon is empty / not 2-D.

boxesToPolygons

boxesToPolygons(boxes: ArrayLike) -> list[np.ndarray]

The four corners of each box (x, y, width, height) as a (4, 2) polygon (clockwise from top-left).

Lets boxes go through the polygon functions (:func:polygonsToMask, :func:polygonIoU, :func:flipPolygons) and into COCO segmentation fields.

Returns:

Type Description
list[ndarray]

A list with one float64 (4, 2) array per box.

Raises:

Type Description
ValueError

If the boxes do not have 4 finite values.

polygonsToBoxes

polygonsToBoxes(polygons: Sequence[ArrayLike] | ndarray) -> np.ndarray

Bounding box (x, y, width, height) of each polygon, in continuous coordinates.

cv.boundingRect works on one integer contour at a time and counts pixels (width = xmax - xmin + 1); this keeps float coordinates and the COCO/YOLO convention width = xmax - xmin.

Parameters:

Name Type Description Default
polygons Sequence[ArrayLike] | ndarray

One polygon (N, 2) or a sequence of polygons.

required

Returns:

Type Description
ndarray

A float64 array of shape (N, 4) ((0, 4) for no polygons).

Raises:

Type Description
ValueError

If a polygon is empty, not 2-D or not finite.

polygonArea

polygonArea(polygon: ArrayLike) -> float

Area of a simple polygon (shoelace formula), in continuous coordinates.

cv.contourArea rounds the points to integers first, which is wrong for normalized or sub-pixel polygons.

Parameters:

Name Type Description Default
polygon ArrayLike

(N, 2) points (or a point list); the polygon is closed implicitly.

required

Returns:

Type Description
float

The absolute area (0 for fewer than 3 points).

Raises:

Type Description
ValueError

If polygon is empty, not 2-D or not finite.

polygonIoU

polygonIoU(polygonA: ArrayLike, polygonB: ArrayLike, resolution: int = 1024) -> float

Intersection over union of two polygons, by rasterizing both over their common bounding box.

OpenCV has no polygon clipping (cv.intersectConvexConvex handles convex shapes only). Rasterization works for any polygons, including concave and self-overlapping ones. Precision: the shared bounding box is scaled so its longer side has resolution pixels and the polygons are drawn with 1/256 sub-pixel accuracy, so the error is about 1 / resolution of the box side, enough for matching and metrics.

Parameters:

Name Type Description Default
polygonA ArrayLike

(N, 2) points.

required
polygonB ArrayLike

(M, 2) points.

required
resolution int

Raster size of the longer side of the common bounding box, in pixels.

1024

Returns:

Type Description
float

A value from 0 (disjoint) to 1 (identical); 0 when either polygon has no area.

Raises:

Type Description
ValueError

If a polygon is empty, not 2-D or not finite, or resolution is less than 1.

maskIoU

maskIoU(maskA: ndarray, maskB: ndarray) -> float

Intersection over union of two binary masks of the same shape (the segmentation counterpart of :func:boxIoU).

Parameters:

Name Type Description Default
maskA ndarray

Binary mask; nonzero (or True) pixels are foreground.

required
maskB ndarray

Binary mask of the same height and width.

required

Returns:

Type Description
float

A value from 0 to 1; 0 when both masks are empty.

Raises:

Type Description
ValueError

If a mask is not a 2-D array or an image, is empty, or the shapes differ.

rleEncode

rleEncode(mask: ndarray) -> dict[str, Any]

Encode a binary mask as COCO uncompressed RLE: {"counts": [...], "size": [height, width]}.

The runs alternate background/foreground starting with background, in column-major (Fortran) order, exactly as pycocotools.mask.encode / frPyObjects read them. pycocotools.mask.frPyObjects(rle, h, w) turns the result into the compressed string form when a dataset needs it; this module stays pure NumPy.

Parameters:

Name Type Description Default
mask ndarray

Binary mask; nonzero (or True) pixels are foreground.

required

Returns:

Type Description
dict[str, Any]

A dict with "counts" (a list of int) and "size" ([height, width]).

Raises:

Type Description
ValueError

If mask is not a 2-D array or an image, or is empty.

rleDecode

rleDecode(rle: dict[str, Any]) -> np.ndarray

Decode COCO uncompressed RLE (see :func:rleEncode) into a uint8 mask with values 0 and 255.

Parameters:

Name Type Description Default
rle dict[str, Any]

{"counts": [...], "size": [height, width]} with integer counts (compressed string counts are not supported; decode those with pycocotools.mask.decode).

required

Raises:

Type Description
ValueError

If size is not positive, counts is not a list of non-negative integers, or the counts do not add up to height * width.

boxesToYolo

boxesToYolo(boxes: ArrayLike, size: tuple[int, int], classIds: ArrayLike | None = None) -> np.ndarray

Convert boxes (x, y, width, height) in pixels to YOLO rows: normalized cx cy w h, with the class first.

Parameters:

Name Type Description Default
boxes ArrayLike

Boxes of shape (N, 4) (or one box).

required
size tuple[int, int]

(width, height) of the image.

required
classIds ArrayLike | None

One class id per box; when given, the rows are class cx cy w h as in a YOLO label file.

None

Returns:

Type Description
ndarray

A float64 array of shape (N, 4), or (N, 5) with classIds. Values are not clipped to [0, 1].

Raises:

Type Description
ValueError

If size is not positive, the boxes are invalid, or classIds has the wrong length.

yoloToBoxes

yoloToBoxes(rows: ArrayLike, size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray | None]

Convert YOLO rows (class cx cy w h or cx cy w h, normalized) to pixel boxes (x, y, width, height).

Parameters:

Name Type Description Default
rows ArrayLike

Array of shape (N, 5) (class first) or (N, 4); extra columns (confidence) are ignored.

required
size tuple[int, int]

(width, height) of the image.

required

Returns:

Type Description
ndarray

(boxes, classIds): float64 boxes of shape (N, 4) and int64 ids of shape (N,), or None

ndarray | None

for classIds when the rows have no class column.

Raises:

Type Description
ValueError

If size is not positive or the rows do not have 4 or more values.

readYoloLabels

readYoloLabels(filename: str | PathLike[str], size: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]

Read a YOLO label file (class cx cy w h per line) into pixel boxes (x, y, width, height) and class ids.

Any path works, including non-ASCII ones; blank lines are skipped and a missing or empty file means "no objects", as YOLO training tools treat it.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path of the .txt label file.

required
size tuple[int, int]

(width, height) of the matching image.

required

Returns:

Type Description
tuple[ndarray, ndarray]

(boxes, classIds): float64 boxes of shape (N, 4) and int64 ids of shape (N,).

Raises:

Type Description
ValueError

If size is not positive, or a line does not have at least 5 numbers.

writeYoloLabels

writeYoloLabels(filename: str | PathLike[str], boxes: ArrayLike, classIds: ArrayLike, size: tuple[int, int], makeDirs: bool = False) -> None

Write pixel boxes (x, y, width, height) and class ids as a YOLO label file (class cx cy w h per line).

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path of the .txt file (any path, including non-ASCII); an empty box list writes an empty file.

required
boxes ArrayLike

Boxes of shape (N, 4).

required
classIds ArrayLike

One integer class id per box.

required
size tuple[int, int]

(width, height) of the matching image.

required
makeDirs bool

Create missing parent directories.

False

Raises:

Type Description
ValueError

If size is not positive, the boxes are invalid, or classIds has the wrong length.

OSError

If the file cannot be written.

labelMapToColor

labelMapToColor(labels: ndarray, palette: ArrayLike | None = None, background: int = 0) -> np.ndarray

Colorize a label map of class ids into a BGR image, for viewing or saving a segmentation.

Parameters:

Name Type Description Default
labels ndarray

2-D integer array of class ids (bool counts as 0/1).

required
palette ArrayLike | None

One BGR color per class id, indexed by id ((K, 3)); None uses distinctColors(labels.max() + 1), so the same ids always get the same colors.

None
background int

The id drawn black (set to -1 to color every id from the palette).

0

Returns:

Type Description
ndarray

uint8 BGR image with the shape of labels.

Raises:

Type Description
ValueError

If labels is not a 2-D integer array, is empty, has negative ids, or an id has no palette entry.

colorToLabelMap

colorToLabelMap(image: ndarray, palette: ArrayLike, background: int = 0) -> np.ndarray

Recover a label map from a colorized segmentation image (the inverse of :func:labelMapToColor).

Parameters:

Name Type Description Default
image ndarray

8-bit BGR (or BGRA) image whose colors come from palette.

required
palette ArrayLike

One BGR color per class id, indexed by id ((K, 3)).

required
background int

The id for pixels whose color is not in the palette.

0

Returns:

Type Description
ndarray

int32 array of class ids with the shape image.shape[:2].

Raises:

Type Description
ValueError

If image is not an 8-bit color image or is empty, or palette is not (K, 3).

instanceMasksToLabelMap

instanceMasksToLabelMap(masks: Sequence[ndarray]) -> np.ndarray

Stack binary instance masks into one label map: mask i gets id i + 1, later masks on top.

Parameters:

Name Type Description Default
masks Sequence[ndarray]

Binary masks of the same shape; nonzero (or True) pixels are foreground.

required

Returns:

Type Description
ndarray

int32 array of ids (0 = background) with the shape of the masks.

Raises:

Type Description
ValueError

If masks is empty, or a mask is not 2-D, is empty or has a different shape.

labelMapToMasks

labelMapToMasks(labels: ndarray, background: int = 0) -> list[np.ndarray]

Split a label map into one binary mask per id (the inverse of :func:instanceMasksToLabelMap).

Parameters:

Name Type Description Default
labels ndarray

2-D integer array of ids.

required
background int

The id that gets no mask.

0

Returns:

Type Description
list[ndarray]

A list of uint8 masks (0/255), one for each id from 1 to labels.max() except background, so

list[ndarray]

masks[i] is id i + 1 when background is 0 (unused ids give all-zero masks).

Raises:

Type Description
ValueError

If labels is not a 2-D integer array, is empty or has negative ids.

drawPolygons

drawPolygons(src: ndarray, polygons: Sequence[ArrayLike] | ndarray, color: Sequence[Color] | Color | None = None, thickness: int = 2, fill: bool = False, alpha: float = 1.0, labels: Sequence[str] | None = None, fontScale: float = 0.5, lineType: int = cv2.LINE_AA) -> np.ndarray

Draw polygons (outlines or filled, optionally translucent) with optional labels, in place.

cv.polylines/cv.fillPoly want int32 (N, 1, 2) arrays in a list, one color for all, and have no transparency; this takes any point lists and gives each polygon its own color by default.

Parameters:

Name Type Description Default
src ndarray

8-bit image to draw on.

required
polygons Sequence[ArrayLike] | ndarray

One polygon (N, 2) or a sequence of polygons (floats are rounded).

required
color Sequence[Color] | Color | None

One color for all polygons, one color per polygon, or None for :func:distinctColors.

None
thickness int

Outline thickness (ignored with fill).

2
fill bool

Fill the polygons instead of outlining them.

False
alpha float

Opacity of the drawing, from 0 to 1.

1.0
labels Sequence[str] | None

One text per polygon, drawn at its top-most point.

None
fontScale float

Hershey font size for the labels.

0.5
lineType int

As for cv.polylines.

LINE_AA

Returns:

Type Description
ndarray

src.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, alpha is outside [0, 1], thickness is not positive, or labels/color has a different length than polygons.

drawSegmentation

drawSegmentation(src: ndarray, labels: ndarray, alpha: float = 0.5, palette: ArrayLike | None = None, background: int = 0) -> np.ndarray

Overlay a label map (or a binary mask) on an image in class colors; returns a new BGR image.

:func:overlayMask tints one mask in one color; this colors every class of a segmentation at once, leaving background pixels untouched.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (converted to BGR). It is not modified.

required
labels ndarray

2-D integer label map with the shape src.shape[:2]. A bool array, or an array whose nonzero values are all 255, is treated as a binary mask (one class, id 1).

required
alpha float

Opacity of the colors, from 0 to 1.

0.5
palette ArrayLike | None

One BGR color per class id, as for :func:labelMapToColor.

None
background int

The id left uncolored.

0

Returns:

Type Description
ndarray

A new uint8 BGR image.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, the label shape does not match, or alpha is outside [0, 1].

flipBoxes

flipBoxes(boxes: ArrayLike, size: tuple[int, int], flipCode: int) -> np.ndarray

Flip boxes (x, y, width, height) with an image, with the flipCode of cv.flip.

cv.flip moves the pixels but not the annotations; this keeps the boxes aligned (continuous coordinates, so a box at x with width w lands at width - x - w).

Parameters:

Name Type Description Default
boxes ArrayLike

Boxes of shape (N, 4) (or one box).

required
size tuple[int, int]

(width, height) of the image.

required
flipCode int

0 (cv.FLIP_MODE_X) flips vertically, 1 (cv.FLIP_MODE_Y) horizontally, -1 both.

required

Returns:

Type Description
ndarray

A float64 array of shape (N, 4), or (4,) for a single input box.

Raises:

Type Description
ValueError

If size is not positive, the boxes are invalid, or flipCode is not 0, 1 or -1.

flipPolygons

flipPolygons(polygons: Sequence[ArrayLike], size: tuple[int, int], flipCode: int) -> list[np.ndarray]

Flip polygons with an image, with the flipCode of cv.flip.

Continuous coordinates like :func:flipBoxes (x becomes width - x); for pixel-center landmarks use :func:flipPoints, which maps x to width - 1 - x like cv.flip moves pixels.

Parameters:

Name Type Description Default
polygons Sequence[ArrayLike]

A list of (N, 2) polygons (or point lists / (N, 1, 2) contours).

required
size tuple[int, int]

(width, height) of the image.

required
flipCode int

0 flips vertically, 1 horizontally, -1 both.

required

Returns:

Type Description
list[ndarray]

A list of float64 (N, 2) arrays. The vertex order is kept (so the winding direction reverses).

Raises:

Type Description
ValueError

If size is not positive, a polygon is empty or not 2-D, or flipCode is not 0, 1 or -1.

imgcodecs

imreadEx

imreadEx(filename: str | PathLike[str], flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None

Read an image like cv.imread, but from any path, including non-ASCII paths on Windows.

cv.imread cannot open paths such as C:/사진/이미지.png on Windows. This reads the file with NumPy and decodes it with cv.imdecode.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to the image file.

required
flags int

cv.IMREAD_* flags, as for cv.imread.

IMREAD_COLOR

Returns:

Type Description
ndarray | None

The image, or None if the file does not exist, cannot be read or cannot be decoded (like cv.imread).

imwriteEx

imwriteEx(filename: str | PathLike[str], img: ndarray, params: Sequence[int] = (), makeDirs: bool = False) -> bool

Write an image like cv.imwrite, but to any path, including non-ASCII paths on Windows.

The format is chosen from the file extension, as in cv.imwrite.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to write to.

required
img ndarray

Image to save.

required
params Sequence[int]

Format-specific cv.IMWRITE_* parameter pairs, e.g. (cv.IMWRITE_JPEG_QUALITY, 90).

()
makeDirs bool

Create missing parent directories. cv.imwrite (and this function by default) just returns False when the directory does not exist.

False

Returns:

Type Description
bool

True on success, False if the image could not be encoded or the file could not be written.

Raises:

Type Description
ValueError

If filename has no file extension.

error

If no encoder exists for the extension (e.g. .xyz), like cv.imwrite.

listImages

listImages(path: str | PathLike[str], recursive: bool = False) -> list[Path]

List the image files in a folder, in natural order (img2.png before img10.png).

Files are recognized by the extensions OpenCV can read (.jpg, .png, .webp, .tif, ... in any letter case). Use with imreadEx to process a folder of images.

Parameters:

Name Type Description Default
path str | PathLike[str]

Folder to list.

required
recursive bool

Also list the images in subfolders.

False

Returns:

Type Description
list[Path]

The image paths.

Raises:

Type Description
NotADirectoryError

If path is not a folder.

imreadAll

imreadAll(filenames: Iterable[str | PathLike[str]], flags: int = cv2.IMREAD_COLOR, *, strict: bool = True) -> list[np.ndarray | None]

Read many images with :func:imreadEx, e.g. a whole folder from :func:listImages.

Parameters:

Name Type Description Default
filenames Iterable[str | PathLike[str]]

The paths to read.

required
flags int

cv.IMREAD_* flags, as for cv.imread.

IMREAD_COLOR
strict bool

Raise on the first file that cannot be read. With False, unreadable files give None in the result (as cv.imread would), so the result lines up with filenames.

True

Returns:

Type Description
list[ndarray | None]

The images, in the order of filenames.

Raises:

Type Description
OSError

If strict and a file does not exist or cannot be decoded; the message names the file.

imwriteAll

imwriteAll(filenames: Iterable[str | PathLike[str]], images: Iterable[ndarray], params: Sequence[int] = (), makeDirs: bool = False, *, strict: bool = True) -> list[bool]

Write many images with :func:imwriteEx, pairing each path with the image at the same position.

Parameters:

Name Type Description Default
filenames Iterable[str | PathLike[str]]

The paths to write to; the format comes from each extension.

required
images Iterable[ndarray]

The images, one per path.

required
params Sequence[int]

Format-specific cv.IMWRITE_* parameter pairs, used for every file.

()
makeDirs bool

Create missing parent directories.

False
strict bool

Raise on the first file that cannot be written. With False, failures give False in the result.

True

Returns:

Type Description
list[bool]

One True / False per file, in order.

Raises:

Type Description
ValueError

If there are more paths than images or more images than paths, or a path has no extension.

OSError

If strict and a file could not be encoded or written; the message names the file.

imreadUrl

imreadUrl(url: str, flags: int = cv2.IMREAD_COLOR, timeout: float | None = None, headers: Mapping[str, str] | None = None, maxBytes: int | None = None) -> np.ndarray | None

Download an image from url and decode it like cv.imread (which cannot read from a URL).

Parameters:

Name Type Description Default
url str

http(s):// or file:// URL of the image.

required
flags int

cv.IMREAD_* flags, as for cv.imread (cv.IMREAD_COLOR by default, like cv.imread; pass cv.IMREAD_UNCHANGED to keep an alpha channel).

IMREAD_COLOR
timeout float | None

Timeout in seconds for the request. None uses the global default.

None
headers Mapping[str, str] | None

Extra HTTP headers, e.g. {"Authorization": "Bearer ..."}. A User-Agent given here replaces the default one.

None
maxBytes int | None

Largest response accepted, in bytes. Larger downloads stop early with a ValueError instead of being held in memory. None accepts any size.

None

Returns:

Type Description
ndarray | None

The decoded image, or None if the data cannot be decoded (like cv.imread).

Raises:

Type Description
URLError

If the request fails (including HTTP errors).

ValueError

If maxBytes is below 1, or the response is larger than maxBytes.

toPillow

toPillow(src: ndarray) -> Image.Image

Convert an OpenCV image to a Pillow image, fixing the channel order (BGR to RGB, BGRA to RGBA).

Every single-channel dtype Pillow has a mode for is accepted, so masks, depth maps and float images round-trip through :func:fromPillow unchanged:

src Pillow mode
uint8 gray "L"
uint8 gray + alpha (2 ch.) "LA"
uint8 BGR / BGRA "RGB" / "RGBA"
uint16 gray "I;16"
int32 gray "I"
float32 gray "F"
bool gray "1"

Parameters:

Name Type Description Default
src ndarray

Image to convert. Color images must be 8-bit; Pillow has no 16-bit or float color modes.

required

Raises:

Type Description
ValueError

If the image is empty, or its dtype or channel count has no Pillow mode.

fromPillow

fromPillow(image: Image) -> np.ndarray

Convert a Pillow image to an OpenCV image: BGR, BGRA (with transparency) or grayscale.

Handles the cases where np.asarray(image) silently gives the wrong result: palette images ("P", which would give palette indices instead of colors), "CMYK" (4 channels that are not BGRA), "YCbCr", "LAB", "HSV", "LA", premultiplied-alpha ("RGBa", "La"), 1-bit and big-endian 16-bit images. Every Pillow mode is accepted.

Returns:

Type Description
ndarray

uint8 BGR for color images, BGRA for images with transparency (a palette with a transparent entry,

ndarray

"RGBA", "LA", "PA", "RGBa", "La"), a 2-D array for grayscale: uint8 for "L" and

ndarray

"1", uint16 for 16-bit ("I;16" in any byte order), int32 for "I", float32 for "F".

imencodeBase64

imencodeBase64(img: ndarray, ext: str = '.png', params: Sequence[int] = (), *, dataUri: bool = False) -> str

Encode an image as a base64 string, e.g. for JSON APIs or HTML <img src=...>.

Parameters:

Name Type Description Default
img ndarray

Image to encode.

required
ext str

Image format, as for cv.imencode (".png", ".jpg", ".webp", ...).

'.png'
params Sequence[int]

Format-specific cv.IMWRITE_* parameter pairs.

()
dataUri bool

Return a data URI ("data:image/png;base64,...") instead of the bare base64 text.

False

Raises:

Type Description
ValueError

If img is empty or cannot be encoded in this format.

imdecodeBase64

imdecodeBase64(data: str | bytes, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None

Decode a base64 string or a data URI ("data:image/png;base64,...") into an image.

Parameters:

Name Type Description Default
data str | bytes

Base64 text (str or bytes), with or without a data: prefix. Whitespace is ignored.

required
flags int

cv.IMREAD_* flags, as for cv.imdecode.

IMREAD_COLOR

Returns:

Type Description
ndarray | None

The image, or None if the bytes are not a decodable image (like cv.imdecode).

Raises:

Type Description
ValueError

If data is not valid base64.

Image file metadata

ImageInfo

Bases: NamedTuple

Header information of an image file, from :func:imageInfo.

width instance-attribute

width: int

Stored width in pixels (before the EXIF orientation is applied).

height instance-attribute

height: int

Stored height in pixels (before the EXIF orientation is applied).

channels instance-attribute

channels: int

Number of channels of the stored image (1 for grayscale and palette images, 3 for RGB, 4 for RGBA / CMYK).

mode instance-attribute

mode: str

Pillow mode, e.g. "RGB", "RGBA", "L", "P", "I;16".

format instance-attribute

format: str

File format, e.g. "JPEG", "PNG", "WEBP", "TIFF".

fileSize instance-attribute

fileSize: int

Size of the file in bytes.

exifOrientation instance-attribute

exifOrientation: int

EXIF orientation tag (1-8); 1 when the file has none.

imageInfo

imageInfo(filename: str | PathLike[str]) -> ImageInfo

Read the size, channels, format, file size and EXIF orientation of an image file without decoding it.

cv.imread has to decode the whole file to tell you its size; here Pillow parses only the header, so listing the dimensions of a folder of large photos is fast. Works with any path, including non-ASCII paths.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to the image file.

required

Returns:

Name Type Description
An ImageInfo

class:ImageInfo named tuple (width, height, channels, mode, format, fileSize, exifOrientation).

ImageInfo

width and height are as stored; for exifOrientation 5-8 the displayed image is height wide.

Raises:

Type Description
OSError

If the file does not exist or is not an image Pillow recognizes.

exifOrientation

exifOrientation(filename: str | PathLike[str]) -> int

Return the EXIF orientation tag (1-8) of an image file, or 1 when it has none.

Only the file header is read. Values: 1 upright, 2 mirrored, 3 rotated 180°, 4 flipped vertically, 5 transposed, 6 rotated 90° clockwise, 7 transversed, 8 rotated 90° counter-clockwise (the image must be rotated / flipped that way to display upright, see :func:imreadOriented).

Raises:

Type Description
OSError

If the file does not exist or is not an image Pillow recognizes.

imreadOriented

imreadOriented(filename: str | PathLike[str], flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None

Read an image and apply its EXIF orientation, whatever the flags and the file format.

OpenCV honors the orientation tag only in some cases: with cv.IMREAD_COLOR / cv.IMREAD_GRAYSCALE it rotates JPEG, PNG, WebP and TIFF files, but with cv.IMREAD_UNCHANGED (needed to keep the alpha channel or 16-bit depth) and with every cv.IMREAD_REDUCED_* flag the image comes out as stored, i.e. sideways for phone photos. This reads the tag with Pillow and applies the rotation / flip itself, so the result is upright for every flag; like :func:imreadEx it works with non-ASCII paths.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to the image file.

required
flags int

cv.IMREAD_* flags, as for cv.imread. cv.IMREAD_IGNORE_ORIENTATION is added internally so the orientation is never applied twice.

IMREAD_COLOR

Returns:

Type Description
ndarray | None

The upright image, or None if the file cannot be read or decoded (like cv.imread).

imreadResized

imreadResized(filename: str | PathLike[str], size: tuple[int, int] | None = None, scale: float | None = None, width: int | None = None, height: int | None = None, flags: int = cv2.IMREAD_COLOR, interpolation: int | None = None) -> np.ndarray | None

Read an image and resize it in one call, decoding JPEG files at reduced size when possible.

Give exactly one of size (exact (width, height)), scale (a factor), width or height (the other side keeps the aspect ratio, see :func:resizeEx). For scale 1/2, 1/4 or 1/8 with cv.IMREAD_COLOR / cv.IMREAD_GRAYSCALE the file is decoded with the matching cv.IMREAD_REDUCED_* flag, which for JPEG skips most of the decoding work (other formats are decoded in full and then shrunk). The EXIF orientation is applied as in :func:imreadOriented (OpenCV ignores it for reduced decoding).

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to the image file.

required
size tuple[int, int] | None

Target size as (width, height).

None
scale float | None

Scale factor, e.g. 0.5 for half size.

None
width int | None

Target width; the height follows the aspect ratio.

None
height int | None

Target height; the width follows the aspect ratio.

None
flags int

cv.IMREAD_* flags, as for cv.imread.

IMREAD_COLOR
interpolation int | None

cv.INTER_* flag, as for :func:resizeEx.

None

Returns:

Type Description
ndarray | None

The resized image, or None if the file cannot be read or decoded (like cv.imread).

Raises:

Type Description
ValueError

If not exactly one of size, scale, width and height is given, or it is not positive.

imencodeEx

imencodeEx(ext: str, img: ndarray, params: Sequence[int] = ()) -> bytes

Encode an image to bytes like cv.imencode, raising instead of returning (False, None).

cv.imencode returns an (ok, buffer) tuple and a NumPy array, so sending the result over HTTP or writing it to a stream takes an unpacking, a check and .tobytes() every time. Here encoding failures (unknown extension, unsupported dtype or channel count) raise a ValueError naming the format.

Parameters:

Name Type Description Default
ext str

File extension that selects the format, e.g. ".png", ".jpg", ".webp" ("png" works too).

required
img ndarray

Image to encode.

required
params Sequence[int]

Format-specific cv.IMWRITE_* parameter pairs, e.g. (cv.IMWRITE_JPEG_QUALITY, 90).

()

Returns:

Type Description
bytes

The encoded file content.

Raises:

Type Description
ValueError

If the image is empty or cannot be encoded in this format.

imdecodeEx

imdecodeEx(data: bytes | bytearray | memoryview | ndarray, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None

Decode an image from bytes (an HTTP body, a file object's read()) like cv.imdecode.

cv.imdecode only accepts a NumPy array, so np.frombuffer(data, np.uint8) is repeated before every call and fails on empty input. Any bytes-like object or uint8 array is accepted here.

Parameters:

Name Type Description Default
data bytes | bytearray | memoryview | ndarray

The encoded file content.

required
flags int

cv.IMREAD_* flags, as for cv.imdecode.

IMREAD_COLOR

Returns:

Type Description
ndarray | None

The image, or None if the data is empty or not a decodable image (like cv.imdecode).

convertImageFormat

convertImageFormat(src: str | PathLike[str], dst: str | PathLike[str], quality: int | None = None, background: float | Sequence[float] = (255, 255, 255), makeDirs: bool = False) -> bool

Convert an image file to another format, chosen from the extension of dst.

The file is read as stored (cv.IMREAD_UNCHANGED: alpha channel and 16-bit depth are kept) with the EXIF orientation applied, since the tag is not carried over to the new file. Transparent images are composited onto background with :func:flattenAlpha when the target format has no alpha (JPEG), where cv.imwrite would silently drop the alpha channel and expose the hidden pixels. 16-bit and float images are scaled to 8-bit (uint16 by 1 / 257, floats from [0, 1] or by their maximum when above 1) when the target format cannot store the depth (JPEG, WebP, AVIF, BMP, GIF ...), where cv.imwrite would saturate them to white; PNG / TIFF / JPEG 2000 / PNM / PFM keep 16-bit and EXR / HDR / PFM / TIFF keep floats.

Parameters:

Name Type Description Default
src str | PathLike[str]

Path of the image to convert.

required
dst str | PathLike[str]

Path to write to; the format comes from its extension.

required
quality int | None

JPEG / WebP / AVIF quality (0-100). Ignored for other formats.

None
background float | Sequence[float]

Background color for flattening transparency, white by default.

(255, 255, 255)
makeDirs bool

Create missing parent directories of dst.

False

Returns:

Type Description
bool

True on success, False if src cannot be read or dst cannot be written (like cv.imwrite).

Raises:

Type Description
ValueError

If dst has no file extension.

error

If no encoder exists for the extension of dst, like cv.imwrite.

imgproc

Color conversion

toGray

toGray(src: ndarray) -> np.ndarray

Convert a grayscale, BGR or BGRA image to single-channel grayscale.

cv.cvtColor(img, cv.COLOR_BGR2GRAY) raises an error when img is already grayscale, so code that accepts any image needs a channel check first. Grayscale input is returned as a copy.

Raises:

Type Description
ValueError

If src does not have 1, 3 or 4 channels, or is empty.

toBGR

toBGR(src: ndarray) -> np.ndarray

Convert a grayscale, BGR or BGRA image to 3-channel BGR (the alpha channel is dropped).

Raises:

Type Description
ValueError

If src does not have 1, 3 or 4 channels, or is empty.

toBGRA

toBGRA(src: ndarray, alpha: float | None = None) -> np.ndarray

Convert a grayscale, BGR or BGRA image to 4-channel BGRA.

Parameters:

Name Type Description Default
src ndarray

Image to convert.

required
alpha float | None

Alpha value for images without an alpha channel. By default fully opaque (255 for 8-bit images, 65535 for 16-bit, 1.0 for float). For BGRA input, the existing alpha is kept unless this is given.

None

Raises:

Type Description
ValueError

If src does not have 1, 3 or 4 channels or is empty, or alpha is not a finite number in the range of the image dtype.

flattenAlpha

flattenAlpha(src: ndarray, fill: float | Sequence[float] | ndarray = (255, 255, 255)) -> np.ndarray

Composite a transparent (BGRA) image onto a background and return 3-channel BGR.

cv.cvtColor(img, cv.COLOR_BGRA2BGR) just drops the alpha channel, so transparent areas show whatever color the hidden pixels happen to have (often black). Use this before saving as JPEG or passing to code that expects BGR.

Parameters:

Name Type Description Default
src ndarray

Image to flatten. Images without an alpha channel are converted with toBGR.

required
fill float | Sequence[float] | ndarray

Background color (white by default; a scalar or BGR), or a background image of the same height and width.

(255, 255, 255)

Returns:

Type Description
ndarray

A BGR image with the dtype of src.

Raises:

Type Description
ValueError

If src does not have 1, 3 or 4 channels or is empty, fill is not finite, or a background image has a different size.

hexToBGR

hexToBGR(hexColor: str) -> tuple[int, ...]

Convert a CSS-style hex color to an OpenCV BGR tuple, e.g. "#ff8800" to (0, 136, 255).

Accepts "#rrggbb", "#rgb" and, with alpha, "#rrggbbaa" / "#rgba" (giving (b, g, r, a)); the # is optional. Saves reversing the channel order by hand, which is easy to get wrong.

Raises:

Type Description
ValueError

If the text is not a hex color.

bgrToHex

bgrToHex(color: Sequence[float]) -> str

Convert an OpenCV BGR (or BGRA) color to a hex string, e.g. (0, 136, 255) to "#ff8800".

Raises:

Type Description
ValueError

If color does not have 3 or 4 values in [0, 255].

distinctColors

distinctColors(count: int, seed: int | None = None) -> list[tuple[int, int, int]]

count BGR colors that are easy to tell apart, for drawing classes, tracks or clusters.

The first 12 are a fixed palette (red, green, blue, yellow, magenta, cyan, ...); further colors step around the hue circle by the golden ratio, so the same count always gives the same colors and no two are equal.

Parameters:

Name Type Description Default
count int

How many colors.

required
seed int | None

Shuffle the colors with this random seed; None keeps the fixed order.

None

Raises:

Type Description
ValueError

If count is negative.

Color adjustment

adjustBrightnessContrast

adjustBrightnessContrast(src: ndarray, brightness: float = 0, contrast: float = 1.0) -> np.ndarray

Change brightness and contrast like the sliders of a photo editor.

Each value v becomes (v - 128) * contrast + 128 + brightness, so contrast pivots around mid-gray instead of black (cv.convertScaleAbs(src, alpha, beta) scales around 0 and takes the absolute value).

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (the alpha channel is kept).

required
brightness float

Added to every value, e.g. -50 to 50.

0
contrast float

1 keeps the contrast, > 1 increases it, < 1 reduces it, 0 gives flat gray.

1.0

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, contrast is negative, or a value is not finite.

adjustHSV

adjustHSV(src: ndarray, hue: float = 0, saturation: float = 1.0, value: float = 1.0) -> np.ndarray

Shift the hue and scale the saturation and brightness (value) of a BGR image.

Saves the HSV round trip and its pitfalls: OpenCV stores 8-bit hue as degrees / 2 (0 to 179), and hue must wrap around instead of being clipped.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR or BGRA image (the alpha channel is kept).

required
hue float

Hue rotation in degrees, e.g. 180 for complementary colors.

0
saturation float

Saturation factor; 0 gives grayscale, > 1 more vivid colors.

1.0
value float

Brightness factor.

1.0

Raises:

Type Description
ValueError

If src is not an 8-bit color image or is empty, a factor is negative, or a value is not finite.

autoContrast

autoContrast(src: ndarray, clip: float = 0.01, *, perChannel: bool = False) -> np.ndarray

Stretch the levels so the darkest pixels become black and the brightest white (like "Auto Levels").

cv.normalize(..., cv.NORM_MINMAX) uses the exact minimum and maximum, so a single noisy pixel prevents any stretch. Here a fraction clip of the pixels at each end is allowed to saturate.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (the alpha channel is kept).

required
clip float

Fraction of pixels clipped at each end, e.g. 0.01 for 1%.

0.01
perChannel bool

Stretch each channel separately. This also removes color casts, but can shift colors; by default all channels share one stretch, which keeps the colors.

False

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, or clip is outside [0, 0.5).

whiteBalance

whiteBalance(src: ndarray, method: str = 'whitePatch') -> np.ndarray

Remove a color cast, so that white and gray objects look neutral.

OpenCV's white balancing lives in the xphoto contrib module, which opencv-python does not include.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR or BGRA image (the alpha channel is kept).

required
method str

"whitePatch" (default) assumes that the brightest pixels (the top 0.5%, ignoring blown-out ones) are white. "grayWorld" assumes that the average color of the scene is gray; it also works without white objects, but shifts the colors of scenes dominated by one color (e.g. a green object on black).

'whitePatch'

Raises:

Type Description
ValueError

If src is not an 8-bit color image or is empty, or method is unknown.

matchHistograms

matchHistograms(src: ndarray, reference: ndarray) -> np.ndarray

Remap the tones of src so that its histogram matches the one of reference, channel by channel.

Useful to make photos from different cameras or lighting look alike before comparing them. OpenCV has no histogram specification; cv.equalizeHist only matches a flat histogram.

Parameters:

Name Type Description Default
src ndarray

8-bit image to adjust (grayscale, BGR or BGRA; the alpha channel is kept).

required
reference ndarray

8-bit image with the target look, of any size, with the same number of color channels.

required

Returns:

Type Description
ndarray

The adjusted image.

Raises:

Type Description
ValueError

If the images are not 8-bit, are empty, or their color channels differ.

colorTransfer

colorTransfer(src: ndarray, reference: ndarray) -> np.ndarray

Give src the color mood of reference (Reinhard et al. 2001 color transfer in Lab space).

The mean and spread of each Lab channel are matched, which carries over the overall tint, brightness and colorfulness while keeping the content. Gentler than matchHistograms, which matches the full distribution.

Parameters:

Name Type Description Default
src ndarray

8-bit BGR or BGRA image to recolor (the alpha channel is kept).

required
reference ndarray

8-bit BGR or BGRA image with the target colors, of any size.

required

Returns:

Type Description
ndarray

The recolored image.

Raises:

Type Description
ValueError

If an image is not 8-bit BGR or BGRA, or is empty.

Quality and comparison

sharpnessScore

sharpnessScore(src: ndarray) -> float

Variance of the Laplacian, the standard measure of focus: low values mean a blurry image.

Only comparable between images of the same scene and size. A common starting threshold for "blurry" is around 100 for 8-bit photos, but it depends on the content.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required

Raises:

Type Description
ValueError

If src is empty or has an unsupported channel count.

ssim

ssim(a: ndarray, b: ndarray, dataRange: float | None = None) -> float

Structural similarity (SSIM) of two images: 1 for identical images, lower for more different ones.

cv.PSNR exists, but SSIM, which follows perceived quality much better, is only in the quality contrib module. This implements the standard definition (Wang et al. 2004: Gaussian window with sigma 1.5, K1 = 0.01, K2 = 0.03); color images are averaged over the channels.

Parameters:

Name Type Description Default
a ndarray

First image.

required
b ndarray

Second image with the same shape and dtype.

required
dataRange float | None

Value range (255 for 8-bit). By default taken from the dtype; 1.0 for float images.

None

Raises:

Type Description
ValueError

If the shapes differ, the images are empty, or dataRange is not positive.

diffMask

diffMask(a: ndarray, b: ndarray, threshold: float = 25, minArea: float = 0) -> np.ndarray

Mask of the pixels that differ between two images, e.g. to spot changes between two frames or versions.

Parameters:

Name Type Description Default
a ndarray

First image.

required
b ndarray

Second image with the same shape.

required
threshold float

A pixel differs when any channel differs by more than this.

25
minArea float

Remove differing regions smaller than this many pixels (noise, compression artifacts).

0

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255, of shape a.shape[:2].

Raises:

Type Description
ValueError

If the shapes differ, the images are empty, or threshold or minArea is negative.

imageHash

imageHash(src: ndarray, hashSize: int = 8, method: str = 'difference') -> int

Perceptual hash of an image, for finding duplicates and near-duplicates.

Similar images (resized, recompressed, slightly edited) get hashes that differ in only a few bits; compare them with hashDistance. OpenCV's img_hash module is in contrib, which opencv-python does not include.

Parameters:

Name Type Description Default
src ndarray

Image to hash (grayscale, BGR or BGRA).

required
hashSize int

The hash has hashSize * hashSize bits (64 by default).

8
method str

"difference" (dHash: brightness gradients, the default), "average" (aHash: brighter than the mean) or "perceptual" (pHash: low DCT frequencies, the most robust to edits).

'difference'

Returns:

Type Description
int

The hash as a non-negative integer (e.g. format(h, "016x") for a 64-bit hex string).

Raises:

Type Description
ValueError

If src is empty or has an unsupported channel count, hashSize is below 2, or method is unknown.

hashDistance

hashDistance(a: int, b: int) -> int

Number of differing bits between two imageHash values (Hamming distance).

For 64-bit hashes, 0 means identical or nearly so, up to about 10 usually means the same picture, and unrelated images are around 32.

Raises:

Type Description
ValueError

If a hash is negative.

Masks and contours

findContoursEx

findContoursEx(image: ndarray, mode: int = cv2.RETR_EXTERNAL, method: int = cv2.CHAIN_APPROX_SIMPLE, minArea: float = 0.0, *, sort: bool = True) -> list[np.ndarray]

cv.findContours for any image, with the contours sorted by area and small ones filtered out.

cv.findContours only accepts single-channel 8-bit images and returns the contours in scan order. Here any image works (nonzero pixels are foreground, so pass a thresholded image or mask), and the result is a plain list, largest contour first. Use cv.findContours directly when you need the hierarchy.

Parameters:

Name Type Description Default
image ndarray

Mask or image; nonzero (or True) pixels are foreground (for color images, any nonzero channel).

required
mode int

Retrieval mode, as for cv.findContours (default cv.RETR_EXTERNAL: outer contours only).

RETR_EXTERNAL
method int

Approximation, as for cv.findContours.

CHAIN_APPROX_SIMPLE
minArea float

Drop contours whose cv.contourArea is smaller than this.

0.0
sort bool

Sort by area, largest first. If false, keep OpenCV's order.

True

Returns:

Type Description
list[ndarray]

A list of contours, each of shape (N, 1, 2), ready for cv.drawContours.

Raises:

Type Description
ValueError

If image is not a 2-D array or an image, is empty, or minArea is not a finite number.

fillHoles

fillHoles(mask: ndarray, maxHoleArea: int | None = None) -> np.ndarray

Fill the holes of the objects in a binary mask, i.e. background regions not connected to the image border.

Parameters:

Name Type Description Default
mask ndarray

Binary mask; nonzero (or True) pixels are foreground. Color images count any nonzero channel.

required
maxHoleArea int | None

If given, only holes up to this many pixels are filled.

None

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255.

Raises:

Type Description
ValueError

If mask is not a 2-D array or an image, is empty, or maxHoleArea is negative.

removeSmallObjects

removeSmallObjects(mask: ndarray, minArea: float, connectivity: int = 8) -> np.ndarray

Remove connected foreground regions smaller than minArea pixels from a binary mask.

Parameters:

Name Type Description Default
mask ndarray

Binary mask; nonzero (or True) pixels are foreground.

required
minArea float

Regions with fewer pixels are removed.

required
connectivity int

8 (diagonal neighbors connect) or 4.

8

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255.

Raises:

Type Description
ValueError

If connectivity is not 4 or 8, minArea is negative or not finite, or mask is not a 2-D array or an image, or is empty.

largestComponent

largestComponent(mask: ndarray, connectivity: int = 8) -> np.ndarray

Keep only the largest connected foreground region of a binary mask (e.g. the main object of a segmentation).

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255; all zeros if the mask is empty.

Raises:

Type Description
ValueError

If connectivity is not 4 or 8, or mask is not a 2-D array or an image, or is empty.

skeletonize

skeletonize(mask: ndarray) -> np.ndarray

Thin the shapes of a binary mask to 1-pixel-wide lines that keep their topology (Zhang-Suen thinning).

Useful for measuring line lengths, finding junctions or vectorizing drawings. OpenCV's thinning lives in the ximgproc contrib module, which opencv-python does not include.

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255.

Raises:

Type Description
ValueError

If mask is not a 2-D array or an image, or is empty.

cutout

cutout(src: ndarray, mask: ndarray, feather: float = 0) -> np.ndarray

Cut an object out of an image: a BGRA image whose alpha channel is the mask, ready to save as PNG.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image (an existing alpha channel is combined with the mask).

required
mask ndarray

2-D mask with the shape src.shape[:2]. bool and 0/255 masks give hard edges; other 8-bit values are used as partial transparency.

required
feather float

Soften the edge with a Gaussian blur of this sigma, in pixels.

0

Returns:

Type Description
ndarray

uint8 BGRA image.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, the mask shape does not match, or feather is negative.

maskBoundingRect

maskBoundingRect(mask: ndarray) -> tuple[int, int, int, int] | None

Bounding box (x, y, width, height) of the nonzero pixels of a mask, or None if it is empty.

Simpler than cv.boundingRect(cv.findNonZero(mask)), which fails on color masks and on an all-zero mask.

Raises:

Type Description
ValueError

If mask is not a 2-D array or an image, or has no pixels.

applyMask

applyMask(src: ndarray, mask: ndarray, fill: float | Sequence[float] = 0) -> np.ndarray

Keep the pixels where mask is nonzero and fill the rest with fill.

cv.bitwise_and(src, src, mask=mask) only gives a black background, wants an 8-bit single-channel mask, and fails on float images. This works for any dtype and channel count and any fill color.

Parameters:

Name Type Description Default
src ndarray

Image.

required
mask ndarray

2-D array (or image) of the shape src.shape[:2]; nonzero (or True) pixels are kept.

required
fill float | Sequence[float]

Value for the pixels outside the mask: a scalar, or one value per channel of src (as fill in :func:cropRect and :func:cropContour).

0

Returns:

Type Description
ndarray

A new array with the dtype and shape of src.

Raises:

Type Description
ValueError

If the mask shape does not match, src is empty, or fill is not finite.

binarize

binarize(src: ndarray, method: Method | float = 'otsu', *, invert: bool = False, blockSize: int = 31, C: float = 10, blur: int = 0) -> np.ndarray

Turn any image into a 0/255 mask: Otsu (default), adaptive, triangle, or a fixed threshold.

cv.threshold wants a grayscale 8-bit image and returns (value, image); the adaptive variant is a different function with its own flags. Here the input can be color, and the common choices are one argument.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image (8-bit, or any dtype for a fixed threshold).

required
method Method | float

"otsu" (automatic global threshold), "adaptive" (local mean, for uneven lighting such as photographed documents), "triangle" (for images with one dominant background peak), or a number to use as the fixed threshold.

'otsu'
invert bool

Foreground is dark instead of light (cv.THRESH_BINARY_INV), e.g. black text on white paper.

False
blockSize int

Neighborhood size for "adaptive", odd and at least 3.

31
C float

Constant subtracted from the local mean for "adaptive".

10
blur int

Gaussian blur kernel (odd) applied before thresholding; 0 to skip. A little blur (3 or 5) removes speckles from Otsu and adaptive results.

0

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255, of shape src.shape[:2].

Raises:

Type Description
ValueError

If src is empty or has an unsupported channel count, method is unknown or a non-finite number, a named method is used on a non-8-bit image, or blockSize/blur is not odd.

morphology

morphology(src: ndarray, op: Operation, ksize: int | tuple[int, int] = 3, shape: Literal['ellipse', 'rect', 'cross'] = 'ellipse', iterations: int = 1) -> np.ndarray

cv.morphologyEx with the kernel built for you: morphology(mask, "open", 5).

OpenCV needs cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5)) and the cv.MORPH_* constant for every call. Here the operation is a word and the kernel a size.

Parameters:

Name Type Description Default
src ndarray

Mask or image (any dtype and channel count that cv.morphologyEx accepts).

required
op Operation

"erode", "dilate", "open" (remove specks), "close" (fill small gaps), "gradient" (outline), "tophat" or "blackhat".

required
ksize int | tuple[int, int]

Kernel size, one number or (width, height).

3
shape Literal['ellipse', 'rect', 'cross']

Kernel shape: "ellipse" (default, direction-neutral), "rect" or "cross".

'ellipse'
iterations int

How many times to apply it.

1

Raises:

Type Description
ValueError

If src is empty, op or shape is unknown, ksize is not positive, or iterations is below 1.

contourStats

contourStats(contour: ndarray) -> ContourStats

Measure a contour once: area, perimeter, box, centroid, aspect ratio, extent, solidity, circularity, ...

OpenCV computes each of these with a different call (and solidity needs cv.convexHull first). This returns them all as a named tuple, so filtering shapes is one comparison per property.

Parameters:

Name Type Description Default
contour ndarray

Contour of shape (N, 1, 2) or (N, 2), as from cv.findContours.

required

Raises:

Type Description
ValueError

If the contour has no points.

ContourStats

Bases: NamedTuple

The usual shape measurements of a contour (see :func:contourStats).

area instance-attribute

area: float

cv.contourArea: pixels inside the contour.

perimeter instance-attribute

perimeter: float

cv.arcLength of the closed contour.

rect instance-attribute

rect: tuple[int, int, int, int]

Upright bounding box (x, y, w, h).

center instance-attribute

center: tuple[float, float]

Centroid (x, y) from the image moments (the box center if the area is 0).

aspectRatio instance-attribute

aspectRatio: float

w / h of the bounding box.

extent instance-attribute

extent: float

area / (w * h): how much of the bounding box the shape fills (1 for an upright rectangle).

solidity instance-attribute

solidity: float

area / hull area: 1 for convex shapes, lower for shapes with dents or holes.

circularity instance-attribute

circularity: float

4 * pi * area / perimeter ** 2: 1 for a circle, lower for elongated or ragged shapes.

equivalentDiameter instance-attribute

equivalentDiameter: float

Diameter of the circle with the same area.

orientation instance-attribute

orientation: float

Angle in degrees of the major axis from cv.fitEllipse (0 if there are fewer than 5 points).

sortContours

sortContours(contours: Sequence[ndarray], method: SortMethod = 'left-to-right') -> list[np.ndarray]

Sort contours by position or size.

Reading order ("left-to-right", "top-to-bottom") uses the bounding box; "area" and "perimeter" put the largest first. cv.findContours returns them in scan order, which is neither.

Parameters:

Name Type Description Default
contours Sequence[ndarray]

Contours as from cv.findContours or :func:findContoursEx.

required
method SortMethod

"left-to-right", "right-to-left", "top-to-bottom", "bottom-to-top", "area" or "perimeter".

'left-to-right'

Returns:

Type Description
list[ndarray]

A new list, in the requested order.

Raises:

Type Description
ValueError

If method is unknown.

filterContours

filterContours(contours: Sequence[ndarray], minArea: float = 0.0, maxArea: float = math.inf, minAspectRatio: float = 0.0, maxAspectRatio: float = math.inf, minSolidity: float = 0.0, minCircularity: float = 0.0, minExtent: float = 0.0, minPerimeter: float = 0.0) -> list[np.ndarray]

Keep the contours whose measurements fall within the given ranges.

Each limit defaults to "no limit", so filterContours(cnts, minArea=100, minCircularity=0.8) keeps the round shapes of at least 100 pixels. See :class:ContourStats for what the properties mean.

Returns:

Type Description
list[ndarray]

A new list, in the original order.

Raises:

Type Description
ValueError

If a limit is NaN or negative, or a minimum exceeds its maximum.

contoursToMask

contoursToMask(contours: ndarray | Sequence[ndarray], size: tuple[int, int], thickness: int = cv2.FILLED, lineType: int = cv2.LINE_8) -> np.ndarray

Draw contours into a new mask of size: filled (default) or as outlines.

The inverse of :func:findContoursEx. cv.drawContours needs an existing image, the -1 for "all", a color and cv.FILLED, and it rejects a bare (N, 2) array.

Parameters:

Name Type Description Default
contours ndarray | Sequence[ndarray]

One contour or a sequence of contours, each (N, 1, 2) or (N, 2).

required
size tuple[int, int]

(width, height) of the mask.

required
thickness int

cv.FILLED (default) fills the shapes; a positive value draws outlines that thick.

FILLED
lineType int

As for cv.drawContours.

LINE_8

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255.

Raises:

Type Description
ValueError

If size is not positive.

cropContour

cropContour(src: ndarray, contour: ndarray, margin: int = 0, fill: float | Sequence[float] | None = 0, *, transparent: bool = False) -> np.ndarray

Crop the bounding box of a contour, with the pixels outside the contour blanked out.

Parameters:

Name Type Description Default
src ndarray

Image to crop (any dtype, 1, 3 or 4 channels).

required
contour ndarray

Contour of shape (N, 1, 2) or (N, 2).

required
margin int

Extra pixels around the bounding box (clipped at the image border).

0
fill float | Sequence[float] | None

Value for the pixels outside the contour: a scalar or one value per channel (as fill in :func:cropRect and :func:applyMask). None keeps the original pixels (a plain bounding-box crop).

0
transparent bool

Return BGRA with the outside transparent instead of filled with fill (8-bit images only).

False

Returns:

Type Description
ndarray

The cropped image. Its size is the bounding box plus margins, clipped to the image.

Raises:

Type Description
ValueError

If src is empty, margin is negative, the contour has no points, is not finite or lies outside the image, fill is not finite, or transparent is used on a non-8-bit image.

approxContour

approxContour(contour: ndarray, epsilon: float = 0.02, closed: bool = True) -> np.ndarray

cv.approxPolyDP with the tolerance given as a fraction of the perimeter.

The usual way to find the corners of a document or a sign is approxPolyDP(c, 0.02 * arcLength(c, True)); the absolute tolerance OpenCV takes depends on the image size, the fraction does not.

Parameters:

Name Type Description Default
contour ndarray

Contour of shape (N, 1, 2).

required
epsilon float

Tolerance as a fraction of the perimeter, e.g. 0.02 (2%). Larger values give fewer corners.

0.02
closed bool

Whether the contour is closed (as for cv.arcLength and cv.approxPolyDP).

True

Returns:

Type Description
ndarray

The simplified contour, shape (M, 1, 2).

Raises:

Type Description
ValueError

If epsilon is negative or not finite, or the contour has no points or is not finite.

mergeContours

mergeContours(contours: Sequence[ndarray]) -> np.ndarray

Merge contours into one: the convex hull around all their points.

When a detection breaks into pieces (a letter and its dot, a logo split by a highlight), the hull of all the pieces is the usual single outline. For a tight, concave outline, draw the pieces with :func:contoursToMask, dilate, and run :func:findContoursEx again.

Returns:

Type Description
ndarray

A contour of shape (M, 1, 2).

Raises:

Type Description
ValueError

If there are no contours, or a contour has no points or is not finite.

drawContoursEx

drawContoursEx(img: ndarray, contours: Sequence[ndarray], colors: Sequence[Sequence[float]] | None = None, labels: bool | Sequence[str] = False, thickness: int = 2, fontScale: float = 0.5) -> np.ndarray

Draw every contour in its own color, optionally with an index or text label at its centroid.

For checking what a segmentation found. cv.drawContours draws them all in one color, so touching shapes cannot be told apart. Like cv.drawContours, this draws in place and returns img.

Parameters:

Name Type Description Default
img ndarray

8-bit grayscale, BGR or BGRA image to draw on. On a grayscale image the luminance of each color is used (convert with :func:toBGR first to see the colors).

required
contours Sequence[ndarray]

Contours as from :func:findContoursEx.

required
colors Sequence[Sequence[float]] | None

BGR colors, cycled through. By default :func:distinctColors.

None
labels bool | Sequence[str]

True writes the index of each contour at its centroid; a sequence gives the texts.

False
thickness int

Outline thickness, or cv.FILLED.

2
fontScale float

Hershey font size for the labels.

0.5

Returns:

Type Description
ndarray

img, with the contours drawn on it.

Raises:

Type Description
ValueError

If img is not 8-bit, is empty or has an unsupported channel count, a contour has no points or is not finite, fontScale is not positive, or labels or colors has a different length than contours.

boundingRects

boundingRects(contours: Sequence[ndarray]) -> np.ndarray

cv.boundingRect of every contour, as an (N, 4) int32 array of (x, y, w, h).

Ready for :func:boxIoU, for slicing, or for sorting with NumPy. Empty for no contours.

asContour

asContour(points: ArrayLike) -> np.ndarray

Turn any list of points into an OpenCV contour: an int32 array of shape (N, 1, 2).

cv.drawContours, cv.contourArea, cv.boundingRect and friends want exactly that layout and integer type, while points usually come as [(x, y), ...] or an (N, 2) float array.

Parameters:

Name Type Description Default
points ArrayLike

(N, 2), (N, 1, 2) or a sequence of (x, y) pairs. Floats are rounded.

required

Raises:

Type Description
ValueError

If the points are not 2-D, are not finite, or there are none.

Matching and detection

findTemplate

findTemplate(src: ndarray, templ: ndarray, threshold: float = 0.8, maxCount: int | None = None, method: int = cv2.TM_CCOEFF_NORMED) -> np.ndarray

Find where templ appears in src: the matches as boxes, not a score map.

cv.matchTemplate returns a map of scores; turning it into matches means thresholding, finding maxima with cv.minMaxLoc and suppressing the overlapping neighbors of each match. This does all of that.

Parameters:

Name Type Description Default
src ndarray

Image to search in.

required
templ ndarray

Template image, not larger than src. If one of the two is grayscale, both are compared in grayscale.

required
threshold float

Minimum score in [0, 1]; 1 is a perfect match.

0.8
maxCount int | None

Return at most this many matches.

None
method int

cv.TM_CCOEFF_NORMED (default), cv.TM_CCORR_NORMED or cv.TM_SQDIFF_NORMED. For TM_SQDIFF_NORMED the score is 1 - difference, so higher is always better.

TM_CCOEFF_NORMED

Returns:

Type Description
ndarray

A float64 array of shape (N, 5) with one row (x, y, width, height, score) per match, best first;

ndarray

empty (0, 5) when nothing is found. The boxes do not overlap by more than half the template in either

ndarray

direction. matches[:, :4] are the boxes for :func:drawBoxes or :func:nms.

Raises:

Type Description
ValueError

If an image is empty, method is not normalized, threshold is outside [0, 1], maxCount is negative, or templ is larger than src.

matchFeatures

matchFeatures(src: ndarray, reference: ndarray, method: Detector = 'ORB', maxFeatures: int = 2000, ratio: float = 0.75, mask: ndarray | None = None, referenceMask: ndarray | None = None) -> FeatureMatches

Find corresponding points between two images (detect, describe, match, Lowe's ratio test).

The usual twelve lines before cv.findHomography: create the detector, compute both descriptor sets, pick the right matcher norm (Hamming for binary descriptors, L2 for SIFT), knnMatch with k=2, keep the matches whose best distance is clearly below the second best, and unpack the keypoints to point arrays.

Parameters:

Name Type Description Default
src ndarray

First image (any channel count; converted to grayscale).

required
reference ndarray

Second image, the one src is matched to (as in :func:alignImages).

required
method Detector

"ORB" (default, fast, binary descriptors) or "SIFT" (slower, more robust to scale and lighting). Both ship with every OpenCV distribution from 4.4 on.

'ORB'
maxFeatures int

Keypoint limit for ORB and SIFT.

2000
ratio float

Lowe's ratio; lower keeps fewer but more reliable matches.

0.75
mask ndarray | None

Optional 8-bit mask of where to look for keypoints in src.

None
referenceMask ndarray | None

The same for reference.

None

Returns:

Name Type Description
A FeatureMatches

class:FeatureMatches. srcPoints and dstPoints are empty (0, 2) arrays if nothing

FeatureMatches

matches; pass them to cv.findHomography or cv.estimateAffinePartial2D for the transform.

Raises:

Type Description
ValueError

If an image is empty or has an unsupported channel count, method is unknown, ratio is not in (0, 1], or maxFeatures is not positive.

FeatureMatches

Bases: NamedTuple

The result of :func:matchFeatures.

srcPoints instance-attribute

srcPoints: ndarray

Matched keypoint locations in src, shape (N, 2) float32.

dstPoints instance-attribute

dstPoints: ndarray

The corresponding locations in reference, shape (N, 2) float32 (dst as in cv.findHomography).

srcKeypoints instance-attribute

srcKeypoints: list[KeyPoint]

All keypoints found in src (for cv.drawMatches).

dstKeypoints instance-attribute

dstKeypoints: list[KeyPoint]

All keypoints found in reference.

matches instance-attribute

matches: list[DMatch]

The matches that passed the ratio test (for cv.drawMatches), one per row of the point arrays.

alignImages

alignImages(src: ndarray, reference: ndarray, method: Detector = 'ORB', motion: Literal['homography', 'affine', 'similarity'] = 'homography', maxFeatures: int = 2000, ratio: float = 0.75, ransacThreshold: float = 5.0, minMatches: int = 10) -> tuple[np.ndarray, np.ndarray]

Warp src onto reference so that the same content lands on the same pixels.

For registering a scanned form to its template, stacking photos, or comparing before/after shots taken from slightly different positions. Combines :func:matchFeatures, cv.findHomography (or cv.estimateAffine2D / cv.estimateAffinePartial2D) with RANSAC and the warp.

Parameters:

Name Type Description Default
src ndarray

Image to align.

required
reference ndarray

Image to align to; the output has its size.

required
method Detector

Feature detector, as for :func:matchFeatures.

'ORB'
motion Literal['homography', 'affine', 'similarity']

"homography" (perspective, 8 degrees of freedom), "affine" (6) or "similarity" (rotation, scale and translation only; the most stable when the images are nearly aligned already).

'homography'
maxFeatures int

Keypoint limit.

2000
ratio float

Lowe's ratio for the matches.

0.75
ransacThreshold float

Reprojection error in pixels above which a match counts as an outlier.

5.0
minMatches int

Fail when fewer matches pass the ratio test.

10

Returns:

Type Description
ndarray

(aligned, M): the warped image (same dtype and channels as src, size of reference) and the

ndarray

transform, 3x3 for a homography or 2x3 otherwise, mapping src coordinates to reference.

Raises:

Type Description
ValueError

If an image is empty, ransacThreshold is not positive, minMatches is too small for motion, too few matches are found, or the transform cannot be estimated.

findLines

findLines(src: ndarray, minLength: float = 30, maxGap: float = 10, threshold: int = 50, rho: float = 1.0, theta: float = np.pi / 180, edges: ndarray | None = None) -> np.ndarray

Line segments in an image, as an (N, 4) array of (x1, y1, x2, y2), longest first.

cv.HoughLinesP needs an edge image first and returns an (N, 1, 4) array or None. Here any image works (edges come from :func:autoCanny unless edges is given) and the result is always an array.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image (16-bit and float images are stretched to 8 bits).

required
minLength float

Shortest segment to report, in pixels.

30
maxGap float

Largest gap bridged between collinear edge pixels.

10
threshold int

Accumulator votes a line needs (cv.HoughLinesP).

50
rho float

Distance resolution in pixels.

1.0
theta float

Angle resolution in radians.

pi / 180
edges ndarray | None

A binary edge image to use instead of running autoCanny.

None

Returns:

Type Description
ndarray

A float64 array of shape (N, 4); empty (0, 4) when nothing is found.

Raises:

Type Description
ValueError

If src is empty or a parameter is not positive.

findCircles

findCircles(src: ndarray, minRadius: int = 0, maxRadius: int = 0, minDist: float | None = None, sensitivity: float = 30, edgeThreshold: float = 100, blur: int = 5) -> np.ndarray

Circles in an image, as an (N, 3) array of (x, y, radius), strongest first.

cv.HoughCircles needs a blurred single-channel image, has parameters named dp, param1 and param2, and returns (1, N, 3) or None. Here any image works, the accumulator resolution (dp=1.5) suits clean filled or outlined circles, and the result is always an array.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
minRadius int

Smallest radius to look for (0: no limit).

0
maxRadius int

Largest radius (0: no limit).

0
minDist float | None

Minimum distance between circle centers; by default a quarter of the smaller image side.

None
sensitivity float

Accumulator threshold (param2): lower finds more circles, including false ones.

30
edgeThreshold float

Upper Canny threshold (param1).

100
blur int

Median blur kernel (odd) applied first; 0 to skip.

5

Returns:

Type Description
ndarray

A float64 array of shape (N, 3); empty (0, 3) when nothing is found.

Raises:

Type Description
ValueError

If src is empty, minRadius or maxRadius is negative, blur is even, or a threshold is not positive.

findBlobs

findBlobs(src: ndarray, minArea: float = 10, maxArea: float | None = None, *, dark: bool = True, minCircularity: float | None = None, minConvexity: float | None = None, minInertia: float | None = None, minThreshold: int = 10, maxThreshold: int = 220) -> np.ndarray

Blobs (round-ish spots) in an image, as an (N, 3) array of (x, y, diameter), largest first.

cv.SimpleBlobDetector needs a Params object with a dozen fields, each filter enabled separately, and returns KeyPoint objects. Here the common knobs are keyword arguments and the rest keep OpenCV's defaults.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
minArea float

Smallest blob, in pixels.

10
maxArea float | None

Largest blob; None for no limit.

None
dark bool

Look for dark blobs on a light background (default); False for light blobs.

True
minCircularity float | None

0 to 1; None disables the filter.

None
minConvexity float | None

0 to 1; None disables the filter.

None
minInertia float | None

0 (lines) to 1 (circles); None disables the filter.

None
minThreshold int

Lowest of the thresholds the detector scans.

10
maxThreshold int

Highest threshold scanned.

220

Returns:

Type Description
ndarray

A float64 array of shape (N, 3); empty (0, 3) when nothing is found.

Raises:

Type Description
ValueError

If src is empty or a limit is out of range.

Geometry and filters

resizeEx

resizeEx(src: ndarray, width: int | None = None, height: int | None = None, interpolation: int | None = None) -> np.ndarray

Resize an image, keeping the aspect ratio when only width or height is given.

cv.resize needs the full target size, so resizing "to 640 pixels wide" means computing the height yourself.

Parameters:

Name Type Description Default
src ndarray

Image to resize.

required
width int | None

Target width in pixels.

None
height int | None

Target height in pixels. If both are given, the image is resized to exactly (width, height).

None
interpolation int | None

cv.INTER_* flag. By default cv.INTER_AREA when shrinking and cv.INTER_LINEAR when enlarging, as recommended by OpenCV.

None

Returns:

Type Description
ndarray

The resized image.

Raises:

Type Description
ValueError

If src is empty, neither width nor height is given, or a size is not positive.

letterbox

letterbox(src: ndarray, size: tuple[int, int], color: float | Sequence[float] = 0, interpolation: int | None = None) -> Letterbox

Fit an image into size keeping its aspect ratio, and pad the rest with color.

Common as preprocessing for neural networks with a fixed input size.

Parameters:

Name Type Description Default
src ndarray

Image to fit.

required
size tuple[int, int]

Output size as (width, height), like cv.resize.

required
color float | Sequence[float]

Padding color (BGR for color images).

0
interpolation int | None

cv.INTER_* flag; chosen like in :func:resizeEx by default.

None

Returns:

Type Description
Letterbox

class:Letterbox (image, scale, (left, top)). A point (x, y) in src is at

Letterbox

(x * scale + left, y * scale + top) in image.

Raises:

Type Description
ValueError

If size is not positive, src is empty, or color is not finite.

Letterbox

Bases: NamedTuple

The result of :func:letterbox: the padded image and how to map coordinates back.

image instance-attribute

image: ndarray

The resized and padded image, of the requested size.

scale instance-attribute

scale: float

Factor the source was resized by.

offset instance-attribute

offset: tuple[int, int]

(left, top): where the resized source starts in image. A point (x, y) of the source is at (x * scale + left, y * scale + top); :func:scaleBoxes with inverse=True maps boxes back.

fourPointTransform

fourPointTransform(src: ndarray, pts: ArrayLike, size: tuple[int, int] | None = None, flags: int = cv2.INTER_LINEAR) -> np.ndarray

Warp the quadrilateral pts in src to an upright rectangle (e.g. a photographed document).

The four points may be given in any order. Without size, the output size follows the longest edges of the quadrilateral, so the content keeps its proportions.

Parameters:

Name Type Description Default
src ndarray

Image to warp.

required
pts ArrayLike

The 4 corners, as an array of shape (4, 2) or an OpenCV contour of shape (4, 1, 2), e.g. from cv.approxPolyDP.

required
size tuple[int, int] | None

Output size as (width, height).

None
flags int

Interpolation, as for cv.warpPerspective.

INTER_LINEAR

Returns:

Type Description
ndarray

The warped image.

Raises:

Type Description
ValueError

If src is empty, pts does not hold exactly 4 finite points, the points are degenerate, or size is not positive.

translate

translate(src: ndarray, dx: float, dy: float, borderMode: int = cv2.BORDER_CONSTANT, borderValue: float | Sequence[float] = 0) -> np.ndarray

Shift an image by (dx, dy) pixels, keeping its size (OpenCV has no function for this).

Parameters:

Name Type Description Default
src ndarray

Image to shift.

required
dx float

Shift to the right (negative: to the left). Fractions are interpolated.

required
dy float

Shift down (negative: up).

required
borderMode int

How to fill the uncovered area, as for cv.warpAffine (e.g. cv.BORDER_REPLICATE).

BORDER_CONSTANT
borderValue float | Sequence[float]

Fill color for cv.BORDER_CONSTANT.

0

Returns:

Type Description
ndarray

The shifted image, with the shape and dtype of src.

Raises:

Type Description
ValueError

If src is empty, or dx or dy is not finite.

transformPoints

transformPoints(points: ArrayLike, M: ArrayLike) -> np.ndarray

Apply a 2x3 affine or a 3x3 perspective matrix to points.

cv.transform and cv.perspectiveTransform need float arrays of shape (N, 1, 2) and a different function for each kind of matrix. This takes points in any common layout and either matrix, e.g. to map keypoints or box corners through the matrix used by cv.warpAffine or cv.warpPerspective.

Parameters:

Name Type Description Default
points ArrayLike

One point (x, y), an array of shape (N, 2) or a contour of shape (N, 1, 2).

required
M ArrayLike

A 2x3 affine matrix (cv.getRotationMatrix2D, cv.getAffineTransform) or a 3x3 perspective matrix (cv.getPerspectiveTransform, cv.findHomography).

required

Returns:

Type Description
ndarray

The transformed points as float64, in the same shape as points.

Raises:

Type Description
ValueError

If the points do not have 2 coordinates or M is neither 2x3 nor 3x3.

cropRotatedRect

cropRotatedRect(src: ndarray, rect: tuple[tuple[float, float], tuple[float, float], float], flags: int = cv2.INTER_LINEAR, borderMode: int = cv2.BORDER_CONSTANT, borderValue: float | Sequence[float] = 0) -> np.ndarray

Cut out a rotated rectangle as an upright image (e.g. a tilted label or license plate).

OpenCV describes rotated boxes as ((cx, cy), (width, height), angle) (cv.minAreaRect, cv.RotatedRect) but has no function to extract one.

Parameters:

Name Type Description Default
src ndarray

Image to crop from.

required
rect tuple[tuple[float, float], tuple[float, float], float]

The rotated box, as returned by cv.minAreaRect.

required
flags int

Interpolation, as for cv.warpAffine.

INTER_LINEAR
borderMode int

How to fill the parts of the box outside the image, as for cv.warpAffine (cv.BORDER_CONSTANT with borderValue by default, like cv.warpAffine).

BORDER_CONSTANT
borderValue float | Sequence[float]

Fill color for cv.BORDER_CONSTANT.

0

Returns:

Type Description
ndarray

An image of size (round(width), round(height)) whose x axis runs along the box's width side.

Raises:

Type Description
ValueError

If src is empty, rect is not finite, or the box is smaller than one pixel.

deskew

deskew(src: ndarray, maxAngle: float = 45.0, borderMode: int = cv2.BORDER_CONSTANT, borderValue: float | Sequence[float] | None = None) -> tuple[np.ndarray, float]

Straighten a scanned or photographed page whose text lines are tilted.

The angle is found from the text itself: the image is rotated until the ink is concentrated in as few rows as possible (a projection-profile search, first in 1° and then in 0.1° steps). Works for dark text on a light background and the other way around. The page is rotated with rotateEx, so no corner is cut off.

Parameters:

Name Type Description Default
src ndarray

Image of a page (grayscale, BGR or BGRA).

required
maxAngle float

Largest tilt to look for, in degrees.

45.0
borderMode int

How to fill the corners uncovered by the rotation, as for cv.warpAffine.

BORDER_CONSTANT
borderValue float | Sequence[float] | None

Fill color for cv.BORDER_CONSTANT. By default the median color of the image border, so the new corners match the paper.

None

Returns:

Type Description
ndarray

(dst, angle): the straightened image and the rotation applied to it, in degrees

float

(positive is counter-clockwise, as for cv.getRotationMatrix2D). angle is 0 for an empty page.

Raises:

Type Description
ValueError

If src is empty, or maxAngle is negative or not below 90.

autoCanny

autoCanny(src: ndarray, sigma: float = 0.33, apertureSize: int = 3, L2gradient: bool = False) -> np.ndarray

cv.Canny with the two thresholds chosen from the image itself.

The thresholds are (1 - sigma) * median and (1 + sigma) * median of the pixel values, a common heuristic that works well across lighting conditions without manual tuning.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image. Color images are converted to grayscale; 16-bit and float images are stretched to 8 bits first (cv.Canny accepts only 8-bit input).

required
sigma float

Width of the threshold band around the median; smaller values give fewer edges.

0.33
apertureSize int

Sobel aperture, as in cv.Canny.

3
L2gradient bool

Use the more accurate L2 gradient norm, as in cv.Canny.

False

Returns:

Type Description
ndarray

Single-channel edge map (0 or 255).

Raises:

Type Description
ValueError

If src is empty or has an unsupported channel count, or sigma is outside [0, 1].

equalizeHistEx

equalizeHistEx(src: ndarray, *, clahe: bool = False, clipLimit: float = 2.0, tileGridSize: tuple[int, int] = (8, 8)) -> np.ndarray

cv.equalizeHist for color images too, optionally with CLAHE (adaptive equalization).

cv.equalizeHist only accepts grayscale images. Equalizing B, G and R separately shifts the colors, so color images are equalized on the lightness channel of the Lab color space instead. The alpha channel of BGRA images is kept.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image.

required
clahe bool

Use cv.createCLAHE (local, contrast-limited) instead of global equalization.

False
clipLimit float

CLAHE contrast limit.

2.0
tileGridSize tuple[int, int]

CLAHE grid size, as (columns, rows).

(8, 8)

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, has an unsupported channel count, or clipLimit is not positive.

unsharpMask

unsharpMask(src: ndarray, sigma: float = 1.0, amount: float = 1.0, threshold: int = 0) -> np.ndarray

Sharpen with an unsharp mask: src + amount * (src - GaussianBlur(src, sigma)).

The standard sharpening filter of photo editors; OpenCV has no function for it.

Parameters:

Name Type Description Default
src ndarray

Image to sharpen (any number of channels).

required
sigma float

Gaussian blur radius in pixels; larger values sharpen coarser details.

1.0
amount float

Strength; 0 returns the image unchanged, 1 doubles the local contrast.

1.0
threshold int

Only sharpen where the difference to the blurred image is at least this large, which avoids amplifying noise in flat areas.

0

Raises:

Type Description
ValueError

If sigma is not positive, or amount or threshold is negative.

pixelate

pixelate(src: ndarray, blockSize: int = 16, rect: tuple[int, int, int, int] | None = None) -> np.ndarray

Mosaic the image, or only the box rect, e.g. to anonymize faces or license plates.

Each blockSize x blockSize block is replaced by its average color.

Parameters:

Name Type Description Default
src ndarray

Image to pixelate.

required
blockSize int

Size of the blocks in pixels.

16
rect tuple[int, int, int, int] | None

Box (x, y, width, height) to pixelate, e.g. from a detector; it may extend outside the image. By default the whole image.

None

Returns:

Type Description
ndarray

A new image; the area outside rect is unchanged.

Raises:

Type Description
ValueError

If src is empty or blockSize is not positive.

Drawing

drawLabel

drawLabel(img: ndarray, rect: tuple[int, int, int, int], text: str, color: Color, thickness: int = 2, fontScale: float = 0.5, textColor: Color | None = None, fontPath: str | PathLike[str] | None = None, fontSize: int = 16) -> np.ndarray

Draw a box with a filled label tag above it, like the output of an object detector.

Like cv.rectangle and the other OpenCV drawing functions, this draws in place and returns img. The tag moves inside the box when there is no room above it.

Parameters:

Name Type Description Default
img ndarray

8-bit grayscale, BGR or BGRA image to draw on.

required
rect tuple[int, int, int, int]

The box as (x, y, width, height), e.g. from cv.boundingRect.

required
text str

Label text. The built-in OpenCV font supports ASCII only; pass fontPath for any Unicode text (e.g. Korean).

required
color Color

Box and tag color (BGR).

required
thickness int

Box line thickness.

2
fontScale float

Size of the built-in OpenCV font.

0.5
textColor Color | None

Text color. By default black or white, whichever contrasts better with color.

None
fontPath str | PathLike[str] | None

TrueType/OpenType font for the label; then fontSize (pixels) is used instead of fontScale.

None
fontSize int

Font size in pixels when fontPath is given.

16

Returns:

Type Description
ndarray

img, with the box and label drawn on it.

Raises:

Type Description
ValueError

If img is not 8-bit, is empty or has an unsupported channel count, fontScale is not positive, or color is not a scalar or BGR color.

overlayMask

overlayMask(src: ndarray, mask: ndarray, color: Color = (0, 0, 255), alpha: float = 0.5) -> np.ndarray

Tint the pixels selected by mask with color, e.g. to visualize a segmentation.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image. It is not modified.

required
mask ndarray

2-D array with the shape src.shape[:2]; nonzero (or True) pixels are tinted.

required
color Color

Tint color (BGR). For grayscale images, its luminance is used.

(0, 0, 255)
alpha float

Opacity of the tint, from 0 to 1.

0.5

Returns:

Type Description
ndarray

A new image with the same shape as src.

Raises:

Type Description
ValueError

If src is not 8-bit, is empty or has an unsupported channel count, the mask shape does not match, or alpha is outside [0, 1].

drawBoxes

drawBoxes(img: ndarray, boxes: Sequence[Sequence[float]] | ndarray, labels: Sequence[str] | None = None, colors: Sequence[Color] | Color | None = None, thickness: int = 2, fontScale: float = 0.5, fontPath: str | PathLike[str] | None = None, fontSize: int = 16) -> np.ndarray

Draw many boxes (x, y, width, height) at once, each with an optional label tag, in place.

The loop around :func:drawLabel that every detection demo writes, with one color per box from a fixed palette by default.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
boxes Sequence[Sequence[float]] | ndarray

Boxes as (N, 4); floats are rounded.

required
labels Sequence[str] | None

One text per box, or None for plain boxes.

None
colors Sequence[Color] | Color | None

One color per box, one color for all, or None for :func:distinctColors.

None
thickness int

Line thickness.

2
fontScale float

Hershey font size for the labels.

0.5
fontPath str | PathLike[str] | None

TrueType font for Unicode labels (see :func:drawLabel).

None
fontSize int

Font size in pixels for fontPath.

16

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty, or labels or colors has a different length than boxes.

drawPoints

drawPoints(img: ndarray, points: Sequence[Sequence[float]] | ndarray, color: Color = (0, 0, 255), radius: int = 3, thickness: int = cv2.FILLED, labels: bool | Sequence[str] = False, fontScale: float = 0.5) -> np.ndarray

Draw points (keypoints, corners, landmarks) as circles, optionally numbered, in place.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
points Sequence[Sequence[float]] | ndarray

(N, 2) coordinates, or an (N, 1, 2) contour; floats are rounded.

required
color Color

Circle color.

(0, 0, 255)
radius int

Circle radius in pixels.

3
thickness int

cv.FILLED (default) or an outline thickness.

FILLED
labels bool | Sequence[str]

True writes the index next to each point; a sequence gives the texts.

False
fontScale float

Hershey font size for the labels.

0.5

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty, the points are not 2-D, radius is negative, or labels has a different length.

drawGrid

drawGrid(img: ndarray, step: int | tuple[int, int], color: Color = (0, 255, 0), thickness: int = 1, offset: tuple[int, int] = (0, 0)) -> np.ndarray

Draw a grid of lines every step pixels, in place (for tile layouts, calibration or alignment checks).

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
step int | tuple[int, int]

Cell size, one number or (width, height).

required
color Color

Line color.

(0, 255, 0)
thickness int

Line thickness.

1
offset tuple[int, int]

(x, y) of the first vertical and horizontal line.

(0, 0)

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty or step is not positive.

drawDashedLine

drawDashedLine(img: ndarray, pt1: tuple[int, int], pt2: tuple[int, int], color: Color, thickness: int = 1, dashLength: int = 10, gapLength: int | None = None, lineType: int = cv2.LINE_8) -> np.ndarray

Draw a dashed line, in place like cv.line (which only draws solid lines).

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
pt1 tuple[int, int]

Start point (x, y).

required
pt2 tuple[int, int]

End point (x, y).

required
color Color

Line color.

required
thickness int

Line thickness.

1
dashLength int

Length of each dash in pixels.

10
gapLength int | None

Length of each gap; by default equal to dashLength.

None
lineType int

As for cv.line.

LINE_8

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty, or dashLength or gapLength is not positive.

drawDashedRectangle

drawDashedRectangle(img: ndarray, rect: tuple[int, int, int, int], color: Color, thickness: int = 1, dashLength: int = 10, gapLength: int | None = None) -> np.ndarray

Draw a dashed rectangle (x, y, width, height), in place like cv.rectangle.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
rect tuple[int, int, int, int]

The box as (x, y, width, height).

required
color Color

Line color.

required
thickness int

Line thickness.

1
dashLength int

Length of each dash in pixels.

10
gapLength int | None

Length of each gap; by default equal to dashLength.

None

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty, or dashLength or gapLength is not positive.

drawRoundedRectangle

drawRoundedRectangle(img: ndarray, rect: tuple[int, int, int, int], color: Color, thickness: int = 1, radius: int = 8, lineType: int = cv2.LINE_8) -> np.ndarray

Draw a rectangle (x, y, width, height) with rounded corners, in place like cv.rectangle.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
rect tuple[int, int, int, int]

The box, as for drawDashedRectangle.

required
color Color

Line or fill color.

required
thickness int

Line thickness; cv.FILLED (negative) fills the shape.

1
radius int

Corner radius in pixels, reduced to fit small boxes.

8
lineType int

As for cv.rectangle (cv.LINE_AA for smooth corners).

LINE_8

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is empty, the box has no area, or radius is negative.

drawHistogram

drawHistogram(src: ndarray, size: tuple[int, int] = (512, 200), *, log: bool = False) -> np.ndarray

Plot the histogram of an 8-bit image (one curve per channel, in its own color) as a new image.

cv.calcHist only returns the numbers.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (alpha is ignored).

required
size tuple[int, int]

Plot size as (width, height).

(512, 200)
log bool

Use a logarithmic vertical scale, which shows small counts next to large peaks. On a linear scale, the few tallest spikes are clipped at the top.

False

Returns:

Type Description
ndarray

An 8-bit BGR image with a dark background.

Raises:

Type Description
ValueError

If src is not 8-bit, is empty or has an unsupported channel count, or size is not positive.

putTextEx

putTextEx(img: ndarray, text: str, org: tuple[int, int], fontPath: str | PathLike[str], fontSize: int, color: float | Sequence[float]) -> np.ndarray

Draw text with a TrueType/OpenType font, so any Unicode text (e.g. Korean) can be rendered.

cv.putText only supports the built-in Hershey fonts, which cover ASCII only. Like cv.putText, this draws in place and returns img.

Parameters:

Name Type Description Default
img ndarray

8-bit grayscale, BGR or BGRA image to draw on. Grayscale images stay grayscale.

required
text str

Text to draw. \n starts a new line.

required
org tuple[int, int]

Top-left corner of the text, as (x, y). Note that cv.putText uses the bottom-left corner instead.

required
fontPath str | PathLike[str]

Path to a .ttf/.otf/.ttc font file. Loaded fonts are cached.

required
fontSize int

Font size in pixels.

required
color float | Sequence[float]

Text color (BGR, or a scalar). On grayscale images, the luminance of a BGR color is used.

required

Returns:

Type Description
ndarray

img, with the text drawn on it.

Raises:

Type Description
ValueError

If img is not 8-bit, is empty or has an unsupported channel count, fontSize is not positive, or color is outside [0, 255].

Image statistics and quality checks

ImageStats

Bases: NamedTuple

Summary of an image as returned by imageStats.

mean instance-attribute

mean: tuple[float, ...]

Mean of each channel (alpha included for BGRA).

std instance-attribute

std: tuple[float, ...]

Standard deviation of each channel.

brightness instance-attribute

brightness: float

Mean gray level in [0, 1] (see brightnessScore).

contrast instance-attribute

contrast: float

RMS contrast in [0, 1] (see contrastScore).

sharpness instance-attribute

sharpness: float

Variance of the Laplacian (see sharpnessScore).

entropy instance-attribute

entropy: float

Shannon entropy of the gray histogram in bits (see entropy).

isGray instance-attribute

isGray: bool

True when the image is 2-D or all its color channels are equal.

imageStats

imageStats(src: ndarray) -> ImageStats

Summarize an image in one call: size, dtype, per-channel mean and std, range, brightness, contrast, sharpness, entropy and whether it is grayscale.

Handy for quick inspection in a notebook or for logging dataset statistics; cv.meanStdDev and cv.minMaxLoc cover only parts of this and the latter rejects color images.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count.

isGrayscale

isGrayscale(src: ndarray, tolerance: float = 0) -> bool

Whether an image carries no color: it is single-channel, or its B, G and R channels are (nearly) equal.

img.ndim == 2 misses the common case of a gray picture stored as 3-channel BGR (JPEG scans, frames from cv.VideoCapture). The alpha channel of BGRA images is ignored.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
tolerance float

Largest allowed difference between the channels of any pixel (0 means exactly equal; a few levels absorb JPEG chroma noise).

0

Raises:

Type Description
ValueError

If src is empty, has a wrong channel count, or tolerance is negative.

isBlank

isBlank(src: ndarray, tolerance: float = 2.0) -> bool

Whether an image is uniform (a single flat color), e.g. a black frame, a white page or a failed capture.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
tolerance float

An image is blank when the standard deviation of every color channel is at most this value, in the units of the image (gray levels for 8-bit).

2.0

Raises:

Type Description
ValueError

If src is empty, has a wrong channel count, or tolerance is negative.

isBlurry

isBlurry(src: ndarray, threshold: float = 100.0) -> bool

Whether an image is out of focus: its sharpnessScore (variance of the Laplacian) is below threshold.

The score depends on the content and the image size as much as on the focus, so threshold is only a starting point (100 suits typical 8-bit photos); calibrate it on sharp and blurry samples of your own data.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
threshold float

Sharpness score below which the image counts as blurry.

100.0

Raises:

Type Description
ValueError

If src is empty, has a wrong channel count, or threshold is not finite or negative.

brightnessScore

brightnessScore(src: ndarray) -> float

Mean gray level of an image normalized to [0, 1] (0 is black, 1 is white).

cv.mean returns a 4-tuple in the units of the dtype; this gives one number that is comparable between 8-bit, 16-bit and float images.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count.

contrastScore

contrastScore(src: ndarray) -> float

RMS contrast: standard deviation of the gray levels normalized to [0, 1].

0 for a flat image, 0.5 for a half black / half white image. Useful for sorting images by how washed out they are or for choosing which ones need autoContrast.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count.

colorfulness

colorfulness(src: ndarray) -> float

Colorfulness metric of Hasler and Süsstrunk (2003): 0 for gray images, roughly 20-40 for average photos and above 60 for very vivid ones.

Computed on the opponent color axes rg = R - G and yb = (R + G) / 2 - B as sqrt(std_rg² + std_yb²) + 0.3 * sqrt(mean_rg² + mean_yb²). Non-8-bit images are scaled to the 0-255 range first so the numbers stay comparable.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count.

exposureScore

exposureScore(src: ndarray, lowThreshold: float = 0.05, highThreshold: float = 0.95) -> tuple[float, float]

Fractions of under-exposed and over-exposed pixels, for flagging too dark or blown-out images.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
lowThreshold float

Gray level (normalized to [0, 1]) at or below which a pixel counts as under-exposed.

0.05
highThreshold float

Gray level (normalized to [0, 1]) at or above which a pixel counts as over-exposed.

0.95

Returns:

Type Description
tuple[float, float]

(underExposed, overExposed), each in [0, 1].

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count, or a threshold is outside [0, 1] or lowThreshold exceeds highThreshold.

entropy

entropy(src: ndarray, bins: int = 256) -> float

Shannon entropy of the gray-level histogram in bits: 0 for a flat image, up to 8 for 8-bit images.

A rough measure of how much detail or texture an image holds; near-zero values flag blank or almost blank images, and it is a common feature for picking informative frames.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
bins int

Number of histogram bins over the dtype range ([0, 255] for 8-bit, [0, 1] for float).

256

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count, or bins is below 1.

estimateNoise

estimateNoise(src: ndarray) -> float

Estimate the standard deviation of additive Gaussian noise in an image (Immerkær 1996, fast noise variance estimation).

Works without a clean reference: a Laplacian-like 3x3 kernel cancels smooth structure and edges contribute little on average. Strongly textured images (fine patterns, hair) overestimate the noise.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image, at least 3x3 pixels.

required

Returns:

Type Description
float

The noise sigma in the units of the image (gray levels for 8-bit).

Raises:

Type Description
ValueError

If src is empty, has a wrong channel count or is smaller than 3x3.

mse

mse(a: ndarray, b: ndarray) -> float

Mean squared error between two images of the same shape (0 for identical images).

cv.PSNR gives a logarithmic score, and cv.norm(a, b, cv.NORM_L2) an unnormalized sum; this is the plain per-value mean in float64, so 8-bit inputs do not overflow.

Raises:

Type Description
ValueError

If the shapes differ or the images are empty.

mae

mae(a: ndarray, b: ndarray) -> float

Mean absolute error between two images of the same shape (0 for identical images).

Less sensitive to a few large outliers than mse; the per-value mean of cv.absdiff computed in float64.

Raises:

Type Description
ValueError

If the shapes differ or the images are empty.

histogramEx

histogramEx(src: ndarray, bins: int = 256, mask: ndarray | None = None, channels: list[int] | tuple[int, ...] | None = None, normalize: bool = False) -> np.ndarray

Per-channel histogram of an image as a (channels, bins) array.

cv.calcHist takes lists of images, channels and ranges, needs the ranges spelled out per dtype and returns a (bins, 1) column per call; this takes any image and returns one row per channel over the dtype range ([0, 255] for 8-bit, [0, 65535] for 16-bit, [0, 1] for float).

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
bins int

Number of bins per channel.

256
mask ndarray | None

Optional uint8 mask of the same height and width; only pixels where it is non-zero are counted.

None
channels list[int] | tuple[int, ...] | None

Channel indices to include (all by default).

None
normalize bool

Divide each row by its sum so the rows are probability distributions.

False

Returns:

Type Description
ndarray

float64 array of shape (len(channels), bins).

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count, bins is below 1, a channel index is out of range, or the mask has a different size.

histogramCompare

histogramCompare(a: ndarray, b: ndarray, method: int = cv2.HISTCMP_CORREL, bins: int = 32, colorSpace: str = 'hsv') -> float

Compare the color distributions of two images (any sizes) with cv.compareHist.

cv.compareHist needs two histograms built with the same cv.calcHist setup; this builds and normalizes them for you. Images with different channel counts are brought to the same color space first.

Parameters:

Name Type Description Default
a ndarray

First image (grayscale, BGR or BGRA).

required
b ndarray

Second image; may have a different size or channel count.

required
method int

cv.HISTCMP_* method. For HISTCMP_CORREL and HISTCMP_INTERSECT higher means more similar; for HISTCMP_CHISQR, HISTCMP_BHATTACHARYYA and HISTCMP_HELLINGER lower means more similar.

HISTCMP_CORREL
bins int

Bins per channel.

32
colorSpace str

"hsv" (joint hue-saturation histogram, robust to brightness changes), "bgr" (joint 3-D color histogram) or "gray" (1-D intensity histogram).

'hsv'

Raises:

Type Description
ValueError

If an image is empty or has a wrong channel count, bins is below 1 or colorSpace is unknown.

dominantHue

dominantHue(src: ndarray, bins: int = 36) -> float

The most common hue of an image in degrees [0, 360), weighted by saturation so gray pixels do not vote.

0 is red, 120 green, 240 blue. The hue histogram peak is refined by the circular mean of the hues inside the peak bin. Returns 0.0 for images without any saturated pixel (grayscale images).

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image.

required
bins int

Number of hue bins over the circle.

36

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count, or bins is below 1.

meanColor

meanColor(src: ndarray, mask: ndarray | None = None) -> tuple[float, ...]

Mean value of each channel, optionally over a mask: one number for gray, (b, g, r) for BGR images.

cv.mean always returns four values (zeros for missing channels) and requires a uint8 mask.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype with 1, 3 or 4 channels.

required
mask ndarray | None

Optional mask of the same height and width; only pixels where it is non-zero are averaged.

None

Returns:

Type Description
tuple[float, ...]

A tuple with one float per channel of src (zeros when the mask selects no pixel).

Raises:

Type Description
ValueError

If src is empty or has a wrong channel count, or the mask has a different size.

Color arithmetic

CSS_COLORS module-attribute

CSS_COLORS: dict[str, Color] = {name: (hexToBGR(h)[0], hexToBGR(h)[1], hexToBGR(h)[2]) for name, h in _CSS_HEX.items()}

The 148 CSS named colors ("red", "steelblue", ...) as BGR tuples, for :func:colorName and drawing.

lightenColor

lightenColor(color: Sequence[float], amount: float) -> Color

Lighten a BGR color by moving its HLS lightness toward white, e.g. for the fill of a box drawn in color.

Parameters:

Name Type Description Default
color Sequence[float]

BGR color.

required
amount float

0 leaves the color as is, 1 gives white.

required

Raises:

Type Description
ValueError

If color is not a BGR color in [0, 255] or amount is not in [0, 1].

darkenColor

darkenColor(color: Sequence[float], amount: float) -> Color

Darken a BGR color by moving its HLS lightness toward black, e.g. for the border of a box filled in color.

Parameters:

Name Type Description Default
color Sequence[float]

BGR color.

required
amount float

0 leaves the color as is, 1 gives black.

required

Raises:

Type Description
ValueError

If color is not a BGR color in [0, 255] or amount is not in [0, 1].

blendColors

blendColors(a: Sequence[float], b: Sequence[float], t: float = 0.5) -> Color

Mix two BGR colors: t = 0 gives a, t = 1 gives b, 0.5 the midpoint.

Raises:

Type Description
ValueError

If a color is not a BGR color in [0, 255] or t is not in [0, 1].

complementaryColor

complementaryColor(color: Sequence[float]) -> Color

The color on the opposite side of the hue circle (hue + 180°), keeping lightness and saturation.

Different from :func:invertColor: the complement of a dark red is a dark cyan, not a light cyan.

Raises:

Type Description
ValueError

If color is not a BGR color in [0, 255].

invertColor

invertColor(color: Sequence[float]) -> Color

The negative of a BGR color: 255 - value per channel, like cv.bitwise_not on a pixel.

Raises:

Type Description
ValueError

If color is not a BGR color in [0, 255].

colorDistance

colorDistance(a: Sequence[float], b: Sequence[float], space: str = 'lab') -> float

Distance between two BGR colors: CIE76 ΔE in Lab (how different they look) or Euclidean in BGR.

In Lab a ΔE of about 2 is the smallest difference most people notice, and 100 separates black from white.

Parameters:

Name Type Description Default
a Sequence[float]

First BGR color.

required
b Sequence[float]

Second BGR color.

required
space str

"lab" for CIE76 ΔE (perceptual) or "bgr" for plain Euclidean distance in [0, 441].

'lab'

Raises:

Type Description
ValueError

If a color is not a BGR color in [0, 255] or space is unknown.

nearestColor

nearestColor(color: Sequence[float], palette: Sequence[Sequence[float]] | ndarray, space: str = 'lab') -> int

Index of the palette color closest to color (CIE76 in Lab by default), e.g. to snap to a color legend.

Parameters:

Name Type Description Default
color Sequence[float]

BGR color.

required
palette Sequence[Sequence[float]] | ndarray

BGR colors, as a sequence of tuples or an array of shape (N, 3).

required
space str

"lab" or "bgr", as for :func:colorDistance.

'lab'

Raises:

Type Description
ValueError

If color or a palette entry is not a BGR color in [0, 255], the palette is empty, or space is unknown.

colorName

colorName(color: Sequence[float]) -> str

Name of the CSS color closest to a BGR color (CIE76 in Lab), e.g. (30, 20, 220) gives "crimson".

Useful for logging or labeling the result of dominantColors. For colors with two CSS names (aqua / cyan, gray / grey, ...) the alphabetically first name is returned.

Raises:

Type Description
ValueError

If color is not a BGR color in [0, 255].

textColorFor

textColorFor(background: Sequence[float]) -> Color

Black or white, whichever reads better on background; the rule used by :func:drawLabel.

Returns:

Type Description
Color

(0, 0, 0) for light backgrounds (luminance above 140) and (255, 255, 255) for dark ones.

Raises:

Type Description
ValueError

If background is not a BGR color in [0, 255].

randomColors

randomColors(count: int, seed: int | None = None, saturation: float = 1.0, value: float = 1.0) -> list[Color]

count random BGR colors with random hues and the given saturation and brightness.

Unlike :func:distinctColors (a fixed, maximally different sequence) these are random, so two calls with different seeds give different palettes, e.g. for per-instance colors in a demo.

Parameters:

Name Type Description Default
count int

How many colors.

required
seed int | None

Random seed for reproducible colors.

None
saturation float

HSV saturation in [0, 1]; lower is more pastel.

1.0
value float

HSV brightness in [0, 1]; lower is darker.

1.0

Raises:

Type Description
ValueError

If count is negative or saturation / value is not in [0, 1].

gradientPalette

gradientPalette(start: Sequence[float], end: Sequence[float], count: int) -> list[Color]

count BGR colors interpolated linearly from start to end (both included).

Parameters:

Name Type Description Default
start Sequence[float]

First color.

required
end Sequence[float]

Last color.

required
count int

How many colors; 1 gives [start].

required

Raises:

Type Description
ValueError

If a color is not a BGR color in [0, 255] or count is negative.

colormapPalette

colormapPalette(colormap: int, count: int) -> list[Color]

count BGR colors sampled evenly from an OpenCV colormap, e.g. cv.COLORMAP_VIRIDIS.

cv.applyColorMap only maps whole images; this gives the colors themselves, for drawing classes or a legend in the colormap's order.

Parameters:

Name Type Description Default
colormap int

cv.COLORMAP_* constant.

required
count int

How many colors, from the darkest end (0) to the brightest (255) of the map.

required

Raises:

Type Description
ValueError

If count is negative.

Data augmentation

addNoise

addNoise(src: ndarray, kind: str = 'gaussian', amount: float | None = None, seed: int | None = None) -> np.ndarray

Add synthetic sensor noise to an image.

OpenCV has no noise generator except cv.randn/cv.randu, which need a preallocated array of the right type and leave the clipping and the salt-and-pepper logic to you. The result keeps the dtype of src and is clipped to its range ([0, 255] for 8-bit, [0, 1] for float images).

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image of any dtype (noise is added to every channel, including alpha).

required
kind str

"gaussian" adds normal noise with standard deviation amount (as a fraction of the value range, default 0.1); "salt_pepper" sets a fraction amount (default 0.05) of the pixels to black or white; "poisson" applies shot noise whose strength depends on the brightness (amount scales the photon count, default 1, larger is less noisy); "speckle" multiplies every value by 1 + N(0, amount) (default 0.1).

'gaussian'
amount float | None

Noise strength, see kind.

None
seed int | None

Random seed for reproducible noise.

None

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is empty, kind is unknown, or amount is negative or not finite (for "salt_pepper" it must also be at most 1).

motionBlur

motionBlur(src: ndarray, size: int = 15, angle: float = 0.0) -> np.ndarray

Blur along a line, like a camera or object moving during the exposure.

cv.blur and cv.GaussianBlur only blur isotropically; a directional kernel must be built by hand.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
size int

Length of the motion in pixels (the kernel is size x size).

15
angle float

Direction of the motion in degrees, counter-clockwise from the x axis; 0 is horizontal.

0.0

Returns:

Type Description
ndarray

The blurred image, with the dtype of src.

Raises:

Type Description
ValueError

If src is empty, size is smaller than 1, or angle is not finite.

vignette

vignette(src: ndarray, strength: float = 0.5, radius: float = 1.0) -> np.ndarray

Darken the image towards the corners with a smooth Gaussian falloff, like a cheap lens.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image (the alpha channel is not changed).

required
strength float

Darkening at the corners: 0 leaves the image unchanged, 1 makes the corners black.

0.5
radius float

Size of the bright area relative to the half diagonal; smaller values darken a larger area.

1.0

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is empty, strength is outside [0, 1], or radius is not positive.

jpegArtifacts

jpegArtifacts(src: ndarray, quality: int = 30) -> np.ndarray

Add JPEG compression artifacts (blocking, ringing) by an encode/decode round trip in memory.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (the alpha channel is kept as is).

required
quality int

JPEG quality from 1 (worst) to 100.

30

Returns:

Type Description
ndarray

The re-encoded image with the shape of src.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, or quality is outside [1, 100].

randomErase

randomErase(src: ndarray, size: int | tuple[int, int] | None = None, count: int = 1, fill: float | Sequence[float] | str = 0, seed: int | None = None) -> np.ndarray

Blank out random rectangles ("cutout" / random erasing) so a model cannot rely on one region.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image of any dtype.

required
size int | tuple[int, int] | None

Patch size as (width, height) or one side; by default a quarter of the image in each direction.

None
count int

Number of patches.

1
fill float | Sequence[float] | str

Fill value or color, or "random" for uniform noise in the value range of the image.

0
seed int | None

Random seed for the patch positions (and the noise).

None

Returns:

Type Description
ndarray

A new image with the patches erased.

Raises:

Type Description
ValueError

If src is empty, size is not positive or larger than the image, count is negative, or fill is not a valid color for the dtype.

solarize

solarize(src: ndarray, threshold: float = 128) -> np.ndarray

Invert every value above threshold (the darkroom "Sabattier" effect).

A standard augmentation (AutoAugment, RandAugment) that Pillow has in ImageOps but OpenCV lacks.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image of any dtype.

required
threshold float

Values at or above it are inverted within the value range ([0, 255] for 8-bit, [0, 1] for float images).

128

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is empty or threshold is not finite.

posterize

posterize(src: ndarray, bits: int = 4) -> np.ndarray

Reduce the number of tone levels per channel to 2 ** bits (flat, poster-like colors).

A standard augmentation (AutoAugment, RandAugment) that Pillow has in ImageOps but OpenCV lacks.

Parameters:

Name Type Description Default
src ndarray

Grayscale, BGR or BGRA image of any dtype. Integer images keep their bits most significant bits; float images in [0, 1] are quantized to 2 ** bits levels.

required
bits int

Bits to keep per channel, from 1 to the bit depth of the dtype (8 for 8-bit images).

4

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is empty or bits is outside the valid range.

randomCrop

randomCrop(src: ndarray, size: tuple[int, int], boxes: ArrayLike | None = None, seed: int | None = None) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Crop a window of size at a random position.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
size tuple[int, int]

Crop size as (width, height), at most the image size.

required
boxes ArrayLike | None

Optional boxes (N, 4) as (x, y, width, height); they are shifted and clipped to the crop (boxes outside become zero-sized, so the rows stay aligned with your labels).

None
seed int | None

Random seed.

None

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The crop, or (crop, boxes) when boxes is given.

Raises:

Type Description
ValueError

If src is empty, size is not positive or exceeds the image, or boxes is malformed.

randomFlip

randomFlip(src: ndarray, horizontal: float = 0.5, vertical: float = 0.0, boxes: ArrayLike | None = None, seed: int | None = None) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Flip the image horizontally and/or vertically with the given probabilities.

cv.flip always flips; the coin toss and the box bookkeeping are left to you.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
horizontal float

Probability of a horizontal (left-right) flip.

0.5
vertical float

Probability of a vertical (top-bottom) flip.

0.0
boxes ArrayLike | None

Optional boxes (N, 4) as (x, y, width, height) to flip along.

None
seed int | None

Random seed.

None

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The (possibly) flipped image, or (image, boxes) when boxes is given.

Raises:

Type Description
ValueError

If src is empty, a probability is outside [0, 1], or boxes is malformed.

randomRotate

randomRotate(src: ndarray, maxAngle: float = 15, boxes: ArrayLike | None = None, seed: int | None = None, crop: bool = False, borderValue: float | Sequence[float] = 0) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Rotate around the center by a random angle in [-maxAngle, maxAngle] degrees.

Like :func:rotateEx, the canvas grows so no corner is cut off unless crop is set; boxes are rotated with the image and replaced by the axis-aligned box around their rotated corners (they grow a little for large angles).

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
maxAngle float

Largest rotation in degrees (either direction).

15
boxes ArrayLike | None

Optional boxes (N, 4) as (x, y, width, height).

None
seed int | None

Random seed.

None
crop bool

Keep the size of src and cut off the corners, instead of enlarging the canvas.

False
borderValue float | Sequence[float]

Fill value or color for the uncovered areas.

0

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The rotated image, or (image, boxes) when boxes is given.

Raises:

Type Description
ValueError

If src is empty, maxAngle is negative or not finite, borderValue is not a valid color, or boxes is malformed.

randomScale

randomScale(src: ndarray, scaleRange: tuple[float, float] = (0.8, 1.2), boxes: ArrayLike | None = None, seed: int | None = None, interpolation: int | None = None) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Resize by a random factor drawn uniformly from scaleRange (the output size changes).

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
scaleRange tuple[float, float]

(low, high) factors, both positive.

(0.8, 1.2)
boxes ArrayLike | None

Optional boxes (N, 4) as (x, y, width, height); they are scaled by the same factor.

None
seed int | None

Random seed.

None
interpolation int | None

cv.INTER_* flag; INTER_AREA to shrink and INTER_LINEAR to enlarge by default.

None

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The resized image, or (image, boxes) when boxes is given.

Raises:

Type Description
ValueError

If src is empty, scaleRange is not positive or low > high, or boxes is malformed.

randomPerspective

randomPerspective(src: ndarray, distortion: float = 0.1, boxes: ArrayLike | None = None, seed: int | None = None, borderValue: float | Sequence[float] = 0) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Warp the image as if seen from a slightly different viewpoint, by jittering its four corners.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
distortion float

Largest corner displacement as a fraction of the width and height, e.g. 0.1 for 10%.

0.1
boxes ArrayLike | None

Optional boxes (N, 4) as (x, y, width, height); each is replaced by the axis-aligned box around its warped corners, clipped to the image.

None
seed int | None

Random seed.

None
borderValue float | Sequence[float]

Fill value or color for the uncovered areas.

0

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The warped image (same size as src), or (image, boxes) when boxes is given.

Raises:

Type Description
ValueError

If src is empty, distortion is outside [0, 0.5), borderValue is not a valid color, or boxes is malformed.

randomBrightnessContrast

randomBrightnessContrast(src: ndarray, brightness: float = 0.2, contrast: float = 0.2, seed: int | None = None) -> np.ndarray

Apply :func:adjustBrightnessContrast with random amounts.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (the alpha channel is kept).

required
brightness float

Largest brightness shift as a fraction of 255 (drawn from [-brightness, brightness]).

0.2
contrast float

Largest contrast change; the factor is drawn from [1 - contrast, 1 + contrast].

0.2
seed int | None

Random seed.

None

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is not 8-bit or is empty, or a limit is negative, above 1, or not finite.

randomHSV

randomHSV(src: ndarray, hue: float = 10, saturation: float = 0.3, value: float = 0.3, seed: int | None = None) -> np.ndarray

Apply :func:adjustHSV with random amounts (hue shift, saturation and brightness factors).

Parameters:

Name Type Description Default
src ndarray

8-bit BGR or BGRA image (the alpha channel is kept).

required
hue float

Largest hue shift in degrees (drawn from [-hue, hue]).

10
saturation float

Largest saturation change; the factor is drawn from [1 - saturation, 1 + saturation].

0.3
value float

Largest brightness change; the factor is drawn from [1 - value, 1 + value].

0.3
seed int | None

Random seed.

None

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is not an 8-bit color image or is empty, or a limit is negative, not finite, or (for saturation and value) above 1.

randomBlur

randomBlur(src: ndarray, maxKernel: int = 7, seed: int | None = None) -> np.ndarray

Gaussian-blur with a random odd kernel size from 1 (no blur) to maxKernel.

Parameters:

Name Type Description Default
src ndarray

Image of any dtype and channel count.

required
maxKernel int

Largest kernel size; rounded down to an odd number.

7
seed int | None

Random seed.

None

Returns:

Type Description
ndarray

A new image with the same shape and dtype as src.

Raises:

Type Description
ValueError

If src is empty or maxKernel is smaller than 1.

mosaic

mosaic(images: Sequence[ndarray], size: tuple[int, int], boxes: Sequence[ArrayLike] | None = None, seed: int | None = None) -> np.ndarray | tuple[np.ndarray, np.ndarray]

Combine four images into one YOLO-style mosaic around a random center point.

Each image is scaled to cover its quadrant (keeping its aspect ratio) and cropped so the quadrants meet at the center. Boxes are scaled, shifted and clipped to their quadrant.

Parameters:

Name Type Description Default
images Sequence[ndarray]

Exactly four images with the same dtype and channel count (sizes may differ).

required
size tuple[int, int]

Output size as (width, height).

required
boxes Sequence[ArrayLike] | None

Optional list of four box arrays (N_i, 4) as (x, y, width, height), one per image.

None
seed int | None

Random seed for the center point.

None

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

The mosaic, or (mosaic, boxes) when boxes is given: the transformed boxes of all four images

ndarray | tuple[ndarray, ndarray]

concatenated in order, so labels concatenate the same way (boxes outside their quadrant are zero-sized).

Raises:

Type Description
ValueError

If there are not four images, they differ in dtype or channels, size is not positive, or boxes does not have four entries.

mixup

mixup(a: ndarray, b: ndarray, alpha: float = 0.5, lam: float | None = None, seed: int | None = None) -> tuple[np.ndarray, float]

Blend two images, lam * a + (1 - lam) * b (mixup), with lam drawn from Beta(alpha, alpha).

b is resized to the size of a. Use the returned lam to mix the labels the same way.

Parameters:

Name Type Description Default
a ndarray

First image (grayscale, BGR or BGRA, any dtype).

required
b ndarray

Second image with the same dtype and channels; any size.

required
alpha float

Beta distribution parameter; smaller values favor one image, 1 is uniform.

0.5
lam float | None

Fixed mixing weight in [0, 1] instead of a random one.

None
seed int | None

Random seed.

None

Returns:

Type Description
tuple[ndarray, float]

(image, lam) with the image in the dtype of a.

Raises:

Type Description
ValueError

If an image is empty, the images differ in dtype or channels, alpha is not positive, or lam is outside [0, 1].

cutMix

cutMix(a: ndarray, b: ndarray, alpha: float = 1.0, seed: int | None = None) -> tuple[np.ndarray, float]

Paste a random rectangle of b into a (CutMix).

b is resized to the size of a; the patch covers a fraction 1 - lam of the area, with lam drawn from Beta(alpha, alpha). The returned lam is the exact fraction of a that remains, for label mixing.

Parameters:

Name Type Description Default
a ndarray

Image that receives the patch (grayscale, BGR or BGRA, any dtype).

required
b ndarray

Image the patch is taken from, with the same dtype and channels; any size.

required
alpha float

Beta distribution parameter; 1 draws the area fraction uniformly.

1.0
seed int | None

Random seed.

None

Returns:

Type Description
tuple[ndarray, float]

(image, lam) with the image in the dtype of a.

Raises:

Type Description
ValueError

If an image is empty, the images differ in dtype or channels, or alpha is not positive.

Documents and OCR

removeShadow

removeShadow(src: ndarray, kernelSize: int = 21, blurSize: int = 21) -> np.ndarray

Flatten uneven lighting on a photographed page so the paper becomes uniformly white.

The background is estimated per channel by dilating away the text and smoothing with a median blur; the image is then divided by it. A classic recipe that OpenCV does not package.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image of a page.

required
kernelSize int

Dilation kernel; must be larger than the text stroke width so the text vanishes.

21
blurSize int

Median blur kernel (odd) that smooths the background estimate.

21

Returns:

Type Description
ndarray

An image of the same shape and dtype with a flat, bright background.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or kernelSize/blurSize is not a valid kernel size.

enhanceDocument

enhanceDocument(src: ndarray, mode: EnhanceMode = 'gray') -> np.ndarray

Give a photographed page the look of a flatbed scan: flat white paper and crisp dark text.

Removes shadows (:func:removeShadow), stretches the contrast and sharpens; "binary" ends with an adaptive threshold for OCR or fax-style output.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image of a page.

required
mode EnhanceMode

"gray" (grayscale result), "color" (keeps the colors, e.g. stamps and highlights) or "binary" (0/255 mask).

'gray'

Returns:

Type Description
ndarray

uint8 image: 2-D for "gray" and "binary", the same channels as src for "color"

ndarray

(grayscale input stays grayscale).

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or mode is unknown.

sauvolaThreshold

sauvolaThreshold(src: ndarray, windowSize: int = 25, k: float = 0.2, r: float = 128.0, invert: bool = False) -> np.ndarray

Sauvola local threshold: the standard binarization for OCR of unevenly lit or stained documents.

Threshold T = m * (1 + k * (s / r - 1)) from the local mean m and standard deviation s, computed with integral images. OpenCV only has it in the ximgproc contrib module (niBlackThreshold with BINARIZATION_SAUVOLA).

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image.

required
windowSize int

Side of the square neighborhood (odd); 2-3 times the text height works well.

25
k float

Sensitivity, usually 0.2-0.5; larger values thin the text.

0.2
r float

Dynamic range of the standard deviation, 128 for 8-bit images.

128.0
invert bool

Return the text (pixels below the threshold) as 255 instead of the paper, like cv.THRESH_BINARY_INV.

False

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255: 255 where the pixel is above its local threshold (the paper).

Raises:

Type Description
ValueError

If src is empty or not 8-bit, windowSize is not odd, or k/r is not finite.

niblackThreshold

niblackThreshold(src: ndarray, windowSize: int = 25, k: float = -0.2, invert: bool = False) -> np.ndarray

Niblack local threshold T = m + k * s from the local mean and standard deviation.

Simpler than :func:sauvolaThreshold and noisier on blank paper, but useful when the text contrast is low. OpenCV only has it in the ximgproc contrib module.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image.

required
windowSize int

Side of the square neighborhood (odd).

25
k float

Weight of the standard deviation; negative values (-0.2) favor dark text on light paper.

-0.2
invert bool

Return the text (pixels below the threshold) as 255 instead of the paper.

False

Returns:

Type Description
ndarray

uint8 mask with values 0 and 255: 255 where the pixel is above its local threshold.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, windowSize is not odd, or k is not finite.

removeSpeckles

removeSpeckles(src: ndarray, maxArea: int = 10) -> np.ndarray

Remove the tiny ink specks (dust, noise) from a binarized document, keeping its polarity.

:func:cv2u.removeSmallObjects treats nonzero pixels as foreground, which on black-on-white text removes the paper. This works on the ink, whichever value it has, and also accepts grayscale or color pages (the specks are painted over with the paper color).

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA document.

required
maxArea int

Ink regions with up to this many pixels are removed.

10

Returns:

Type Description
ndarray

A new image of the same shape and dtype.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or maxArea is negative.

removeLines

removeLines(src: ndarray, horizontal: bool = True, vertical: bool = True, minLength: float | None = None, thickness: int = 3) -> np.ndarray

Erase table rules and underlines from a document so OCR sees only the text.

Long runs of ink are found by opening with a thin horizontal / vertical structuring element. On a binary image the line pixels are set to the paper value; on grayscale or color images they are filled with cv.inpaint.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA document (binarized or not).

required
horizontal bool

Remove horizontal lines.

True
vertical bool

Remove vertical lines.

True
minLength float | None

Shortest line to remove, in pixels, or as a fraction of the image size when below 1. By default a tenth of the image width / height.

None
thickness int

Width of the strip erased around each line, in pixels (covers anti-aliased edges).

3

Returns:

Type Description
ndarray

A new image of the same shape and dtype.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, minLength is not positive, or thickness is not positive.

detectTextLines

detectTextLines(src: ndarray, minHeight: int = 5, dilateWidth: int | None = None) -> np.ndarray

Bounding boxes of the text lines of a page, top to bottom, ready for cropping into an OCR engine.

The text is binarized, smeared horizontally so the characters of a line join, and the connected regions are measured. Deskew first (:func:cv2u.deskew) if the lines are tilted.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image of a page.

required
minHeight int

Ignore regions lower than this many pixels (noise, rules).

5
dilateWidth int | None

Horizontal smear that joins characters and words, in pixels. By default about twice the median character height, which bridges word spaces but not columns.

None

Returns:

Type Description
ndarray

int32 array of shape (N, 4) with one (x, y, w, h) box per line, sorted top to bottom (then

ndarray

left to right). Empty for a blank page.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or minHeight/dilateWidth is not positive.

detectTextBlocks

detectTextBlocks(src: ndarray, minHeight: int = 5, dilateSize: tuple[int, int] | None = None) -> np.ndarray

Bounding boxes of the text blocks (paragraphs, columns) of a page, top to bottom.

Like :func:detectTextLines, but the ink is smeared both ways so that neighboring lines merge into one region while blocks separated by a wider gap stay apart.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image of a page.

required
minHeight int

Ignore regions lower than this many pixels.

5
dilateSize tuple[int, int] | None

Smear as (width, height) in pixels. By default about 3 and 1.5 times the median character height.

None

Returns:

Type Description
ndarray

int32 array of shape (N, 4) with one (x, y, w, h) box per block, sorted top to bottom

ndarray

(then left to right). Empty for a blank page.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or minHeight/dilateSize is not positive.

removeBorder

removeBorder(src: ndarray, threshold: float | None = None, margin: int = 0) -> np.ndarray

Crop away the dark frame a scanner or copier leaves around a page.

The page is the largest bright region; the image is cropped to its bounding box. For a uniform border of any color see :func:cv2u.cropToContent.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image.

required
threshold float | None

Gray level above which a pixel counts as paper; by default chosen by Otsu's method.

None
margin int

Extra pixels trimmed from each side of the page (positive) or kept around it (negative).

0

Returns:

Type Description
ndarray

The cropped page. The whole image if nothing bright is found.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or threshold is not finite.

estimateSkew

estimateSkew(src: ndarray, maxAngle: float = 45.0) -> float

Tilt of the text lines of a page, in degrees, without rotating it (the angle :func:cv2u.deskew applies).

Uses the same projection-profile search as deskew: rotate the ink until it concentrates in as few rows as possible, first in 1° and then in 0.1° steps.

Parameters:

Name Type Description Default
src ndarray

Image of a page (grayscale, BGR or BGRA).

required
maxAngle float

Largest tilt to look for, in degrees.

45.0

Returns:

Type Description
float

The counter-clockwise rotation (as for cv.getRotationMatrix2D) that levels the lines; 0 for a blank

float

page.

Raises:

Type Description
ValueError

If src is empty, or maxAngle is negative or not below 90.

detectPage

detectPage(src: ndarray, minAreaRatio: float = 0.2) -> np.ndarray | None

Find the four corners of a photographed page (or card, receipt, whiteboard) for :func:fourPointTransform.

Edges are detected on a blurred grayscale copy, closed, and the largest contour that approximates to a quadrilateral covering at least minAreaRatio of the image is returned.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA photo with the page against a contrasting background.

required
minAreaRatio float

Smallest fraction of the image area the page may cover.

0.2

Returns:

Type Description
ndarray | None

float32 array of shape (4, 2) with the corners ordered top-left, top-right, bottom-right,

ndarray | None

bottom-left, or None if no quadrilateral is found.

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or minAreaRatio is not in [0, 1].

scanDocument

scanDocument(src: ndarray, size: tuple[int, int] | None = None, enhance: bool = True, minAreaRatio: float = 0.2) -> np.ndarray

Photo of a page in, scan out: :func:detectPage + :func:fourPointTransform + :func:enhanceDocument.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA photo of a page.

required
size tuple[int, int] | None

Output size (width, height); by default the size of the page in the photo.

None
enhance bool

Flatten the lighting and sharpen the result ("gray" for grayscale input, "color" otherwise).

True
minAreaRatio float

Passed to :func:detectPage.

0.2

Returns:

Type Description
ndarray

The upright page. If no page outline is found, the whole image (enhanced if asked, resized to size).

Raises:

Type Description
ValueError

If src is empty or not 8-bit, or minAreaRatio is not in [0, 1].

Stitching

stitchImages

stitchImages(images: Sequence[ndarray], mode: Literal['panorama', 'scans'] = 'panorama', confidence: float | None = None) -> np.ndarray

Stitch overlapping images into one with cv.Stitcher, raising on failure instead of returning a code.

cv.Stitcher.stitch returns (status, pano) where pano is None on failure and status is a bare integer. This raises a RuntimeError naming the status (ERR_NEED_MORE_IMGS, ...) and accepts grayscale images (the stitcher needs BGR).

Parameters:

Name Type Description Default
images Sequence[ndarray]

Two or more overlapping images, grayscale or BGR.

required
mode Literal['panorama', 'scans']

"panorama" for photos taken by rotating the camera (perspective warps), "scans" for flat content such as scans or aerial images (affine warps).

'panorama'
confidence float | None

setPanoConfidenceThresh; lower (e.g. 0.3) accepts images with less overlap or texture. None keeps OpenCV's default (1.0).

None

Returns:

Type Description
ndarray

The stitched BGR image.

Raises:

Type Description
ValueError

If fewer than 2 images are given, an image is empty, or mode is unknown.

RuntimeError

If the stitcher fails; the message contains the status name.

stitchPair

stitchPair(a: ndarray, b: ndarray, method: Detector = 'ORB', ratio: float = 0.75, maxFeatures: int = 2000, ransacThreshold: float = 5.0, minMatches: int = 10) -> np.ndarray

Stitch two overlapping images by a homography, on a canvas large enough to hold both.

The simple recipe: :func:matchFeatures, cv.findHomography with RANSAC, and cv.warpPerspective of b onto the plane of a. Unlike the bare warp, the canvas is enlarged (and the origin shifted) so that nothing is cut off; a is pasted on top. No blending, no cropping: the background is black.

Parameters:

Name Type Description Default
a ndarray

Reference image (grayscale or BGR); its plane is kept.

required
b ndarray

Image to warp onto a.

required
method Detector

Feature detector, as for :func:matchFeatures.

'ORB'
ratio float

Lowe's ratio for the matches.

0.75
maxFeatures int

Keypoint limit.

2000
ransacThreshold float

Reprojection error in pixels above which a match counts as an outlier.

5.0
minMatches int

Fail when fewer matches pass the ratio test.

10

Returns:

Type Description
ndarray

The stitched image, same dtype and channel count as a.

Raises:

Type Description
ValueError

If an image is empty, too few matches are found, or the homography cannot be estimated.

Visualization

applyColorMapEx

applyColorMapEx(values: ndarray, colormap: int | ndarray = cv2.COLORMAP_JET, normalize: bool = True, mask: ndarray | None = None) -> np.ndarray

Colorize a 2-D map of any dtype, like cv.applyColorMap which only takes 8-bit input.

Float maps (saliency, depth, attention, probabilities) are scaled to [0, 255] first.

Parameters:

Name Type Description Default
values ndarray

2-D array (or 3-D with one channel) of any numeric dtype.

required
colormap int | ndarray

An OpenCV cv.COLORMAP_* constant, or a (256, 1, 3) / (256, 3) 8-bit lookup table.

COLORMAP_JET
normalize bool

Stretch the minimum and maximum of values to 0 and 255. When False, the values are clipped to [0, 255] (float maps in [0, 1] are scaled by 255 first).

True
mask ndarray | None

Optional 2-D mask with the shape of values; pixels outside it are black.

None

Returns:

Type Description
ndarray

An 8-bit BGR image with the shape of values.

Raises:

Type Description
ValueError

If values is empty or not 2-D, contains NaN/inf, or mask has a different shape.

heatmap

heatmap(src: ndarray, values: ndarray, alpha: float = 0.5, colormap: int | ndarray = cv2.COLORMAP_JET, normalize: bool = True) -> np.ndarray

Overlay a colorized map (attention, saliency, density, CAM) on an image.

cv.applyColorMap needs an 8-bit map of the image size; this takes a float map of any size, resizes it to src and blends it in.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image. It is not modified.

required
values ndarray

2-D map of any numeric dtype and size (resized to src with linear interpolation).

required
alpha float

Opacity of the color map, from 0 to 1.

0.5
colormap int | ndarray

As for :func:applyColorMapEx.

COLORMAP_JET
normalize bool

As for :func:applyColorMapEx.

True

Returns:

Type Description
ndarray

A new BGR image (BGRA keeps the alpha channel of src) with the size of src.

Raises:

Type Description
ValueError

If src is not 8-bit, values is not 2-D, or alpha is outside [0, 1].

colorBar

colorBar(colormap: int | ndarray = cv2.COLORMAP_JET, size: tuple[int, int] = (256, 20), vertical: bool = False, minVal: float | None = None, maxVal: float | None = None, fontScale: float = 0.4) -> np.ndarray

Make a legend strip for a color map, optionally labeled with its value range, as a new BGR image.

Parameters:

Name Type Description Default
colormap int | ndarray

As for :func:applyColorMapEx.

COLORMAP_JET
size tuple[int, int]

Size of the strip as (width, height) (vertical swaps the gradient direction, not the size).

(256, 20)
vertical bool

Run the gradient from the bottom (minimum) to the top instead of left to right.

False
minVal float | None

Value written at the low end; None writes nothing.

None
maxVal float | None

Value written at the high end; None writes nothing.

None
fontScale float

Hershey font size of the labels.

0.4

Returns:

Type Description
ndarray

A BGR image of size; with labels, the strip grows to make room for the text.

Raises:

Type Description
ValueError

If size is not positive or a label value is not finite.

drawArrow

drawArrow(img: ndarray, pt1: Sequence[float], pt2: Sequence[float], color: Color, thickness: int = 2, headSize: int = 10, heads: str = 'end', lineType: int = cv2.LINE_AA) -> np.ndarray

Draw an arrow with a head of a fixed size in pixels, in place.

cv.arrowedLine sizes the head as a fraction of the arrow length, so short arrows (e.g. optical flow) get invisible heads and long ones get huge heads; it also draws a head at one end only.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
pt1 Sequence[float]

Start point (x, y); floats are rounded.

required
pt2 Sequence[float]

End point (x, y).

required
color Color

Arrow color.

required
thickness int

Line thickness.

2
headSize int

Length of the head's sides in pixels.

10
heads str

"end" (head at pt2), "start", "both" or "none".

'end'
lineType int

As for cv.line.

LINE_AA

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If heads is unknown, headSize is negative, or a point is not finite.

drawRotatedRect

drawRotatedRect(img: ndarray, rect: tuple[Sequence[float], Sequence[float], float], color: Color, thickness: int = 2, lineType: int = cv2.LINE_AA) -> np.ndarray

Draw a rotated rectangle ((cx, cy), (w, h), angle) as returned by cv.minAreaRect, in place.

OpenCV has cv.boxPoints but no drawing function for its own RotatedRect.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
rect tuple[Sequence[float], Sequence[float], float]

The rotated rectangle.

required
color Color

Line or fill color.

required
thickness int

Line thickness; cv.FILLED fills the rectangle.

2
lineType int

As for cv.polylines.

LINE_AA

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If rect has a negative size or non-finite values.

drawRotatedBoxes

drawRotatedBoxes(img: ndarray, rects: Sequence[tuple[Sequence[float], Sequence[float], float]], colors: Sequence[Color] | Color | None = None, labels: Sequence[str] | None = None, thickness: int = 2, fontScale: float = 0.5) -> np.ndarray

Draw many rotated rectangles, each with an optional label at its top corner, in place.

The rotated counterpart of :func:drawBoxes for oriented detectors and cv.minAreaRect results.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
rects Sequence[tuple[Sequence[float], Sequence[float], float]]

Rotated rectangles ((cx, cy), (w, h), angle).

required
colors Sequence[Color] | Color | None

One color per box, one color for all, or None for :func:distinctColors.

None
labels Sequence[str] | None

One text per box, or None.

None
thickness int

Line thickness.

2
fontScale float

Hershey font size of the labels.

0.5

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If labels or colors has a different length than rects.

drawPolygon

drawPolygon(img: ndarray, points: Sequence[Sequence[float]] | ndarray, color: Color, thickness: int = 2, closed: bool = True, fill: bool = False, alpha: float = 1.0, lineType: int = cv2.LINE_AA) -> np.ndarray

Draw a polygon from float points, optionally filled with transparency, in place.

cv.polylines and cv.fillPoly need an int32 (N, 1, 2) array and draw opaque only; a translucent fill (segmentation polygons, zones) takes a copy and cv.addWeighted every time.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
points Sequence[Sequence[float]] | ndarray

(N, 2) vertices; floats are rounded.

required
color Color

Outline and fill color.

required
thickness int

Outline thickness; 0 draws no outline.

2
closed bool

Connect the last vertex to the first (ignored when fill is set).

True
fill bool

Fill the polygon.

False
alpha float

Opacity of the drawing, from 0 to 1 (applied to the outline and the fill).

1.0
lineType int

As for cv.polylines.

LINE_AA

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If points is not 2-D or not finite, or alpha is outside [0, 1].

drawSkeleton

drawSkeleton(img: ndarray, keypoints: Sequence[Sequence[float]] | ndarray, connections: Sequence[tuple[int, int]] = COCO_SKELETON, colors: Sequence[Color] | Color | None = None, radius: int = 4, thickness: int = 2, minScore: float = 0.0) -> np.ndarray

Draw pose keypoints and the limbs between them, in place.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
keypoints Sequence[Sequence[float]] | ndarray

(K, 2) coordinates or (K, 3) with a confidence score in the third column.

required
connections Sequence[tuple[int, int]]

Pairs of keypoint indices to join; :data:COCO_SKELETON by default. Pairs with an index outside keypoints are skipped, so partial detections draw fine.

COCO_SKELETON
colors Sequence[Color] | Color | None

One color per connection, one color for all, or None for :func:distinctColors. Each joint takes the color of its first connection.

None
radius int

Joint circle radius; 0 draws limbs only.

4
thickness int

Limb line thickness.

2
minScore float

Keypoints with a score below this are not drawn (and neither are their limbs). Keypoints at (0, 0) with no score column are also skipped, the usual marker for "not detected".

0.0

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If keypoints has fewer than 2 columns, radius is negative, or colors has a different length than connections.

COCO_SKELETON module-attribute

COCO_SKELETON: tuple[tuple[int, int], ...] = ((0, 1), (0, 2), (1, 3), (2, 4), (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16))

Keypoint pairs of the 17-keypoint COCO skeleton (nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles).

drawTrajectory

drawTrajectory(img: ndarray, points: Sequence[Sequence[float]] | ndarray, color: Color | None = None, thickness: int = 2, fade: bool = True, maxPoints: int | None = None, endColor: Color | None = None) -> np.ndarray

Draw a track (object path, mouse trail) as a polyline that fades out towards its oldest points, in place.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
points Sequence[Sequence[float]] | ndarray

(N, 2) positions from oldest to newest; floats are rounded.

required
color Color | None

Color at the newest point; None uses green.

None
thickness int

Line thickness at the newest segment.

2
fade bool

Darken and thin the line towards the oldest point. False draws a plain polyline.

True
maxPoints int | None

Only draw the last maxPoints positions.

None
endColor Color | None

Color at the oldest point when fading; None fades towards black (or the image's zero level).

None

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If points is not 2-D or not finite, or maxPoints is not positive.

drawCrosshair

drawCrosshair(img: ndarray, center: Sequence[float], color: Color, size: int = 20, gap: int = 4, thickness: int = 1, lineType: int = cv2.LINE_AA) -> np.ndarray

Draw a crosshair (four ticks around a center with a gap), in place.

cv.drawMarker draws a full cross that covers the point of interest.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
center Sequence[float]

(x, y); floats are rounded.

required
color Color

Line color.

required
size int

Half length of the crosshair in pixels, from the center to the tip of a tick.

20
gap int

Empty radius around the center.

4
thickness int

Line thickness.

1
lineType int

As for cv.line.

LINE_AA

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If size is not positive, gap is negative or not smaller than size.

drawTextBlock

drawTextBlock(img: ndarray, lines: Sequence[str] | str, org: tuple[int, int] = (10, 10), fontScale: float = 0.5, color: Color = (255, 255, 255), background: Color | None = (0, 0, 0), alpha: float = 0.6, padding: int = 6, lineSpacing: float = 1.3, thickness: int = 1) -> np.ndarray

Write several lines of text on a translucent panel (an on-screen display), in place.

cv.putText writes one line, with no background, and needs getTextSize math for the line height.

Parameters:

Name Type Description Default
img ndarray

8-bit image to draw on.

required
lines Sequence[str] | str

Text lines (a single string is split at newlines). The Hershey font covers ASCII only.

required
org tuple[int, int]

Top-left corner (x, y) of the panel.

(10, 10)
fontScale float

Hershey font size.

0.5
color Color

Text color.

(255, 255, 255)
background Color | None

Panel color; None draws text only.

(0, 0, 0)
alpha float

Opacity of the panel, from 0 to 1.

0.6
padding int

Space in pixels between the text and the panel border.

6
lineSpacing float

Line height as a multiple of the text height.

1.3
thickness int

Text stroke thickness.

1

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If img is not 8-bit, alpha is outside [0, 1], padding is negative, or fontScale / lineSpacing is not positive.

drawFPS

drawFPS(img: ndarray, fps: float, org: tuple[int, int] = (10, 10), fontScale: float = 0.6) -> np.ndarray

Write "FPS: 29.9" on a translucent panel, in place (see :func:drawTextBlock).

Raises:

Type Description
ValueError

If fps is not finite.

drawProgressBar

drawProgressBar(img: ndarray, progress: float, org: tuple[int, int], size: tuple[int, int] = (200, 12), color: Color = (0, 200, 0), background: Color = (60, 60, 60), border: Color | None = None) -> np.ndarray

Draw a horizontal progress bar filled to progress (0 to 1), in place.

Parameters:

Name Type Description Default
img ndarray

Image to draw on.

required
progress float

Fraction done, clipped to [0, 1].

required
org tuple[int, int]

Top-left corner (x, y).

required
size tuple[int, int]

Bar size as (width, height).

(200, 12)
color Color

Fill color.

(0, 200, 0)
background Color

Track color.

(60, 60, 60)
border Color | None

Outline color; None draws no outline.

None

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If progress is not finite or size is not positive.

drawLegend

drawLegend(img: ndarray, labels: Sequence[str], colors: Sequence[Color] | None = None, org: tuple[int, int] = (10, 10), swatch: int = 14, fontScale: float = 0.5, color: Color = (255, 255, 255), background: Color | None = (0, 0, 0), alpha: float = 0.6, padding: int = 6) -> np.ndarray

Draw a legend panel with a color swatch next to each label, in place.

Pairs with :func:drawBoxes / :func:distinctColors to explain which color is which class.

Parameters:

Name Type Description Default
img ndarray

8-bit image to draw on.

required
labels Sequence[str]

One text per entry.

required
colors Sequence[Color] | None

One color per entry; None uses :func:distinctColors.

None
org tuple[int, int]

Top-left corner (x, y) of the panel.

(10, 10)
swatch int

Side of the color squares in pixels.

14
fontScale float

Hershey font size.

0.5
color Color

Text color.

(255, 255, 255)
background Color | None

Panel color; None draws no panel.

(0, 0, 0)
alpha float

Opacity of the panel.

0.6
padding int

Space between the entries and the panel border.

6

Returns:

Type Description
ndarray

img.

Raises:

Type Description
ValueError

If colors has a different length than labels, swatch is not positive, or see :func:drawTextBlock.

compareImages

compareImages(a: ndarray, b: ndarray, mode: str = 'side', split: float = 0.5, labels: Sequence[str] | None = None, gap: int = 0, color: Color = (0, 0, 0), fontScale: float = 0.5) -> np.ndarray

Put two images next to each other for a before/after comparison, as a new BGR image.

Parameters:

Name Type Description Default
a ndarray

8-bit grayscale, BGR or BGRA image (the reference size).

required
b ndarray

8-bit image; resized to the size of a when it differs.

required
mode str

"side" (left/right), "vertical" (top/bottom), "split" (left part of a and right part of b with a divider), "blend" (cv.addWeighted with split as the weight of b) or "diff" (absolute difference, colorized with cv.COLORMAP_JET).

'side'
split float

Position of the divider as a fraction of the width for "split"; blend weight for "blend".

0.5
labels Sequence[str] | None

Two titles drawn above the images for "side" / "vertical"; ignored by the other modes.

None
gap int

Space between the images for "side" / "vertical"; divider thickness for "split".

0
color Color

Color of the gap, the divider and the title strips.

(0, 0, 0)
fontScale float

Hershey font size of the labels.

0.5

Returns:

Type Description
ndarray

A new BGR image.

Raises:

Type Description
ValueError

If an image is not 8-bit, mode is unknown, split is outside [0, 1], gap is negative or labels does not have two entries.

labeledMontage

labeledMontage(images: Sequence[ndarray], labels: Sequence[str], cols: int | None = None, cellSize: tuple[int, int] | None = None, gap: int = 4, color: Color = (0, 0, 0), fontScale: float = 0.5) -> np.ndarray

Arrange images in a grid with a title strip above each one, as a new BGR image.

:func:montage places the images only; naming each tile ("input", "blur 3", "blur 5") is the usual next step.

Parameters:

Name Type Description Default
images Sequence[ndarray]

8-bit images; sizes and channels may differ.

required
labels Sequence[str]

One title per image.

required
cols int | None

Number of columns; by default as square as possible.

None
cellSize tuple[int, int] | None

Fit every image into (width, height) first with :func:letterbox.

None
gap int

Space between the cells.

4
color Color

Color of the gaps, the padding and the title strips.

(0, 0, 0)
fontScale float

Hershey font size of the titles.

0.5

Returns:

Type Description
ndarray

A new BGR image.

Raises:

Type Description
ValueError

If images is empty, labels has a different length, or cols is not positive.

blendImages

blendImages(images: Sequence[ndarray], weights: Sequence[float] | None = None) -> np.ndarray

Average any number of images with optional weights (cv.addWeighted takes exactly two).

Images are resized to the first one and converted to its channel count; the weights are normalized, so [1, 1, 2] means the last image counts twice.

Parameters:

Name Type Description Default
images Sequence[ndarray]

8-bit grayscale, BGR or BGRA images.

required
weights Sequence[float] | None

One non-negative weight per image; None gives equal weights.

None

Returns:

Type Description
ndarray

A new 8-bit image with the shape of images[0].

Raises:

Type Description
ValueError

If images is empty, an image is not 8-bit, or weights has a different length, a negative or non-finite entry, or sums to zero.

videoio

readFrames

readFrames(source: VideoSource, step: int = 1, start: int = 0) -> Iterator[np.ndarray]

Iterate over the frames of a video file, stream or camera.

Replaces the usual cap = cv.VideoCapture(...) / while True: ok, frame = cap.read() / cap.release() loop: for frame in cv.readFrames("video.mp4", step=5): .... The capture is released when the iteration ends, also on break.

Parameters:

Name Type Description Default
source VideoSource

File path or URL, or a camera index.

required
step int

Yield every step-th frame (skipped frames are not decoded).

1
start int

Number of frames to skip at the beginning.

0

Returns:

Type Description
Iterator[ndarray]

An iterator over the frames (8-bit BGR images).

Raises:

Type Description
OSError

If the source cannot be opened.

ValueError

If step < 1 or start < 0.

writeVideo

writeVideo(filename: str | PathLike[str], frames: Iterable[ndarray], fps: float, fourcc: str | None = None) -> int

Write frames to a video file.

The frame size and color mode are taken from the first frame, and the codec from the file extension (.avi: MJPG, .mp4/.m4v/.mov: mp4v) unless fourcc is given.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Output path.

required
frames Iterable[ndarray]

8-bit BGR or grayscale frames, all of the same size. Any iterable works, including a generator such as :func:readFrames.

required
fps float

Frame rate.

required
fourcc str | None

Four-character codec code, e.g. "XVID".

None

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
ValueError

If there are no frames, a frame has a different size or channel count than the first one or is not 8-bit grayscale/BGR, fps is not positive, or no codec is known for the file extension.

OSError

If the video writer cannot be opened (for example, the codec is not available).

readFrameAt

readFrameAt(source: str | PathLike[str], index: int | None = None, seconds: float | None = None) -> np.ndarray | None

Read a single frame of a video file, by frame number or by time, e.g. for a thumbnail.

Replaces opening a capture, seeking with cap.set(cv.CAP_PROP_POS_FRAMES, ...), reading and releasing. Seeking is exact for most files, but may land on a nearby key frame for some codecs.

Parameters:

Name Type Description Default
source str | PathLike[str]

Video file path or URL.

required
index int | None

Frame number, starting at 0.

None
seconds float | None

Time from the start, in seconds. Give either index or seconds.

None

Returns:

Type Description
ndarray | None

The frame, or None if the video is shorter.

Raises:

Type Description
OSError

If the video cannot be opened.

ValueError

If not exactly one of index and seconds is given, or it is negative.

videoInfo

videoInfo(source: VideoSource) -> VideoInfo

Return the size, frame rate and frame count of a video in one call.

Raises:

Type Description
OSError

If the source cannot be opened.

VideoInfo

Bases: NamedTuple

Properties of a video, as reported by OpenCV. frameCount may be an estimate for some formats.

width instance-attribute

width: int

height instance-attribute

height: int

fps instance-attribute

fps: float

frameCount instance-attribute

frameCount: int

duration property

duration: float

Length in seconds (frameCount / fps), or 0.0 if the frame rate is unknown.

Readers and writers

VideoReader

A cv.VideoCapture that is a context manager, an iterator and knows its properties.

cv.VideoCapture needs isOpened() checks, a while True: ok, frame = cap.read() loop, get() calls with CAP_PROP_* constants and a release(). This class opens the source (or raises), iterates over the frames, exposes width/height/fps/frameCount and seeks by frame or by time.

Parameters:

Name Type Description Default
source VideoSource

File path or URL, or a camera index.

required

Raises:

Type Description
OSError

If the source cannot be opened.

Example
with VideoReader("video.mp4") as video:
    for frame in video:
        ...

info instance-attribute

info = VideoInfo(width=int(self._cap.get(cv2.CAP_PROP_FRAME_WIDTH)), height=int(self._cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), fps=float(self._cap.get(cv2.CAP_PROP_FPS)), frameCount=max(0, int(self._cap.get(cv2.CAP_PROP_FRAME_COUNT))))

Size, frame rate and frame count (see :class:VideoInfo).

width property

width: int

Frame width in pixels.

height property

height: int

Frame height in pixels.

fps property

fps: float

Frame rate, or 0.0 when unknown (cameras and some streams).

frameCount property

frameCount: int

Number of frames (an estimate for some formats, 0 for cameras).

position property

position: int

Index of the frame that the next :meth:read returns.

isOpened property

isOpened: bool

False after :meth:release.

read

read() -> np.ndarray | None

Read the next frame, or return None at the end (instead of a (False, None) tuple).

seek

seek(index: int) -> None

Move to frame index (0-based), so that the next :meth:read returns it.

Seeking is exact for most files, but may land on a nearby key frame for some codecs. Not supported by cameras.

Raises:

Type Description
ValueError

If index is negative.

seekTime

seekTime(seconds: float) -> None

Move to the frame at seconds from the start (see :meth:seek).

Raises:

Type Description
ValueError

If seconds is negative or not finite.

frames

frames(step: int = 1, start: int = 0, end: int | None = None) -> Iterator[np.ndarray]

Iterate over the frames from start to end (exclusive), every step-th one.

Frames are skipped with grab() (no decoding), which also works for cameras; start seeks when it is before the current position.

Raises:

Type Description
ValueError

If step < 1, start < 0 or end < start.

release

release() -> None

Release the capture. Safe to call more than once.

VideoWriterEx

A cv.VideoWriter that takes its codec, size and color mode from the first frame written.

cv.VideoWriter must be given a fourcc code, the frame size and isColor before the first frame exists, silently writes nothing when a frame has the wrong size, and fails on a missing folder. This writer is opened lazily on the first :meth:write, chooses the codec from the file extension (.avi: MJPG, .mp4/.m4v/.mov: mp4v), converts grayscale frames to BGR when writing color, and validates every frame. Non-ASCII paths are supported on Windows (cv.VideoWriter accepts them, unlike cv.imwrite).

Parameters:

Name Type Description Default
filename str | PathLike[str]

Output path.

required
fps float

Frame rate.

required
fourcc str | None

Four-character codec code, e.g. "XVID". By default chosen from the file extension.

None
isColor bool | None

True for a BGR file, False for grayscale; by default taken from the first frame.

None
makeDirs bool

Create missing parent directories.

False

Raises:

Type Description
ValueError

If fps is not positive, fourcc has not 4 characters or no codec is known for the extension.

Example
with VideoWriterEx("out.mp4", fps=30) as writer:
    for frame in frames:
        writer.write(frame)

frameCount property

frameCount: int

Number of frames written so far.

size property

size: tuple[int, int] | None

Frame size (width, height), or None before the first frame.

isColor property

isColor: bool | None

Whether the file is written in color, or None before the first frame when not given.

isOpened property

isOpened: bool

True between the first :meth:write and :meth:release.

write

write(frame: ndarray) -> None

Write one 8-bit grayscale or BGR frame; the first one opens the file.

Raises:

Type Description
ValueError

If the frame is not 8-bit grayscale/BGR, or has a different size than the first frame, or is grayscale/color while the file is the other and cannot be converted.

OSError

If the writer cannot be opened (for example, the codec is not available).

release

release() -> None

Close the file. Safe to call more than once; nothing is written if no frame was.

CameraStream

Capture frames in a background thread, always keeping only the latest one.

cv.VideoCapture.read() on a live camera or RTSP stream returns frames from an internal buffer, so a slow consumer gets stale frames that lag seconds behind. This reads continuously in a daemon thread and drops the frames nobody asked for, so :meth:read always returns the newest frame. Works on files too (where it plays them as fast as it can).

Parameters:

Name Type Description Default
source VideoSource

Camera index, URL or file path.

required
maxWait float

Seconds to wait in :meth:read for the first frame before giving up.

5.0

Raises:

Type Description
OSError

If the source cannot be opened.

Example
with CameraStream(0) as camera:
    while True:
        frame = camera.read()
        ...

isRunning property

isRunning: bool

True while the capture thread runs.

ended property

ended: bool

True once the source stopped delivering frames (end of file, camera lost).

fps property

fps: float

Measured capture frame rate (0.0 until a few frames arrived).

start

start() -> CameraStream

Start the capture thread. Returns self so it can be chained.

read

read() -> np.ndarray | None

Return the latest frame, or None if none arrived within maxWait or the stream ended.

Returns the same frame again when no new one arrived in the meantime, as long as the source is still running. Once the source has ended (:attr:ended), the last frame is returned once more if it has not been read yet, then None forever, so a while (frame := stream.read()) is not None loop terminates on a file. The thread is started if needed.

stop

stop() -> None

Stop the thread and release the capture. Safe to call more than once.

FPSCounter

Measure a loop's frame rate as a moving average over the last window ticks.

Parameters:

Name Type Description Default
window int

Number of ticks the average covers.

30
clock Callable[[], float]

Time source returning seconds (time.perf_counter by default); injectable for tests.

perf_counter

Raises:

Type Description
ValueError

If window < 2.

Example
counter = FPSCounter()
for frame in cv.readFrames(0):
    fps = counter.tick()

fps property

fps: float

Frames per second over the ticks in the window.

tick

tick() -> float

Record a frame and return the current frame rate (0.0 until two ticks happened).

reset

reset() -> None

Forget all ticks.

frameToTime

frameToTime(index: int, fps: float) -> float

Convert a frame index to seconds from the start.

Raises:

Type Description
ValueError

If fps is not positive.

timeToFrame

timeToFrame(seconds: float, fps: float) -> int

Convert seconds from the start to the frame index shown at that time (rounded down).

Raises:

Type Description
ValueError

If fps is not positive or seconds is not finite.

formatTimestamp

formatTimestamp(seconds: float, ms: bool = True) -> str

Format seconds as "HH:MM:SS.mmm" (or "HH:MM:SS" with ms=False), for overlays and file names.

Raises:

Type Description
ValueError

If seconds is negative or not finite.

Video files

extractFrames

extractFrames(source: VideoPath, outDir: VideoPath, step: int = 1, start: int = 0, end: int | None = None, ext: str = '.jpg', prefix: str = 'frame_', digits: int = 6, progress: Callable[[int, int], None] | None = None) -> list[Path]

Save the frames of a video as image files named by frame index, e.g. frame_000012.jpg.

The read loop, zero-padded names and the non-ASCII path problem of cv.imwrite on Windows are handled (frames are written with :func:imwriteEx). The directory is created if needed.

Parameters:

Name Type Description Default
source VideoPath

Video file path or URL.

required
outDir VideoPath

Directory to write the images into.

required
step int

Save every step-th frame.

1
start int

First frame index to save.

0
end int | None

Stop before this frame index (None: until the end).

None
ext str

Image file extension, e.g. ".png".

'.jpg'
prefix str

File name prefix.

'frame_'
digits int

Number of digits of the zero-padded frame index.

6
progress Callable[[int, int], None] | None

Called as progress(index, frameCount) after each saved frame (frameCount may be 0).

None

Returns:

Type Description
list[Path]

The paths of the saved images, in frame order.

Raises:

Type Description
OSError

If the video cannot be opened or an image cannot be written.

ValueError

If step < 1, start < 0 or end < start.

trimVideo

trimVideo(source: VideoPath, dst: VideoPath, start: float, end: float | None = None, byTime: bool = True, fourcc: str | None = None) -> int

Cut a part of a video into a new file.

Parameters:

Name Type Description Default
source VideoPath

Video file path.

required
dst VideoPath

Output path; the codec is chosen from its extension (see :func:writeVideo).

required
start float

Start, in seconds (or a frame index when byTime=False).

required
end float | None

End (exclusive), in seconds or frames; None for the end of the video.

None
byTime bool

Whether start/end are seconds (True) or frame indices.

True
fourcc str | None

Codec override.

None

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
OSError

If the source cannot be opened or the writer cannot be created.

ValueError

If start is negative, end < start, or the range contains no frames.

concatVideos

concatVideos(sources: Sequence[VideoPath], dst: VideoPath, fourcc: str | None = None) -> int

Join videos one after another into one file, resized to the size of the first one.

Parameters:

Name Type Description Default
sources Sequence[VideoPath]

Video file paths, in order.

required
dst VideoPath

Output path.

required
fourcc str | None

Codec override.

None

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
OSError

If a source cannot be opened or the writer cannot be created.

ValueError

If sources is empty.

resizeVideo

resizeVideo(source: VideoPath, dst: VideoPath, size: tuple[int, int] | None = None, scale: float | None = None, width: int | None = None, height: int | None = None, interpolation: int | None = None, fourcc: str | None = None) -> int

Resize every frame of a video, keeping the aspect ratio when only one dimension is given.

Give exactly one of size ((width, height)), scale, or width and/or height (as for :func:resizeEx).

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
OSError

If the source cannot be opened or the writer cannot be created.

ValueError

If no or conflicting target sizes are given, or they are not positive.

videoToGif

videoToGif(source: VideoPath, dst: VideoPath, fps: float | None = None, size: tuple[int, int] | None = None, step: int = 1, maxFrames: int | None = None, loop: int = 0) -> int

Convert a video (or a part of it) to an animated GIF with Pillow.

cv.VideoWriter cannot write GIFs. Frames are converted from BGR to RGB; step and maxFrames keep the file small.

Parameters:

Name Type Description Default
source VideoPath

Video file path.

required
dst VideoPath

Output .gif path.

required
fps float | None

Playback frame rate of the GIF (default: the video's rate divided by step).

None
size tuple[int, int] | None

Output (width, height); None keeps the frame size.

None
step int

Take every step-th frame.

1
maxFrames int | None

Stop after this many frames.

None
loop int

Number of repetitions, 0 for forever.

0

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
OSError

If the source cannot be opened.

ValueError

If the video has no frames, step < 1, maxFrames < 1 or fps is not positive.

imagesToVideo

imagesToVideo(images: Sequence[VideoPath | ndarray], dst: VideoPath, fps: float = 30, fourcc: str | None = None) -> int

Write image files and/or arrays to a video file, e.g. to make a time-lapse from a folder.

Paths are read with :func:imreadEx (any path, non-ASCII included); see :func:listImages to collect them. All images must have the same size, as for :func:writeVideo.

Returns:

Type Description
int

The number of frames written.

Raises:

Type Description
OSError

If an image file cannot be read.

ValueError

As :func:writeVideo (no images, size mismatch, bad fps or codec).

detectScenes

detectScenes(source: VideoPath, threshold: float = 30.0, minLength: int = 15, step: int = 1) -> list[int]

Find the frame indices where the scene changes (hard cuts).

Frames are downscaled to about 64 pixels wide and converted to grayscale; a cut is reported where the mean absolute difference between consecutive compared frames exceeds threshold (0-255). Gradual fades and very fast motion may be missed or over-reported; for those use a dedicated library such as PySceneDetect.

Parameters:

Name Type Description Default
source VideoPath

Video file path.

required
threshold float

Mean absolute gray difference (0-255) that counts as a cut; lower is more sensitive.

30.0
minLength int

Minimum number of frames between two cuts.

15
step int

Compare every step-th frame (faster, but cuts are reported at a multiple of step).

1

Returns:

Type Description
list[int]

The indices of the first frame of each new scene, in increasing order (the first frame is not included).

Raises:

Type Description
OSError

If the video cannot be opened.

ValueError

If threshold is negative or not finite, minLength < 1 or step < 1.

sampleFrames

sampleFrames(source: VideoPath, count: int) -> list[np.ndarray]

Read count evenly spaced frames of a video, e.g. for a preview or a dataset sample.

Seeks with CAP_PROP_POS_FRAMES (like :func:readFrameAt), so it is fast on long videos, but may land on a nearby key frame for some codecs. Fewer frames are returned when the video is shorter than count.

Raises:

Type Description
OSError

If the video cannot be opened.

ValueError

If count < 1.

videoThumbnail

videoThumbnail(source: VideoPath, count: int = 4, size: tuple[int, int] | None = None, cols: int | None = None, gap: int = 0) -> np.ndarray

Make a contact-sheet image of count evenly spaced frames.

Parameters:

Name Type Description Default
source VideoPath

Video file path.

required
count int

Number of frames.

4
size tuple[int, int] | None

(width, height) of each cell; None keeps the frame size.

None
cols int | None

Number of columns of the grid (default: as square as possible, see :func:montage).

None
gap int

Space in pixels between the cells.

0

Returns:

Type Description
ndarray

The montage image.

Raises:

Type Description
OSError

If the video cannot be opened.

ValueError

If count < 1 or the video has no frames.

highgui

imshowInline

imshowInline(img: ndarray, maxSize: tuple[int, int] | None = None, ext: str = '.png') -> None

Show an image inline in a Jupyter notebook (cv.imshow does not work there).

The image is encoded with cv.imencode, so BGR images show their real colors without a BGR-to-RGB conversion, unlike matplotlib.pyplot.imshow.

Parameters:

Name Type Description Default
img ndarray

8-bit grayscale, BGR or BGRA image.

required
maxSize tuple[int, int] | None

If given, shrink larger images to fit into (width, height).

None
ext str

Encoding used for the notebook output, ".png" (lossless) or ".jpg" (smaller).

'.png'

Raises:

Type Description
ImportError

If IPython is not installed (Jupyter always provides it).

ValueError

If img is empty or cannot be encoded.

imshowEx

imshowEx(winname: str, img: ndarray, maxSize: tuple[int, int] = (1280, 720)) -> None

cv.imshow that shrinks images larger than maxSize so the whole image fits on the screen.

cv.imshow shows images at 100%, so a 4000x3000 photo is cropped by the screen. The aspect ratio is kept, and images that already fit are shown unchanged.

Parameters:

Name Type Description Default
winname str

Window name.

required
img ndarray

Image to show.

required
maxSize tuple[int, int]

Largest displayed size, as (width, height).

(1280, 720)

Raises:

Type Description
ValueError

If img is empty or maxSize is not positive.

calib3d

Camera calibration helpers; the OpenCV calib3d functions (cv.calibrateCamera, cv.undistort, ...) stay available as they are.

Camera calibration

CameraCalibration

Bases: NamedTuple

The result of :func:calibrateCameraEx (everything cv.calibrateCamera returns, plus the image size).

cameraMatrix instance-attribute

cameraMatrix: ndarray

Intrinsic matrix, shape (3, 3) float64.

distCoeffs instance-attribute

distCoeffs: ndarray

Distortion coefficients (k1, k2, p1, p2, k3, ...), shape (1, N) float64.

imageSize instance-attribute

imageSize: tuple[int, int]

Size of the calibration images as (width, height).

rms instance-attribute

rms: float

Overall RMS reprojection error in pixels (below 1.0 is a good calibration).

rvecs instance-attribute

rvecs: tuple[ndarray, ...]

Rotation vector of the board in each view, shape (3, 1) each.

tvecs instance-attribute

tvecs: tuple[ndarray, ...]

Translation vector of the board in each view, shape (3, 1) each.

usedViews class-attribute instance-attribute

usedViews: tuple[int, ...] = ()

Indices into the views given to :func:calibrateCameraEx of the views where the board was found; rvecs[i] / tvecs[i] belong to views[usedViews[i]]. Empty for calibrations loaded from files written before this field existed.

makeChessboard

makeChessboard(patternSize: tuple[int, int], squareSize: int = 50, border: int = 1) -> np.ndarray

Render a chessboard image with the given number of inner corners, for printing or for tests.

OpenCV detects a board by its inner corners, so a board with (7, 6) inner corners has 8 x 7 squares. The top-left square is black.

Parameters:

Name Type Description Default
patternSize tuple[int, int]

Inner corners as (columns, rows), the value to pass to :func:findChessboardEx later.

required
squareSize int

Square side in pixels.

50
border int

White margin around the board, in squares (the detector needs some white around the board).

1

Returns:

Type Description
ndarray

8-bit grayscale image with columns + 1 + 2 * border by rows + 1 + 2 * border squares of

ndarray

squareSize pixels.

Raises:

Type Description
ValueError

If patternSize has fewer than 2 corners per side, squareSize is not positive or border is negative.

objectPointsGrid

objectPointsGrid(patternSize: tuple[int, int], squareSize: float = 1.0) -> np.ndarray

Return the 3D coordinates of the inner chessboard corners, lying in the z = 0 plane.

The objp = np.zeros((cols * rows, 3)); objp[:, :2] = np.mgrid[...].T.reshape(-1, 2) boilerplate from the OpenCV tutorial, in the row-major order cv.findChessboardCorners returns the corners in.

Parameters:

Name Type Description Default
patternSize tuple[int, int]

Inner corners per row and column as (columns, rows), like cv.findChessboardCorners.

required
squareSize float

Side of one square in your unit (mm, cm, ...); the translations come out in the same unit.

1.0

Returns:

Type Description
ndarray

Points of shape (columns * rows, 3) float32.

Raises:

Type Description
ValueError

If patternSize has fewer than 2 corners per side or squareSize is not positive.

findChessboardEx

findChessboardEx(src: ndarray, patternSize: tuple[int, int], refine: bool = True, flags: int | None = None) -> np.ndarray | None

Find and refine the inner corners of a chessboard in one call.

cv.findChessboardCorners returns (found, corners) with corners of shape (N, 1, 2) that still need cv.cornerSubPix on a grayscale copy for sub-pixel accuracy. This converts to grayscale, uses the more robust cv.findChessboardCornersSB when the build has it, refines, and returns a flat point array.

Parameters:

Name Type Description Default
src ndarray

Grayscale or BGR(A) image.

required
patternSize tuple[int, int]

Inner corners as (columns, rows).

required
refine bool

Run cv.cornerSubPix on the corners (not needed after findChessboardCornersSB, which is already sub-pixel accurate, but harmless).

True
flags int | None

cv.CALIB_CB_* flags; None picks the detector's default.

None

Returns:

Type Description
ndarray | None

The corners as (columns * rows, 2) float32, or None if the board was not found.

Raises:

Type Description
ValueError

If src is empty or patternSize is invalid.

calibrateCameraEx

calibrateCameraEx(views: Sequence[ndarray], patternSize: tuple[int, int], squareSize: float = 1.0, imageSize: tuple[int, int] | None = None, flags: int = 0) -> CameraCalibration

Calibrate a camera from chessboard images (or already detected corners).

The whole tutorial loop: detect the board in every image with :func:findChessboardEx (views where it is not found are skipped and listed by their absence in usedViews), build the object points with :func:objectPointsGrid, and run cv.calibrateCamera.

Parameters:

Name Type Description Default
views Sequence[ndarray]

Images of the chessboard, or corner arrays of shape (N, 2) such as :func:findChessboardEx returns (then imageSize is required). Mixing the two is not supported.

required
patternSize tuple[int, int]

Inner corners as (columns, rows).

required
squareSize float

Side of one square in your unit; tvecs come out in the same unit.

1.0
imageSize tuple[int, int] | None

(width, height) of the images, needed only when views are corner arrays.

None
flags int

cv.CALIB_* flags for cv.calibrateCamera.

0

Returns:

Name Type Description
A CameraCalibration

class:CameraCalibration. Its rvecs / tvecs have one entry per used view, so when a board was

CameraCalibration

missed they are shorter than views; usedViews maps them back to the input indices.

Raises:

Type Description
ValueError

If fewer than 3 views contain the board, imageSize is missing for corner input, a corner array has the wrong number of points, or patternSize / squareSize are invalid.

reprojectionErrors

reprojectionErrors(calib: CameraCalibration, patternSize: tuple[int, int], squareSize: float, cornersList: Sequence[ndarray | None]) -> np.ndarray

Return the RMS reprojection error of every view, to spot the bad images in a calibration set.

cv.calibrateCamera reports a single overall error; per-view errors need cv.projectPoints and cv.norm in a loop. Views with an error well above the others are usually blurred or mis-detected: drop them and calibrate again.

Parameters:

Name Type Description Default
calib CameraCalibration

The calibration whose rvecs / tvecs belong to cornersList.

required
patternSize tuple[int, int]

Inner corners as (columns, rows).

required
squareSize float

Square size used for the calibration.

required
cornersList Sequence[ndarray | None]

The detected corners of each view, (N, 2) each: either one per used view (same order as calib.rvecs), or one per original view given to :func:calibrateCameraEx (then the views listed in calib.usedViews are picked, so the output of :func:findChessboardEx for every image can be passed as is, None entries included).

required

Returns:

Type Description
ndarray

One RMS error in pixels per used view, shape (len(calib.rvecs),) float64.

Raises:

Type Description
ValueError

If the number of views matches neither calib.rvecs nor calib.usedViews, a selected entry is None, or a corner array has the wrong size.

undistortEx

undistortEx(src: ndarray, calib: CameraCalibration | ndarray, distCoeffs: ndarray | None = None, alpha: float = 0.0, crop: bool = True) -> np.ndarray

Undistort an image with cv.getOptimalNewCameraMatrix + cv.undistort and crop the valid area.

cv.undistort alone keeps the original camera matrix, which leaves black curved borders or cuts off content; the tutorial recipe computes a new matrix and crops to the returned ROI. This does both.

Parameters:

Name Type Description Default
src ndarray

Image taken with the calibrated camera (any channel count).

required
calib CameraCalibration | ndarray

A :class:CameraCalibration, or the (3, 3) camera matrix (then pass distCoeffs).

required
distCoeffs ndarray | None

Distortion coefficients when calib is a matrix.

None
alpha float

Free scaling parameter of cv.getOptimalNewCameraMatrix: 0 keeps only valid pixels (no black corners), 1 keeps every source pixel (black corners).

0.0
crop bool

Crop to the valid ROI. With False the result has the size of src.

True

Returns:

Type Description
ndarray

The undistorted image, same dtype and channels as src.

Raises:

Type Description
ValueError

If src is empty, distCoeffs is missing for a matrix input, alpha is not in [0, 1], or src has a different size than the calibration images (the matrix would not apply).

saveCalibration

saveCalibration(filename: str | PathLike[str], calib: CameraCalibration) -> None

Save a calibration as a JSON file.

OpenCV's cv.FileStorage writes YAML/XML and cannot open non-ASCII paths on Windows; JSON is readable everywhere and works with any path. Keys: cameraMatrix, distCoeffs, imageSize, rms, rvecs, tvecs, usedViews.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path to write to (.json).

required
calib CameraCalibration

The calibration to save.

required

loadCalibration

loadCalibration(filename: str | PathLike[str]) -> CameraCalibration

Load a calibration written by :func:saveCalibration.

Parameters:

Name Type Description Default
filename str | PathLike[str]

Path of the JSON file.

required

Returns:

Name Type Description
The CameraCalibration

class:CameraCalibration.

Raises:

Type Description
OSError

If the file cannot be read.

ValueError

If the file is not valid JSON or lacks a required key.

dnn

cv.dnn is the cv2u.dnn package: it adds the helpers below and passes every cv2.dnn name (cv.dnn.readNet, cv.dnn.NMSBoxes, ...) through.

Inference

PreprocessInfo

Bases: NamedTuple

How :func:preprocessImage mapped the image into the network input; needed to map boxes back.

scale instance-attribute

scale: tuple[float, float]

(sx, sy): a point (x, y) of the original image is at (x * sx + left, y * sy + top) in the blob.

pad instance-attribute

pad: tuple[int, int]

(left, top) letterbox padding in pixels ((0, 0) without letterboxing).

inputSize instance-attribute

inputSize: tuple[int, int]

Network input (width, height).

originalSize instance-attribute

originalSize: tuple[int, int]

Original image (width, height).

Detections

Bases: NamedTuple

Decoded detections in the coordinates of the original image, best score first.

boxes instance-attribute

boxes: ndarray

(N, 4) float32 boxes (x, y, width, height), clipped to the original image.

scores instance-attribute

scores: ndarray

(N,) float32 confidences.

classIds instance-attribute

classIds: ndarray

(N,) int32 class indices.

size property

size: int

Number of detections (len() of a named tuple is always its field count, 3).

loadModel

loadModel(path: str | PathLike[str], config: str | PathLike[str] | None = None, backend: int | None = None, target: int | None = None, preferGpu: bool = False) -> Any

Load a model with cv.dnn.readNet, from any path, with clear errors.

cv.dnn.readNet cannot open non-ASCII paths on Windows and reports a missing file as a C++ assertion. ONNX, TFLite and TensorFlow models are read from memory instead (readNetFromONNX(buffer) etc.), so the path only has to be readable by Python; other formats fall back to readNet(path, config).

Parameters:

Name Type Description Default
path str | PathLike[str]

Model file (.onnx, .tflite, .pb, or anything readNet understands).

required
config str | PathLike[str] | None

Optional text config for the model (e.g. .pbtxt).

None
backend int | None

cv.dnn.DNN_BACKEND_* to set, or None for OpenCV's default.

None
target int | None

cv.dnn.DNN_TARGET_* to set.

None
preferGpu bool

Use the CUDA backend and target when this OpenCV build has it; silently keeps the default otherwise. Ignored when backend is given.

False

Returns:

Type Description
Any

A cv.dnn.Net.

Raises:

Type Description
FileNotFoundError

If path or config does not exist.

RuntimeError

If this OpenCV build has no dnn module.

readClassNames

readClassNames(path: str | PathLike[str]) -> list[str]

Read class names from a text file, one per line (coco.names style), skipping blank lines.

Opened by Python, so Unicode paths and UTF-8 names (with or without BOM) work everywhere.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

preprocessImage

preprocessImage(src: ndarray, size: tuple[int, int], letterboxPad: bool = True, color: Color = (114, 114, 114), scale: float = 1 / 255, mean: Sequence[float] = (0, 0, 0), swapRB: bool = True, dtype: DTypeLike = np.float32) -> tuple[np.ndarray, PreprocessInfo]

Turn an image into an NCHW blob for Net.setInput and remember how to map results back.

cv.dnn.blobFromImage resizes without keeping the aspect ratio and forgets the geometry, so boxes from the network cannot be mapped back to the image. This letterboxes (like YOLO), normalizes and returns the :class:PreprocessInfo that :func:postprocessDetections needs.

Parameters:

Name Type Description Default
src ndarray

8-bit grayscale, BGR or BGRA image (always fed to the network as 3 channels).

required
size tuple[int, int]

Network input (width, height).

required
letterboxPad bool

Keep the aspect ratio and pad with color (True), or stretch like blobFromImage.

True
color Color

Padding color (BGR).

(114, 114, 114)
scale float

Multiplier applied after mean subtraction (1/255 maps 8-bit pixels to [0, 1]).

1 / 255
mean Sequence[float]

Per-channel values subtracted first, in the channel order of the blob (RGB when swapRB).

(0, 0, 0)
swapRB bool

Convert BGR to RGB, as most trained models expect.

True
dtype DTypeLike

Blob data type.

float32

Returns:

Type Description
tuple[ndarray, PreprocessInfo]

(blob, info): the (1, 3, height, width) blob and the mapping info.

Raises:

Type Description
ValueError

If src is empty, size is not positive, or scale/mean are not finite.

inferImage

inferImage(net: _Net, src: ndarray, outputNames: Sequence[str] | None = None, size: tuple[int, int] | None = None) -> list[np.ndarray]

setInput + forward for every output layer, as a list of arrays.

Net.forward() returns only the first output; getting all of them means asking for getUnconnectedOutLayersNames() every time. cv.dnn also does not accept a plain image.

Parameters:

Name Type Description Default
net _Net

A cv.dnn.Net (or any object with setInput, forward and getUnconnectedOutLayersNames).

required
src ndarray

A ready (1, C, H, W) blob, or an image which is then passed through :func:preprocessImage with size and default options (use :func:preprocessImage yourself when you need the :class:PreprocessInfo to map boxes back).

required
outputNames Sequence[str] | None

Layers to return; all unconnected output layers by default.

None
size tuple[int, int] | None

Network input (width, height), required when src is an image.

None

Returns:

Type Description
list[ndarray]

One array per output layer.

Raises:

Type Description
ValueError

If src is an image and size is missing, or src is neither an image nor a blob.

postprocessDetections

postprocessDetections(output: ArrayLike, info: PreprocessInfo, scoreThreshold: float = 0.25, iouThreshold: float = 0.45, maxCount: int | None = None, boxFormat: str = 'cxcywh', hasObjectness: bool = False, classAgnostic: bool = False, normalized: bool = False, transpose: bool | None = None) -> Detections

Decode a raw YOLO-style detector output into boxes on the original image.

Handles the (1, N, 4 + C) and (1, 4 + C, N) layouts (YOLOv5 to YOLOv11 and similar), an optional objectness column, threshold filtering, undoing the letterbox of :func:preprocessImage, clipping and per-class NMS. cv.dnn leaves all of this to the user.

Parameters:

Name Type Description Default
output ArrayLike

Network output with one row per candidate: 4 box values, optionally an objectness score, then one score per class.

required
info PreprocessInfo

From :func:preprocessImage.

required
scoreThreshold float

Candidates whose best class score (times objectness) is below this are dropped.

0.25
iouThreshold float

NMS overlap threshold.

0.45
maxCount int | None

Keep at most this many detections.

None
boxFormat str

"cxcywh" (YOLO), "xywh" or "xyxy".

'cxcywh'
hasObjectness bool

Column 4 is an objectness score multiplied into the class scores (YOLOv5/v7).

False
classAgnostic bool

Run NMS over all classes at once instead of per class.

False
normalized bool

Box values are in [0, 1] relative to the network input instead of pixels.

False
transpose bool | None

Force the (4 + C, N) layout (True) or (N, 4 + C) (False); None picks the layout whose first axis is the longer one, which is right for every real model but may be wrong for tiny synthetic outputs.

None

Returns:

Type Description
Detections

class:Detections sorted by descending score.

Raises:

Type Description
ValueError

If the output has no class columns, boxFormat is unknown, or a threshold is not finite.

postprocessClassification

postprocessClassification(output: ArrayLike, topK: int = 5, softmax: bool = True) -> list[tuple[int, float]]

Top-k (classId, probability) pairs from a classifier output.

Parameters:

Name Type Description Default
output ArrayLike

Output of shape (1, C) or (C,).

required
topK int

How many classes to return (fewer when the model has fewer classes).

5
softmax bool

Apply :func:softmax first (False when the model already outputs probabilities).

True

Returns:

Type Description
list[tuple[int, float]]

A list sorted by descending probability.

Raises:

Type Description
ValueError

If output is not one vector or topK is not positive.

softmax

softmax(x: ArrayLike, axis: int = -1) -> np.ndarray

Softmax along axis, numerically stable (the maximum is subtracted first).

Raw classifier outputs (logits) need it to become probabilities; OpenCV has no NumPy-level softmax.

Returns:

Type Description
ndarray

A float32 array of the same shape, summing to 1 along axis.

sigmoid

sigmoid(x: ArrayLike) -> np.ndarray

Logistic function 1 / (1 + exp(-x)), for objectness and multi-label class logits.

Returns:

Type Description
ndarray

A float32 array of the same shape, without overflow warnings for large negative inputs.

drawDetections

drawDetections(src: ndarray, detections: Detections, classNames: Sequence[str] | None = None, colors: Sequence[Color] | None = None, thickness: int = 2, fontScale: float = 0.5, showScore: bool = True, fontPath: str | PathLike[str] | None = None, fontSize: int = 16) -> np.ndarray

Draw :class:Detections as labeled boxes, one color per class, in place.

Parameters:

Name Type Description Default
src ndarray

8-bit image to draw on (modified and returned, like cv.rectangle).

required
detections Detections

From :func:postprocessDetections.

required
classNames Sequence[str] | None

Label text per class id; ids without a name are shown as numbers.

None
colors Sequence[Color] | None

One color per class id; :func:distinctColors by default.

None
thickness int

Box line thickness.

2
fontScale float

Hershey font size for the labels.

0.5
showScore bool

Append the score ("cat 0.87").

True
fontPath str | PathLike[str] | None

TrueType font for Unicode class names (see :func:drawLabel).

None
fontSize int

Font size in pixels for fontPath.

16

Returns:

Type Description
ndarray

src.

Raises:

Type Description
ValueError

If src is empty.

flag

Named constants for magic numbers that OpenCV functions take without a constant of their own. OpenCV's own constants (cv.FILLED, cv.ROTATE_90_CLOCKWISE, cv.FILTER_SCHARR, ...) are used as they are.

Constant Value Use
FLIP_MODE_X, FLIP_MODE_Y, FLIP_MODE_XY 0, 1, -1 cv.flip(src, flipCode)
DDEPTH_SAME -1 ddepth of cv.filter2D, cv.Sobel, cv.Laplacian, ...: same depth as the source
ALL_CONTOURS -1 contourIdx of cv.drawContours: draw every contour
REDUCE_TO_ROW, REDUCE_TO_COL 0, 1 dim of cv.reduce
WAIT_FOREVER 0 delay of cv.waitKey: wait for a key press
KEY_ESC, KEY_ENTER, KEY_SPACE, KEY_TAB, KEY_BACKSPACE 27, 13, 32, 9, 8 Return value of cv.waitKey

Arrow and function keys are not included: the codes returned by cv.waitKeyEx differ between platforms and GUI backends.

Named constants for the magic numbers that OpenCV functions take without a constant of their own.

OpenCV already has constants for most flags (cv.ROTATE_90_CLOCKWISE, cv.FILLED, cv.FILTER_SCHARR, ...). These cover the remaining cases, so code reads cv.flip(img, cv.FLIP_MODE_Y) instead of cv.flip(img, 1).

FLIP_MODE_X module-attribute

FLIP_MODE_X = 0

cv.flip flipCode: flip around the x-axis (upside down).

FLIP_MODE_Y module-attribute

FLIP_MODE_Y = 1

cv.flip flipCode: flip around the y-axis (mirror left-right).

FLIP_MODE_XY module-attribute

FLIP_MODE_XY = -1

cv.flip flipCode: flip around both axes (same as rotating by 180°).

DDEPTH_SAME module-attribute

DDEPTH_SAME = -1

ddepth/dtype meaning "same depth as the source", e.g. cv.filter2D(src, cv.DDEPTH_SAME, kernel).

Accepted by cv.filter2D, cv.sepFilter2D, cv.boxFilter, cv.Sobel, cv.Scharr, cv.Laplacian, and as dtype by cv.add, cv.subtract, cv.multiply and cv.divide.

ALL_CONTOURS module-attribute

ALL_CONTOURS = -1

cv.drawContours contourIdx: draw every contour.

Example: cv.drawContours(img, contours, cv.ALL_CONTOURS, color).

REDUCE_TO_ROW module-attribute

REDUCE_TO_ROW = 0

cv.reduce dim: reduce every column, giving a single row (shape (1, width)).

REDUCE_TO_COL module-attribute

REDUCE_TO_COL = 1

cv.reduce dim: reduce every row, giving a single column (shape (height, 1)).

WAIT_FOREVER module-attribute

WAIT_FOREVER = 0

cv.waitKey delay: wait until a key is pressed, e.g. cv.waitKey(cv.WAIT_FOREVER).

KEY_BACKSPACE module-attribute

KEY_BACKSPACE = 8

Key code returned by cv.waitKey for Backspace.

KEY_TAB module-attribute

KEY_TAB = 9

Key code returned by cv.waitKey for Tab.

KEY_ENTER module-attribute

KEY_ENTER = 13

Key code returned by cv.waitKey for Enter. Some Linux backends return 10 ("\n") instead.

KEY_ESC module-attribute

KEY_ESC = 27

Key code returned by cv.waitKey for Escape, e.g. if cv.waitKey(1) == cv.KEY_ESC: break.

KEY_SPACE module-attribute

KEY_SPACE = 32

Key code returned by cv.waitKey for the space bar.