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 |
required |
scale
|
float
|
Isotropic scale factor applied with the rotation. |
1.0
|
flags
|
int
|
Interpolation, as for |
INTER_LINEAR
|
borderMode
|
int
|
How to fill the corners uncovered by the rotation, as for |
BORDER_CONSTANT
|
borderValue
|
float | Sequence[float]
|
Fill color for |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The rotated image; its size is the bounding box of the rotated input. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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]
|
|
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 |
required |
rho
|
ArrayLike
|
Distance(s) from the origin. |
required |
angleInDegrees
|
bool
|
|
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 |
required |
color
|
float | Sequence[float]
|
A scalar, or one value per channel (BGR, or BGRA for |
required |
channels
|
int
|
|
3
|
dtype
|
DTypeLike
|
Pixel type. |
uint8
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
dtype
|
DTypeLike | None
|
Pixel type of the result; by default that of |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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'
|
channels
|
int
|
|
3
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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 |
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 |
required |
overlap
|
int
|
Pixels shared by neighboring tiles, to avoid artifacts at tile borders. |
0
|
Returns:
| Type | Description |
|---|---|
list[tuple[ndarray, tuple[int, int]]]
|
|
list[tuple[ndarray, tuple[int, int]]]
|
Tiles are views of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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]]]
|
|
required |
size
|
tuple[int, int]
|
Output size as |
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 |
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 |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The processed image, the size of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
margin
|
int
|
Grow the box by this many pixels on every side (negative values shrink it). |
0
|
fill
|
float | Sequence[float] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new array (not a view of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
fill
|
float | Sequence[float] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new array. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
upperb
|
Sequence[float]
|
Upper bound |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Single-channel mask (0 or 255). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
boxesB
|
ArrayLike
|
One box or an array of shape |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
ndarray
|
|
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
scale
|
float | tuple[float, float]
|
One factor, or |
required |
offset
|
tuple[float, float]
|
|
(0, 0)
|
inverse
|
bool
|
Undo the transform instead: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
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 |
required |
ratio
|
float
|
Fraction of the width and height to add on each side ( |
0.0
|
margin
|
float
|
Fixed number of pixels to add on each side, after |
0.0
|
size
|
tuple[int, int] | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
ndarray
|
below 0. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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: |
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 |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
(0, 0)
|
alpha
|
float
|
Overall opacity from 0 (invisible) to 1, multiplied with the overlay's alpha channel (the same
name as in :func: |
1.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is not 8-bit, is empty or has an unsupported channel count, or |
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.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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: |
20000
|
seed
|
int
|
Seed, for reproducible results. |
0
|
Returns:
| Type | Description |
|---|---|
list[tuple[tuple[int, ...], float]]
|
A list of |
list[tuple[tuple[int, ...], float]]
|
grayscale) and |
Raises:
| Type | Description |
|---|---|
ValueError
|
As for :func: |
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: |
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:
kmeansColorsand :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
|
ordered from the most to the least common color, and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
quantile
|
float
|
Used to estimate |
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
|
colors found. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If scikit-learn is not installed. |
ValueError
|
If |
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
|
|
Clusters
|
cluster. Paint the result with :func: |
Raises:
| Type | Description |
|---|---|
ImportError
|
If scikit-learn is not installed. |
ValueError
|
If |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the shape and dtype of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
eps
|
float
|
Maximum distance between two points of the same group. |
required |
minSamples
|
int
|
Minimum number of points that forms a group; |
2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Labels of shape |
ndarray
|
group), as in :func: |
Raises:
| Type | Description |
|---|---|
ImportError
|
If scikit-learn is not installed. |
ValueError
|
If |
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, |
required |
angle
|
float
|
Rotation in degrees. |
required |
center
|
tuple[float, float]
|
Center of rotation |
(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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a value is not finite or |
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, |
required |
scale
|
float | tuple[float, float]
|
One factor, or |
required |
center
|
tuple[float, float]
|
Fixed point |
(0, 0)
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The scaled points as float64, in the shape of |
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 |
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, |
required |
size
|
tuple[int, int]
|
Image size as |
required |
flipCode
|
int
|
As for |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The flipped points as float64, in the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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, |
required |
size
|
tuple[int, int]
|
Image size as |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The normalized points as float64, in the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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, |
required |
size
|
tuple[int, int]
|
Image size as |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The pixel coordinates as float64, in the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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, |
required |
size
|
tuple[int, int]
|
Image size as |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The clipped points as float64, in the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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, |
required |
b
|
ArrayLike
|
One point, |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
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, |
required |
b
|
ArrayLike
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
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 |
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 |
required |
p2
|
ArrayLike
|
End point |
required |
degrees
|
bool
|
Return degrees ( |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a point is not one finite |
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 |
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 |
required |
line
|
Line
|
Two points |
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 |
required |
epsilon
|
float
|
Simplification tolerance as a fraction of each polygon's perimeter ( |
0.0
|
minArea
|
float
|
Drop polygons whose |
0
|
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
A list of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
value
|
int
|
Value of the polygon pixels, 1 to 255. |
255
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
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
|
|
required |
Returns:
| Type | Description |
|---|---|
float
|
The absolute area (0 for fewer than 3 points). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
polygonB
|
ArrayLike
|
|
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 |
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 |
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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]
|
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
classIds
|
ArrayLike | None
|
One class id per box; when given, the rows are |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray | None
|
for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
boxes
|
ArrayLike
|
Boxes of shape |
required |
classIds
|
ArrayLike
|
One integer class id per box. |
required |
size
|
tuple[int, int]
|
|
required |
makeDirs
|
bool
|
Create missing parent directories. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
required |
palette
|
ArrayLike | None
|
One BGR color per class id, indexed by id ( |
None
|
background
|
int
|
The id drawn black (set to |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
palette
|
ArrayLike
|
One BGR color per class id, indexed by id ( |
required |
background
|
int
|
The id for pixels whose color is not in the palette. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
list[ndarray]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
color
|
Sequence[Color] | Color | None
|
One color for all polygons, one color per polygon, or |
None
|
thickness
|
int
|
Outline thickness (ignored with |
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 |
LINE_AA
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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: |
None
|
background
|
int
|
The id left uncolored. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
flipCode
|
int
|
0 ( |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
size
|
tuple[int, int]
|
|
required |
flipCode
|
int
|
0 flips vertically, 1 horizontally, -1 both. |
required |
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
A list of float64 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
IMREAD_COLOR
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The image, or |
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 |
()
|
makeDirs
|
bool
|
Create missing parent directories. |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
error
|
If no encoder exists for the extension (e.g. |
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 |
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
|
|
IMREAD_COLOR
|
strict
|
bool
|
Raise on the first file that cannot be read. With |
True
|
Returns:
| Type | Description |
|---|---|
list[ndarray | None]
|
The images, in the order of |
Raises:
| Type | Description |
|---|---|
OSError
|
If |
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 |
()
|
makeDirs
|
bool
|
Create missing parent directories. |
False
|
strict
|
bool
|
Raise on the first file that cannot be written. With |
True
|
Returns:
| Type | Description |
|---|---|
list[bool]
|
One |
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are more paths than images or more images than paths, or a path has no extension. |
OSError
|
If |
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
|
|
required |
flags
|
int
|
|
IMREAD_COLOR
|
timeout
|
float | None
|
Timeout in seconds for the request. |
None
|
headers
|
Mapping[str, str] | None
|
Extra HTTP headers, e.g. |
None
|
maxBytes
|
int | None
|
Largest response accepted, in bytes. Larger downloads stop early with a |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The decoded image, or |
Raises:
| Type | Description |
|---|---|
URLError
|
If the request fails (including HTTP errors). |
ValueError
|
If |
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
|
|
ndarray
|
|
ndarray
|
|
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 |
'.png'
|
params
|
Sequence[int]
|
Format-specific |
()
|
dataUri
|
bool
|
Return a data URI ( |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
required |
flags
|
int
|
|
IMREAD_COLOR
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The image, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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).
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
|
|
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
|
|
IMREAD_COLOR
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The upright image, or |
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 |
None
|
scale
|
float | None
|
Scale factor, e.g. |
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
|
|
IMREAD_COLOR
|
interpolation
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The resized image, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If not exactly one of |
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. |
required |
img
|
ndarray
|
Image to encode. |
required |
params
|
Sequence[int]
|
Format-specific |
()
|
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
|
|
IMREAD_COLOR
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The image, or |
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 |
False
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
error
|
If no encoder exists for the extension of |
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 |
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 |
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 |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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. |
0
|
contrast
|
float
|
|
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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. |
0
|
saturation
|
float
|
Saturation factor; |
1.0
|
value
|
float
|
Brightness factor. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
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 |
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'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shapes differ, the images are empty, or |
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 |
8
|
method
|
str
|
|
'difference'
|
Returns:
| Type | Description |
|---|---|
int
|
The hash as a non-negative integer (e.g. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
mode
|
int
|
Retrieval mode, as for |
RETR_EXTERNAL
|
method
|
int
|
Approximation, as for |
CHAIN_APPROX_SIMPLE
|
minArea
|
float
|
Drop contours whose |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
maxHoleArea
|
int | None
|
If given, only holes up to this many pixels are filled. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
minArea
|
float
|
Regions with fewer pixels are removed. |
required |
connectivity
|
int
|
8 (diagonal neighbors connect) or 4. |
8
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
feather
|
float
|
Soften the edge with a Gaussian blur of this sigma, in pixels. |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
fill
|
float | Sequence[float]
|
Value for the pixels outside the mask: a scalar, or one value per channel of |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new array with the dtype and shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the mask shape does not match, |
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'
|
invert
|
bool
|
Foreground is dark instead of light ( |
False
|
blockSize
|
int
|
Neighborhood size for |
31
|
C
|
float
|
Constant subtracted from the local mean for |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
op
|
Operation
|
|
required |
ksize
|
int | tuple[int, int]
|
Kernel size, one number or |
3
|
shape
|
Literal['ellipse', 'rect', 'cross']
|
Kernel shape: |
'ellipse'
|
iterations
|
int
|
How many times to apply it. |
1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the contour has no points. |
ContourStats ¶
Bases: NamedTuple
The usual shape measurements of a contour (see :func:contourStats).
center
instance-attribute
¶
center: tuple[float, float]
Centroid (x, y) from the image moments (the box center if the area is 0).
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 |
required |
method
|
SortMethod
|
|
'left-to-right'
|
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
A new list, in the requested order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
size
|
tuple[int, int]
|
|
required |
thickness
|
int
|
|
FILLED
|
lineType
|
int
|
As for |
LINE_8
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
0
|
transparent
|
bool
|
Return BGRA with the outside transparent instead of filled with |
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 |
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 |
required |
epsilon
|
float
|
Tolerance as a fraction of the perimeter, e.g. |
0.02
|
closed
|
bool
|
Whether the contour is closed (as for |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The simplified contour, shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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: |
required |
contours
|
Sequence[ndarray]
|
Contours as from :func: |
required |
colors
|
Sequence[Sequence[float]] | None
|
BGR colors, cycled through. By default :func: |
None
|
labels
|
bool | Sequence[str]
|
|
False
|
thickness
|
int
|
Outline thickness, or |
2
|
fontScale
|
float
|
Hershey font size for the labels. |
0.5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
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 |
required |
threshold
|
float
|
Minimum score in |
0.8
|
maxCount
|
int | None
|
Return at most this many matches. |
None
|
method
|
int
|
|
TM_CCOEFF_NORMED
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
ndarray
|
empty |
ndarray
|
direction. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty, |
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 |
required |
method
|
Detector
|
|
'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 |
None
|
referenceMask
|
ndarray | None
|
The same for |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
FeatureMatches
|
class: |
FeatureMatches
|
matches; pass them to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty or has an unsupported channel count, |
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).
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: |
'ORB'
|
motion
|
Literal['homography', 'affine', 'similarity']
|
|
'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
|
|
ndarray
|
transform, |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty, |
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 ( |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
30
|
edgeThreshold
|
float
|
Upper Canny threshold ( |
100
|
blur
|
int
|
Median blur kernel (odd) applied first; 0 to skip. |
5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A float64 array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
dark
|
bool
|
Look for dark blobs on a light background (default); |
True
|
minCircularity
|
float | None
|
|
None
|
minConvexity
|
float | None
|
|
None
|
minInertia
|
float | None
|
|
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
interpolation
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The resized image. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
color
|
float | Sequence[float]
|
Padding color (BGR for color images). |
0
|
interpolation
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
Letterbox
|
class: |
Letterbox
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Letterbox ¶
Bases: NamedTuple
The result of :func:letterbox: the padded image and how to map coordinates back.
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 |
required |
size
|
tuple[int, int] | None
|
Output size as |
None
|
flags
|
int
|
Interpolation, as for |
INTER_LINEAR
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The warped image. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
BORDER_CONSTANT
|
borderValue
|
float | Sequence[float]
|
Fill color for |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The shifted image, with the shape and dtype of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
M
|
ArrayLike
|
A 2x3 affine matrix ( |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The transformed points as float64, in the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the points do not have 2 coordinates or |
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 |
required |
flags
|
int
|
Interpolation, as for |
INTER_LINEAR
|
borderMode
|
int
|
How to fill the parts of the box outside the image, as for |
BORDER_CONSTANT
|
borderValue
|
float | Sequence[float]
|
Fill color for |
0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
An image of size |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
BORDER_CONSTANT
|
borderValue
|
float | Sequence[float] | None
|
Fill color for |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
float
|
(positive is counter-clockwise, as for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
required |
sigma
|
float
|
Width of the threshold band around the median; smaller values give fewer edges. |
0.33
|
apertureSize
|
int
|
Sobel aperture, as in |
3
|
L2gradient
|
bool
|
Use the more accurate L2 gradient norm, as in |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Single-channel edge map (0 or 255). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
False
|
clipLimit
|
float
|
CLAHE contrast limit. |
2.0
|
tileGridSize
|
tuple[int, int]
|
CLAHE grid size, as |
(8, 8)
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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; |
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 |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image; the area outside |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
text
|
str
|
Label text. The built-in OpenCV font supports ASCII only; pass |
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 |
None
|
fontPath
|
str | PathLike[str] | None
|
TrueType/OpenType font for the label; then |
None
|
fontSize
|
int
|
Font size in pixels when |
16
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
labels
|
Sequence[str] | None
|
One text per box, or |
None
|
colors
|
Sequence[Color] | Color | None
|
One color per box, one color for all, or |
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: |
None
|
fontSize
|
int
|
Font size in pixels for |
16
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
color
|
Color
|
Circle color. |
(0, 0, 255)
|
radius
|
int
|
Circle radius in pixels. |
3
|
thickness
|
int
|
|
FILLED
|
labels
|
bool | Sequence[str]
|
|
False
|
fontScale
|
float
|
Hershey font size for the labels. |
0.5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
color
|
Color
|
Line color. |
(0, 255, 0)
|
thickness
|
int
|
Line thickness. |
1
|
offset
|
tuple[int, int]
|
|
(0, 0)
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
pt2
|
tuple[int, int]
|
End point |
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 |
None
|
lineType
|
int
|
As for |
LINE_8
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
color
|
Color
|
Line or fill color. |
required |
thickness
|
int
|
Line thickness; |
1
|
radius
|
int
|
Corner radius in pixels, reduced to fit small boxes. |
8
|
lineType
|
int
|
As for |
LINE_8
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
(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 |
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. |
required |
org
|
tuple[int, int]
|
Top-left corner of the text, as |
required |
fontPath
|
str | PathLike[str]
|
Path to a |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Image statistics and quality checks¶
ImageStats ¶
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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.05
|
highThreshold
|
float
|
Gray level (normalized to |
0.95
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
256
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
HISTCMP_CORREL
|
bins
|
int
|
Bins per channel. |
32
|
colorSpace
|
str
|
|
'hsv'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty or has a wrong channel count, |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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 |
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 |
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 |
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'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a color is not a BGR color in |
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 |
required |
space
|
str
|
|
'lab'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
textColorFor ¶
textColorFor(background: Sequence[float]) -> Color
Black or white, whichever reads better on background; the rule used by :func:drawLabel.
Returns:
| Type | Description |
|---|---|
Color
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
1.0
|
value
|
float
|
HSV brightness in |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a color is not a BGR color in |
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
|
|
required |
count
|
int
|
How many colors, from the darkest end (0) to the brightest (255) of the map. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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'
|
amount
|
float | None
|
Noise strength, see |
None
|
seed
|
int | None
|
Random seed for reproducible noise. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the same shape and dtype as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
15
|
angle
|
float
|
Direction of the motion in degrees, counter-clockwise from the x axis; |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The blurred image, with the dtype of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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.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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
count
|
int
|
Number of patches. |
1
|
fill
|
float | Sequence[float] | str
|
Fill value or color, or |
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 |
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 ( |
128
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the same shape and dtype as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
boxes
|
ArrayLike | None
|
Optional boxes |
None
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
The crop, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
The (possibly) flipped image, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
seed
|
int | None
|
Random seed. |
None
|
crop
|
bool
|
Keep the size of |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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]
|
|
(0.8, 1.2)
|
boxes
|
ArrayLike | None
|
Optional boxes |
None
|
seed
|
int | None
|
Random seed. |
None
|
interpolation
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
The resized image, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
boxes
|
ArrayLike | None
|
Optional boxes |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
0.2
|
contrast
|
float
|
Largest contrast change; the factor is drawn from |
0.2
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the same shape and dtype as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
10
|
saturation
|
float
|
Largest saturation change; the factor is drawn from |
0.3
|
value
|
float
|
Largest brightness change; the factor is drawn from |
0.3
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new image with the same shape and dtype as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
boxes
|
Sequence[ArrayLike] | None
|
Optional list of four box arrays |
None
|
seed
|
int | None
|
Random seed for the center point. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
The mosaic, or |
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, |
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, |
0.5
|
lam
|
float | None
|
Fixed mixing weight in |
None
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty, the images differ in dtype or channels, |
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.0
|
seed
|
int | None
|
Random seed. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an image is empty, the images differ in dtype or channels, or |
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 |
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'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
(grayscale input stays grayscale). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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
|
|
ndarray
|
left to right). Empty for a blank page. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
(then left to right). Empty for a blank page. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
float
|
page. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
ndarray | None
|
bottom-left, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
None
|
enhance
|
bool
|
Flatten the lighting and sharpen the result ( |
True
|
minAreaRatio
|
float
|
Passed to :func: |
0.2
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The upright page. If no page outline is found, the whole image (enhanced if asked, resized to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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'
|
confidence
|
float | None
|
|
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 |
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 |
required |
method
|
Detector
|
Feature detector, as for :func: |
'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 |
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 |
COLORMAP_JET
|
normalize
|
bool
|
Stretch the minimum and maximum of |
True
|
mask
|
ndarray | None
|
Optional 2-D mask with the shape of |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
An 8-bit BGR image with the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
alpha
|
float
|
Opacity of the color map, from 0 to 1. |
0.5
|
colormap
|
int | ndarray
|
As for :func: |
COLORMAP_JET
|
normalize
|
bool
|
As for :func: |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new BGR image (BGRA keeps the alpha channel of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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: |
COLORMAP_JET
|
size
|
tuple[int, int]
|
Size of the strip as |
(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
|
maxVal
|
float | None
|
Value written at the high end; |
None
|
fontScale
|
float
|
Hershey font size of the labels. |
0.4
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A BGR image of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
pt2
|
Sequence[float]
|
End point |
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'
|
lineType
|
int
|
As for |
LINE_AA
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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; |
2
|
lineType
|
int
|
As for |
LINE_AA
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
colors
|
Sequence[Color] | Color | None
|
One color per box, one color for all, or |
None
|
labels
|
Sequence[str] | None
|
One text per box, or |
None
|
thickness
|
int
|
Line thickness. |
2
|
fontScale
|
float
|
Hershey font size of the labels. |
0.5
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
color
|
Color
|
Outline and fill color. |
required |
thickness
|
int
|
Outline thickness; |
2
|
closed
|
bool
|
Connect the last vertex to the first (ignored when |
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 |
LINE_AA
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
connections
|
Sequence[tuple[int, int]]
|
Pairs of keypoint indices to join; :data: |
COCO_SKELETON
|
colors
|
Sequence[Color] | Color | None
|
One color per connection, one color for all, or |
None
|
radius
|
int
|
Joint circle radius; |
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
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
|
required |
color
|
Color | None
|
Color at the newest point; |
None
|
thickness
|
int
|
Line thickness at the newest segment. |
2
|
fade
|
bool
|
Darken and thin the line towards the oldest point. |
True
|
maxPoints
|
int | None
|
Only draw the last |
None
|
endColor
|
Color | None
|
Color at the oldest point when fading; |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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]
|
|
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 |
LINE_AA
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
(10, 10)
|
fontScale
|
float
|
Hershey font size. |
0.5
|
color
|
Color
|
Text color. |
(255, 255, 255)
|
background
|
Color | None
|
Panel color; |
(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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
org
|
tuple[int, int]
|
Top-left corner |
required |
size
|
tuple[int, int]
|
Bar size as |
(200, 12)
|
color
|
Color
|
Fill color. |
(0, 200, 0)
|
background
|
Color
|
Track color. |
(60, 60, 60)
|
border
|
Color | None
|
Outline color; |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
|
org
|
tuple[int, int]
|
Top-left corner |
(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; |
(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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
mode
|
str
|
|
'side'
|
split
|
float
|
Position of the divider as a fraction of the width for |
0.5
|
labels
|
Sequence[str] | None
|
Two titles drawn above the images for |
None
|
gap
|
int
|
Space between the images for |
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, |
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 |
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 |
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
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new 8-bit image with the shape of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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: |
required |
fps
|
float
|
Frame rate. |
required |
fourcc
|
str | None
|
Four-character codec code, e.g. |
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, |
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 |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The frame, or |
Raises:
| Type | Description |
|---|---|
OSError
|
If the video cannot be opened. |
ValueError
|
If not exactly one of |
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.
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).
frameCount
property
¶
frameCount: int
Number of frames (an estimate for some formats, 0 for cameras).
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 |
seekTime ¶
seekTime(seconds: float) -> None
Move to the frame at seconds from the start (see :meth:seek).
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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. |
None
|
isColor
|
bool | None
|
|
None
|
makeDirs
|
bool
|
Create missing parent directories. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
with VideoWriterEx("out.mp4", fps=30) as writer:
for frame in frames:
writer.write(frame)
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.
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: |
5.0
|
Raises:
| Type | Description |
|---|---|
OSError
|
If the source cannot be opened. |
Example
with CameraStream(0) as camera:
while True:
frame = camera.read()
...
ended
property
¶
ended: bool
True once the source stopped delivering frames (end of file, camera lost).
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.
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 ( |
perf_counter
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
counter = FPSCounter()
for frame in cv.readFrames(0):
fps = counter.tick()
frameToTime ¶
frameToTime(index: int, fps: float) -> float
Convert a frame index to seconds from the start.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
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 |
1
|
start
|
int
|
First frame index to save. |
0
|
end
|
int | None
|
Stop before this frame index ( |
None
|
ext
|
str
|
Image file extension, e.g. |
'.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 |
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 |
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: |
required |
start
|
float
|
Start, in seconds (or a frame index when |
required |
end
|
float | None
|
End (exclusive), in seconds or frames; |
None
|
byTime
|
bool
|
Whether |
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 |
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 |
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 |
required |
fps
|
float | None
|
Playback frame rate of the GIF (default: the video's rate divided by |
None
|
size
|
tuple[int, int] | None
|
Output |
None
|
step
|
int
|
Take every |
1
|
maxFrames
|
int | None
|
Stop after this many frames. |
None
|
loop
|
int
|
Number of repetitions, |
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, |
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: |
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 |
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 |
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 |
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
|
|
None
|
cols
|
int | None
|
Number of columns of the grid (default: as square as possible, see :func: |
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 |
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 |
None
|
ext
|
str
|
Encoding used for the notebook output, |
'.png'
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If IPython is not installed (Jupyter always provides it). |
ValueError
|
If |
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 |
(1280, 720)
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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).
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 |
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 |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
refine
|
bool
|
Run |
True
|
flags
|
int | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
The corners as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
patternSize
|
tuple[int, int]
|
Inner corners as |
required |
squareSize
|
float
|
Side of one square in your unit; |
1.0
|
imageSize
|
tuple[int, int] | None
|
|
None
|
flags
|
int
|
|
0
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
CameraCalibration
|
class: |
CameraCalibration
|
missed they are shorter than |
Raises:
| Type | Description |
|---|---|
ValueError
|
If fewer than 3 views contain the board, |
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 |
required |
patternSize
|
tuple[int, int]
|
Inner corners as |
required |
squareSize
|
float
|
Square size used for the calibration. |
required |
cornersList
|
Sequence[ndarray | None]
|
The detected corners of each view, |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One RMS error in pixels per used view, shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the number of views matches neither |
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: |
required |
distCoeffs
|
ndarray | None
|
Distortion coefficients when |
None
|
alpha
|
float
|
Free scaling parameter of |
0.0
|
crop
|
bool
|
Crop to the valid ROI. With |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The undistorted image, same dtype and channels as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 ( |
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: |
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.
Detections ¶
Bases: NamedTuple
Decoded detections in the coordinates of the original image, best score first.
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 ( |
required |
config
|
str | PathLike[str] | None
|
Optional text config for the model (e.g. |
None
|
backend
|
int | None
|
|
None
|
target
|
int | None
|
|
None
|
preferGpu
|
bool
|
Use the CUDA backend and target when this OpenCV build has it; silently keeps the default
otherwise. Ignored when |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
A |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If |
RuntimeError
|
If this OpenCV build has no |
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 |
required |
letterboxPad
|
bool
|
Keep the aspect ratio and pad with |
True
|
color
|
Color
|
Padding color (BGR). |
(114, 114, 114)
|
scale
|
float
|
Multiplier applied after |
1 / 255
|
mean
|
Sequence[float]
|
Per-channel values subtracted first, in the channel order of the blob (RGB when |
(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]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
required |
src
|
ndarray
|
A ready |
required |
outputNames
|
Sequence[str] | None
|
Layers to return; all unconnected output layers by default. |
None
|
size
|
tuple[int, int] | None
|
Network input |
None
|
Returns:
| Type | Description |
|---|---|
list[ndarray]
|
One array per output layer. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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: |
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'
|
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 |
False
|
transpose
|
bool | None
|
Force the |
None
|
Returns:
| Type | Description |
|---|---|
Detections
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the output has no class columns, |
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 |
required |
topK
|
int
|
How many classes to return (fewer when the model has fewer classes). |
5
|
softmax
|
bool
|
Apply :func: |
True
|
Returns:
| Type | Description |
|---|---|
list[tuple[int, float]]
|
A list sorted by descending probability. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
detections
|
Detections
|
From :func: |
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: |
None
|
thickness
|
int
|
Box line thickness. |
2
|
fontScale
|
float
|
Hershey font size for the labels. |
0.5
|
showScore
|
bool
|
Append the score ( |
True
|
fontPath
|
str | PathLike[str] | None
|
TrueType font for Unicode class names (see :func: |
None
|
fontSize
|
int
|
Font size in pixels for |
16
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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_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.