diff --git a/CHANGELOG.md b/CHANGELOG.md
index 30a060d..f44f843 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,64 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.0.0] - 2026-11-08
+
+The first stable release: 162 new APIs (135 -> 297), two new subpackages (`cv2u.calib3d`, `cv2u.dnn`), and a one-time
+clean-up of the existing API (consistent names, signatures and validation). From 1.0 on, the public API follows
+semantic versioning and renames keep a deprecated alias (see [Design principles](docs/principles.md)).
+
+### Added
+
+- `VideoReader`, `VideoWriterEx` and `CameraStream`: context-manager/iterator capture with seeking, a lazily-opened writer that infers codec, size and color mode from the first frame, and a threaded latest-frame camera reader.
+- `FPSCounter`, `frameToTime`, `timeToFrame`, `formatTimestamp`: frame-rate measurement and frame/time conversions.
+- `extractFrames`, `trimVideo`, `concatVideos`, `resizeVideo`, `videoToGif`, `imagesToVideo`: video file editing utilities with Unicode-safe paths and automatic directory creation.
+- `detectScenes`, `sampleFrames`, `videoThumbnail`: scene-cut detection and evenly spaced frame sampling / contact sheets.
+- Data augmentation (`imgproc`): seeded noise, motion blur, vignette, JPEG artifacts, random erase, solarize and posterize (`addNoise`, `motionBlur`, `vignette`, `jpegArtifacts`, `randomErase`, `solarize`, `posterize`).
+- Seeded random transforms that keep detection boxes aligned: `randomCrop`, `randomFlip`, `randomRotate`, `randomScale`, `randomPerspective`; photometric `randomBrightnessContrast`, `randomHSV`, `randomBlur`.
+- Multi-image augmentations `mosaic` (YOLO-style 4-image mosaic with boxes), `mixup` and `cutMix` (both return the mixing weight `lam` for labels).
+- `maskToPolygons`, `polygonsToMask`, `boxesToPolygons`, `polygonsToBoxes`, `polygonArea`, `polygonIoU`, `maskIoU`: polygon annotations and overlap measures (`polygonIoU` rasterizes at a configurable resolution, so it works for concave polygons).
+- `rleEncode`, `rleDecode`: COCO uncompressed RLE (column-major, pycocotools-compatible) without a pycocotools dependency.
+- `boxesToYolo`, `yoloToBoxes`, `readYoloLabels`, `writeYoloLabels`: YOLO normalized rows and `.txt` label files on any path, with `makeDirs`.
+- `labelMapToColor`, `colorToLabelMap`, `instanceMasksToLabelMap`, `labelMapToMasks`, `drawSegmentation`, `drawPolygons`: label maps, instance masks and their visualization with distinct class colors.
+- `flipBoxes`, `flipPoints`, `flipPolygons`: flip annotations together with `cv.flip` (same `flipCode` semantics as `FLIP_MODE_*`).
+- `cv2u.dnn` subpackage (mirrors `cv.dnn`; every `cv2.dnn` name passes through): `loadModel`, `readClassNames`, `preprocessImage`, `inferImage`, `postprocessDetections`, `postprocessClassification`, `softmax`, `sigmoid`, `drawDetections`, and the `PreprocessInfo` / `Detections` named tuples for running detectors and classifiers end to end.
+- `heatmap`, `applyColorMapEx` and `colorBar`: colorize float maps of any size, overlay them on an image and draw a legend strip.
+- `drawArrow` (pixel-sized heads, both ends), `drawRotatedRect`/`drawRotatedBoxes` (from `cv.minAreaRect`), `drawPolygon` (float points, translucent fill), `drawSkeleton` with `COCO_SKELETON`, `drawTrajectory` (fading tracks) and `drawCrosshair`.
+- HUD helpers `drawTextBlock`, `drawFPS`, `drawProgressBar` and `drawLegend` with translucent panels.
+- `compareImages` (side, vertical, split, blend, diff), `labeledMontage` (titled grid) and `blendImages` (weighted average of N images).
+- `imageStats`/`ImageStats`, `isGrayscale`, `isBlank`, `isBlurry`, `brightnessScore`, `contrastScore`, `exposureScore`, `entropy`, `estimateNoise` (Immerkær) and `colorfulness` (Hasler & Süsstrunk): one-call image statistics and quality checks for any gray/BGR/BGRA image and dtype.
+- `mse`, `mae`, `histogramEx` (per-channel `(channels, bins)` histograms), `histogramCompare` (normalized HSV/BGR/gray histograms through `cv.compareHist`), `dominantHue` and `meanColor`.
+- Document and OCR preprocessing (`imgproc`): `removeShadow`, `enhanceDocument`, `sauvolaThreshold`, `niblackThreshold` (integral-image local thresholds, no contrib needed), `removeSpeckles`, `removeLines`.
+- Page layout: `detectTextLines`, `detectTextBlocks`, `removeBorder`, `estimateSkew` (the angle behind `deskew`), `detectPage` and `scanDocument` (detect + `fourPointTransform` + enhance).
+- `cv2u.calib3d` subpackage: `CameraCalibration`, `makeChessboard`, `objectPointsGrid`, `findChessboardEx`, `calibrateCameraEx`, `reprojectionErrors`, `undistortEx`, `saveCalibration`, `loadCalibration` for chessboard camera calibration, undistortion and a JSON calibration file.
+- `stitchImages` (`cv.Stitcher` with exceptions and status names) and `stitchPair` (homography stitch on an enlarged canvas).
+- `imageInfo`, `ImageInfo`, `exifOrientation`: image file header metadata (size, channels, mode, format, file size, EXIF orientation) without decoding.
+- `imreadOriented`, `imreadResized`: read with the EXIF orientation applied for every flag and format, and read-and-resize with `IMREAD_REDUCED_*` fast paths for 1/2, 1/4, 1/8 scales.
+- `imencodeEx`, `imdecodeEx`, `convertImageFormat`: encode to `bytes` with errors raised, decode from any bytes-like object, and convert files between formats (alpha flattened for JPEG, orientation applied, `quality`).
+- Color arithmetic (`imgproc`): `CSS_COLORS`, `lightenColor`, `darkenColor`, `blendColors`, `complementaryColor`, `invertColor`, `colorDistance`, `nearestColor`, `colorName`, `textColorFor`, `randomColors`, `gradientPalette`, `colormapPalette`.
+- Point sets (`core`): `rotatePoints`, `scalePoints`, `translatePoints`, `flipPoints`, `normalizePoints`, `denormalizePoints`, `clipPoints`, `pointsBoundingBox`, `distancePoints`, `nearestPoints`, `orderPoints`, `polygonCentroid`, `angleBetween`, `lineIntersection`, `pointLineDistance`.
+- `Clusters` and `Letterbox` named tuples (see Changed). `CameraCalibration.usedViews` lists the input views `calibrateCameraEx` used
+ (views without a board are skipped), and `reprojectionErrors` accepts the original corner list with `None` entries.
+
+### Changed
+- `DBSCAN` is now `dbscanColors(src, eps, minSamples=4)` and returns `Clusters(maps, centers)` like the other clusterers; labels are `0 .. k-1` with noise `-1` (was `(maps, labels)` with noise `0` and clusters from `1`). `clusterPoints` follows the same convention (noise `-1`, `int32` labels).
+- `drawDBSCAN(src, maps, labels)` is now `drawClusters(src, maps)`: returns a new image, accepts gray or BGR input; noise pixels keep their original color.
+- `kmeansColors`, `meanShiftColors`, `peakColors` and `dbscanColors` return a `Clusters(maps, centers)` named tuple, and `letterbox` returns `Letterbox(image, scale, offset)`; tuple unpacking keeps working.
+- Renamed: `DHEdge` -> `boldEdges`, `cropEx` -> `cropRect`, `centerCrop` -> `cropCenter`, `detectBlobs` -> `findBlobs`, `urlread` -> `imreadUrl` (now defaults to `IMREAD_COLOR` like `cv.imread`).
+- Renamed parameters: `matchFeatures(src, reference, ..., mask, referenceMask)` (was `dst`, `dstMask`); `overlayImage(alpha=)` (was `opacity`); `cropContour`, `applyMask` and `flattenAlpha` take `fill=` (was `background`); `expandBoxes(margin=)` (was `pixels`).
+- `imcolor(size, color, channels=3)` and `makeGradient(size, ...)` take `size=(width, height)` like `cv.resize` instead of a NumPy shape; `channels=1` gives a 2-D image.
+- `putTextEx(img, ...)` and `drawContoursEx(img, contours, colors=None, labels=False, thickness=2, fontScale=0.5)` draw in place and return `img` like every other `draw*` function (they returned a BGR copy); grayscale images stay grayscale.
+- `findTemplate` returns a float64 `(N, 5)` array `[x, y, w, h, score]` instead of a list of tuples, so the result feeds `nms` and `drawBoxes` directly.
+- `cropRect` raises `ValueError` when the box lies entirely outside the image instead of returning an empty array.
+- `cropRotatedRect` defaults to `borderMode=cv.BORDER_CONSTANT` like `rotateEx` and `translate`; `rotateEx` has explicit defaults (`INTER_LINEAR`, `BORDER_CONSTANT`, `0`).
+- `drawRoundedRectangle(img, rect, color, thickness=1, radius=8, lineType=...)`: `radius` comes before `lineType`. `drawPoints` default `fontScale` is 0.5.
+- Boolean switches are keyword-only: `padToSize(center=)`, `scaleBoxes(inverse=)`, `equalizeHistEx(clahe=)`, `binarize(invert=)`, `autoContrast(perChannel=)`, `findBlobs(dark=)`, `findContoursEx(sort=)`, `cropContour(transparent=)`, `drawHistogram(log=)`, `imencodeBase64(dataUri=)`, `imreadAll(strict=)`, `imwriteAll(strict=)`.
+- `autoCanny` accepts 16-bit and float images (stretched to 8 bits) instead of raising; `findLines` does the same. `nms` rejects `iouThreshold > 1`. `minArea` is a `float` everywhere.
+- Validation is now uniform: every function rejects empty images, and every numeric parameter rejects NaN/infinity and out-of-range values, with a `ValueError` naming the argument (about 50 functions gained checks). Every public function has complete `Args`/`Returns`/`Raises` docstrings.
+
+### Removed
+- `DBSCAN`, `drawDBSCAN`, `DHEdge`, `cropEx`, `centerCrop`, `detectBlobs` and `urlread` (renamed above). 1.0.0 is a one-time reset without deprecated aliases; from 1.0 on, renames keep a deprecated alias for at least one minor release.
+
## [0.4.0] - 2026-11-07
3 new APIs (132 -> 135), and the hot paths measured.
diff --git a/README.md b/README.md
index fcc77b3..5be9762 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,10 @@
# Python OpenCV Utilities
Python OpenCV Utilities provides useful extensions for [OpenCV](https://opencv.org/)
-and can be used as a **drop-in replacement for `cv2`**.
+and can be used as a **drop-in replacement for `cv2`**. It covers the everyday gaps (Unicode paths, aspect-ratio
+resize, crop-free rotation, Unicode text) and whole workflows: video reading and editing, data augmentation,
+annotation formats (COCO polygons, RLE, YOLO), running ONNX models with `cv.dnn`, camera calibration, document
+scanning and OCR preprocessing, image statistics and visualization.
```python
import cv2u as cv # instead of: import cv2 as cv
@@ -41,12 +44,12 @@ pip install "python-opencv-utils[opencv]" # opencv-python
pip install "python-opencv-utils[headless]" # opencv-python-headless (servers, Docker; no GUI)
pip install "python-opencv-utils[contrib]" # opencv-contrib-python
pip install "python-opencv-utils[contrib-headless]" # opencv-contrib-python-headless
-pip install "python-opencv-utils[opencv,cluster]" # also scikit-learn (meanShiftColors, DBSCAN, clusterPoints)
+pip install "python-opencv-utils[opencv,cluster]" # also scikit-learn (meanShiftColors, dbscanColors, clusterPoints)
```
If the project already has OpenCV installed, `pip install python-opencv-utils` without an extra uses it.
Dependencies: OpenCV 4.10 or newer (including OpenCV 5), `numpy>=2`, `pillow`.
-The optional `cluster` extra adds `scikit-learn` for `meanShiftColors`, `DBSCAN` and `clusterPoints`.
+The optional `cluster` extra adds `scikit-learn` for `meanShiftColors`, `dbscanColors` and `clusterPoints`.
`dominantColors`, `colorQuantize` and `kmeansColors` work without it (they use `cv.kmeans`).
> [!NOTE]
@@ -82,7 +85,7 @@ src = cv.imreadEx("C:/사진/고양이.jpg") # cv.imread fails on non-ASCII pat
small = cv.resizeEx(src, width=640) # keeps the aspect ratio
boxed, scale, (left, top) = cv.letterbox(src, (640, 640)) # fit + pad, e.g. for a model input
logo = cv.imread("logo.png", cv.IMREAD_UNCHANGED) # BGRA with transparency
-stamped = cv.overlayImage(small, logo, org=(10, 10), opacity=0.8)
+stamped = cv.overlayImage(small, logo, org=(10, 10), alpha=0.8)
cv.imwriteEx("C:/사진/비교.png", cv.hconcatEx([small, stamped], gap=8))
```
@@ -109,7 +112,7 @@ img = cv.imread("street.jpg")
detections = [((40, 60, 120, 200), "person", 0.94), ((200, 90, 160, 110), "자동차", 0.88)]
crops = []
for box, name, score in detections:
- crops.append(cv.cropEx(img, box, margin=10, fill=0)) # safe even at the image border
+ crops.append(cv.cropRect(img, box, margin=10, fill=0)) # safe even at the image border
cv.drawLabel(img, box, f"{name} {score:.2f}", (0, 200, 255), fontPath="C:/Windows/Fonts/malgun.ttf")
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
@@ -139,6 +142,81 @@ lines = cv.findLines(img, minLength=100) # (N, 4) segments, longest first
aligned, M = cv.alignImages(cv.imread("scan.png"), cv.imread("template.png")) # feature match + RANSAC + warp
```
+### Training data
+
+```python
+import cv2u as cv
+
+img = cv.imread("train/0001.jpg")
+size = (img.shape[1], img.shape[0])
+boxes, classIds = cv.readYoloLabels("train/0001.txt", size) # normalized rows -> pixel (x, y, w, h)
+img, boxes = cv.randomFlip(img, horizontal=0.5, boxes=boxes, seed=1) # the boxes follow the image
+img, boxes = cv.randomRotate(img, maxAngle=10, boxes=boxes, seed=1)
+img = cv.randomHSV(cv.addNoise(img, "gaussian", seed=1), hue=10, seed=1)
+cv.writeYoloLabels("aug/0001.txt", boxes, classIds, size, makeDirs=True)
+cv.imwriteEx("aug/0001.jpg", cv.jpegArtifacts(img, quality=40))
+
+tiles = cv.imreadAll(["train/0001.jpg", "train/0002.jpg", "train/0003.jpg", "train/0004.jpg"])
+labels = [cv.readYoloLabels(f"train/{i:04d}.txt", (t.shape[1], t.shape[0]))[0] for i, t in enumerate(tiles, 1)]
+big, bigBoxes = cv.mosaic(tiles, (640, 640), boxes=labels, seed=1) # YOLO-style 4-image mosaic
+polygons = cv.maskToPolygons(cv.binarize(img, "otsu", invert=True)) # COCO polygons from a mask
+rle = cv.rleEncode(cv.polygonsToMask(polygons, size)) # and uncompressed RLE, no pycocotools needed
+```
+
+### Running a model
+
+```python
+import cv2u as cv
+
+net = cv.dnn.loadModel("C:/모델/yolov8n.onnx") # Unicode path; FileNotFoundError instead of a C++ assertion
+names = cv.dnn.readClassNames("coco.names")
+img = cv.imread("street.jpg")
+blob, info = cv.dnn.preprocessImage(img, (640, 640)) # letterbox + blob; info remembers the geometry
+output = cv.dnn.inferImage(net, blob)[0] # every output layer, not just the first
+dets = cv.dnn.postprocessDetections(
+ output, info, scoreThreshold=0.3
+) # YOLO rows -> Detections(boxes, scores, classIds)
+cv.imwrite("result.png", cv.dnn.drawDetections(img, dets, names)) # boxes on the original image
+```
+
+Everything else in `cv.dnn` (`cv.dnn.readNet`, `cv.dnn.blobFromImage`, `cv.dnn.NMSBoxes`, ...) is passed through from OpenCV.
+
+### Video tools
+
+```python
+import cv2u as cv
+
+fps = cv.FPSCounter()
+with cv.VideoReader("input.mp4") as video, cv.VideoWriterEx("out.mp4", fps=video.fps) as writer:
+ video.seekTime(5.0) # start at 00:05
+ for frame in video:
+ fps.tick()
+ writer.write(cv.drawFPS(cv.autoCanny(frame), fps.fps)) # codec, size and color mode from the first frame
+
+cuts = cv.detectScenes("input.mp4", threshold=30) # frame indices where a new shot starts
+print([cv.formatTimestamp(cv.frameToTime(i, video.fps)) for i in cuts]) # "00:00:12.400", ...
+cv.extractFrames("input.mp4", "frames/", step=30, ext=".png") # one file every 30 frames
+cv.videoToGif("input.mp4", "preview.gif", fps=10, size=(320, 180), maxFrames=50)
+cv.imwrite("sheet.jpg", cv.videoThumbnail("input.mp4", count=6, cols=3)) # contact sheet
+```
+
+### Documents and quality
+
+```python
+import cv2u as cv
+
+photo = cv.imread("receipt.jpg")
+page = cv.scanDocument(photo) # detect the page, warp it upright, clean the background
+mask = cv.sauvolaThreshold(page, invert=True) # local threshold for OCR, no contrib module needed
+for x, y, w, h in cv.detectTextLines(page): # one box per text line, top to bottom
+ cv.drawDashedRectangle(page, (x, y, w, h), (0, 160, 255))
+
+stats = cv.imageStats(photo) # ImageStats(width, height, channels, dtype, mean, std, ..., sharpness, entropy, isGray)
+if cv.isBlurry(photo) or cv.isBlank(photo):
+ print("retake:", stats.sharpness, stats.contrast)
+cv.imwrite("compare.png", cv.compareImages(photo, page, mode="side", labels=["photo", "scan"]))
+```
+
### rotateEx
Rotates an image without cropping its corners. The canvas grows to fit the result.
@@ -172,7 +250,7 @@ for i, contour in enumerate(cv.sortContours(round_ones, "left-to-right")):
stats = cv.contourStats(contour) # area, perimeter, rect, center, solidity, circularity, ...
cv.drawLabel(scan, stats.rect, f"{i}: {stats.area:.0f} px", (0, 160, 255))
cv.imwriteEx(f"out/piece_{i}.png", cv.cropContour(scan, contour, transparent=True), makeDirs=True)
-debug = cv.drawContoursEx(scan, contours, labels=True) # each contour in its own color, numbered
+debug = cv.drawContoursEx(cv.toBGR(scan), contours, labels=True) # each contour in its own color, numbered
for x, y, w, h, score in cv.findTemplate(scan, cv.imread("logo.png"), threshold=0.9):
print(f"logo at ({x}, {y}), score {score:.2f}")
@@ -204,13 +282,13 @@ images, simply add up, so it neither needs a sample nor splits flat colors apart
`meanShiftColors` added two clusters of 421 and 79 pixels. `bins` and `sigma` make it finer or coarser, and
`minRegion` absorbs small speckles into the surrounding region.
-
+
On a real photo of a sneaker, `peakColors` separates background, the dark and bright
greens and the white parts into 4 clean regions. `meanShiftColors` finds 6 colors but leaves the surface
-speckled, and `DBSCAN` with `eps=1.7` splits the image into 496 tiny clusters, which mostly reproduces the input.
+speckled, and `dbscanColors` with `eps=1.7` splits the image into 496 tiny clusters, which mostly reproduces the input.
Note that the dark-red star (15 pixels, 0.04% of the image, almost black) merges into the background with every
-color clustering except that very fine `DBSCAN`; details this small are below what a palette can keep.
+color clustering except that very fine `dbscanColors`; details this small are below what a palette can keep.
```python
import cv2u as cv
@@ -263,39 +341,55 @@ Full reference with parameters and exceptions: np.random.Generator:
@pytest.fixture(scope="session")
def bgr(rng: np.random.Generator) -> np.ndarray:
"""A 1080p BGR photo-like image: smooth gradients plus noise and a few shapes."""
- img = cv.makeGradient((1080, 1920, 3), (40, 60, 90), (200, 180, 160))
+ img = cv.makeGradient((1920, 1080), (40, 60, 90), (200, 180, 160))
noise = rng.integers(-20, 20, img.shape, np.int16)
img = np.clip(img.astype(np.int16) + noise, 0, 255).astype(np.uint8)
cv.circle(img, (600, 500), 200, (255, 255, 255), -1)
diff --git a/benchmarks/test_benchmarks.py b/benchmarks/test_benchmarks.py
index 4d3faaa..584c4bb 100644
--- a/benchmarks/test_benchmarks.py
+++ b/benchmarks/test_benchmarks.py
@@ -15,8 +15,8 @@ def test_rotateEx(benchmark, bgr):
benchmark(cv.rotateEx, bgr, 30)
-def test_cropEx(benchmark, bgr):
- benchmark(cv.cropEx, bgr, (-100, -100, 800, 600))
+def test_cropRect(benchmark, bgr):
+ benchmark(cv.cropRect, bgr, (-100, -100, 800, 600))
def test_montage(benchmark, small):
diff --git a/benchmarks/test_overhead.py b/benchmarks/test_overhead.py
index f392c5d..68e4c38 100644
--- a/benchmarks/test_overhead.py
+++ b/benchmarks/test_overhead.py
@@ -78,8 +78,8 @@ def test_findContoursEx_vs_findContours(mask):
)
-def test_cropEx_vs_slicing(bgr):
- _assert_close("cropEx", lambda: cv.cropEx(bgr, (100, 100, 800, 600)), lambda: bgr[100:700, 100:900].copy())
+def test_cropRect_vs_slicing(bgr):
+ _assert_close("cropRect", lambda: cv.cropRect(bgr, (100, 100, 800, 600)), lambda: bgr[100:700, 100:900].copy())
def test_padToMultiple_vs_copyMakeBorder(bgr):
diff --git a/cv2u/__init__.py b/cv2u/__init__.py
index ea20c13..d73eece 100644
--- a/cv2u/__init__.py
+++ b/cv2u/__init__.py
@@ -26,45 +26,94 @@
from . import _cv2_exports
from ._cv2_exports import * # noqa: F403
+from . import dnn # noqa: F401 (cv2u.dnn replaces cv2.dnn and passes its names through)
+from .calib3d import (
+ CameraCalibration,
+ calibrateCameraEx,
+ findChessboardEx,
+ loadCalibration,
+ makeChessboard,
+ objectPointsGrid,
+ reprojectionErrors,
+ saveCalibration,
+ undistortEx,
+)
from .core import (
- DBSCAN,
- DHEdge,
+ Clusters,
+ angleBetween,
+ boldEdges,
+ boxesToPolygons,
+ boxesToYolo,
boxIoU,
cartesianToPolar,
- centerCrop,
centerPoint,
clipBoxes,
+ clipPoints,
clusterPoints,
colorQuantize,
- cropEx,
+ colorToLabelMap,
+ cropCenter,
+ cropRect,
cropToContent,
+ dbscanColors,
+ denormalizePoints,
+ distancePoints,
dominantColors,
- drawDBSCAN,
+ drawClusters,
+ drawPolygons,
+ drawSegmentation,
expandBoxes,
+ flipBoxes,
+ flipPoints,
+ flipPolygons,
gammaCorrection,
hconcatEx,
imcolor,
imcolorLike,
inRangeEx,
+ instanceMasksToLabelMap,
isInside,
kmeansColors,
+ labelMapToColor,
+ labelMapToMasks,
+ lineIntersection,
makeGradient,
mapTiles,
+ maskIoU,
+ maskToPolygons,
meanShiftColors,
mergeTiles,
montage,
+ nearestPoints,
nms,
+ normalizePoints,
+ orderPoints,
overlayImage,
padToMultiple,
padToSize,
peakColors,
+ pointLineDistance,
+ pointsBoundingBox,
polarToCartesian,
+ polygonArea,
+ polygonCentroid,
+ polygonIoU,
+ polygonsToBoxes,
+ polygonsToMask,
+ readYoloLabels,
+ rleDecode,
+ rleEncode,
rotateEx,
+ rotatePoints,
scaleBoxes,
+ scalePoints,
splitTiles,
+ translatePoints,
vconcatEx,
+ writeYoloLabels,
xywhToXyxy,
xyxyToXywh,
+ yoloToBoxes,
)
from .flag import (
ALL_CONTOURS,
@@ -86,23 +135,37 @@
imshowInline,
)
from .imgcodecs import (
+ ImageInfo,
+ convertImageFormat,
+ exifOrientation,
fromPillow,
+ imageInfo,
imdecodeBase64,
+ imdecodeEx,
imencodeBase64,
+ imencodeEx,
imreadAll,
imreadEx,
+ imreadOriented,
+ imreadResized,
+ imreadUrl,
imwriteAll,
imwriteEx,
listImages,
toPillow,
- urlread,
)
from .imgproc import (
+ COCO_SKELETON,
+ CSS_COLORS,
ContourStats,
FeatureMatches,
+ ImageStats,
+ Letterbox,
+ addNoise,
adjustBrightnessContrast,
adjustHSV,
alignImages,
+ applyColorMapEx,
applyMask,
approxContour,
asContour,
@@ -110,67 +173,158 @@
autoContrast,
bgrToHex,
binarize,
+ blendColors,
+ blendImages,
boundingRects,
+ brightnessScore,
+ colorBar,
+ colorDistance,
+ colorfulness,
+ colormapPalette,
+ colorName,
colorTransfer,
+ compareImages,
+ complementaryColor,
contourStats,
contoursToMask,
+ contrastScore,
cropContour,
cropRotatedRect,
+ cutMix,
cutout,
+ darkenColor,
deskew,
- detectBlobs,
+ detectPage,
+ detectTextBlocks,
+ detectTextLines,
diffMask,
distinctColors,
+ dominantHue,
+ drawArrow,
drawBoxes,
drawContoursEx,
+ drawCrosshair,
drawDashedLine,
drawDashedRectangle,
+ drawFPS,
drawGrid,
drawHistogram,
drawLabel,
+ drawLegend,
drawPoints,
+ drawPolygon,
+ drawProgressBar,
+ drawRotatedBoxes,
+ drawRotatedRect,
drawRoundedRectangle,
+ drawSkeleton,
+ drawTextBlock,
+ drawTrajectory,
+ enhanceDocument,
+ entropy,
equalizeHistEx,
+ estimateNoise,
+ estimateSkew,
+ exposureScore,
fillHoles,
filterContours,
+ findBlobs,
findCircles,
findContoursEx,
findLines,
findTemplate,
flattenAlpha,
fourPointTransform,
+ gradientPalette,
hashDistance,
+ heatmap,
hexToBGR,
+ histogramCompare,
+ histogramEx,
imageHash,
+ imageStats,
+ invertColor,
+ isBlank,
+ isBlurry,
+ isGrayscale,
+ jpegArtifacts,
+ labeledMontage,
largestComponent,
letterbox,
+ lightenColor,
+ mae,
maskBoundingRect,
matchFeatures,
matchHistograms,
+ meanColor,
mergeContours,
+ mixup,
morphology,
+ mosaic,
+ motionBlur,
+ mse,
+ nearestColor,
+ niblackThreshold,
overlayMask,
pixelate,
+ posterize,
putTextEx,
+ randomBlur,
+ randomBrightnessContrast,
+ randomColors,
+ randomCrop,
+ randomErase,
+ randomFlip,
+ randomHSV,
+ randomPerspective,
+ randomRotate,
+ randomScale,
+ removeBorder,
+ removeLines,
+ removeShadow,
removeSmallObjects,
+ removeSpeckles,
resizeEx,
+ sauvolaThreshold,
+ scanDocument,
sharpnessScore,
skeletonize,
+ solarize,
sortContours,
ssim,
+ stitchImages,
+ stitchPair,
+ textColorFor,
toBGR,
toBGRA,
toGray,
transformPoints,
translate,
unsharpMask,
+ vignette,
whiteBalance,
)
from .videoio import (
+ CameraStream,
+ FPSCounter,
VideoInfo,
+ VideoReader,
+ VideoWriterEx,
+ concatVideos,
+ detectScenes,
+ extractFrames,
+ formatTimestamp,
+ frameToTime,
+ imagesToVideo,
readFrameAt,
readFrames,
+ resizeVideo,
+ sampleFrames,
+ timeToFrame,
+ trimVideo,
videoInfo,
+ videoThumbnail,
+ videoToGif,
writeVideo,
)
@@ -182,7 +336,8 @@
# Only the cv2u extensions. OpenCV names are reachable as attributes, not through ``import *``.
__all__ = [
"ALL_CONTOURS",
- "DBSCAN",
+ "COCO_SKELETON",
+ "CSS_COLORS",
"DDEPTH_SAME",
"FLIP_MODE_X",
"FLIP_MODE_XY",
@@ -195,13 +350,24 @@
"REDUCE_TO_COL",
"REDUCE_TO_ROW",
"WAIT_FOREVER",
+ "CameraCalibration",
+ "CameraStream",
+ "Clusters",
"ContourStats",
- "DHEdge",
+ "FPSCounter",
"FeatureMatches",
+ "ImageInfo",
+ "ImageStats",
+ "Letterbox",
"VideoInfo",
+ "VideoReader",
+ "VideoWriterEx",
+ "addNoise",
"adjustBrightnessContrast",
"adjustHSV",
"alignImages",
+ "angleBetween",
+ "applyColorMapEx",
"applyMask",
"approxContour",
"asContour",
@@ -209,113 +375,252 @@
"autoContrast",
"bgrToHex",
"binarize",
+ "blendColors",
+ "blendImages",
+ "boldEdges",
"boundingRects",
"boxIoU",
+ "boxesToPolygons",
+ "boxesToYolo",
+ "brightnessScore",
+ "calibrateCameraEx",
"cartesianToPolar",
- "centerCrop",
"centerPoint",
"clipBoxes",
+ "clipPoints",
"clusterPoints",
+ "colorBar",
+ "colorDistance",
+ "colorName",
"colorQuantize",
+ "colorToLabelMap",
"colorTransfer",
+ "colorfulness",
+ "colormapPalette",
+ "compareImages",
+ "complementaryColor",
+ "concatVideos",
"contourStats",
"contoursToMask",
+ "contrastScore",
+ "convertImageFormat",
+ "cropCenter",
"cropContour",
- "cropEx",
+ "cropRect",
"cropRotatedRect",
"cropToContent",
+ "cutMix",
"cutout",
+ "darkenColor",
+ "dbscanColors",
+ "denormalizePoints",
"deskew",
- "detectBlobs",
+ "detectPage",
+ "detectScenes",
+ "detectTextBlocks",
+ "detectTextLines",
"diffMask",
+ "distancePoints",
"distinctColors",
"dominantColors",
+ "dominantHue",
+ "drawArrow",
"drawBoxes",
+ "drawClusters",
"drawContoursEx",
- "drawDBSCAN",
+ "drawCrosshair",
"drawDashedLine",
"drawDashedRectangle",
+ "drawFPS",
"drawGrid",
"drawHistogram",
"drawLabel",
+ "drawLegend",
"drawPoints",
+ "drawPolygon",
+ "drawPolygons",
+ "drawProgressBar",
+ "drawRotatedBoxes",
+ "drawRotatedRect",
"drawRoundedRectangle",
+ "drawSegmentation",
+ "drawSkeleton",
+ "drawTextBlock",
+ "drawTrajectory",
+ "enhanceDocument",
+ "entropy",
"equalizeHistEx",
+ "estimateNoise",
+ "estimateSkew",
+ "exifOrientation",
"expandBoxes",
+ "exposureScore",
+ "extractFrames",
"fillHoles",
"filterContours",
+ "findBlobs",
+ "findChessboardEx",
"findCircles",
"findContoursEx",
"findLines",
"findTemplate",
"flattenAlpha",
+ "flipBoxes",
+ "flipPoints",
+ "flipPolygons",
+ "formatTimestamp",
"fourPointTransform",
+ "frameToTime",
"fromPillow",
"gammaCorrection",
+ "gradientPalette",
"hashDistance",
"hconcatEx",
+ "heatmap",
"hexToBGR",
+ "histogramCompare",
+ "histogramEx",
"imageHash",
+ "imageInfo",
+ "imageStats",
+ "imagesToVideo",
"imcolor",
"imcolorLike",
"imdecodeBase64",
+ "imdecodeEx",
"imencodeBase64",
+ "imencodeEx",
"imreadAll",
"imreadEx",
+ "imreadOriented",
+ "imreadResized",
+ "imreadUrl",
"imshowEx",
"imshowInline",
"imwriteAll",
"imwriteEx",
"inRangeEx",
+ "instanceMasksToLabelMap",
+ "invertColor",
+ "isBlank",
+ "isBlurry",
+ "isGrayscale",
"isInside",
+ "jpegArtifacts",
"kmeansColors",
+ "labelMapToColor",
+ "labelMapToMasks",
+ "labeledMontage",
"largestComponent",
"letterbox",
+ "lightenColor",
+ "lineIntersection",
"listImages",
+ "loadCalibration",
+ "mae",
+ "makeChessboard",
"makeGradient",
"mapTiles",
"maskBoundingRect",
+ "maskIoU",
+ "maskToPolygons",
"matchFeatures",
"matchHistograms",
+ "meanColor",
"meanShiftColors",
"mergeContours",
"mergeTiles",
+ "mixup",
"montage",
"morphology",
+ "mosaic",
+ "motionBlur",
+ "mse",
+ "nearestColor",
+ "nearestPoints",
+ "niblackThreshold",
"nms",
+ "normalizePoints",
+ "objectPointsGrid",
+ "orderPoints",
"overlayImage",
"overlayMask",
"padToMultiple",
"padToSize",
"peakColors",
"pixelate",
+ "pointLineDistance",
+ "pointsBoundingBox",
"polarToCartesian",
+ "polygonArea",
+ "polygonCentroid",
+ "polygonIoU",
+ "polygonsToBoxes",
+ "polygonsToMask",
+ "posterize",
"putTextEx",
+ "randomBlur",
+ "randomBrightnessContrast",
+ "randomColors",
+ "randomCrop",
+ "randomErase",
+ "randomFlip",
+ "randomHSV",
+ "randomPerspective",
+ "randomRotate",
+ "randomScale",
"readFrameAt",
"readFrames",
+ "readYoloLabels",
+ "removeBorder",
+ "removeLines",
+ "removeShadow",
"removeSmallObjects",
+ "removeSpeckles",
+ "reprojectionErrors",
"resizeEx",
+ "resizeVideo",
+ "rleDecode",
+ "rleEncode",
"rotateEx",
+ "rotatePoints",
+ "sampleFrames",
+ "sauvolaThreshold",
+ "saveCalibration",
"scaleBoxes",
+ "scalePoints",
+ "scanDocument",
"sharpnessScore",
"skeletonize",
+ "solarize",
"sortContours",
"splitTiles",
"ssim",
+ "stitchImages",
+ "stitchPair",
+ "textColorFor",
+ "timeToFrame",
"toBGR",
"toBGRA",
"toGray",
"toPillow",
"transformPoints",
"translate",
+ "translatePoints",
+ "trimVideo",
+ "undistortEx",
"unsharpMask",
- "urlread",
"vconcatEx",
"videoInfo",
+ "videoThumbnail",
+ "videoToGif",
+ "vignette",
"whiteBalance",
"writeVideo",
+ "writeYoloLabels",
"xywhToXyxy",
"xyxyToXywh",
+ "yoloToBoxes",
]
if TYPE_CHECKING:
diff --git a/cv2u/_cv2_exports.pyi b/cv2u/_cv2_exports.pyi
index d80bcb4..c8d41b7 100644
--- a/cv2u/_cv2_exports.pyi
+++ b/cv2u/_cv2_exports.pyi
@@ -2207,7 +2207,6 @@ from cv2 import (
distanceTransformWithLabels as distanceTransformWithLabels,
divSpectrums as divSpectrums,
divide as divide,
- dnn as dnn,
dnn_registerLayer as dnn_registerLayer,
dnn_unregisterLayer as dnn_unregisterLayer,
drawChessboardCorners as drawChessboardCorners,
@@ -4702,7 +4701,6 @@ __all__ = [
"distanceTransformWithLabels",
"divSpectrums",
"divide",
- "dnn",
"dnn_registerLayer",
"dnn_unregisterLayer",
"drawChessboardCorners",
diff --git a/cv2u/_validate.py b/cv2u/_validate.py
index c13213e..c86d008 100644
--- a/cv2u/_validate.py
+++ b/cv2u/_validate.py
@@ -1,11 +1,23 @@
"""Argument checks shared by the extensions: one wording for every function."""
import math
+import numbers
+from collections.abc import Sequence
from typing import Any
import numpy as np
-__all__ = ["check_color", "check_finite", "check_image_not_empty"]
+__all__ = [
+ "as_color",
+ "check_channels",
+ "check_color",
+ "check_finite",
+ "check_image_not_empty",
+ "check_size",
+ "check_uint8",
+ "is_single_color",
+ "to_uint8",
+]
def check_finite(name: str, value: float, *, positive: bool = False, nonnegative: bool = False) -> None:
@@ -41,3 +53,93 @@ def check_image_not_empty(name: str, image: np.ndarray) -> None:
"""Raise ``ValueError`` for an image without pixels (OpenCV would fail with an assertion from its C++ code)."""
if image.size == 0:
raise ValueError(f"{name} must not be empty, got shape {image.shape}")
+
+
+def check_channels(name: str, image: np.ndarray) -> int:
+ """Return the channel count (1, 3 or 4) of a grayscale, BGR or BGRA image, or raise ``ValueError``.
+
+ Shared by every function that accepts "any image": a 2-D array counts as one channel, and anything else
+ (a 1-D array, a 2-channel image, a batch) is rejected with a message naming the argument.
+ """
+ channels = 1 if image.ndim == 2 else int(image.shape[2]) if image.ndim == 3 else 0
+ if channels not in (1, 3, 4):
+ raise ValueError(f"{name} must have 1, 3 or 4 channels, got shape {image.shape}")
+ return channels
+
+
+def check_uint8(name: str, image: np.ndarray) -> int:
+ """Return the channel count of a non-empty 8-bit grayscale, BGR or BGRA image, or raise ``ValueError``.
+
+ OpenCV's drawing and document functions accept only ``uint8`` and fail (or draw garbage) on other depths.
+ """
+ if image.dtype != np.uint8:
+ raise ValueError(f"{name} must be an 8-bit (uint8) image, got dtype {image.dtype}")
+ check_image_not_empty(name, image)
+ return check_channels(name, image)
+
+
+def check_size(name: str, size: Sequence[float]) -> tuple[int, int]:
+ """Return a ``(width, height)`` size as positive ints, or raise ``ValueError``.
+
+ ``NaN``, infinities, zeros and negative values would surface later as an OpenCV assertion or an empty array.
+ """
+ if len(size) != 2:
+ raise ValueError(f"{name} must be (width, height), got {size!r}")
+ width, height = float(size[0]), float(size[1])
+ if not (math.isfinite(width) and math.isfinite(height)) or width < 1 or height < 1:
+ raise ValueError(f"{name} must be a positive (width, height) size, got {size!r}")
+ return int(width), int(height)
+
+
+def is_single_color(value: object) -> bool:
+ """Whether ``value`` is one color (a number, or 1, 3 or 4 numbers) rather than a sequence of colors.
+
+ Accepts Python and NumPy scalars and 1-D sequences or arrays of numbers, so a row of ``Clusters.centers``
+ (``np.array([0, 0, 255], np.uint8)``) counts as one color and is not mistaken for a palette of three. Two
+ numbers are never one color (no image has 2 channels): ``[200, 100]`` is two gray levels.
+ """
+ if isinstance(value, (bool, np.bool_)):
+ return False
+ if isinstance(value, (numbers.Real, np.number)):
+ return True
+ if isinstance(value, np.ndarray):
+ return value.ndim == 1 and value.size in (1, 3, 4) and np.issubdtype(value.dtype, np.number)
+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
+ return False
+ return len(value) in (1, 3, 4) and all(
+ isinstance(v, (numbers.Real, np.number)) and not isinstance(v, (bool, np.bool_)) for v in value
+ )
+
+
+def as_color(value: Any) -> float | tuple[float, ...]:
+ """One color as a Python ``float`` or tuple of floats, so OpenCV accepts it.
+
+ OpenCV rejects NumPy integer scalars and ``uint8`` arrays as colors ("Scalar value for argument 'color' is not
+ numeric"); a row of ``Clusters.centers`` or a ``np.uint8`` level has to be converted first.
+ """
+ if isinstance(value, (np.ndarray, np.generic)):
+ value = value.tolist()
+ if isinstance(value, numbers.Real):
+ return float(value)
+ return tuple(float(v) for v in value)
+
+
+def to_uint8(src: np.ndarray) -> np.ndarray:
+ """8-bit version of an image for formats and functions that only take ``uint8``, scaled by the dtype range.
+
+ Integer images are divided by their dtype peak (``65535`` for 16-bit). Float images are assumed to be in
+ ``[0, 1]``; when their maximum exceeds 1 they are scaled by that maximum instead. A plain ``astype(np.uint8)``
+ wraps 16-bit values around and ``cv.imwrite`` saturates them to white.
+ """
+ if src.dtype == np.uint8:
+ return src
+ values = src.astype(np.float64)
+ if np.issubdtype(src.dtype, np.integer):
+ peak = float(np.iinfo(src.dtype).max)
+ else:
+ finite = values[np.isfinite(values)]
+ top = float(np.max(finite)) if finite.size else 1.0
+ peak = top if top > 1.0 else 1.0
+ scaled = np.clip(np.nan_to_num(values) * (255.0 / peak), 0, 255)
+ out: np.ndarray = np.rint(scaled).astype(np.uint8)
+ return out
diff --git a/cv2u/calib3d/__init__.py b/cv2u/calib3d/__init__.py
new file mode 100644
index 0000000..3a1a120
--- /dev/null
+++ b/cv2u/calib3d/__init__.py
@@ -0,0 +1,23 @@
+from .calibrate import (
+ CameraCalibration,
+ calibrateCameraEx,
+ findChessboardEx,
+ loadCalibration,
+ makeChessboard,
+ objectPointsGrid,
+ reprojectionErrors,
+ saveCalibration,
+ undistortEx,
+)
+
+__all__ = [
+ "CameraCalibration",
+ "calibrateCameraEx",
+ "findChessboardEx",
+ "loadCalibration",
+ "makeChessboard",
+ "objectPointsGrid",
+ "reprojectionErrors",
+ "saveCalibration",
+ "undistortEx",
+]
diff --git a/cv2u/calib3d/calibrate.py b/cv2u/calib3d/calibrate.py
new file mode 100644
index 0000000..f94ede0
--- /dev/null
+++ b/cv2u/calib3d/calibrate.py
@@ -0,0 +1,381 @@
+"""Camera calibration with a chessboard: corner detection, calibration, undistortion and a JSON file format."""
+
+import json
+import os
+from collections.abc import Sequence
+from typing import Any, NamedTuple
+
+import cv2
+import numpy as np
+
+from .._validate import check_finite, check_image_not_empty
+
+__all__ = [
+ "CameraCalibration",
+ "calibrateCameraEx",
+ "findChessboardEx",
+ "loadCalibration",
+ "makeChessboard",
+ "objectPointsGrid",
+ "reprojectionErrors",
+ "saveCalibration",
+ "undistortEx",
+]
+
+
+class CameraCalibration(NamedTuple):
+ """The result of :func:`calibrateCameraEx` (everything ``cv.calibrateCamera`` returns, plus the image size)."""
+
+ cameraMatrix: np.ndarray
+ """Intrinsic matrix, shape ``(3, 3)`` float64."""
+ distCoeffs: np.ndarray
+ """Distortion coefficients ``(k1, k2, p1, p2, k3, ...)``, shape ``(1, N)`` float64."""
+ imageSize: tuple[int, int]
+ """Size of the calibration images as ``(width, height)``."""
+ rms: float
+ """Overall RMS reprojection error in pixels (below 1.0 is a good calibration)."""
+ rvecs: tuple[np.ndarray, ...]
+ """Rotation vector of the board in each view, shape ``(3, 1)`` each."""
+ tvecs: tuple[np.ndarray, ...]
+ """Translation vector of the board in each view, shape ``(3, 1)`` each."""
+ 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."""
+
+
+def _check_pattern(patternSize: tuple[int, int]) -> tuple[int, int]:
+ cols, rows = int(patternSize[0]), int(patternSize[1])
+ if cols < 2 or rows < 2:
+ raise ValueError(f"patternSize must have at least 2 inner corners per side, got {patternSize}")
+ return cols, rows
+
+
+def 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.
+
+ Args:
+ patternSize: Inner corners per row and column as ``(columns, rows)``, like ``cv.findChessboardCorners``.
+ squareSize: Side of one square in your unit (mm, cm, ...); the translations come out in the same unit.
+
+ Returns:
+ Points of shape ``(columns * rows, 3)`` float32.
+
+ Raises:
+ ValueError: If ``patternSize`` has fewer than 2 corners per side or ``squareSize`` is not positive.
+ """
+ cols, rows = _check_pattern(patternSize)
+ check_finite("squareSize", squareSize, positive=True)
+ grid = np.zeros((cols * rows, 3), np.float32)
+ grid[:, :2] = np.mgrid[0:cols, 0:rows].T.reshape(-1, 2) * squareSize
+ return grid
+
+
+def 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.
+
+ Args:
+ patternSize: Inner corners as ``(columns, rows)``, the value to pass to :func:`findChessboardEx` later.
+ squareSize: Square side in pixels.
+ border: White margin around the board, in squares (the detector needs some white around the board).
+
+ Returns:
+ 8-bit grayscale image with ``columns + 1 + 2 * border`` by ``rows + 1 + 2 * border`` squares of
+ ``squareSize`` pixels.
+
+ Raises:
+ ValueError: If ``patternSize`` has fewer than 2 corners per side, ``squareSize`` is not positive or ``border``
+ is negative.
+ """
+ cols, rows = _check_pattern(patternSize)
+ if squareSize < 1:
+ raise ValueError(f"squareSize must be positive, got {squareSize}")
+ if border < 0:
+ raise ValueError(f"border must not be negative, got {border}")
+ squares_x, squares_y = cols + 1, rows + 1
+ cells = (np.indices((squares_y, squares_x)).sum(axis=0) % 2 * 255).astype(np.uint8)
+ board = np.kron(cells, np.ones((squareSize, squareSize), np.uint8))
+ margin = border * squareSize
+ return cv2.copyMakeBorder(board, margin, margin, margin, margin, cv2.BORDER_CONSTANT, value=255)
+
+
+def _gray(src: np.ndarray) -> np.ndarray:
+ if src.ndim == 2:
+ return src
+ if src.shape[2] == 4:
+ return cv2.cvtColor(src, cv2.COLOR_BGRA2GRAY)
+ return cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
+
+
+def findChessboardEx(
+ src: np.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.
+
+ Args:
+ src: Grayscale or BGR(A) image.
+ patternSize: Inner corners as ``(columns, rows)``.
+ refine: Run ``cv.cornerSubPix`` on the corners (not needed after ``findChessboardCornersSB``, which is
+ already sub-pixel accurate, but harmless).
+ flags: ``cv.CALIB_CB_*`` flags; ``None`` picks the detector's default.
+
+ Returns:
+ The corners as ``(columns * rows, 2)`` float32, or ``None`` if the board was not found.
+
+ Raises:
+ ValueError: If ``src`` is empty or ``patternSize`` is invalid.
+ """
+ check_image_not_empty("src", src)
+ cols, rows = _check_pattern(patternSize)
+ gray = _gray(src)
+ if hasattr(cv2, "findChessboardCornersSB"):
+ found, corners = cv2.findChessboardCornersSB(gray, (cols, rows), flags=flags or 0)
+ else: # pragma: no cover - OpenCV < 4.0
+ found, corners = cv2.findChessboardCorners(
+ gray,
+ (cols, rows),
+ flags=flags if flags is not None else cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE,
+ )
+ if not found or corners is None:
+ return None
+ corners = np.ascontiguousarray(corners, np.float32).reshape(-1, 1, 2)
+ if refine:
+ criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
+ corners = cv2.cornerSubPix(gray, corners, (5, 5), (-1, -1), criteria)
+ return corners.reshape(-1, 2)
+
+
+def _as_corners(cornersList: Sequence[np.ndarray], count: int) -> list[np.ndarray]:
+ views = []
+ for index, corners in enumerate(cornersList):
+ points = np.asarray(corners, np.float32).reshape(-1, 2)
+ if len(points) != count:
+ raise ValueError(f"view {index} has {len(points)} corners, expected {count} for the pattern size")
+ views.append(points.reshape(-1, 1, 2))
+ return views
+
+
+def calibrateCameraEx(
+ views: Sequence[np.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``.
+
+ Args:
+ views: Images of the chessboard, or corner arrays of shape ``(N, 2)`` such as :func:`findChessboardEx`
+ returns (then ``imageSize`` is required). Mixing the two is not supported.
+ patternSize: Inner corners as ``(columns, rows)``.
+ squareSize: Side of one square in your unit; ``tvecs`` come out in the same unit.
+ imageSize: ``(width, height)`` of the images, needed only when ``views`` are corner arrays.
+ flags: ``cv.CALIB_*`` flags for ``cv.calibrateCamera``.
+
+ Returns:
+ A :class:`CameraCalibration`. Its ``rvecs`` / ``tvecs`` have one entry per *used* view, so when a board was
+ missed they are shorter than ``views``; ``usedViews`` maps them back to the input indices.
+
+ Raises:
+ ValueError: If fewer than 3 views contain the board, ``imageSize`` is missing for corner input, a corner
+ array has the wrong number of points, or ``patternSize`` / ``squareSize`` are invalid.
+ """
+ cols, rows = _check_pattern(patternSize)
+ objp = objectPointsGrid((cols, rows), squareSize)
+ if len(views) == 0:
+ raise ValueError("views must not be empty")
+ first = np.asarray(views[0])
+ is_corners = (first.ndim == 2 and first.shape[1] == 2) or (first.ndim == 3 and first.shape[1:] == (1, 2))
+ if not is_corners:
+ height, width = views[0].shape[:2]
+ size = (width, height)
+ found = [(i, findChessboardEx(view, (cols, rows))) for i, view in enumerate(views)]
+ used = [i for i, c in found if c is not None]
+ corners_list = [c for _, c in found if c is not None]
+ else:
+ if imageSize is None:
+ raise ValueError("imageSize is required when views are corner arrays")
+ size = (int(imageSize[0]), int(imageSize[1]))
+ used = list(range(len(views)))
+ corners_list = list(views)
+ if len(corners_list) < 3:
+ raise ValueError(f"the chessboard was found in only {len(corners_list)} view(s), need at least 3")
+ image_points = _as_corners(corners_list, cols * rows)
+ rms, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(
+ [objp] * len(image_points), image_points, size, None, None, flags=flags
+ )
+ return CameraCalibration(
+ np.asarray(camera_matrix, np.float64),
+ np.asarray(dist_coeffs, np.float64).reshape(1, -1),
+ size,
+ float(rms),
+ tuple(np.asarray(r, np.float64).reshape(3, 1) for r in rvecs),
+ tuple(np.asarray(t, np.float64).reshape(3, 1) for t in tvecs),
+ tuple(used),
+ )
+
+
+def reprojectionErrors(
+ calib: CameraCalibration,
+ patternSize: tuple[int, int],
+ squareSize: float,
+ cornersList: Sequence[np.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.
+
+ Args:
+ calib: The calibration whose ``rvecs`` / ``tvecs`` belong to ``cornersList``.
+ patternSize: Inner corners as ``(columns, rows)``.
+ squareSize: Square size used for the calibration.
+ cornersList: The detected corners of each view, ``(N, 2)`` each: either one per used view (same order as
+ ``calib.rvecs``), or one per *original* view given to :func:`calibrateCameraEx` (then the views listed
+ in ``calib.usedViews`` are picked, so the output of :func:`findChessboardEx` for every image can be
+ passed as is, ``None`` entries included).
+
+ Returns:
+ One RMS error in pixels per used view, shape ``(len(calib.rvecs),)`` float64.
+
+ Raises:
+ ValueError: If the number of views matches neither ``calib.rvecs`` nor ``calib.usedViews``, a selected
+ entry is ``None``, or a corner array has the wrong size.
+ """
+ cols, rows = _check_pattern(patternSize)
+ objp = objectPointsGrid((cols, rows), squareSize)
+ count = len(calib.rvecs)
+ used = calib.usedViews
+ if len(cornersList) == count:
+ selected = list(cornersList)
+ elif len(used) == count and len(cornersList) > max(used, default=-1):
+ selected = [cornersList[i] for i in used]
+ else:
+ raise ValueError(f"cornersList has {len(cornersList)} views, but calib has {count} (usedViews: {len(used)})")
+ for index, corners in enumerate(selected):
+ if corners is None:
+ raise ValueError(f"view {index} has no corners (None), but it was used for the calibration")
+ errors = []
+ views = _as_corners([c for c in selected if c is not None], cols * rows)
+ for corners, rvec, tvec in zip(views, calib.rvecs, calib.tvecs, strict=True):
+ projected, _ = cv2.projectPoints(objp, rvec, tvec, calib.cameraMatrix, calib.distCoeffs)
+ diff = projected.reshape(-1, 2) - corners.reshape(-1, 2)
+ errors.append(float(np.sqrt(np.mean(np.sum(diff**2, axis=1)))))
+ return np.array(errors, np.float64)
+
+
+def undistortEx(
+ src: np.ndarray,
+ calib: CameraCalibration | np.ndarray,
+ distCoeffs: np.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.
+
+ Args:
+ src: Image taken with the calibrated camera (any channel count).
+ calib: A :class:`CameraCalibration`, or the ``(3, 3)`` camera matrix (then pass ``distCoeffs``).
+ distCoeffs: Distortion coefficients when ``calib`` is a matrix.
+ alpha: Free scaling parameter of ``cv.getOptimalNewCameraMatrix``: ``0`` keeps only valid pixels (no black
+ corners), ``1`` keeps every source pixel (black corners).
+ crop: Crop to the valid ROI. With ``False`` the result has the size of ``src``.
+
+ Returns:
+ The undistorted image, same dtype and channels as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``distCoeffs`` is missing for a matrix input, ``alpha`` is not in
+ ``[0, 1]``, or ``src`` has a different size than the calibration images (the matrix would not apply).
+ """
+ check_image_not_empty("src", src)
+ check_finite("alpha", alpha, nonnegative=True)
+ if alpha > 1:
+ raise ValueError(f"alpha must be in [0, 1], got {alpha}")
+ height, width = src.shape[:2]
+ if isinstance(calib, CameraCalibration):
+ camera_matrix, coeffs = calib.cameraMatrix, calib.distCoeffs
+ if calib.imageSize != (width, height):
+ raise ValueError(f"src has size {(width, height)}, but calib is for {calib.imageSize}")
+ else:
+ if distCoeffs is None:
+ raise ValueError("distCoeffs is required when calib is a camera matrix")
+ camera_matrix, coeffs = np.asarray(calib, np.float64), np.asarray(distCoeffs, np.float64)
+ new_matrix, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, coeffs, (width, height), alpha, (width, height))
+ result: np.ndarray = cv2.undistort(src, camera_matrix, coeffs, None, new_matrix)
+ if crop:
+ x, y, w, h = (int(v) for v in roi)
+ if w > 0 and h > 0:
+ result = result[y : y + h, x : x + w]
+ return result
+
+
+def saveCalibration(filename: str | os.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``.
+
+ Args:
+ filename: Path to write to (``.json``).
+ calib: The calibration to save.
+ """
+ data: dict[str, Any] = {
+ "cameraMatrix": calib.cameraMatrix.tolist(),
+ "distCoeffs": calib.distCoeffs.reshape(-1).tolist(),
+ "imageSize": list(calib.imageSize),
+ "rms": calib.rms,
+ "rvecs": [r.reshape(-1).tolist() for r in calib.rvecs],
+ "tvecs": [t.reshape(-1).tolist() for t in calib.tvecs],
+ "usedViews": list(calib.usedViews),
+ }
+ with open(os.fspath(filename), "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2)
+
+
+def loadCalibration(filename: str | os.PathLike[str]) -> CameraCalibration:
+ """Load a calibration written by :func:`saveCalibration`.
+
+ Args:
+ filename: Path of the JSON file.
+
+ Returns:
+ The :class:`CameraCalibration`.
+
+ Raises:
+ OSError: If the file cannot be read.
+ ValueError: If the file is not valid JSON or lacks a required key.
+ """
+ with open(os.fspath(filename), encoding="utf-8") as f:
+ data = json.load(f)
+ try:
+ return CameraCalibration(
+ np.asarray(data["cameraMatrix"], np.float64).reshape(3, 3),
+ np.asarray(data["distCoeffs"], np.float64).reshape(1, -1),
+ (int(data["imageSize"][0]), int(data["imageSize"][1])),
+ float(data["rms"]),
+ tuple(np.asarray(r, np.float64).reshape(3, 1) for r in data.get("rvecs", [])),
+ tuple(np.asarray(t, np.float64).reshape(3, 1) for t in data.get("tvecs", [])),
+ tuple(int(i) for i in data.get("usedViews", [])),
+ )
+ except (KeyError, TypeError) as exc:
+ raise ValueError(f"not a calibration file: {os.fspath(filename)!r} ({exc})") from exc
diff --git a/cv2u/core/__init__.py b/cv2u/core/__init__.py
index cc12822..e64d066 100644
--- a/cv2u/core/__init__.py
+++ b/cv2u/core/__init__.py
@@ -1,50 +1,136 @@
+from .annotations import (
+ boxesToPolygons,
+ boxesToYolo,
+ colorToLabelMap,
+ drawPolygons,
+ drawSegmentation,
+ flipBoxes,
+ flipPolygons,
+ instanceMasksToLabelMap,
+ labelMapToColor,
+ labelMapToMasks,
+ maskIoU,
+ maskToPolygons,
+ polygonArea,
+ polygonIoU,
+ polygonsToBoxes,
+ polygonsToMask,
+ readYoloLabels,
+ rleDecode,
+ rleEncode,
+ writeYoloLabels,
+ yoloToBoxes,
+)
from .boxes import boxIoU, clipBoxes, expandBoxes, nms, scaleBoxes, xywhToXyxy, xyxyToXywh
-from .cluster import DBSCAN, clusterPoints, colorQuantize, dominantColors, drawDBSCAN, kmeansColors, meanShiftColors
+from .cluster import (
+ Clusters,
+ clusterPoints,
+ colorQuantize,
+ dbscanColors,
+ dominantColors,
+ drawClusters,
+ kmeansColors,
+ meanShiftColors,
+)
from .compose import hconcatEx, montage, overlayImage, vconcatEx
-from .extension import DHEdge, cartesianToPolar, centerPoint, gammaCorrection, isInside, polarToCartesian
+from .extension import boldEdges, cartesianToPolar, centerPoint, gammaCorrection, isInside, polarToCartesian
from .images import imcolor, imcolorLike, makeGradient
from .layout import mapTiles, mergeTiles, padToMultiple, padToSize, splitTiles
from .peaks import peakColors
-from .roi import centerCrop, cropEx, cropToContent, inRangeEx
+from .points import (
+ angleBetween,
+ clipPoints,
+ denormalizePoints,
+ distancePoints,
+ flipPoints,
+ lineIntersection,
+ nearestPoints,
+ normalizePoints,
+ orderPoints,
+ pointLineDistance,
+ pointsBoundingBox,
+ polygonCentroid,
+ rotatePoints,
+ scalePoints,
+ translatePoints,
+)
+from .roi import cropCenter, cropRect, cropToContent, inRangeEx
from .rotate import rotateEx
__all__ = [
- "DBSCAN",
- "DHEdge",
+ "Clusters",
+ "angleBetween",
+ "boldEdges",
"boxIoU",
+ "boxesToPolygons",
+ "boxesToYolo",
"cartesianToPolar",
- "centerCrop",
"centerPoint",
"clipBoxes",
+ "clipPoints",
"clusterPoints",
"colorQuantize",
- "cropEx",
+ "colorToLabelMap",
+ "cropCenter",
+ "cropRect",
"cropToContent",
+ "dbscanColors",
+ "denormalizePoints",
+ "distancePoints",
"dominantColors",
- "drawDBSCAN",
+ "drawClusters",
+ "drawPolygons",
+ "drawSegmentation",
"expandBoxes",
+ "flipBoxes",
+ "flipPoints",
+ "flipPolygons",
"gammaCorrection",
"hconcatEx",
"imcolor",
"imcolorLike",
"inRangeEx",
+ "instanceMasksToLabelMap",
"isInside",
"kmeansColors",
+ "labelMapToColor",
+ "labelMapToMasks",
+ "lineIntersection",
"makeGradient",
"mapTiles",
+ "maskIoU",
+ "maskToPolygons",
"meanShiftColors",
"mergeTiles",
"montage",
+ "nearestPoints",
"nms",
+ "normalizePoints",
+ "orderPoints",
"overlayImage",
"padToMultiple",
"padToSize",
"peakColors",
+ "pointLineDistance",
+ "pointsBoundingBox",
"polarToCartesian",
+ "polygonArea",
+ "polygonCentroid",
+ "polygonIoU",
+ "polygonsToBoxes",
+ "polygonsToMask",
+ "readYoloLabels",
+ "rleDecode",
+ "rleEncode",
"rotateEx",
+ "rotatePoints",
"scaleBoxes",
+ "scalePoints",
"splitTiles",
+ "translatePoints",
"vconcatEx",
+ "writeYoloLabels",
"xywhToXyxy",
"xyxyToXywh",
+ "yoloToBoxes",
]
diff --git a/cv2u/core/annotations.py b/cv2u/core/annotations.py
new file mode 100644
index 0000000..b640dd7
--- /dev/null
+++ b/cv2u/core/annotations.py
@@ -0,0 +1,824 @@
+"""Annotation formats: polygons, RLE masks, YOLO labels, label maps and the conversions between them.
+
+Detection and segmentation datasets store the same objects in different shapes: a binary mask, a list of polygons
+(COCO), a run-length encoding (COCO RLE), normalized ``class cx cy w h`` rows (YOLO) or a label map of class ids.
+OpenCV has ``cv.findContours`` and ``cv.fillPoly`` for two of the steps and nothing for the rest; this module
+holds the small, well-defined conversions and measures (area, IoU, flips) that every dataset script rewrites.
+
+Conventions: boxes are ``(x, y, width, height)``, polygons are ``(N, 2)`` arrays (or lists) of ``(x, y)`` points,
+sizes are ``(width, height)``, label maps are 2-D integer arrays of class ids with ``background`` (default 0) for
+"no object". Coordinates are continuous (a pixel spans ``[x, x + 1)``), as in COCO and YOLO.
+"""
+
+import os
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+import cv2
+import numpy as np
+from numpy.typing import ArrayLike
+
+from .._validate import as_color, check_color, check_finite, check_image_not_empty, check_size, is_single_color
+from ..imgproc.color import distinctColors
+from ..imgproc.contour import approxContour, asContour, contoursToMask
+from ..imgproc.draw import _luminance
+from ..imgproc.mask import _foreground
+from .boxes import _boxes
+
+__all__ = [
+ "boxesToPolygons",
+ "boxesToYolo",
+ "colorToLabelMap",
+ "drawPolygons",
+ "drawSegmentation",
+ "flipBoxes",
+ "flipPolygons",
+ "instanceMasksToLabelMap",
+ "labelMapToColor",
+ "labelMapToMasks",
+ "maskIoU",
+ "maskToPolygons",
+ "polygonArea",
+ "polygonIoU",
+ "polygonsToBoxes",
+ "polygonsToMask",
+ "readYoloLabels",
+ "rleDecode",
+ "rleEncode",
+ "writeYoloLabels",
+ "yoloToBoxes",
+]
+
+Color = float | Sequence[float]
+
+
+def _polygon(polygon: ArrayLike, name: str = "polygon") -> np.ndarray:
+ """One polygon as a float64 ``(N, 2)`` array (accepts ``(N, 1, 2)`` contours and point lists)."""
+ array = np.asarray(polygon, dtype=np.float64)
+ if array.size == 0:
+ raise ValueError(f"{name} must not be empty")
+ if array.shape[-1] != 2:
+ raise ValueError(f"{name} must have 2 coordinates (x, y) per point, got shape {array.shape}")
+ if array.ndim > 3 or (array.ndim == 3 and array.shape[1] != 1):
+ raise ValueError(f"{name} must be (N, 2) points or an (N, 1, 2) contour, got shape {array.shape}")
+ if not np.all(np.isfinite(array)):
+ raise ValueError(f"{name} must be finite")
+ return array.reshape(-1, 2)
+
+
+def _polygons(polygons: Sequence[ArrayLike] | np.ndarray, name: str = "polygons") -> list[np.ndarray]:
+ """A sequence of polygons (or one polygon, as an ``(N, 2)`` array or point list) as float64 ``(N, 2)`` arrays.
+
+ Each polygon may be an ``(N, 2)`` array, an ``(N, 1, 2)`` contour or a list of ``(x, y)`` points, and the
+ polygons may have different lengths. The sequence is walked element-wise: ``np.asarray`` on the whole list
+ would turn equal-length contours into a 4-D array and ragged ones into an error.
+ """
+ if isinstance(polygons, np.ndarray):
+ if polygons.size == 0 and polygons.ndim <= 1:
+ return []
+ if polygons.ndim == 2 and polygons.shape[-1] == 2:
+ return [_polygon(polygons, name)] # one polygon
+ if polygons.ndim == 3 and polygons.shape[-1] == 2:
+ return [_polygon(p, name) for p in polygons] # equal-length polygons, or one (N, 1, 2) contour
+ raise ValueError(f"{name} must be a sequence of (N, 2) polygons, got shape {polygons.shape}")
+ items = list(polygons)
+ if len(items) == 0:
+ return []
+ if _is_point(items[0]):
+ return [_polygon(items, name)] # one polygon as a list of (x, y) points
+ return [_polygon(p, name) for p in items]
+
+
+def _is_point(item: object) -> bool:
+ """Whether a sequence element is one ``(x, y)`` point rather than a polygon."""
+ if isinstance(item, np.ndarray):
+ return item.ndim == 1
+ return isinstance(item, Sequence) and len(item) == 2 and all(isinstance(v, (int, float, np.number)) for v in item)
+
+
+def _label_map(labels: np.ndarray, name: str = "labels") -> np.ndarray:
+ if labels.ndim != 2:
+ raise ValueError(f"{name} must be a 2-D array of class ids, got shape {labels.shape}")
+ check_image_not_empty(name, labels)
+ if labels.dtype == bool:
+ return labels.astype(np.int32)
+ if not np.issubdtype(labels.dtype, np.integer):
+ raise ValueError(f"{name} must be an integer array of class ids, got dtype {labels.dtype}")
+ if labels.size and int(labels.min()) < 0:
+ raise ValueError(f"{name} must not contain negative class ids, got {int(labels.min())}")
+ return labels
+
+
+def _flip_code(flipCode: int) -> int:
+ if flipCode not in (0, 1, -1):
+ raise ValueError(f"flipCode must be 0 (vertical), 1 (horizontal) or -1 (both), got {flipCode}")
+ return flipCode
+
+
+# --- masks and polygons ----------------------------------------------------------
+
+
+def maskToPolygons(mask: np.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`.
+
+ Args:
+ mask: Binary mask; nonzero (or ``True``) pixels are foreground (color masks count any nonzero channel).
+ epsilon: Simplification tolerance as a fraction of each polygon's perimeter (``0.01`` = 1%); 0 keeps every
+ contour point.
+ minArea: Drop polygons whose ``cv.contourArea`` is smaller than this.
+
+ Returns:
+ A list of ``int32`` arrays of shape ``(N, 2)``, largest area first. The inverse is :func:`polygonsToMask`.
+
+ Raises:
+ ValueError: If ``mask`` is not a 2-D array or an image, is empty, or ``epsilon``/``minArea`` is negative.
+ """
+ check_finite("epsilon", epsilon, nonnegative=True)
+ check_finite("minArea", minArea, nonnegative=True)
+ fg = _foreground(mask)
+ contours, _ = cv2.findContours(fg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
+ items = []
+ for contour in contours:
+ if epsilon > 0:
+ contour = approxContour(contour, epsilon)
+ area = cv2.contourArea(contour)
+ if len(contour) >= 3 and area >= minArea:
+ items.append((contour.reshape(-1, 2).astype(np.int32), area))
+ items.sort(key=lambda item: item[1], reverse=True)
+ return [polygon for polygon, _ in items]
+
+
+def polygonsToMask(polygons: Sequence[ArrayLike] | np.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.
+
+ Args:
+ polygons: One polygon ``(N, 2)`` or a sequence of polygons (an empty sequence gives an all-zero mask).
+ size: ``(width, height)`` of the mask.
+ value: Value of the polygon pixels, 1 to 255.
+
+ Returns:
+ ``uint8`` mask with values 0 and ``value``.
+
+ Raises:
+ ValueError: If ``size`` is not positive, ``value`` is outside ``[1, 255]`` or a polygon is empty / not 2-D.
+ """
+ if not 1 <= value <= 255:
+ raise ValueError(f"value must be between 1 and 255, got {value}")
+ mask = contoursToMask([asContour(p) for p in _polygons(polygons)], check_size("size", size))
+ if value != 255:
+ mask[mask != 0] = value
+ return mask
+
+
+def 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:
+ A list with one float64 ``(4, 2)`` array per box.
+
+ Raises:
+ ValueError: If the boxes do not have 4 finite values.
+ """
+ array = _boxes(boxes, "boxes") if np.size(boxes) else np.zeros((0, 4))
+ out = []
+ for x, y, w, h in array:
+ out.append(np.array([[x, y], [x + w, y], [x + w, y + h], [x, y + h]], dtype=np.float64))
+ return out
+
+
+def polygonsToBoxes(polygons: Sequence[ArrayLike] | np.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``.
+
+ Args:
+ polygons: One polygon ``(N, 2)`` or a sequence of polygons.
+
+ Returns:
+ A float64 array of shape ``(N, 4)`` (``(0, 4)`` for no polygons).
+
+ Raises:
+ ValueError: If a polygon is empty, not 2-D or not finite.
+ """
+ items = _polygons(polygons)
+ if not items:
+ return np.zeros((0, 4), dtype=np.float64)
+ boxes = np.empty((len(items), 4), dtype=np.float64)
+ for i, polygon in enumerate(items):
+ low, high = polygon.min(axis=0), polygon.max(axis=0)
+ boxes[i] = (low[0], low[1], high[0] - low[0], high[1] - low[1])
+ return boxes
+
+
+def 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.
+
+ Args:
+ polygon: ``(N, 2)`` points (or a point list); the polygon is closed implicitly.
+
+ Returns:
+ The absolute area (0 for fewer than 3 points).
+
+ Raises:
+ ValueError: If ``polygon`` is empty, not 2-D or not finite.
+ """
+ points = _polygon(polygon)
+ if len(points) < 3:
+ return 0.0
+ x, y = points[:, 0], points[:, 1]
+ return float(abs(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) / 2)
+
+
+def 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.
+
+ Args:
+ polygonA: ``(N, 2)`` points.
+ polygonB: ``(M, 2)`` points.
+ resolution: Raster size of the longer side of the common bounding box, in pixels.
+
+ Returns:
+ A value from 0 (disjoint) to 1 (identical); 0 when either polygon has no area.
+
+ Raises:
+ ValueError: If a polygon is empty, not 2-D or not finite, or ``resolution`` is less than 1.
+ """
+ if resolution < 1:
+ raise ValueError(f"resolution must be at least 1, got {resolution}")
+ a, b = _polygon(polygonA, "polygonA"), _polygon(polygonB, "polygonB")
+ if len(a) < 3 or len(b) < 3:
+ return 0.0
+ both = np.concatenate([a, b])
+ low, high = both.min(axis=0), both.max(axis=0)
+ extent = float(max(high[0] - low[0], high[1] - low[1]))
+ if extent <= 0:
+ return 0.0
+ scale = resolution / extent
+ shift = 8
+ width = int(np.ceil((high[0] - low[0]) * scale)) + 1
+ height = int(np.ceil((high[1] - low[1]) * scale)) + 1
+ masks = []
+ for polygon in (a, b):
+ fixed = np.rint((polygon - low) * scale * (1 << shift)).astype(np.int32).reshape(-1, 1, 2)
+ mask = np.zeros((height, width), np.uint8)
+ cv2.fillPoly(mask, [fixed], 1, cv2.LINE_8, shift)
+ masks.append(mask.astype(bool))
+ union = int(np.count_nonzero(masks[0] | masks[1]))
+ if union == 0:
+ return 0.0
+ return int(np.count_nonzero(masks[0] & masks[1])) / union
+
+
+def maskIoU(maskA: np.ndarray, maskB: np.ndarray) -> float:
+ """Intersection over union of two binary masks of the same shape (the segmentation counterpart of :func:`boxIoU`).
+
+ Args:
+ maskA: Binary mask; nonzero (or ``True``) pixels are foreground.
+ maskB: Binary mask of the same height and width.
+
+ Returns:
+ A value from 0 to 1; 0 when both masks are empty.
+
+ Raises:
+ ValueError: If a mask is not a 2-D array or an image, is empty, or the shapes differ.
+ """
+ a, b = _foreground(maskA), _foreground(maskB)
+ if a.shape != b.shape:
+ raise ValueError(f"maskB must have the shape {a.shape}, got {b.shape}")
+ union = int(np.count_nonzero(a | b))
+ if union == 0:
+ return 0.0
+ return int(np.count_nonzero(a & b)) / union
+
+
+# --- run-length encoding ---------------------------------------------------------
+
+
+def rleEncode(mask: np.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.
+
+ Args:
+ mask: Binary mask; nonzero (or ``True``) pixels are foreground.
+
+ Returns:
+ A dict with ``"counts"`` (a list of ``int``) and ``"size"`` (``[height, width]``).
+
+ Raises:
+ ValueError: If ``mask`` is not a 2-D array or an image, or is empty.
+ """
+ fg2 = _foreground(mask)
+ fg = fg2.ravel(order="F")
+ changes = np.flatnonzero(fg[1:] != fg[:-1]) + 1
+ starts = np.concatenate([[0], changes])
+ ends = np.concatenate([changes, [fg.size]])
+ counts = ends - starts
+ if fg[0]:
+ counts = np.concatenate([[0], counts]) # the first run is background; COCO stores it as a 0-length run
+ height, width = fg2.shape
+ return {"counts": [int(c) for c in counts], "size": [int(height), int(width)]}
+
+
+def rleDecode(rle: dict[str, Any]) -> np.ndarray:
+ """Decode COCO uncompressed RLE (see :func:`rleEncode`) into a ``uint8`` mask with values 0 and 255.
+
+ Args:
+ rle: ``{"counts": [...], "size": [height, width]}`` with integer counts (compressed string counts are not
+ supported; decode those with ``pycocotools.mask.decode``).
+
+ Raises:
+ ValueError: If ``size`` is not positive, ``counts`` is not a list of non-negative integers, or the counts do
+ not add up to ``height * width``.
+ """
+ height, width = (int(v) for v in rle["size"])
+ if height < 1 or width < 1:
+ raise ValueError(f"rle['size'] must be positive [height, width], got {rle['size']}")
+ counts = rle["counts"]
+ if isinstance(counts, (str, bytes)):
+ raise ValueError("rle['counts'] must be a list of run lengths; compressed RLE strings are not supported")
+ runs = np.asarray(counts, dtype=np.int64).reshape(-1)
+ if runs.size and runs.min() < 0:
+ raise ValueError("rle['counts'] must not contain negative run lengths")
+ if int(runs.sum()) != height * width:
+ raise ValueError(f"rle['counts'] must add up to {height * width} pixels, got {int(runs.sum())}")
+ values = np.arange(runs.size) % 2 # background, foreground, background, ...
+ flat = np.repeat(values.astype(np.uint8), runs)
+ return np.asarray(flat.reshape((height, width), order="F"), dtype=np.uint8) * 255
+
+
+# --- YOLO labels -----------------------------------------------------------------
+
+
+def 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.
+
+ Args:
+ boxes: Boxes of shape ``(N, 4)`` (or one box).
+ size: ``(width, height)`` of the image.
+ classIds: One class id per box; when given, the rows are ``class cx cy w h`` as in a YOLO label file.
+
+ Returns:
+ A float64 array of shape ``(N, 4)``, or ``(N, 5)`` with ``classIds``. Values are not clipped to ``[0, 1]``.
+
+ Raises:
+ ValueError: If ``size`` is not positive, the boxes are invalid, or ``classIds`` has the wrong length.
+ """
+ width, height = check_size("size", size)
+ array = _boxes(boxes, "boxes") if np.size(boxes) else np.zeros((0, 4))
+ rows = np.stack(
+ [
+ (array[:, 0] + array[:, 2] / 2) / width,
+ (array[:, 1] + array[:, 3] / 2) / height,
+ array[:, 2] / width,
+ array[:, 3] / height,
+ ],
+ axis=1,
+ )
+ if classIds is None:
+ return rows
+ ids = np.asarray(classIds, dtype=np.float64).reshape(-1)
+ if len(ids) != len(array):
+ raise ValueError(f"classIds must have one value per box, got {len(ids)} for {len(array)} boxes")
+ return np.concatenate([ids[:, None], rows], axis=1)
+
+
+def 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)``.
+
+ Args:
+ rows: Array of shape ``(N, 5)`` (class first) or ``(N, 4)``; extra columns (confidence) are ignored.
+ size: ``(width, height)`` of the image.
+
+ Returns:
+ ``(boxes, classIds)``: float64 boxes of shape ``(N, 4)`` and ``int64`` ids of shape ``(N,)``, or ``None``
+ for ``classIds`` when the rows have no class column.
+
+ Raises:
+ ValueError: If ``size`` is not positive or the rows do not have 4 or more values.
+ """
+ width, height = check_size("size", size)
+ array = np.asarray(rows, dtype=np.float64)
+ if array.size == 0:
+ return np.zeros((0, 4), dtype=np.float64), np.zeros(0, dtype=np.int64)
+ if array.ndim == 1:
+ array = array[None]
+ if array.ndim != 2 or array.shape[1] < 4:
+ raise ValueError(f"rows must have shape (N, 4) or (N, 5+), got shape {array.shape}")
+ if not np.all(np.isfinite(array)):
+ raise ValueError("rows must be finite")
+ has_class = array.shape[1] >= 5
+ values = array[:, 1:5] if has_class else array[:, :4]
+ w, h = values[:, 2] * width, values[:, 3] * height
+ boxes = np.stack([values[:, 0] * width - w / 2, values[:, 1] * height - h / 2, w, h], axis=1)
+ return boxes, (np.rint(array[:, 0]).astype(np.int64) if has_class else None)
+
+
+def readYoloLabels(filename: str | os.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.
+
+ Args:
+ filename: Path of the ``.txt`` label file.
+ size: ``(width, height)`` of the matching image.
+
+ Returns:
+ ``(boxes, classIds)``: float64 boxes of shape ``(N, 4)`` and ``int64`` ids of shape ``(N,)``.
+
+ Raises:
+ ValueError: If ``size`` is not positive, or a line does not have at least 5 numbers.
+ """
+ check_size("size", size)
+ path = Path(filename)
+ rows: list[list[float]] = []
+ if path.is_file():
+ for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
+ parts = line.split()
+ if not parts:
+ continue
+ if len(parts) < 5:
+ raise ValueError(f"{path}: line {number} must have 'class cx cy w h', got {line!r}")
+ rows.append([float(v) for v in parts[:5]])
+ if not rows:
+ return np.zeros((0, 4), dtype=np.float64), np.zeros(0, dtype=np.int64)
+ boxes, ids = yoloToBoxes(np.array(rows), size)
+ assert ids is not None
+ return boxes, ids
+
+
+def writeYoloLabels(
+ filename: str | os.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).
+
+ Args:
+ filename: Path of the ``.txt`` file (any path, including non-ASCII); an empty box list writes an empty file.
+ boxes: Boxes of shape ``(N, 4)``.
+ classIds: One integer class id per box.
+ size: ``(width, height)`` of the matching image.
+ makeDirs: Create missing parent directories.
+
+ Raises:
+ ValueError: If ``size`` is not positive, the boxes are invalid, or ``classIds`` has the wrong length.
+ OSError: If the file cannot be written.
+ """
+ rows = boxesToYolo(boxes, size, classIds)
+ path = Path(filename)
+ if makeDirs:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lines = [f"{round(r[0])} {r[1]:.6f} {r[2]:.6f} {r[3]:.6f} {r[4]:.6f}" for r in rows]
+ path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
+
+
+# --- label maps ------------------------------------------------------------------
+
+
+def labelMapToColor(labels: np.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.
+
+ Args:
+ labels: 2-D integer array of class ids (``bool`` counts as 0/1).
+ palette: One BGR color per class id, indexed by id (``(K, 3)``); ``None`` uses
+ ``distinctColors(labels.max() + 1)``, so the same ids always get the same colors.
+ background: The id drawn black (set to ``-1`` to color every id from the palette).
+
+ Returns:
+ ``uint8`` BGR image with the shape of ``labels``.
+
+ Raises:
+ ValueError: If ``labels`` is not a 2-D integer array, is empty, has negative ids, or an id has no palette
+ entry.
+ """
+ ids = _label_map(labels)
+ top = int(ids.max()) if ids.size else 0
+ if palette is None:
+ lut = np.array(distinctColors(top + 1), dtype=np.uint8).reshape(-1, 3)
+ else:
+ given = np.asarray(palette, dtype=np.float64).reshape(-1, 3)
+ check_color("palette", [float(v) for v in given.ravel()], np.dtype(np.uint8))
+ lut = given.astype(np.uint8)
+ if top >= len(lut):
+ raise ValueError(f"palette must have a color for every class id up to {top}, got {len(lut)} colors")
+ if 0 <= background < len(lut):
+ lut = lut.copy()
+ lut[background] = 0
+ out: np.ndarray = lut[ids]
+ return out
+
+
+def colorToLabelMap(image: np.ndarray, palette: ArrayLike, background: int = 0) -> np.ndarray:
+ """Recover a label map from a colorized segmentation image (the inverse of :func:`labelMapToColor`).
+
+ Args:
+ image: 8-bit BGR (or BGRA) image whose colors come from ``palette``.
+ palette: One BGR color per class id, indexed by id (``(K, 3)``).
+ background: The id for pixels whose color is not in the palette.
+
+ Returns:
+ ``int32`` array of class ids with the shape ``image.shape[:2]``.
+
+ Raises:
+ ValueError: If ``image`` is not an 8-bit color image or is empty, or ``palette`` is not ``(K, 3)``.
+ """
+ if image.ndim != 3 or image.shape[2] < 3 or image.dtype != np.uint8:
+ raise ValueError(f"image must be an 8-bit BGR image, got shape {image.shape} and dtype {image.dtype}")
+ check_image_not_empty("image", image)
+ lut = np.asarray(palette, dtype=np.float64)
+ if lut.ndim != 2 or lut.shape[1] != 3 or lut.size == 0:
+ raise ValueError(f"palette must have shape (K, 3), got shape {lut.shape}")
+ check_color("palette", [float(v) for v in lut.ravel()], np.dtype(np.uint8))
+
+ def pack(bgr: np.ndarray) -> np.ndarray:
+ values = bgr.astype(np.int64)
+ return (values[..., 0] << 16) | (values[..., 1] << 8) | values[..., 2]
+
+ codes = pack(lut.astype(np.uint8))
+ unique, first = np.unique(codes, return_index=True) # duplicate colors map to the lowest id
+ pixels = pack(image[..., :3])
+ position = np.searchsorted(unique, pixels)
+ position = np.clip(position, 0, len(unique) - 1)
+ found = unique[position] == pixels
+ out = np.full(pixels.shape, background, dtype=np.int32)
+ out[found] = first[position[found]]
+ return out
+
+
+def instanceMasksToLabelMap(masks: Sequence[np.ndarray]) -> np.ndarray:
+ """Stack binary instance masks into one label map: mask ``i`` gets id ``i + 1``, later masks on top.
+
+ Args:
+ masks: Binary masks of the same shape; nonzero (or ``True``) pixels are foreground.
+
+ Returns:
+ ``int32`` array of ids (0 = background) with the shape of the masks.
+
+ Raises:
+ ValueError: If ``masks`` is empty, or a mask is not 2-D, is empty or has a different shape.
+ """
+ if len(masks) == 0:
+ raise ValueError("masks must contain at least one mask")
+ first = _foreground(masks[0])
+ out = np.zeros(first.shape, dtype=np.int32)
+ for i, mask in enumerate(masks):
+ fg = _foreground(mask)
+ if fg.shape != first.shape:
+ raise ValueError(f"masks must all have the shape {first.shape}, got {fg.shape} for mask {i}")
+ out[fg.astype(bool)] = i + 1
+ return out
+
+
+def labelMapToMasks(labels: np.ndarray, background: int = 0) -> list[np.ndarray]:
+ """Split a label map into one binary mask per id (the inverse of :func:`instanceMasksToLabelMap`).
+
+ Args:
+ labels: 2-D integer array of ids.
+ background: The id that gets no mask.
+
+ Returns:
+ A list of ``uint8`` masks (0/255), one for each id from 1 to ``labels.max()`` except ``background``, so
+ ``masks[i]`` is id ``i + 1`` when ``background`` is 0 (unused ids give all-zero masks).
+
+ Raises:
+ ValueError: If ``labels`` is not a 2-D integer array, is empty or has negative ids.
+ """
+ ids = _label_map(labels)
+ top = int(ids.max())
+ return [np.asarray(ids == i, dtype=np.uint8) * 255 for i in range(1, top + 1) if i != background]
+
+
+# --- drawing ---------------------------------------------------------------------
+
+
+def drawPolygons(
+ src: np.ndarray,
+ polygons: Sequence[ArrayLike] | np.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.
+
+ Args:
+ src: 8-bit image to draw on.
+ polygons: One polygon ``(N, 2)`` or a sequence of polygons (floats are rounded).
+ color: One color for all polygons, one color per polygon, or ``None`` for :func:`distinctColors`.
+ thickness: Outline thickness (ignored with ``fill``).
+ fill: Fill the polygons instead of outlining them.
+ alpha: Opacity of the drawing, from 0 to 1.
+ labels: One text per polygon, drawn at its top-most point.
+ fontScale: Hershey font size for the labels.
+ lineType: As for ``cv.polylines``.
+
+ Returns:
+ ``src``.
+
+ Raises:
+ ValueError: If ``src`` is not 8-bit or is empty, ``alpha`` is outside ``[0, 1]``, ``thickness`` is not
+ positive, or ``labels``/``color`` has a different length than ``polygons``.
+ """
+ if src.dtype != np.uint8:
+ raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
+ if not 0.0 <= alpha <= 1.0:
+ raise ValueError(f"alpha must be between 0 and 1, got {alpha}")
+ if thickness < 1:
+ raise ValueError(f"thickness must be positive, got {thickness}")
+ items = _polygons(polygons)
+ count = len(items)
+ if labels is not None and len(labels) != count:
+ raise ValueError(f"labels must have one entry per polygon, got {len(labels)} for {count} polygons")
+ palette: list[Color]
+ if color is None:
+ palette = list(distinctColors(max(count, 1)))
+ elif is_single_color(color):
+ palette = [as_color(color)] * max(count, 1)
+ else:
+ palette = [as_color(c) for c in color] # type: ignore[union-attr]
+ if len(palette) != count:
+ raise ValueError(f"color must have one entry per polygon, got {len(palette)} for {count} polygons")
+ for entry in palette:
+ check_color("color", [entry] if isinstance(entry, float) else list(entry), src.dtype)
+ if count == 0 or alpha == 0:
+ return src
+ canvas = src.copy() if alpha < 1 else src
+ for i, polygon in enumerate(items):
+ contour = asContour(polygon)
+ if fill:
+ cv2.fillPoly(canvas, [contour], palette[i], lineType)
+ else:
+ cv2.polylines(canvas, [contour], True, palette[i], thickness, lineType)
+ if labels is not None:
+ x, y = (int(v) for v in contour[int(np.argmin(contour[:, 0, 1])), 0])
+ (tw, th), baseline = cv2.getTextSize(labels[i], cv2.FONT_HERSHEY_SIMPLEX, fontScale, 1)
+ top = max(y - th - baseline - 2, 0)
+ cv2.rectangle(canvas, (x, top), (x + tw + 2, top + th + baseline + 2), palette[i], cv2.FILLED)
+ # A scalar 255 would be expanded by OpenCV to (255, 0, 0): blue text on BGR images.
+ level = 0 if _luminance(palette[i]) > 140 else 255
+ text_color: Color = level if canvas.ndim == 2 else (level,) * canvas.shape[2]
+ cv2.putText(
+ canvas, labels[i], (x + 1, top + th + 1), cv2.FONT_HERSHEY_SIMPLEX, fontScale, text_color, 1, lineType
+ )
+ if alpha < 1:
+ cv2.addWeighted(src, 1 - alpha, canvas, alpha, 0, dst=src)
+ return src
+
+
+def drawSegmentation(
+ src: np.ndarray,
+ labels: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image (converted to BGR). It is not modified.
+ labels: 2-D integer label map with the shape ``src.shape[:2]``. A ``bool`` array, or an array whose nonzero
+ values are all 255, is treated as a binary mask (one class, id 1).
+ alpha: Opacity of the colors, from 0 to 1.
+ palette: One BGR color per class id, as for :func:`labelMapToColor`.
+ background: The id left uncolored.
+
+ Returns:
+ A new ``uint8`` BGR image.
+
+ Raises:
+ ValueError: If ``src`` is not 8-bit or is empty, the label shape does not match, or ``alpha`` is outside
+ ``[0, 1]``.
+ """
+ from ..imgproc.color import toBGR
+
+ if src.dtype != np.uint8:
+ raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
+ if not 0.0 <= alpha <= 1.0:
+ raise ValueError(f"alpha must be between 0 and 1, got {alpha}")
+ if labels.ndim != 2 or labels.shape != src.shape[:2]:
+ raise ValueError(f"labels must have the shape {src.shape[:2]}, got {labels.shape}")
+ ids = labels
+ if labels.dtype == bool or (np.issubdtype(labels.dtype, np.integer) and np.all((labels == 0) | (labels == 255))):
+ ids = (labels != 0).astype(np.int32)
+ colors = labelMapToColor(ids, palette, background)
+ out = toBGR(src)
+ blended = cv2.addWeighted(out, 1 - alpha, colors, alpha, 0)
+ selected = np.ascontiguousarray(ids != background).view(np.uint8)
+ dst: np.ndarray = cv2.copyTo(blended, selected, out)
+ return dst
+
+
+# --- flips -----------------------------------------------------------------------
+
+
+def 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``).
+
+ Args:
+ boxes: Boxes of shape ``(N, 4)`` (or one box).
+ size: ``(width, height)`` of the image.
+ flipCode: 0 (``cv.FLIP_MODE_X``) flips vertically, 1 (``cv.FLIP_MODE_Y``) horizontally, -1 both.
+
+ Returns:
+ A float64 array of shape ``(N, 4)``, or ``(4,)`` for a single input box.
+
+ Raises:
+ ValueError: If ``size`` is not positive, the boxes are invalid, or ``flipCode`` is not 0, 1 or -1.
+ """
+ width, height = check_size("size", size)
+ code = _flip_code(flipCode)
+ single = np.ndim(boxes) == 1 and np.size(boxes) > 0
+ out = _boxes(boxes, "boxes").copy() if np.size(boxes) else np.zeros((0, 4))
+ if code in (1, -1):
+ out[:, 0] = width - out[:, 0] - out[:, 2]
+ if code in (0, -1):
+ out[:, 1] = height - out[:, 1] - out[:, 3]
+ return out[0] if single else out
+
+
+def _flip_polygon(points: ArrayLike, size: tuple[int, int], flipCode: int) -> np.ndarray:
+ """Flip one polygon in continuous coordinates (``x`` becomes ``width - x``).
+
+ Continuous coordinates: ``x`` becomes ``width - x``. For integer pixel indices (the center convention of
+ ``cv.findContours``), subtract 1 from the flipped coordinates.
+
+ Args:
+ points: ``(N, 2)`` points (or a point list / ``(N, 1, 2)`` contour).
+ size: ``(width, height)`` of the image.
+ flipCode: 0 flips vertically, 1 horizontally, -1 both.
+
+ Returns:
+ A float64 array of shape ``(N, 2)``.
+
+ Raises:
+ ValueError: If ``size`` is not positive, the points are empty or not 2-D, or ``flipCode`` is not 0, 1 or -1.
+ """
+ width, height = check_size("size", size)
+ code = _flip_code(flipCode)
+ out = _polygon(points, "points").copy()
+ if code in (1, -1):
+ out[:, 0] = width - out[:, 0]
+ if code in (0, -1):
+ out[:, 1] = height - out[:, 1]
+ return out
+
+
+def 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.
+
+ Args:
+ polygons: A list of ``(N, 2)`` polygons (or point lists / ``(N, 1, 2)`` contours).
+ size: ``(width, height)`` of the image.
+ flipCode: 0 flips vertically, 1 horizontally, -1 both.
+
+ Returns:
+ A list of float64 ``(N, 2)`` arrays. The vertex order is kept (so the winding direction reverses).
+
+ Raises:
+ ValueError: If ``size`` is not positive, a polygon is empty or not 2-D, or ``flipCode`` is not 0, 1 or -1.
+ """
+ check_size("size", size)
+ _flip_code(flipCode)
+ return [_flip_polygon(p, size, flipCode) for p in _polygons(polygons)]
diff --git a/cv2u/core/boxes.py b/cv2u/core/boxes.py
index d083336..f6e80cb 100644
--- a/cv2u/core/boxes.py
+++ b/cv2u/core/boxes.py
@@ -58,6 +58,9 @@ def xywhToXyxy(boxes: ArrayLike) -> np.ndarray:
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:
+ ValueError: If the last dimension of ``boxes`` does not have 4 values.
"""
array = np.array(boxes, copy=True)
if array.shape[-1:] != (4,):
@@ -68,7 +71,11 @@ def xywhToXyxy(boxes: ArrayLike) -> np.ndarray:
def xyxyToXywh(boxes: ArrayLike) -> np.ndarray:
- """Convert boxes from corners ``(x1, y1, x2, y2)`` to ``(x, y, width, height)`` (inverse of :func:`xywhToXyxy`)."""
+ """Convert boxes from corners ``(x1, y1, x2, y2)`` to ``(x, y, width, height)`` (inverse of :func:`xywhToXyxy`).
+
+ Raises:
+ ValueError: If the last dimension of ``boxes`` does not have 4 values.
+ """
array = np.array(boxes, copy=True)
if array.shape[-1:] != (4,):
raise ValueError(f"boxes must end in 4 values (x1, y1, x2, y2), got shape {array.shape}")
@@ -100,13 +107,16 @@ def nms(
An ``int64`` array of indices into ``boxes``, in descending score order (empty if none survive).
Raises:
- ValueError: If ``boxes`` and ``scores`` disagree in length, or a threshold is out of range.
+ ValueError: If ``boxes`` and ``scores`` disagree in length, ``iouThreshold`` is outside ``[0, 1]``,
+ ``scoreThreshold`` is not finite, or ``maxCount`` is negative.
"""
array = _boxes(boxes, "boxes") if np.size(boxes) else np.zeros((0, 4))
score_array = np.asarray(scores, dtype=np.float64).reshape(-1)
if len(score_array) != len(array):
raise ValueError(f"scores must have one value per box, got {len(score_array)} for {len(array)} boxes")
check_finite("iouThreshold", iouThreshold, nonnegative=True)
+ if iouThreshold > 1:
+ raise ValueError(f"iouThreshold must be in [0, 1], got {iouThreshold}")
check_finite("scoreThreshold", scoreThreshold)
if maxCount is not None and maxCount < 0:
raise ValueError(f"maxCount must not be negative, got {maxCount}")
@@ -154,11 +164,14 @@ def _nms_numpy(array: np.ndarray, order: np.ndarray, iouThreshold: float, maxCou
def 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:`cropEx` or
+ Boxes that lie completely outside become zero-sized at the border. Useful before :func:`cropRect` or
:func:`drawLabel` on detections near the edge.
Returns:
A float64 array of shape ``(N, 4)``, or ``(4,)`` for a single input box.
+
+ Raises:
+ ValueError: If ``size`` is smaller than 1x1, or the boxes do not have 4 finite values each.
"""
width, height = size
if width < 1 or height < 1:
@@ -177,6 +190,7 @@ def 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.
@@ -215,7 +229,7 @@ def scaleBoxes(
def expandBoxes(
boxes: ArrayLike,
ratio: float = 0.0,
- pixels: 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.
@@ -224,7 +238,7 @@ def expandBoxes(
boxes: Boxes ``(x, y, width, height)``.
ratio: Fraction of the width and height to add on each side (``0.1`` adds 10% left and right, 10% top and
bottom). Negative values shrink.
- pixels: Fixed number of pixels to add on each side, after ``ratio``.
+ margin: Fixed number of pixels to add on each side, after ``ratio`` (as ``margin`` in :func:`cropRect`).
size: ``(width, height)`` of the image; when given, the result is clipped to it.
Returns:
@@ -232,15 +246,15 @@ def expandBoxes(
below 0.
Raises:
- ValueError: If ``ratio`` or ``pixels`` is not finite.
+ ValueError: If ``ratio`` or ``margin`` is not finite, or the boxes do not have 4 finite values each.
"""
check_finite("ratio", ratio)
- check_finite("pixels", pixels)
+ check_finite("margin", margin)
single = np.ndim(boxes) == 1
array = _boxes(boxes, "boxes")
# Shrinking stops at the center point, so the box never flips.
- grow_x = np.maximum(array[:, 2] * ratio + pixels, -array[:, 2] / 2)
- grow_y = np.maximum(array[:, 3] * ratio + pixels, -array[:, 3] / 2)
+ grow_x = np.maximum(array[:, 2] * ratio + margin, -array[:, 2] / 2)
+ grow_y = np.maximum(array[:, 3] * ratio + margin, -array[:, 3] / 2)
out = np.stack(
[
array[:, 0] - grow_x,
diff --git a/cv2u/core/cluster.py b/cv2u/core/cluster.py
index 5a9cb9c..605876e 100644
--- a/cv2u/core/cluster.py
+++ b/cv2u/core/cluster.py
@@ -1,25 +1,39 @@
"""Clustering of pixel colors and of points.
``kmeansColors``, ``dominantColors`` and ``colorQuantize`` use OpenCV's ``cv.kmeans`` and need nothing else.
-``DBSCAN``, ``meanShiftColors`` and ``clusterPoints`` need the ``cluster`` extra (scikit-learn).
+``dbscanColors``, ``meanShiftColors`` and ``clusterPoints`` need the ``cluster`` extra (scikit-learn).
"""
-from typing import Any
+from typing import Any, NamedTuple
import cv2
import numpy as np
from numpy.typing import ArrayLike
+from .._validate import check_finite, check_image_not_empty
+
__all__ = [
- "DBSCAN",
+ "Clusters",
"clusterPoints",
"colorQuantize",
+ "dbscanColors",
"dominantColors",
- "drawDBSCAN",
+ "drawClusters",
"kmeansColors",
"meanShiftColors",
]
+
+class Clusters(NamedTuple):
+ """The result of :func:`kmeansColors`, :func:`meanShiftColors`, :func:`peakColors` and :func:`dbscanColors`."""
+
+ maps: np.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: np.ndarray
+ """The color of every cluster as ``uint8``, shape ``(k, channels)`` (BGR, or gray for grayscale input)."""
+
+
_INSTALL_HINT = '{name} requires scikit-learn. Install it with: pip install "python-opencv-utils[cluster]"'
@@ -40,41 +54,65 @@ def _check_bgr(src: np.ndarray, name: str = "src") -> None:
def _check_gray_or_bgr(src: np.ndarray) -> int:
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
- channels = 1 if src.ndim == 2 else src.shape[2]
+ channels = 1 if src.ndim == 2 else src.shape[2] if src.ndim == 3 else 0
if channels not in (1, 3):
raise ValueError(f"src must be a grayscale or BGR image, got shape {src.shape}")
+ check_image_not_empty("src", src)
return int(channels)
+def _mean_colors(src: np.ndarray, maps: np.ndarray, count: int) -> np.ndarray:
+ """Truncated mean color of every label ``0 .. count - 1`` (like ``int(cv.mean())``); negative labels are skipped."""
+ labels = maps.ravel().astype(np.intp)
+ pixels = src.reshape(len(labels), -1).astype(np.float64)
+ valid = labels >= 0
+ labels, pixels = labels[valid], pixels[valid]
+ sizes = np.bincount(labels, minlength=count)
+ sums = np.stack([np.bincount(labels, weights=pixels[:, c], minlength=count) for c in range(pixels.shape[1])], 1)
+ return np.floor(sums / np.maximum(sizes, 1)[:, None]).astype(np.uint8)
+
+
# --- DBSCAN / clusterPoints (scikit-learn) ---------------------------------------------
-def DBSCAN(src: np.ndarray, eps: float, minSamples: int) -> tuple[np.ndarray, np.ndarray]:
- """Cluster the pixels of a BGR image in the Lab color space with DBSCAN.
+def dbscanColors(src: np.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]"``.
+ 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.
Args:
- src: 3-channel BGR image.
+ src: 8-bit BGR image.
eps: Maximum Lab color distance between two pixels in the same neighborhood.
minSamples: Minimum number of pixels in a neighborhood for a core point.
Returns:
- ``(maps, labels)``: ``maps`` is the label image with shape ``src.shape[:2]``,
- ``labels`` is the flattened label array. Noise is labeled ``0``, clusters ``1, 2, ...``.
+ :class:`Clusters` ``(maps, centers)`` as for :func:`kmeansColors`: ``maps`` holds the labels
+ ``0 .. len(centers) - 1`` and ``-1`` for noise pixels; ``centers`` holds the mean BGR color of every
+ cluster. Paint the result with :func:`drawClusters`.
Raises:
ImportError: If scikit-learn is not installed.
- ValueError: If ``src`` is not a 3-channel image.
+ ValueError: If ``src`` is not an 8-bit BGR image or is empty, ``eps`` is not positive, or ``minSamples``
+ is below 1.
"""
+ if src.dtype != np.uint8:
+ raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
_check_bgr(src)
- cluster = _sklearn_cluster("DBSCAN")
+ check_image_not_empty("src", src)
+ check_finite("eps", eps, positive=True)
+ if minSamples < 1:
+ raise ValueError(f"minSamples must be at least 1, got {minSamples}")
+ cluster = _sklearn_cluster("dbscanColors")
lab = cv2.cvtColor(src, cv2.COLOR_BGR2LAB).reshape(-1, 3)
- labels: np.ndarray = cluster.DBSCAN(eps=eps, min_samples=minSamples).fit(lab).labels_ + 1
- return labels.reshape(src.shape[:2]), labels
+ labels: np.ndarray = cluster.DBSCAN(eps=eps, min_samples=minSamples).fit(lab).labels_
+ maps = labels.astype(np.int32).reshape(src.shape[:2])
+ count = int(np.max(maps)) + 1
+ return Clusters(maps, _mean_colors(src, maps, count).reshape(count, 3))
def clusterPoints(points: ArrayLike, eps: float, minSamples: int = 2) -> np.ndarray:
@@ -88,44 +126,56 @@ def clusterPoints(points: ArrayLike, eps: float, minSamples: int = 2) -> np.ndar
minSamples: Minimum number of points that forms a group; ``1`` puts every point in some group.
Returns:
- Labels of shape ``(N,)``: ``0`` for noise (points in no group), ``1, 2, ...`` for the groups,
- as in :func:`DBSCAN`.
+ Labels of shape ``(N,)`` (``int32``): ``0, 1, ...`` for the groups and ``-1`` for noise (points in no
+ group), as in :func:`dbscanColors` and scikit-learn.
Raises:
ImportError: If scikit-learn is not installed.
- ValueError: If ``points`` is empty.
+ ValueError: If ``points`` is empty or not finite, ``eps`` is not positive, or ``minSamples`` is below 1.
"""
pts = np.asarray(points, dtype=np.float64)
if pts.ndim == 3 and pts.shape[1] == 1:
pts = pts.reshape(-1, pts.shape[2])
if pts.ndim != 2 or len(pts) == 0:
raise ValueError(f"points must have the shape (N, d) with N > 0, got {pts.shape}")
+ if not np.all(np.isfinite(pts)):
+ raise ValueError("points must be finite")
+ check_finite("eps", eps, positive=True)
+ if minSamples < 1:
+ raise ValueError(f"minSamples must be at least 1, got {minSamples}")
cluster = _sklearn_cluster("clusterPoints")
- labels: np.ndarray = cluster.DBSCAN(eps=eps, min_samples=minSamples).fit(pts).labels_ + 1
- return labels
+ labels: np.ndarray = cluster.DBSCAN(eps=eps, min_samples=minSamples).fit(pts).labels_
+ return labels.astype(np.int32)
+
+
+def drawClusters(src: np.ndarray, maps: np.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.
-def drawDBSCAN(src: np.ndarray, maps: np.ndarray, labels: np.ndarray) -> np.ndarray:
- """Paint each cluster with its mean color.
+ Args:
+ src: 8-bit grayscale or BGR image, the one that was clustered.
+ maps: Label image of shape ``src.shape[:2]``, as returned in :class:`Clusters`.
- Works with the output of :func:`DBSCAN`, and of :func:`kmeansColors` and :func:`meanShiftColors`
- (pass ``maps.ravel()`` as ``labels`` for those).
+ Returns:
+ A new image with the shape and dtype of ``src``; ``src`` is not modified.
Raises:
- ValueError: If ``src`` is not a 3-channel image or the shapes do not match.
+ ValueError: If ``src`` is not an 8-bit grayscale or BGR image or is empty, or ``maps`` has another shape.
"""
- _check_bgr(src)
- if maps.shape != src.shape[:2] or labels.size != maps.size:
- raise ValueError(f"maps/labels do not match src: src {src.shape}, maps {maps.shape}, labels {labels.shape}")
-
- flat_labels = labels.ravel().astype(np.intp)
- count = int(np.max(flat_labels)) + 1
- pixels = src.reshape(-1, 3).astype(np.float64)
- sizes = np.bincount(flat_labels, minlength=count)
- sums = np.stack([np.bincount(flat_labels, weights=pixels[:, c], minlength=count) for c in range(3)], axis=1)
- colors = np.floor(sums / np.maximum(sizes, 1)[:, None]).astype(np.uint8) # truncated mean, like int(cv.mean())
- dst: np.ndarray = colors[flat_labels].reshape(src.shape)
- return dst
+ _check_gray_or_bgr(src)
+ if maps.shape != src.shape[:2]:
+ raise ValueError(f"maps must have the shape {src.shape[:2]}, got {maps.shape}")
+ labels = maps.ravel().astype(np.intp)
+ count = int(np.max(labels)) + 1
+ out = src.reshape(len(labels), -1).copy()
+ if count > 0:
+ colors = _mean_colors(src, maps, count)
+ painted = labels >= 0
+ out[painted] = colors[labels[painted]]
+ return out.reshape(src.shape)
# --- k-means (OpenCV only) -----------------------------------------------------------------
@@ -157,7 +207,7 @@ def kmeansColors(
sampleSize: int = 20000,
seed: int = 0,
maxIter: int = 30,
-) -> tuple[np.ndarray, np.ndarray]:
+) -> 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
@@ -173,11 +223,12 @@ def kmeansColors(
maxIter: Maximum number of k-means iterations.
Returns:
- ``(maps, centers)``: ``maps`` has shape ``src.shape[:2]`` with labels ``0 .. k-1``; ``centers`` has shape
- ``(k, channels)`` and holds the colors (BGR, or gray) as ``uint8``.
+ :class:`Clusters` ``(maps, centers)``: ``maps`` has shape ``src.shape[:2]`` with labels ``0 .. k-1``;
+ ``centers`` has shape ``(k, channels)`` and holds the colors (BGR, or gray) as ``uint8``.
Raises:
- ValueError: If ``src`` is not an 8-bit grayscale or BGR image, or ``k`` is not between 1 and the pixel count.
+ ValueError: If ``src`` is not an 8-bit grayscale or BGR image or is empty, ``k`` is not between 1 and the
+ pixel count, ``sampleSize`` is below ``k``, or ``maxIter`` is below 1.
"""
channels = _check_gray_or_bgr(src)
pixel_count = src.shape[0] * src.shape[1]
@@ -185,6 +236,8 @@ def kmeansColors(
raise ValueError(f"k must be between 1 and the number of pixels ({pixel_count}), got {k}")
if sampleSize < k:
raise ValueError(f"sampleSize must be at least k ({k}), got {sampleSize}")
+ if maxIter < 1:
+ raise ValueError(f"maxIter must be at least 1, got {maxIter}")
space = src if channels == 1 else cv2.cvtColor(src, cv2.COLOR_BGR2LAB)
data = space.reshape(-1, channels).astype(np.float32)
@@ -200,7 +253,7 @@ def kmeansColors(
colors = np.clip(np.rint(centers), 0, 255).astype(np.uint8)
if channels == 3:
colors = np.asarray(cv2.cvtColor(colors.reshape(-1, 1, 3), cv2.COLOR_LAB2BGR), dtype=np.uint8).reshape(-1, 3)
- return maps, colors
+ return Clusters(maps, colors)
def dominantColors(
@@ -245,7 +298,7 @@ def meanShiftColors(
quantile: float = 0.2,
sampleSize: int = 2000,
seed: int = 0,
-) -> tuple[np.ndarray, np.ndarray]:
+) -> 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
@@ -261,15 +314,20 @@ def meanShiftColors(
seed: Seed for the sampling.
Returns:
- ``(maps, centers)`` as for :func:`kmeansColors`; ``len(centers)`` is the number of colors found.
+ :class:`Clusters` ``(maps, centers)`` as for :func:`kmeansColors`; ``len(centers)`` is the number of
+ colors found.
Raises:
ImportError: If scikit-learn is not installed.
- ValueError: If ``src`` is not an 8-bit BGR image, or ``quantile`` is outside ``(0, 1]``.
+ ValueError: If ``src`` is not an 8-bit BGR image or is empty, ``bandwidth`` is not positive, or
+ ``quantile`` is outside ``(0, 1]``.
"""
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
_check_bgr(src)
+ check_image_not_empty("src", src)
+ if bandwidth is not None:
+ check_finite("bandwidth", bandwidth, positive=True)
if not 0.0 < quantile <= 1.0:
raise ValueError(f"quantile must be in (0, 1], got {quantile}")
cluster = _sklearn_cluster("meanShiftColors")
@@ -287,4 +345,4 @@ def meanShiftColors(
maps = _nearest(data, centers).astype(np.int32).reshape(src.shape[:2])
lab = np.clip(np.rint(centers), 0, 255).astype(np.uint8).reshape(-1, 1, 3)
colors = np.asarray(cv2.cvtColor(lab, cv2.COLOR_LAB2BGR), dtype=np.uint8).reshape(-1, 3)
- return maps, colors
+ return Clusters(maps, colors)
diff --git a/cv2u/core/compose.py b/cv2u/core/compose.py
index da3e4d5..a57983c 100644
--- a/cv2u/core/compose.py
+++ b/cv2u/core/compose.py
@@ -6,7 +6,7 @@
import cv2
import numpy as np
-from .._validate import check_color, check_image_not_empty
+from .._validate import check_channels, check_color, check_finite, check_image_not_empty
from ..imgproc.resize import letterbox
__all__ = ["hconcatEx", "montage", "overlayImage", "vconcatEx"]
@@ -14,10 +14,6 @@
_UPCONVERT = {(1, 3): cv2.COLOR_GRAY2BGR, (1, 4): cv2.COLOR_GRAY2BGRA, (3, 4): cv2.COLOR_BGR2BGRA}
-def _channels(img: np.ndarray) -> int:
- return 1 if img.ndim == 2 else int(img.shape[2])
-
-
def _as3d(img: np.ndarray) -> np.ndarray:
return img if img.ndim == 3 else img[..., None]
@@ -48,14 +44,14 @@ def _concat(images: Sequence[np.ndarray], axis: int, color: float | Sequence[flo
if len(dtypes) != 1:
raise ValueError(f"all images must have the same dtype, got {sorted(str(d) for d in dtypes)}")
for img in images:
- if img.ndim not in (2, 3) or _channels(img) not in (1, 3, 4):
- raise ValueError(f"images must have 1, 3 or 4 channels, got shape {img.shape}")
+ check_channels("images", img)
check_image_not_empty("images", img)
- channels = max(_channels(img) for img in images)
+ counts = [check_channels("images", img) for img in images]
+ channels = max(counts)
unified = [
- _as3d(img if _channels(img) == channels else cv2.cvtColor(img, _UPCONVERT[(_channels(img), channels)]))
- for img in images
+ _as3d(img if count == channels else cv2.cvtColor(img, _UPCONVERT[(count, channels)]))
+ for img, count in zip(images, counts, strict=True)
]
dtype = unified[0].dtype
values = _fill_value(color, channels)
@@ -144,9 +140,7 @@ def montage(
return vconcatEx(rows, color=color, gap=gap)
-def overlayImage(
- src: np.ndarray, overlay: np.ndarray, org: tuple[int, int] = (0, 0), opacity: float = 1.0
-) -> np.ndarray:
+def overlayImage(src: np.ndarray, overlay: np.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.
@@ -156,23 +150,26 @@ def overlayImage(
src: 8-bit grayscale, BGR or BGRA image. It is not modified.
overlay: 8-bit grayscale, BGR or BGRA image. Its alpha channel (if any) controls the blending per pixel.
org: Position of the overlay's top-left corner in ``src``, as ``(x, y)``.
- opacity: Overall opacity from 0 (invisible) to 1, multiplied with the overlay's alpha.
+ alpha: Overall opacity from 0 (invisible) to 1, multiplied with the overlay's alpha channel (the same
+ name as in :func:`overlayMask` and ``cv.addWeighted``).
Returns:
A new image with the same shape as ``src``.
Raises:
- ValueError: If an image is not 8-bit or has an unsupported channel count, or ``opacity`` is outside ``[0, 1]``.
+ ValueError: If an image is not 8-bit, is empty or has an unsupported channel count, or ``alpha`` is outside
+ ``[0, 1]``.
"""
if src.dtype != np.uint8 or overlay.dtype != np.uint8:
raise ValueError(f"src and overlay must be 8-bit (uint8), got {src.dtype} and {overlay.dtype}")
check_image_not_empty("src", src)
check_image_not_empty("overlay", overlay)
- for name, img in (("src", src), ("overlay", overlay)):
- if _channels(img) not in (1, 3, 4):
- raise ValueError(f"{name} must have 1, 3 or 4 channels, got shape {img.shape}")
- if not 0.0 <= opacity <= 1.0:
- raise ValueError(f"opacity must be between 0 and 1, got {opacity}")
+ check_channels("src", src)
+ check_channels("overlay", overlay)
+ check_finite("alpha", alpha)
+ if not 0.0 <= alpha <= 1.0:
+ raise ValueError(f"alpha must be between 0 and 1, got {alpha}")
+ opacity = float(alpha)
dst = src.copy()
x, y = org
@@ -185,12 +182,12 @@ def overlayImage(
patch = _as3d(overlay[y0 - y : y1 - y, x0 - x : x1 - x])
if patch.shape[2] == 4:
- alpha = patch[..., 3:4].astype(np.float32) / 255.0
+ weight = patch[..., 3:4].astype(np.float32) / 255.0
fg = patch[..., :3]
else:
- alpha = np.ones((*patch.shape[:2], 1), np.float32)
+ weight = np.ones((*patch.shape[:2], 1), np.float32)
fg = patch
- alpha *= opacity
+ weight *= opacity
region = _as3d(dst[y0:y1, x0:x1]) # a view into dst
src_channels = region.shape[2]
@@ -199,10 +196,10 @@ def overlayImage(
fg = _as3d(cv2.cvtColor(fg, cv2.COLOR_BGR2GRAY if color_channels == 1 else cv2.COLOR_GRAY2BGR))
base = region[..., :color_channels].astype(np.float32)
- blended = base * (1 - alpha) + fg.astype(np.float32) * alpha
+ blended = base * (1 - weight) + fg.astype(np.float32) * weight
region[..., :color_channels] = np.clip(np.rint(blended), 0, 255).astype(np.uint8)
if src_channels == 4:
# "Over" compositing for the destination alpha.
dst_alpha = region[..., 3:4].astype(np.float32) / 255.0
- region[..., 3:4] = np.rint((alpha + dst_alpha * (1 - alpha)) * 255).astype(np.uint8)
+ region[..., 3:4] = np.rint((weight + dst_alpha * (1 - weight)) * 255).astype(np.uint8)
return dst
diff --git a/cv2u/core/extension.py b/cv2u/core/extension.py
index 38905d9..79be55a 100644
--- a/cv2u/core/extension.py
+++ b/cv2u/core/extension.py
@@ -6,10 +6,10 @@
import numpy as np
from numpy.typing import ArrayLike
-from .._validate import check_finite
+from .._validate import check_finite, check_image_not_empty
__all__ = [
- "DHEdge",
+ "boldEdges",
"cartesianToPolar",
"centerPoint",
"gammaCorrection",
@@ -24,24 +24,42 @@ def gammaCorrection(src: np.ndarray, gamma: float = 1.0) -> np.ndarray:
Each value ``v`` becomes ``255 * (v / 255) ** (1 / gamma)``: ``gamma > 1`` brightens the image,
``gamma < 1`` darkens it, and ``gamma == 1`` leaves it unchanged.
+ Args:
+ src: 8-bit image with any number of channels.
+ gamma: Gamma value; ``1`` leaves the image unchanged.
+
Raises:
- ValueError: If ``src`` is not 8-bit or ``gamma`` is not positive.
+ ValueError: If ``src`` is not 8-bit or is empty, or ``gamma`` is not a positive finite number.
"""
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
check_finite("gamma", gamma, positive=True)
table = (np.arange(256) / 255.0) ** (1.0 / gamma) * 255
dst: np.ndarray = cv2.LUT(src, np.clip(table, 0, 255).astype(np.uint8))
return dst
-def centerPoint(contour: np.ndarray) -> tuple[float, float]:
- """Return the centroid ``(x, y)`` of a contour.
+def 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).
+
+ Args:
+ contour: Contour of shape ``(N, 1, 2)`` or ``(N, 2)``, as from ``cv.findContours``.
Raises:
- ValueError: If the contour has zero area.
+ ValueError: If the contour has no points, is not finite, or has zero area (the centroid is undefined).
"""
- moment = cv2.moments(contour)
+ points = np.asarray(contour, dtype=np.float64)
+ if points.size == 0:
+ raise ValueError("contour must not be empty")
+ if points.shape[-1] != 2:
+ raise ValueError(f"contour must have 2 coordinates (x, y) per point, got shape {points.shape}")
+ if not np.all(np.isfinite(points)):
+ raise ValueError("contour must be finite")
+ moment = cv2.moments(points.reshape(-1, 1, 2).astype(np.float32))
if moment["m00"] == 0:
raise ValueError("contour has zero area; centroid is undefined")
return moment["m10"] / moment["m00"], moment["m01"] / moment["m00"]
@@ -103,20 +121,25 @@ def isInside(p: Sequence[float], polygon: ArrayLike) -> bool:
_SHARPEN_KERNEL = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]], dtype=np.float32)
-def DHEdge(src: np.ndarray) -> np.ndarray:
+def boldEdges(src: np.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.
+ contrast-stretched, so edges come out as thick white lines on black. ``cv.Canny`` gives thin, binary edges
+ instead.
Args:
src: 8-bit image with 1 or 3 channels. Color images are processed per channel.
+ Returns:
+ An 8-bit image with the shape of ``src``.
+
Raises:
- ValueError: If ``src`` is not 8-bit.
+ ValueError: If ``src`` is not 8-bit or is empty.
"""
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
gradient = cv2.morphologyEx(src, cv2.MORPH_GRADIENT, _GRADIENT_KERNEL)
sharpen = cv2.filter2D(gradient, -1, _SHARPEN_KERNEL)
return np.clip(math.pi * sharpen.astype(np.float64) - 255, 0, 255).astype(np.uint8)
diff --git a/cv2u/core/images.py b/cv2u/core/images.py
index edf6401..f92ba45 100644
--- a/cv2u/core/images.py
+++ b/cv2u/core/images.py
@@ -6,39 +6,50 @@
import numpy as np
from numpy.typing import DTypeLike
+from .._validate import check_color, check_size
+
__all__ = ["imcolor", "imcolorLike", "makeGradient"]
GradientDirection = Literal["horizontal", "vertical", "raster"]
+def _color_values(name: str, color: float | Sequence[float], channels: int, dtype: DTypeLike) -> np.ndarray:
+ values = np.atleast_1d(np.asarray(color, dtype=np.float64)).ravel()
+ if values.size not in (1, channels):
+ raise ValueError(f"{name} must be a scalar or have {channels} values, got {color!r}")
+ check_color(name, values.tolist(), np.dtype(dtype))
+ return np.broadcast_to(values, (channels,))
+
+
def makeGradient(
- shape: Sequence[int],
+ 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``.
Args:
- shape: ``(height, width)``, ``(height, width, 1)`` or ``(height, width, 3)``.
+ size: Image size as ``(width, height)``, like ``cv.resize``.
start: Start value. A scalar, or one value per channel (BGR).
end: End value. A scalar, or one value per channel (BGR).
direction: ``"horizontal"`` (left to right), ``"vertical"`` (top to bottom), or
``"raster"`` (through every pixel in reading order, row by row).
+ channels: ``3`` for a BGR image (default) or ``1`` for a grayscale image of shape ``(height, width)``.
+
+ Returns:
+ A ``uint8`` image of shape ``(height, width, 3)``, or ``(height, width)`` for ``channels=1``.
Raises:
- ValueError: If ``shape`` does not have 1 or 3 channels, or ``direction`` is unknown.
+ ValueError: If ``size`` is not positive, ``channels`` is not 1 or 3, a value is outside ``[0, 255]`` or
+ does not match the channel count, or ``direction`` is unknown.
"""
- height, width = shape[:2]
- channels = shape[2] if len(shape) == 3 else 1
+ width, height = check_size("size", size)
if channels not in (1, 3):
- raise ValueError(f"shape must have 1 or 3 channels, got {channels}")
-
- def _per_channel(value: float | Sequence[float]) -> np.ndarray:
- arr = np.atleast_1d(np.asarray(value, dtype=np.float64))
- return arr[:1] if channels == 1 else np.broadcast_to(arr, (channels,))
-
- lo, hi = _per_channel(start), _per_channel(end)
+ raise ValueError(f"channels must be 1 or 3, got {channels}")
+ lo = _color_values("start", start, channels, np.uint8)
+ hi = _color_values("end", end, channels, np.uint8)
if direction == "raster":
img = np.linspace(lo, hi, num=height * width, dtype=np.uint8).reshape(height, width, channels)
elif direction == "horizontal":
@@ -49,14 +60,45 @@ def _per_channel(value: float | Sequence[float]) -> np.ndarray:
img = np.broadcast_to(column[:, None, :], (height, width, channels)).copy()
else:
raise ValueError(f"direction must be 'horizontal', 'vertical' or 'raster', got {direction!r}")
- return img.reshape(tuple(shape))
+ return img.reshape(height, width) if channels == 1 else img
-def imcolor(shape: Sequence[int], color: float | Sequence[float], dtype: DTypeLike = np.uint8) -> np.ndarray:
- """Create an image of ``shape`` filled with ``color`` (8-bit by default)."""
- return np.full(shape, color, dtype=dtype)
+def 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).
+
+ Args:
+ size: Image size as ``(width, height)``, like ``cv.resize``.
+ color: A scalar, or one value per channel (BGR, or BGRA for ``channels=4``).
+ channels: ``3`` (BGR, default), ``4`` (BGRA) or ``1`` for a grayscale image of shape ``(height, width)``.
+ dtype: Pixel type.
+
+ Raises:
+ ValueError: If ``size`` is not positive, ``channels`` is not 1, 3 or 4, or ``color`` is not finite, does not
+ match the channel count, or is outside the range of ``dtype``.
+ """
+ width, height = check_size("size", size)
+ if channels not in (1, 3, 4):
+ raise ValueError(f"channels must be 1, 3 or 4, got {channels}")
+ values = _color_values("color", color, channels, dtype)
+ shape = (height, width) if channels == 1 else (height, width, channels)
+ return np.full(shape, values[0] if channels == 1 else values, dtype=dtype)
def imcolorLike(src: np.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``."""
- return np.full_like(src, color, dtype=dtype)
+ """Create an image with the same shape (and, by default, dtype) as ``src`` filled with ``color``.
+
+ Args:
+ src: Image whose shape (and dtype) to copy.
+ color: A scalar, or one value per channel of ``src``.
+ dtype: Pixel type of the result; by default that of ``src``.
+
+ Raises:
+ ValueError: If ``color`` is not finite, does not match the channels of ``src``, or is outside the range of
+ the result dtype.
+ """
+ out_dtype = src.dtype if dtype is None else np.dtype(dtype)
+ channels = 1 if src.ndim < 3 else int(src.shape[-1])
+ values = _color_values("color", color, channels, out_dtype)
+ return np.full_like(src, values[0] if src.ndim < 3 else values, dtype=out_dtype)
diff --git a/cv2u/core/layout.py b/cv2u/core/layout.py
index 1123581..757bc26 100644
--- a/cv2u/core/layout.py
+++ b/cv2u/core/layout.py
@@ -26,9 +26,16 @@ def padToMultiple(src: np.ndarray, multiple: int, color: Color = 0) -> np.ndarra
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]``.
+ Args:
+ src: Image to pad.
+ multiple: The width and height of the result are multiples of this.
+ color: Padding color: a scalar, or one value per channel.
+
Raises:
- ValueError: If ``multiple`` is not positive.
+ ValueError: If ``src`` is empty, ``multiple`` is not positive, or ``color`` is not finite or outside the
+ range of the image dtype.
"""
+ check_image_not_empty("src", src)
if multiple < 1:
raise ValueError(f"multiple must be positive, got {multiple}")
h, w = src.shape[:2]
@@ -41,18 +48,20 @@ def padToMultiple(src: np.ndarray, multiple: int, color: Color = 0) -> np.ndarra
return dst
-def padToSize(src: np.ndarray, size: tuple[int, int], color: Color = 0, center: bool = True) -> np.ndarray:
+def padToSize(src: np.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).
Args:
src: Image to pad.
size: Output size as ``(width, height)``; it must not be smaller than the image.
- color: Padding color.
+ color: Padding color: a scalar, or one value per channel.
center: Center the image; otherwise it stays at the top-left.
Raises:
- ValueError: If ``size`` is smaller than the image.
+ ValueError: If ``src`` is empty, ``size`` is smaller than the image, or ``color`` is not finite or outside
+ the range of the image dtype.
"""
+ check_image_not_empty("src", src)
out_w, out_h = size
h, w = src.shape[:2]
if out_w < w or out_h < h:
@@ -91,8 +100,9 @@ def splitTiles(
Tiles are views of ``src``; use :func:`mergeTiles` to put processed tiles back together.
Raises:
- ValueError: If ``tileSize`` is not positive or ``overlap`` is not smaller than the tile.
+ ValueError: If ``src`` is empty, ``tileSize`` is not positive, or ``overlap`` is not smaller than the tile.
"""
+ check_image_not_empty("src", src)
tile_w, tile_h = tileSize
if tile_w < 1 or tile_h < 1:
raise ValueError(f"tileSize must be positive, got {tileSize}")
@@ -115,11 +125,13 @@ def mergeTiles(tiles: Sequence[tuple[np.ndarray, tuple[int, int]]], size: tuple[
The assembled image, with the dtype of the tiles. Pixels covered by no tile are 0.
Raises:
- ValueError: If ``tiles`` is empty.
+ ValueError: If ``tiles`` is empty or ``size`` is not positive.
"""
if len(tiles) == 0:
raise ValueError("tiles must not be empty")
width, height = size
+ if width < 1 or height < 1:
+ raise ValueError(f"size must be at least 1x1, got {size}")
first = tiles[0][0]
shape = (height, width, *first.shape[2:])
count = np.zeros((height, width), np.uint16)
diff --git a/cv2u/core/peaks.py b/cv2u/core/peaks.py
index 6a8b4ca..a0bbe47 100644
--- a/cv2u/core/peaks.py
+++ b/cv2u/core/peaks.py
@@ -16,11 +16,13 @@
"""
import itertools
-import math
import cv2
import numpy as np
+from .._validate import check_finite, check_image_not_empty
+from .cluster import Clusters
+
__all__ = ["peakColors"]
_NEIGHBORS = [d for d in itertools.product((-1, 0, 1), repeat=3) if d != (0, 0, 0)]
@@ -94,7 +96,7 @@ def peakColors(
sigma: float = 0.75,
minShare: float = 0.01,
minRegion: int = 0,
-) -> tuple[np.ndarray, np.ndarray]:
+) -> 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:
@@ -113,20 +115,19 @@ def peakColors(
such as thin text.
Returns:
- ``(maps, centers)`` as for :func:`kmeansColors`: ``maps`` holds labels ``0 .. n-1``, ordered from the most
- to the least common color, and ``centers`` the mean BGR color of each cluster.
+ :class:`Clusters` ``(maps, centers)`` as for :func:`kmeansColors`: ``maps`` holds labels ``0 .. n-1``,
+ ordered from the most to the least common color, and ``centers`` the mean BGR color of each cluster.
Raises:
- ValueError: If ``src`` is not an 8-bit BGR image, or a parameter is out of range.
+ ValueError: If ``src`` is not an 8-bit BGR image or is empty, or a parameter is out of range.
"""
if src.dtype != np.uint8 or src.ndim != 3 or src.shape[2] != 3:
raise ValueError(f"src must be an 8-bit BGR image, got shape {src.shape} and dtype {src.dtype}")
if not 2 <= bins <= 64:
raise ValueError(f"bins must be between 2 and 64, got {bins}")
- if src.size == 0:
- raise ValueError("src must not be empty")
- if not math.isfinite(sigma) or sigma < 0:
- raise ValueError(f"sigma must be a non-negative finite number, got {sigma}")
+ check_image_not_empty("src", src)
+ check_finite("sigma", sigma, nonnegative=True)
+ check_finite("minShare", minShare)
if not 0.0 <= minShare < 1.0:
raise ValueError(f"minShare must be in [0, 1), got {minShare}")
if minRegion < 0:
@@ -172,4 +173,4 @@ def peakColors(
totals = np.bincount(label_flat, minlength=count)
sums = np.stack([np.bincount(label_flat, weights=pixels[:, c], minlength=count) for c in range(3)], axis=1)
centers = np.clip(np.rint(sums / np.maximum(totals, 1)[:, None]), 0, 255).astype(np.uint8)
- return maps, centers
+ return Clusters(maps, centers)
diff --git a/cv2u/core/points.py b/cv2u/core/points.py
new file mode 100644
index 0000000..5922907
--- /dev/null
+++ b/cv2u/core/points.py
@@ -0,0 +1,379 @@
+"""2-D point sets: transform, normalize, clip, measure and order ``(x, y)`` points.
+
+Keypoints, landmarks and polygon corners go through the same arithmetic in every project: rotate them with the
+image, map them to ``[0, 1]`` and back, flip them with ``cv.flip``, find the nearest matches. OpenCV transforms
+points only through matrices (``cv.transform``, ``cv.perspectiveTransform``) and has no distance matrix, ordering
+or line intersection. Points are ``(x, y)`` pairs: one point, an array of shape ``(N, 2)`` or an OpenCV contour of
+shape ``(N, 1, 2)``; results come back as float64 in the same shape.
+"""
+
+import math
+
+import cv2
+import numpy as np
+from numpy.typing import ArrayLike
+
+from .._validate import check_finite, check_size
+from ..imgproc.geometry import _order_corners
+
+__all__ = [
+ "angleBetween",
+ "clipPoints",
+ "denormalizePoints",
+ "distancePoints",
+ "flipPoints",
+ "lineIntersection",
+ "nearestPoints",
+ "normalizePoints",
+ "orderPoints",
+ "pointLineDistance",
+ "pointsBoundingBox",
+ "polygonCentroid",
+ "rotatePoints",
+ "scalePoints",
+ "translatePoints",
+]
+
+
+def _points(points: ArrayLike, name: str = "points") -> tuple[np.ndarray, tuple[int, ...]]:
+ """Validate points and return them as a float64 ``(N, 2)`` array plus the shape to give the result."""
+ array = np.asarray(points, dtype=np.float64)
+ if array.ndim == 0 or array.shape[-1] != 2:
+ raise ValueError(f"{name} must be (x, y) points: shape (2,), (N, 2) or (N, 1, 2), got shape {array.shape}")
+ if not np.all(np.isfinite(array)):
+ raise ValueError(f"{name} must be finite")
+ return array.reshape(-1, 2), array.shape
+
+
+def _point(point: ArrayLike, name: str) -> tuple[float, float]:
+ pts, shape = _points(point, name)
+ if pts.shape[0] != 1:
+ raise ValueError(f"{name} must be one (x, y) point, got shape {shape}")
+ return float(pts[0, 0]), float(pts[0, 1])
+
+
+def 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.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ angle: Rotation in degrees.
+ center: Center of rotation ``(x, y)``; the origin by default.
+ scale: Isotropic scale applied with the rotation.
+
+ Returns:
+ The rotated points as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If a value is not finite or ``scale`` is not positive.
+ """
+ pts, shape = _points(points)
+ check_finite("angle", angle)
+ check_finite("scale", scale, positive=True)
+ cx, cy = _point(center, "center")
+ matrix = cv2.getRotationMatrix2D((cx, cy), angle, scale)
+ out: np.ndarray = pts @ matrix[:, :2].T + matrix[:, 2]
+ return out.reshape(shape)
+
+
+def 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.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ scale: One factor, or ``(sx, sy)`` for different factors per axis (``new_w / old_w, new_h / old_h``).
+ center: Fixed point ``(x, y)``; the origin by default.
+
+ Returns:
+ The scaled points as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If a value is not finite.
+ """
+ pts, shape = _points(points)
+ sx, sy = (float(scale), float(scale)) if isinstance(scale, (int, float)) else (float(scale[0]), float(scale[1]))
+ check_finite("scale", sx)
+ check_finite("scale", sy)
+ c = np.array(_point(center, "center"))
+ out: np.ndarray = (pts - c) * (sx, sy) + c
+ return out.reshape(shape)
+
+
+def 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:
+ The shifted points as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If a value is not finite.
+ """
+ pts, shape = _points(points)
+ check_finite("dx", dx)
+ check_finite("dy", dy)
+ out: np.ndarray = pts + np.array([dx, dy])
+ return out.reshape(shape)
+
+
+def 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.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ size: Image size as ``(width, height)``.
+ flipCode: As for ``cv.flip``: ``0`` vertical, positive horizontal, negative both.
+
+ Returns:
+ The flipped points as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If ``size`` is not positive.
+ """
+ pts, shape = _points(points)
+ width, height = check_size("size", size)
+ out = pts.copy()
+ if flipCode != 0:
+ out[:, 0] = width - 1 - out[:, 0]
+ if flipCode <= 0:
+ out[:, 1] = height - 1 - out[:, 1]
+ return out.reshape(shape)
+
+
+def normalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray:
+ """Divide pixel coordinates by the image size, giving ``[0, 1]`` coordinates independent of the resolution.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)`` in pixels.
+ size: Image size as ``(width, height)``.
+
+ Returns:
+ The normalized points as float64, in the shape of ``points``. Points outside the image fall outside ``[0, 1]``.
+
+ Raises:
+ ValueError: If ``size`` is not positive.
+ """
+ pts, shape = _points(points)
+ out: np.ndarray = pts / check_size("size", size)
+ return out.reshape(shape)
+
+
+def denormalizePoints(points: ArrayLike, size: tuple[int, int]) -> np.ndarray:
+ """Multiply ``[0, 1]`` coordinates by the image size; the inverse of :func:`normalizePoints`.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)`` in ``[0, 1]``.
+ size: Image size as ``(width, height)``.
+
+ Returns:
+ The pixel coordinates as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If ``size`` is not positive.
+ """
+ pts, shape = _points(points)
+ out: np.ndarray = pts * check_size("size", size)
+ return out.reshape(shape)
+
+
+def 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]``.
+
+ Args:
+ points: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ size: Image size as ``(width, height)``.
+
+ Returns:
+ The clipped points as float64, in the shape of ``points``.
+
+ Raises:
+ ValueError: If ``size`` is not positive.
+ """
+ pts, shape = _points(points)
+ width, height = check_size("size", size)
+ out: np.ndarray = np.clip(pts, 0, (width - 1, height - 1))
+ return out.reshape(shape)
+
+
+def 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:
+ ValueError: If ``points`` is empty or not finite.
+ """
+ pts, _ = _points(points)
+ if pts.shape[0] == 0:
+ raise ValueError("points must not be empty")
+ x0, y0 = np.floor(pts.min(axis=0)).astype(int)
+ x1, y1 = np.ceil(pts.max(axis=0)).astype(int)
+ return int(x0), int(y0), int(x1 - x0 + 1), int(y1 - y0 + 1)
+
+
+def distancePoints(a: ArrayLike, b: ArrayLike) -> np.ndarray:
+ """Euclidean distance from every point in ``a`` to every point in ``b``.
+
+ Args:
+ a: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ b: One point, ``(M, 2)`` or ``(M, 1, 2)``.
+
+ Returns:
+ A float64 array of shape ``(N, M)``; ``float(distancePoints(p, q)[0, 0])`` for two single points.
+ """
+ pa, _ = _points(a, "a")
+ pb, _ = _points(b, "b")
+ diff = pa[:, None, :] - pb[None, :, :]
+ out: np.ndarray = np.sqrt(np.sum(diff * diff, axis=2))
+ return out
+
+
+def 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.
+
+ Args:
+ a: One point, ``(N, 2)`` or ``(N, 1, 2)``.
+ b: ``(M, 2)`` or ``(M, 1, 2)``, with at least one point.
+
+ Returns:
+ ``(indices, distances)``: an ``int64`` array and a float64 array, both of length ``N``.
+
+ Raises:
+ ValueError: If ``b`` is empty.
+ """
+ dist = distancePoints(a, b)
+ if dist.shape[1] == 0:
+ raise ValueError("b must not be empty")
+ indices = np.argmin(dist, axis=1)
+ return indices, dist[np.arange(dist.shape[0]), indices]
+
+
+def 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.
+
+ Args:
+ points: 4 points as ``(4, 2)`` or a contour of shape ``(4, 1, 2)``.
+
+ Returns:
+ A float64 array of shape ``(4, 2)``.
+
+ Raises:
+ ValueError: If there are not exactly 4 points.
+ """
+ pts, _ = _points(points)
+ if pts.shape[0] != 4:
+ raise ValueError(f"points must contain exactly 4 points, got {pts.shape[0]}")
+ ordered: np.ndarray = _order_corners(pts)
+ return ordered
+
+
+def 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:
+ ValueError: If ``points`` is empty or not finite.
+ """
+ pts, _ = _points(points)
+ if pts.shape[0] == 0:
+ raise ValueError("points must not be empty")
+ x, y = pts[:, 0], pts[:, 1]
+ x1, y1 = np.roll(x, -1), np.roll(y, -1)
+ cross = x * y1 - x1 * y
+ area = 0.5 * float(cross.sum())
+ if abs(area) < 1e-12:
+ return float(x.mean()), float(y.mean())
+ return float(((x + x1) * cross).sum() / (6 * area)), float(((y + y1) * cross).sum() / (6 * area))
+
+
+def 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).
+
+ Args:
+ p1: Start point ``(x, y)``.
+ p2: End point ``(x, y)``.
+ degrees: Return degrees (``(-180, 180]``) instead of radians.
+
+ Raises:
+ ValueError: If a point is not one finite ``(x, y)`` pair.
+ """
+ x1, y1 = _point(p1, "p1")
+ x2, y2 = _point(p2, "p2")
+ angle = math.atan2(y2 - y1, x2 - x1)
+ return math.degrees(angle) if degrees else angle
+
+
+Line = tuple[tuple[float, float], tuple[float, float]]
+
+
+def 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:
+ The point ``(x, y)``, or ``None`` if the lines are parallel (including coincident).
+
+ Raises:
+ ValueError: If a line is not two finite points, or its two points coincide.
+ """
+ (x1, y1), (x2, y2) = _line(line1, "line1")
+ (x3, y3), (x4, y4) = _line(line2, "line2")
+ denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
+ if abs(denominator) < 1e-12:
+ return None
+ t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denominator
+ return x1 + t * (x2 - x1), y1 + t * (y2 - y1)
+
+
+def _line(line: Line, name: str) -> tuple[tuple[float, float], tuple[float, float]]:
+ pts, _ = _points(line, name)
+ if pts.shape[0] != 2:
+ raise ValueError(f"{name} must be two points ((x1, y1), (x2, y2)), got {pts.shape[0]} points")
+ if np.array_equal(pts[0], pts[1]):
+ raise ValueError(f"{name} must have two different points, got {line!r}")
+ return (float(pts[0, 0]), float(pts[0, 1])), (float(pts[1, 0]), float(pts[1, 1]))
+
+
+def 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).
+
+ Args:
+ point: The point ``(x, y)``.
+ line: Two points ``((x1, y1), (x2, y2))`` on the line.
+ segment: Measure to the segment: beyond its ends, the distance to the nearer end point.
+
+ Raises:
+ ValueError: If the point or line is not finite, or the line's two points coincide.
+ """
+ px, py = _point(point, "point")
+ (x1, y1), (x2, y2) = _line(line, "line")
+ dx, dy = x2 - x1, y2 - y1
+ t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy)
+ if segment:
+ t = min(1.0, max(0.0, t))
+ return math.hypot(px - (x1 + t * dx), py - (y1 + t * dy))
diff --git a/cv2u/core/roi.py b/cv2u/core/roi.py
index a9f8372..40018ea 100644
--- a/cv2u/core/roi.py
+++ b/cv2u/core/roi.py
@@ -8,14 +8,14 @@
from .._validate import check_color, check_finite, check_image_not_empty
__all__ = [
- "centerCrop",
- "cropEx",
+ "cropCenter",
+ "cropRect",
"cropToContent",
"inRangeEx",
]
-def cropEx(
+def cropRect(
src: np.ndarray,
rect: tuple[int, int, int, int],
margin: int = 0,
@@ -34,26 +34,33 @@ def cropEx(
Otherwise the result has exactly the box size, and the parts outside the image are filled with this color.
Returns:
- A new array (not a view of ``src``). It is empty (size 0) when the box is entirely outside the image and
- ``fill`` is ``None``.
+ A new array (not a view of ``src``).
Raises:
- ValueError: If the box (after ``margin``) has no area.
+ ValueError: If ``src`` is empty, ``rect`` is not finite, the box (after ``margin``) has no area, or the box
+ lies entirely outside the image.
"""
- x, y, w, h = (int(v) for v in rect)
+ check_image_not_empty("src", src)
+ values = [float(v) for v in rect]
+ if len(values) != 4:
+ raise ValueError(f"rect must be (x, y, width, height), got {rect!r}")
+ for value in values:
+ check_finite("rect", value)
+ x, y, w, h = (int(v) for v in values)
x, y, w, h = x - margin, y - margin, w + 2 * margin, h + 2 * margin
if w <= 0 or h <= 0:
- raise ValueError(f"the box has no area: {(x, y, w, h)}")
+ raise ValueError(f"rect has no area after margin={margin}: {(x, y, w, h)}")
height, width = src.shape[:2]
x0, y0, x1, y1 = max(x, 0), max(y, 0), min(x + w, width), min(y + h, height)
+ if x0 >= x1 or y0 >= y1:
+ raise ValueError(f"rect {(x, y, w, h)} lies outside the image of size {width}x{height}")
if fill is None:
- return src[y0 : max(y0, y1), x0 : max(x0, x1)].copy()
+ return src[y0:y1, x0:x1].copy()
out = np.empty((h, w, *src.shape[2:]), dtype=src.dtype)
out[...] = fill # a scalar, or one value per channel
- if x0 < x1 and y0 < y1:
- out[y0 - y : y1 - y, x0 - x : x1 - x] = src[y0:y1, x0:x1]
+ out[y0 - y : y1 - y, x0 - x : x1 - x] = src[y0:y1, x0:x1]
return out
@@ -115,13 +122,17 @@ def inRangeEx(src: np.ndarray, lowerb: Sequence[float], upperb: Sequence[float])
Single-channel mask (0 or 255).
Raises:
- ValueError: If ``src`` does not have 3 channels or the bounds do not have 3 values.
+ ValueError: If ``src`` does not have 3 channels or is empty, the bounds do not have 3 values, or a bound
+ is not finite.
"""
if src.ndim != 3 or src.shape[2] != 3:
raise ValueError(f"src must be a 3-channel (HSV) image, got shape {src.shape}")
+ check_image_not_empty("src", src)
if len(lowerb) != 3 or len(upperb) != 3:
raise ValueError("lowerb and upperb must have 3 values (h, s, v)")
lo, hi = tuple(float(v) for v in lowerb), tuple(float(v) for v in upperb)
+ check_color("lowerb", list(lo))
+ check_color("upperb", list(hi))
if lo[0] <= hi[0]:
mask: np.ndarray = cv2.inRange(src, lo, hi)
return mask
@@ -132,7 +143,7 @@ def inRangeEx(src: np.ndarray, lowerb: Sequence[float], upperb: Sequence[float])
return combined
-def centerCrop(src: np.ndarray, size: tuple[int, int] | int, fill: float | Sequence[float] | None = None) -> np.ndarray:
+def cropCenter(src: np.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).
Args:
@@ -152,4 +163,4 @@ def centerCrop(src: np.ndarray, size: tuple[int, int] | int, fill: float | Seque
if width < 1 or height < 1:
raise ValueError(f"size must be positive, got {size}")
h, w = src.shape[:2]
- return cropEx(src, ((w - width) // 2, (h - height) // 2, width, height), fill=fill)
+ return cropRect(src, ((w - width) // 2, (h - height) // 2, width, height), fill=fill)
diff --git a/cv2u/core/rotate.py b/cv2u/core/rotate.py
index 5dd910f..774f191 100644
--- a/cv2u/core/rotate.py
+++ b/cv2u/core/rotate.py
@@ -1,9 +1,11 @@
import math
-from typing import Any
+from collections.abc import Sequence
import cv2
import numpy as np
+from .._validate import check_finite, check_image_not_empty
+
__all__ = ["rotateEx"]
@@ -11,22 +13,33 @@ def rotateEx(
src: np.ndarray,
angle: float,
scale: float = 1.0,
- flags: int | None = None,
- borderMode: int | None = None,
- borderValue: Any = None,
+ 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.
- The output canvas is enlarged so the whole rotated (and scaled) image fits.
- ``flags``, ``borderMode`` and ``borderValue`` are forwarded to ``cv.warpAffine``.
+ ``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.
+
+ Args:
+ src: Image to rotate.
+ angle: Rotation in degrees, counter-clockwise (as for ``cv.getRotationMatrix2D``).
+ scale: Isotropic scale factor applied with the rotation.
+ flags: Interpolation, as for ``cv.warpAffine``.
+ borderMode: How to fill the corners uncovered by the rotation, as for ``cv.warpAffine``.
+ borderValue: Fill color for ``cv.BORDER_CONSTANT``.
+
+ Returns:
+ The rotated image; its size is the bounding box of the rotated input.
Raises:
- ValueError: If ``angle`` is not finite or ``scale`` is not a positive finite number.
+ ValueError: If ``src`` is empty, ``angle`` is not finite, or ``scale`` is not a positive finite number.
"""
- if not math.isfinite(angle):
- raise ValueError(f"angle must be finite, got {angle}")
- if not math.isfinite(scale) or scale <= 0:
- raise ValueError(f"scale must be a positive finite number, got {scale}")
+ check_image_not_empty("src", src)
+ check_finite("angle", angle)
+ check_finite("scale", scale, positive=True)
height, width = src.shape[:2]
center = (width / 2, height / 2)
matrix = cv2.getRotationMatrix2D(center, angle, scale)
@@ -41,12 +54,7 @@ def rotateEx(
matrix[0, 2] += (bound_width / 2) - center[0]
matrix[1, 2] += (bound_height / 2) - center[1]
- kwargs: dict[str, Any] = {}
- if flags is not None:
- kwargs["flags"] = flags
- if borderMode is not None:
- kwargs["borderMode"] = borderMode
- if borderValue is not None:
- kwargs["borderValue"] = borderValue
-
- return cv2.warpAffine(src, matrix, (bound_width, bound_height), **kwargs)
+ dst: np.ndarray = cv2.warpAffine(
+ src, matrix, (bound_width, bound_height), flags=flags, borderMode=borderMode, borderValue=borderValue
+ )
+ return dst
diff --git a/cv2u/dnn/__init__.py b/cv2u/dnn/__init__.py
new file mode 100644
index 0000000..c714c46
--- /dev/null
+++ b/cv2u/dnn/__init__.py
@@ -0,0 +1,56 @@
+"""``cv2u.dnn``: inference helpers on top of ``cv.dnn``, plus everything from ``cv2.dnn``.
+
+Because ``cv2u`` replaces ``cv2``, this package stands in for ``cv2.dnn`` too: ``cv.dnn.readNet``,
+``cv.dnn.NMSBoxes``, ``cv.dnn.DNN_BACKEND_OPENCV`` and the rest are looked up on ``cv2.dnn`` when they are not
+defined here.
+"""
+
+from typing import Any
+
+import cv2
+
+from .inference import (
+ Detections,
+ PreprocessInfo,
+ drawDetections,
+ inferImage,
+ loadModel,
+ postprocessClassification,
+ postprocessDetections,
+ preprocessImage,
+ readClassNames,
+ sigmoid,
+ softmax,
+)
+
+__all__ = [
+ "Detections",
+ "PreprocessInfo",
+ "drawDetections",
+ "inferImage",
+ "loadModel",
+ "postprocessClassification",
+ "postprocessDetections",
+ "preprocessImage",
+ "readClassNames",
+ "sigmoid",
+ "softmax",
+]
+
+_cv2_dnn: Any = getattr(cv2, "dnn", None)
+
+
+def __getattr__(name: str) -> Any:
+ if _cv2_dnn is not None:
+ try:
+ return getattr(_cv2_dnn, name)
+ except AttributeError:
+ pass
+ raise AttributeError(f"module 'cv2u.dnn' has no attribute {name!r} (not in cv2u and not in cv2.dnn)")
+
+
+def __dir__() -> list[str]:
+ names = set(globals())
+ if _cv2_dnn is not None:
+ names |= set(dir(_cv2_dnn))
+ return sorted(names)
diff --git a/cv2u/dnn/inference.py b/cv2u/dnn/inference.py
new file mode 100644
index 0000000..16d1f8d
--- /dev/null
+++ b/cv2u/dnn/inference.py
@@ -0,0 +1,457 @@
+"""Run a ``cv.dnn`` model end to end: load, preprocess, forward, decode and draw.
+
+``cv.dnn`` stops at ``blobFromImage`` and ``Net.forward``: it does not remember how the image was letterboxed,
+does not decode YOLO-style outputs, does not read Unicode paths on Windows and fails with a C++ assertion for a
+missing file. These helpers fill those gaps with plain NumPy and the box utilities of :mod:`cv2u.core`.
+"""
+
+import os
+from collections.abc import Sequence
+from typing import Any, NamedTuple, Protocol
+
+import cv2
+import numpy as np
+from numpy.typing import ArrayLike, DTypeLike
+
+from .._validate import check_finite, check_image_not_empty
+from ..core.boxes import clipBoxes, nms, scaleBoxes, xyxyToXywh
+from ..imgproc.color import distinctColors
+from ..imgproc.draw import drawBoxes
+from ..imgproc.resize import letterbox
+
+__all__ = [
+ "Detections",
+ "PreprocessInfo",
+ "drawDetections",
+ "inferImage",
+ "loadModel",
+ "postprocessClassification",
+ "postprocessDetections",
+ "preprocessImage",
+ "readClassNames",
+ "sigmoid",
+ "softmax",
+]
+
+Color = float | Sequence[float]
+
+
+class _Net(Protocol):
+ """What :func:`inferImage` needs from ``cv.dnn.Net`` (any object with these methods works)."""
+
+ def setInput(self, blob: np.ndarray) -> None: ...
+
+ def forward(self, outputNames: Sequence[str]) -> Any: ...
+
+ def getUnconnectedOutLayersNames(self) -> Sequence[str]: ...
+
+
+class PreprocessInfo(NamedTuple):
+ """How :func:`preprocessImage` mapped the image into the network input; needed to map boxes back."""
+
+ scale: tuple[float, float]
+ """``(sx, sy)``: a point ``(x, y)`` of the original image is at ``(x * sx + left, y * sy + top)`` in the blob."""
+ pad: tuple[int, int]
+ """``(left, top)`` letterbox padding in pixels (``(0, 0)`` without letterboxing)."""
+ inputSize: tuple[int, int]
+ """Network input ``(width, height)``."""
+ originalSize: tuple[int, int]
+ """Original image ``(width, height)``."""
+
+
+class Detections(NamedTuple):
+ """Decoded detections in the coordinates of the original image, best score first."""
+
+ boxes: np.ndarray
+ """``(N, 4)`` float32 boxes ``(x, y, width, height)``, clipped to the original image."""
+ scores: np.ndarray
+ """``(N,)`` float32 confidences."""
+ classIds: np.ndarray
+ """``(N,)`` int32 class indices."""
+
+ @property
+ def size(self) -> int:
+ """Number of detections (``len()`` of a named tuple is always its field count, 3)."""
+ return len(self.scores)
+
+
+def _require_dnn() -> Any:
+ if not hasattr(cv2, "dnn"):
+ raise RuntimeError("this OpenCV build has no cv2.dnn module; install opencv-python with the dnn module")
+ return cv2.dnn
+
+
+def 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:
+ A float32 array of the same shape, summing to 1 along ``axis``.
+ """
+ array = np.asarray(x, dtype=np.float32)
+ if array.size == 0:
+ return array
+ shifted = np.exp(array - np.max(array, axis=axis, keepdims=True))
+ result: np.ndarray = shifted / np.sum(shifted, axis=axis, keepdims=True)
+ return result
+
+
+def sigmoid(x: ArrayLike) -> np.ndarray:
+ """Logistic function ``1 / (1 + exp(-x))``, for objectness and multi-label class logits.
+
+ Returns:
+ A float32 array of the same shape, without overflow warnings for large negative inputs.
+ """
+ array = np.asarray(x, dtype=np.float32)
+ result: np.ndarray = 0.5 * (1.0 + np.tanh(0.5 * array))
+ return result.astype(np.float32)
+
+
+_softmax = softmax # the ``softmax`` parameter below shadows the function
+
+
+def preprocessImage(
+ src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image (always fed to the network as 3 channels).
+ size: Network input ``(width, height)``.
+ letterboxPad: Keep the aspect ratio and pad with ``color`` (``True``), or stretch like ``blobFromImage``.
+ color: Padding color (BGR).
+ scale: Multiplier applied after ``mean`` subtraction (``1/255`` maps 8-bit pixels to ``[0, 1]``).
+ mean: Per-channel values subtracted first, in the channel order of the blob (RGB when ``swapRB``).
+ swapRB: Convert BGR to RGB, as most trained models expect.
+ dtype: Blob data type.
+
+ Returns:
+ ``(blob, info)``: the ``(1, 3, height, width)`` blob and the mapping info.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``size`` is not positive, or ``scale``/``mean`` are not finite.
+ """
+ check_image_not_empty("src", src)
+ width, height = size
+ if width <= 0 or height <= 0:
+ raise ValueError(f"size must be positive, got {size}")
+ check_finite("scale", scale)
+ mean_values = [float(m) for m in mean]
+ if len(mean_values) not in (1, 3):
+ raise ValueError(f"mean must have 1 or 3 values, got {mean!r}")
+ for value in mean_values:
+ check_finite("mean", value)
+
+ if src.ndim == 2:
+ bgr = cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)
+ elif src.shape[2] == 4:
+ bgr = cv2.cvtColor(src, cv2.COLOR_BGRA2BGR)
+ elif src.shape[2] == 1:
+ bgr = cv2.cvtColor(src[:, :, 0], cv2.COLOR_GRAY2BGR)
+ else:
+ bgr = src
+ h, w = bgr.shape[:2]
+ if letterboxPad:
+ resized, factor, pad = letterbox(bgr, size, color)
+ scales = (factor, factor)
+ else:
+ resized = cv2.resize(bgr, size, interpolation=cv2.INTER_AREA if width < w else cv2.INTER_LINEAR)
+ scales, pad = (width / w, height / h), (0, 0)
+
+ array = resized.astype(np.float32)
+ if swapRB:
+ array = array[:, :, ::-1]
+ array = (array - np.asarray(mean_values, dtype=np.float32)) * np.float32(scale)
+ blob = np.ascontiguousarray(array.transpose(2, 0, 1)[None]).astype(dtype)
+ return blob, PreprocessInfo(scales, pad, (width, height), (w, h))
+
+
+def _rows(output: ArrayLike, transpose: bool | None) -> np.ndarray:
+ array = np.asarray(output, dtype=np.float32)
+ while array.ndim > 2 and array.shape[0] == 1:
+ array = array[0]
+ if array.ndim != 2:
+ raise ValueError(f"output must have shape (1, N, K) or (1, K, N), got {np.shape(output)}")
+ if transpose is None:
+ # YOLOv8-style (1, 4 + C, 8400): the channel axis comes first and is the smaller one.
+ transpose = array.shape[0] < array.shape[1]
+ return array.T if transpose else array
+
+
+def 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.
+
+ Args:
+ output: Network output with one row per candidate: 4 box values, optionally an objectness score, then
+ one score per class.
+ info: From :func:`preprocessImage`.
+ scoreThreshold: Candidates whose best class score (times objectness) is below this are dropped.
+ iouThreshold: NMS overlap threshold.
+ maxCount: Keep at most this many detections.
+ boxFormat: ``"cxcywh"`` (YOLO), ``"xywh"`` or ``"xyxy"``.
+ hasObjectness: Column 4 is an objectness score multiplied into the class scores (YOLOv5/v7).
+ classAgnostic: Run NMS over all classes at once instead of per class.
+ normalized: Box values are in ``[0, 1]`` relative to the network input instead of pixels.
+ transpose: Force the ``(4 + C, N)`` layout (``True``) or ``(N, 4 + C)`` (``False``); ``None`` picks
+ the layout whose first axis is the longer one, which is right for every real model but may be wrong
+ for tiny synthetic outputs.
+
+ Returns:
+ :class:`Detections` sorted by descending score.
+
+ Raises:
+ ValueError: If the output has no class columns, ``boxFormat`` is unknown, or a threshold is not finite.
+ """
+ if boxFormat not in ("cxcywh", "xywh", "xyxy"):
+ raise ValueError(f"boxFormat must be 'cxcywh', 'xywh' or 'xyxy', got {boxFormat!r}")
+ check_finite("scoreThreshold", scoreThreshold)
+ check_finite("iouThreshold", iouThreshold, nonnegative=True)
+ rows = _rows(output, transpose)
+ first_class = 5 if hasObjectness else 4
+ if rows.shape[1] <= first_class:
+ needed = "4 box values, an objectness score" if hasObjectness else "4 box values"
+ raise ValueError(f"output rows need {needed} and at least one class score, got {rows.shape[1]} columns")
+
+ empty = Detections(np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32))
+ if len(rows) == 0:
+ return empty
+ class_scores = rows[:, first_class:]
+ class_ids = np.argmax(class_scores, axis=1)
+ scores = class_scores[np.arange(len(rows)), class_ids]
+ if hasObjectness:
+ scores = scores * rows[:, 4]
+ keep = np.flatnonzero(scores >= scoreThreshold)
+ if len(keep) == 0:
+ return empty
+ boxes = rows[keep, :4].astype(np.float64)
+ scores, class_ids = scores[keep], class_ids[keep]
+
+ if normalized:
+ boxes *= np.array([*info.inputSize, *info.inputSize], dtype=np.float64)
+ if boxFormat == "cxcywh":
+ boxes[:, 0] -= boxes[:, 2] / 2
+ boxes[:, 1] -= boxes[:, 3] / 2
+ elif boxFormat == "xyxy":
+ boxes = xyxyToXywh(boxes)
+ boxes = clipBoxes(scaleBoxes(boxes, info.scale, info.pad, inverse=True), info.originalSize)
+
+ if classAgnostic:
+ offset_boxes = boxes
+ else:
+ # Shift each class to its own region so one NMS call never compares boxes of different classes.
+ offset_boxes = boxes.copy()
+ offset_boxes[:, 0] += class_ids * (max(info.originalSize) + 1.0)
+ order = nms(offset_boxes, scores, iouThreshold, maxCount=maxCount)
+ return Detections(
+ boxes[order].astype(np.float32), scores[order].astype(np.float32), class_ids[order].astype(np.int32)
+ )
+
+
+def postprocessClassification(output: ArrayLike, topK: int = 5, softmax: bool = True) -> list[tuple[int, float]]:
+ """Top-``k`` ``(classId, probability)`` pairs from a classifier output.
+
+ Args:
+ output: Output of shape ``(1, C)`` or ``(C,)``.
+ topK: How many classes to return (fewer when the model has fewer classes).
+ softmax: Apply :func:`softmax` first (``False`` when the model already outputs probabilities).
+
+ Returns:
+ A list sorted by descending probability.
+
+ Raises:
+ ValueError: If ``output`` is not one vector or ``topK`` is not positive.
+ """
+ if topK < 1:
+ raise ValueError(f"topK must be positive, got {topK}")
+ vector = np.asarray(output, dtype=np.float32).squeeze()
+ if vector.ndim != 1 or vector.size == 0:
+ raise ValueError(f"output must be one vector of class scores, got shape {np.shape(output)}")
+ probs = _softmax(vector) if softmax else vector
+ order = np.argsort(-probs, kind="stable")[:topK]
+ return [(int(i), float(probs[i])) for i in order]
+
+
+def loadModel(
+ path: str | os.PathLike[str],
+ config: str | os.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)``.
+
+ Args:
+ path: Model file (``.onnx``, ``.tflite``, ``.pb``, or anything ``readNet`` understands).
+ config: Optional text config for the model (e.g. ``.pbtxt``).
+ backend: ``cv.dnn.DNN_BACKEND_*`` to set, or ``None`` for OpenCV's default.
+ target: ``cv.dnn.DNN_TARGET_*`` to set.
+ preferGpu: Use the CUDA backend and target when this OpenCV build has it; silently keeps the default
+ otherwise. Ignored when ``backend`` is given.
+
+ Returns:
+ A ``cv.dnn.Net``.
+
+ Raises:
+ FileNotFoundError: If ``path`` or ``config`` does not exist.
+ RuntimeError: If this OpenCV build has no ``dnn`` module.
+ """
+ dnn = _require_dnn()
+ model_path = os.fspath(path)
+ if not os.path.isfile(model_path):
+ raise FileNotFoundError(f"model file not found: {model_path}")
+ config_path = None if config is None else os.fspath(config)
+ if config_path is not None and not os.path.isfile(config_path):
+ raise FileNotFoundError(f"config file not found: {config_path}")
+
+ ext = os.path.splitext(model_path)[1].lower()
+ # Only the formats with a buffer reader (unicode-safe paths) are read into memory; the others let OpenCV
+ # open the path itself, so a large Caffe or Darknet model is not loaded twice.
+ if ext == ".onnx" and hasattr(dnn, "readNetFromONNX"):
+ net = dnn.readNetFromONNX(np.fromfile(model_path, dtype=np.uint8))
+ elif ext == ".tflite" and hasattr(dnn, "readNetFromTFLite"):
+ net = dnn.readNetFromTFLite(np.fromfile(model_path, dtype=np.uint8))
+ elif ext == ".pb" and hasattr(dnn, "readNetFromTensorflow"):
+ config_buffer = np.zeros(0, np.uint8) if config_path is None else np.fromfile(config_path, dtype=np.uint8)
+ net = dnn.readNetFromTensorflow(np.fromfile(model_path, dtype=np.uint8), config_buffer)
+ else:
+ net = dnn.readNet(model_path) if config_path is None else dnn.readNet(model_path, config_path)
+
+ if backend is None and preferGpu and hasattr(dnn, "DNN_BACKEND_CUDA"):
+ try:
+ targets = list(dnn.getAvailableTargets(dnn.DNN_BACKEND_CUDA))
+ except cv2.error:
+ targets = []
+ if dnn.DNN_TARGET_CUDA in targets:
+ backend, target = dnn.DNN_BACKEND_CUDA, dnn.DNN_TARGET_CUDA if target is None else target
+ if backend is not None:
+ net.setPreferableBackend(backend)
+ if target is not None:
+ net.setPreferableTarget(target)
+ return net
+
+
+def inferImage(
+ net: _Net,
+ src: np.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.
+
+ Args:
+ net: A ``cv.dnn.Net`` (or any object with ``setInput``, ``forward`` and ``getUnconnectedOutLayersNames``).
+ src: A ready ``(1, C, H, W)`` blob, or an image which is then passed through :func:`preprocessImage`
+ with ``size`` and default options (use :func:`preprocessImage` yourself when you need the
+ :class:`PreprocessInfo` to map boxes back).
+ outputNames: Layers to return; all unconnected output layers by default.
+ size: Network input ``(width, height)``, required when ``src`` is an image.
+
+ Returns:
+ One array per output layer.
+
+ Raises:
+ ValueError: If ``src`` is an image and ``size`` is missing, or ``src`` is neither an image nor a blob.
+ """
+ if src.ndim == 4:
+ blob = src
+ elif src.ndim in (2, 3):
+ if size is None:
+ raise ValueError("size is required when src is an image instead of a blob")
+ blob, _ = preprocessImage(src, size)
+ else:
+ raise ValueError(f"src must be an image or a 4-D blob, got shape {src.shape}")
+ names = list(net.getUnconnectedOutLayersNames()) if outputNames is None else list(outputNames)
+ net.setInput(blob)
+ outputs = net.forward(names)
+ if isinstance(outputs, np.ndarray):
+ return [outputs]
+ return [np.asarray(o) for o in outputs]
+
+
+def readClassNames(path: str | os.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:
+ FileNotFoundError: If the file does not exist.
+ """
+ with open(path, encoding="utf-8-sig") as file:
+ return [line.strip() for line in file if line.strip()]
+
+
+def drawDetections(
+ src: np.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 | os.PathLike[str] | None = None,
+ fontSize: int = 16,
+) -> np.ndarray:
+ """Draw :class:`Detections` as labeled boxes, one color per class, in place.
+
+ Args:
+ src: 8-bit image to draw on (modified and returned, like ``cv.rectangle``).
+ detections: From :func:`postprocessDetections`.
+ classNames: Label text per class id; ids without a name are shown as numbers.
+ colors: One color per class id; :func:`distinctColors` by default.
+ thickness: Box line thickness.
+ fontScale: Hershey font size for the labels.
+ showScore: Append the score (``"cat 0.87"``).
+ fontPath: TrueType font for Unicode class names (see :func:`drawLabel`).
+ fontSize: Font size in pixels for ``fontPath``.
+
+ Returns:
+ ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty.
+ """
+ check_image_not_empty("src", src)
+ class_ids = np.asarray(detections.classIds).reshape(-1)
+ if len(class_ids) == 0:
+ return src
+ palette: Sequence[Color] = colors if colors is not None else distinctColors(int(class_ids.max()) + 1)
+ labels = []
+ for class_id, score in zip(class_ids, detections.scores, strict=True):
+ name = classNames[class_id] if classNames is not None and 0 <= class_id < len(classNames) else str(class_id)
+ labels.append(f"{name} {float(score):.2f}" if showScore else name)
+ box_colors = [palette[int(c) % len(palette)] for c in class_ids]
+ return drawBoxes(src, detections.boxes, labels, box_colors, thickness, fontScale, fontPath, fontSize)
diff --git a/cv2u/highgui/display.py b/cv2u/highgui/display.py
index 32e5ee5..562b7d2 100644
--- a/cv2u/highgui/display.py
+++ b/cv2u/highgui/display.py
@@ -1,6 +1,8 @@
import cv2
import numpy as np
+from .._validate import check_image_not_empty
+
__all__ = ["imshowEx", "imshowInline"]
@@ -29,8 +31,9 @@ def imshowEx(winname: str, img: np.ndarray, maxSize: tuple[int, int] = (1280, 72
maxSize: Largest displayed size, as ``(width, height)``.
Raises:
- ValueError: If ``maxSize`` is not positive.
+ ValueError: If ``img`` is empty or ``maxSize`` is not positive.
"""
+ check_image_not_empty("img", img)
cv2.imshow(winname, _fit(img, maxSize))
@@ -47,8 +50,9 @@ def imshowInline(img: np.ndarray, maxSize: tuple[int, int] | None = None, ext: s
Raises:
ImportError: If IPython is not installed (Jupyter always provides it).
- ValueError: If the image cannot be encoded.
+ ValueError: If ``img`` is empty or cannot be encoded.
"""
+ check_image_not_empty("img", img)
try:
from IPython.display import Image, display
except ImportError as e:
diff --git a/cv2u/imgcodecs/__init__.py b/cv2u/imgcodecs/__init__.py
index ce3658e..421b91e 100644
--- a/cv2u/imgcodecs/__init__.py
+++ b/cv2u/imgcodecs/__init__.py
@@ -1,16 +1,34 @@
from .convert import fromPillow, imdecodeBase64, imencodeBase64, toPillow
from .files import imreadAll, imreadEx, imwriteAll, imwriteEx, listImages
-from .urlread import urlread
+from .meta import (
+ ImageInfo,
+ convertImageFormat,
+ exifOrientation,
+ imageInfo,
+ imdecodeEx,
+ imencodeEx,
+ imreadOriented,
+ imreadResized,
+)
+from .url import imreadUrl
__all__ = [
+ "ImageInfo",
+ "convertImageFormat",
+ "exifOrientation",
"fromPillow",
+ "imageInfo",
"imdecodeBase64",
+ "imdecodeEx",
"imencodeBase64",
+ "imencodeEx",
"imreadAll",
"imreadEx",
+ "imreadOriented",
+ "imreadResized",
+ "imreadUrl",
"imwriteAll",
"imwriteEx",
"listImages",
"toPillow",
- "urlread",
]
diff --git a/cv2u/imgcodecs/convert.py b/cv2u/imgcodecs/convert.py
index 87f0ce0..f5965fe 100644
--- a/cv2u/imgcodecs/convert.py
+++ b/cv2u/imgcodecs/convert.py
@@ -94,7 +94,7 @@ def fromPillow(image: Image.Image) -> np.ndarray:
return cv2.cvtColor(np.array(image.convert("RGB")), cv2.COLOR_RGB2BGR)
-def imencodeBase64(img: np.ndarray, ext: str = ".png", params: Sequence[int] = (), dataUri: bool = False) -> str:
+def imencodeBase64(img: np.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 ``
``.
Args:
@@ -104,8 +104,9 @@ def imencodeBase64(img: np.ndarray, ext: str = ".png", params: Sequence[int] = (
dataUri: Return a data URI (``"data:image/png;base64,..."``) instead of the bare base64 text.
Raises:
- ValueError: If the image cannot be encoded in this format.
+ ValueError: If ``img`` is empty or cannot be encoded in this format.
"""
+ check_image_not_empty("img", img)
try:
ok, buffer = cv2.imencode(ext, img, list(params))
except cv2.error as e:
diff --git a/cv2u/imgcodecs/files.py b/cv2u/imgcodecs/files.py
index 18bf98b..be5f7c4 100644
--- a/cv2u/imgcodecs/files.py
+++ b/cv2u/imgcodecs/files.py
@@ -104,7 +104,7 @@ def listImages(path: str | os.PathLike[str], recursive: bool = False) -> list[Pa
def imreadAll(
- filenames: Iterable[str | os.PathLike[str]], flags: int = cv2.IMREAD_COLOR, strict: bool = True
+ filenames: Iterable[str | os.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`.
@@ -134,6 +134,7 @@ def imwriteAll(
images: Iterable[np.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.
diff --git a/cv2u/imgcodecs/meta.py b/cv2u/imgcodecs/meta.py
new file mode 100644
index 0000000..4ebdc15
--- /dev/null
+++ b/cv2u/imgcodecs/meta.py
@@ -0,0 +1,352 @@
+"""Image file metadata, EXIF orientation, and reading / encoding helpers with clear failure modes."""
+
+import os
+from collections.abc import Sequence
+from pathlib import Path
+from typing import NamedTuple
+
+import cv2
+import numpy as np
+from PIL import Image, UnidentifiedImageError
+
+from .._validate import to_uint8
+from ..imgproc.color import flattenAlpha
+from ..imgproc.resize import resizeEx
+from .files import imreadEx, imwriteEx
+
+__all__ = [
+ "ImageInfo",
+ "convertImageFormat",
+ "exifOrientation",
+ "imageInfo",
+ "imdecodeEx",
+ "imencodeEx",
+ "imreadOriented",
+ "imreadResized",
+]
+
+
+class ImageInfo(NamedTuple):
+ """Header information of an image file, from :func:`imageInfo`."""
+
+ width: int
+ """Stored width in pixels (before the EXIF orientation is applied)."""
+ height: int
+ """Stored height in pixels (before the EXIF orientation is applied)."""
+ channels: int
+ """Number of channels of the stored image (1 for grayscale and palette images, 3 for RGB, 4 for RGBA / CMYK)."""
+ mode: str
+ """Pillow mode, e.g. ``"RGB"``, ``"RGBA"``, ``"L"``, ``"P"``, ``"I;16"``."""
+ format: str
+ """File format, e.g. ``"JPEG"``, ``"PNG"``, ``"WEBP"``, ``"TIFF"``."""
+ fileSize: int
+ """Size of the file in bytes."""
+ exifOrientation: int
+ """EXIF orientation tag (1-8); 1 when the file has none."""
+
+
+def _open(filename: str | os.PathLike[str]) -> Image.Image:
+ """Open an image lazily with Pillow; only the header is parsed."""
+ try:
+ return Image.open(os.fspath(filename))
+ except UnidentifiedImageError as e:
+ raise OSError(f"cannot read image: {os.fspath(filename)!r}") from e
+
+
+def _orientation(image: Image.Image) -> int:
+ value = image.getexif().get(0x0112, 1)
+ return int(value) if isinstance(value, int) and 1 <= value <= 8 else 1
+
+
+def imageInfo(filename: str | os.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.
+
+ Args:
+ filename: Path to the image file.
+
+ Returns:
+ An :class:`ImageInfo` named tuple ``(width, height, channels, mode, format, fileSize, exifOrientation)``.
+ ``width`` and ``height`` are as stored; for ``exifOrientation`` 5-8 the displayed image is ``height`` wide.
+
+ Raises:
+ OSError: If the file does not exist or is not an image Pillow recognizes.
+ """
+ with _open(filename) as image:
+ width, height = image.size
+ return ImageInfo(
+ width=int(width),
+ height=int(height),
+ channels=len(image.getbands()),
+ mode=image.mode,
+ format=image.format or "",
+ fileSize=os.path.getsize(os.fspath(filename)),
+ exifOrientation=_orientation(image),
+ )
+
+
+def exifOrientation(filename: str | os.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:
+ OSError: If the file does not exist or is not an image Pillow recognizes.
+ """
+ with _open(filename) as image:
+ return _orientation(image)
+
+
+def _apply_orientation(img: np.ndarray, orientation: int) -> np.ndarray:
+ """Rotate / flip ``img`` so that an image stored with this EXIF orientation displays upright."""
+ if orientation == 2:
+ return cv2.flip(img, 1)
+ if orientation == 3:
+ return cv2.rotate(img, cv2.ROTATE_180)
+ if orientation == 4:
+ return cv2.flip(img, 0)
+ if orientation == 5:
+ return cv2.transpose(img)
+ if orientation == 6:
+ return cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
+ if orientation == 7:
+ return cv2.flip(cv2.transpose(img), -1)
+ if orientation == 8:
+ return cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
+ return img
+
+
+def _read_header_orientation(filename: str | os.PathLike[str]) -> int:
+ try:
+ with Image.open(os.fspath(filename)) as image:
+ return _orientation(image)
+ except OSError:
+ return 1 # formats Pillow cannot open (e.g. .exr, .hdr) have no EXIF orientation anyway
+
+
+def imreadOriented(filename: str | os.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.
+
+ Args:
+ filename: Path to the image file.
+ flags: ``cv.IMREAD_*`` flags, as for ``cv.imread``. ``cv.IMREAD_IGNORE_ORIENTATION`` is added internally so
+ the orientation is never applied twice.
+
+ Returns:
+ The upright image, or ``None`` if the file cannot be read or decoded (like ``cv.imread``).
+ """
+ img = imreadEx(filename, flags | cv2.IMREAD_IGNORE_ORIENTATION)
+ if img is None:
+ return None
+ return _apply_orientation(img, _read_header_orientation(filename))
+
+
+_REDUCED_FLAGS = {
+ (cv2.IMREAD_COLOR, 2): cv2.IMREAD_REDUCED_COLOR_2,
+ (cv2.IMREAD_COLOR, 4): cv2.IMREAD_REDUCED_COLOR_4,
+ (cv2.IMREAD_COLOR, 8): cv2.IMREAD_REDUCED_COLOR_8,
+ (cv2.IMREAD_GRAYSCALE, 2): cv2.IMREAD_REDUCED_GRAYSCALE_2,
+ (cv2.IMREAD_GRAYSCALE, 4): cv2.IMREAD_REDUCED_GRAYSCALE_4,
+ (cv2.IMREAD_GRAYSCALE, 8): cv2.IMREAD_REDUCED_GRAYSCALE_8,
+}
+
+
+def imreadResized(
+ filename: str | os.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).
+
+ Args:
+ filename: Path to the image file.
+ size: Target size as ``(width, height)``.
+ scale: Scale factor, e.g. ``0.5`` for half size.
+ width: Target width; the height follows the aspect ratio.
+ height: Target height; the width follows the aspect ratio.
+ flags: ``cv.IMREAD_*`` flags, as for ``cv.imread``.
+ interpolation: ``cv.INTER_*`` flag, as for :func:`resizeEx`.
+
+ Returns:
+ The resized image, or ``None`` if the file cannot be read or decoded (like ``cv.imread``).
+
+ Raises:
+ ValueError: If not exactly one of ``size``, ``scale``, ``width`` and ``height`` is given, or it is not
+ positive.
+ """
+ given = [
+ name
+ for name, value in (("size", size), ("scale", scale), ("width", width), ("height", height))
+ if value is not None
+ ]
+ if len(given) != 1:
+ raise ValueError(f"give exactly one of size, scale, width or height, got {given or 'none'}")
+ if size is not None and (size[0] <= 0 or size[1] <= 0):
+ raise ValueError(f"size must be positive, got {size[0]}x{size[1]}")
+ if scale is not None and not (np.isfinite(scale) and scale > 0):
+ raise ValueError(f"scale must be a positive finite number, got {scale}")
+
+ reduced = _REDUCED_FLAGS.get((flags, round(1 / scale))) if scale is not None and 1 / scale in (2, 4, 8) else None
+ img = imreadEx(filename, (reduced if reduced is not None else flags) | cv2.IMREAD_IGNORE_ORIENTATION)
+ if img is None:
+ return None
+ orientation = _read_header_orientation(filename)
+ if scale is not None:
+ if reduced is not None:
+ full_w, full_h = _stored_size(filename, img, round(1 / scale))
+ else:
+ full_h, full_w = img.shape[:2]
+ target: tuple[int, int] = (max(1, int(full_w * scale + 0.5)), max(1, int(full_h * scale + 0.5)))
+ elif size is not None:
+ target = (int(size[0]), int(size[1]))
+ if orientation >= 5:
+ target = (target[1], target[0]) # the final rotation swaps the sides back
+ else:
+ if orientation >= 5:
+ width, height = height, width
+ img = resizeEx(img, width=width, height=height, interpolation=interpolation)
+ return _apply_orientation(img, orientation)
+ if (img.shape[1], img.shape[0]) != target:
+ img = resizeEx(img, width=target[0], height=target[1], interpolation=interpolation)
+ return _apply_orientation(img, orientation)
+
+
+def _stored_size(filename: str | os.PathLike[str], reduced: np.ndarray, factor: int) -> tuple[int, int]:
+ """Full stored ``(width, height)``, from the header when Pillow can read it, else from the reduced image."""
+ try:
+ with Image.open(os.fspath(filename)) as image:
+ return int(image.size[0]), int(image.size[1])
+ except OSError:
+ return reduced.shape[1] * factor, reduced.shape[0] * factor
+
+
+def imencodeEx(ext: str, img: np.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.
+
+ Args:
+ ext: File extension that selects the format, e.g. ``".png"``, ``".jpg"``, ``".webp"`` (``"png"`` works too).
+ img: Image to encode.
+ params: Format-specific ``cv.IMWRITE_*`` parameter pairs, e.g. ``(cv.IMWRITE_JPEG_QUALITY, 90)``.
+
+ Returns:
+ The encoded file content.
+
+ Raises:
+ ValueError: If the image is empty or cannot be encoded in this format.
+ """
+ if img.size == 0:
+ raise ValueError(f"img must not be empty, got shape {img.shape}")
+ if not ext.startswith("."):
+ ext = f".{ext}"
+ try:
+ ok, buffer = cv2.imencode(ext, img, list(params))
+ except cv2.error as e:
+ raise ValueError(f"cannot encode the image as {ext!r}: no encoder or unsupported image type") from e
+ if not ok:
+ raise ValueError(f"cannot encode the image as {ext!r}")
+ return bytes(buffer.tobytes())
+
+
+def imdecodeEx(data: bytes | bytearray | memoryview | np.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.
+
+ Args:
+ data: The encoded file content.
+ flags: ``cv.IMREAD_*`` flags, as for ``cv.imdecode``.
+
+ Returns:
+ The image, or ``None`` if the data is empty or not a decodable image (like ``cv.imdecode``).
+ """
+ buffer = data if isinstance(data, np.ndarray) else np.frombuffer(data, dtype=np.uint8)
+ if buffer.size == 0:
+ return None
+ return cv2.imdecode(np.ascontiguousarray(buffer).reshape(-1), flags)
+
+
+_ALPHA_FORMATS = frozenset({".png", ".webp", ".tif", ".tiff", ".avif", ".bmp", ".jp2"})
+_UINT16_FORMATS = frozenset({".png", ".tif", ".tiff", ".jp2", ".pxm", ".pgm", ".ppm", ".pnm", ".pfm"})
+"""Formats whose OpenCV encoder keeps 16-bit samples without loss (PFM stores them as floats)."""
+_FLOAT_FORMATS = frozenset({".exr", ".hdr", ".pic", ".pfm", ".tif", ".tiff"})
+"""Formats whose OpenCV encoder stores 32-bit float samples (TIFF also takes 16-bit and 64-bit floats)."""
+_QUALITY_FLAGS = {
+ ".jpg": cv2.IMWRITE_JPEG_QUALITY,
+ ".jpeg": cv2.IMWRITE_JPEG_QUALITY,
+ ".jpe": cv2.IMWRITE_JPEG_QUALITY,
+ ".webp": cv2.IMWRITE_WEBP_QUALITY,
+ ".avif": cv2.IMWRITE_AVIF_QUALITY,
+}
+
+
+def convertImageFormat(
+ src: str | os.PathLike[str],
+ dst: str | os.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.
+
+ Args:
+ src: Path of the image to convert.
+ dst: Path to write to; the format comes from its extension.
+ quality: JPEG / WebP / AVIF quality (0-100). Ignored for other formats.
+ background: Background color for flattening transparency, white by default.
+ makeDirs: Create missing parent directories of ``dst``.
+
+ Returns:
+ ``True`` on success, ``False`` if ``src`` cannot be read or ``dst`` cannot be written (like ``cv.imwrite``).
+
+ Raises:
+ ValueError: If ``dst`` has no file extension.
+ cv2.error: If no encoder exists for the extension of ``dst``, like ``cv.imwrite``.
+ """
+ ext = Path(os.fspath(dst)).suffix.lower()
+ if not ext:
+ raise ValueError(f"cannot determine the image format: {os.fspath(dst)!r} has no file extension")
+ img = imreadOriented(src, cv2.IMREAD_UNCHANGED)
+ if img is None:
+ return False
+ if img.ndim == 3 and img.shape[2] == 4 and ext not in _ALPHA_FORMATS:
+ img = flattenAlpha(img, background)
+ keeps_depth = ext in _FLOAT_FORMATS if np.issubdtype(img.dtype, np.floating) else ext in _UINT16_FORMATS
+ if img.dtype != np.uint8 and not keeps_depth:
+ img = to_uint8(img)
+ params: list[int] = []
+ if quality is not None and ext in _QUALITY_FLAGS:
+ params = [_QUALITY_FLAGS[ext], int(quality)]
+ return imwriteEx(dst, img, params, makeDirs)
diff --git a/cv2u/imgcodecs/urlread.py b/cv2u/imgcodecs/url.py
similarity index 84%
rename from cv2u/imgcodecs/urlread.py
rename to cv2u/imgcodecs/url.py
index 751bf54..ed5da25 100644
--- a/cv2u/imgcodecs/urlread.py
+++ b/cv2u/imgcodecs/url.py
@@ -4,24 +4,25 @@
import cv2
import numpy as np
-__all__ = ["urlread"]
+__all__ = ["imreadUrl"]
# Many image hosts reject urllib's default "Python-urllib/3.x" user agent with HTTP 403.
_USER_AGENT = "cv2u (+https://github.com/076923/cv2-utils)"
-def urlread(
+def imreadUrl(
url: str,
- flags: int = cv2.IMREAD_UNCHANGED,
+ 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``.
+ """Download an image from ``url`` and decode it like ``cv.imread`` (which cannot read from a URL).
Args:
url: ``http(s)://`` or ``file://`` URL of the image.
- flags: ``cv.IMREAD_*`` flags, as for ``cv.imread``.
+ flags: ``cv.IMREAD_*`` flags, as for ``cv.imread`` (``cv.IMREAD_COLOR`` by default, like ``cv.imread``;
+ pass ``cv.IMREAD_UNCHANGED`` to keep an alpha channel).
timeout: Timeout in seconds for the request. ``None`` uses the global default.
headers: Extra HTTP headers, e.g. ``{"Authorization": "Bearer ..."}``. A ``User-Agent`` given here
replaces the default one.
@@ -33,7 +34,7 @@ def urlread(
Raises:
urllib.error.URLError: If the request fails (including HTTP errors).
- ValueError: If the response is larger than ``maxBytes``.
+ ValueError: If ``maxBytes`` is below 1, or the response is larger than ``maxBytes``.
"""
if maxBytes is not None and maxBytes < 1:
raise ValueError(f"maxBytes must be at least 1, got {maxBytes}")
diff --git a/cv2u/imgproc/__init__.py b/cv2u/imgproc/__init__.py
index 1841f23..519ab84 100644
--- a/cv2u/imgproc/__init__.py
+++ b/cv2u/imgproc/__init__.py
@@ -1,4 +1,24 @@
from .adjust import adjustBrightnessContrast, adjustHSV, autoContrast, colorTransfer, matchHistograms, whiteBalance
+from .augment import (
+ addNoise,
+ cutMix,
+ jpegArtifacts,
+ mixup,
+ mosaic,
+ motionBlur,
+ posterize,
+ randomBlur,
+ randomBrightnessContrast,
+ randomCrop,
+ randomErase,
+ randomFlip,
+ randomHSV,
+ randomPerspective,
+ randomRotate,
+ randomScale,
+ solarize,
+ vignette,
+)
from .binary import binarize, morphology
from .color import bgrToHex, distinctColors, flattenAlpha, hexToBGR, toBGR, toBGRA, toGray
from .contour import (
@@ -14,7 +34,21 @@
mergeContours,
sortContours,
)
-from .detect import detectBlobs, findCircles, findLines
+from .detect import findBlobs, findCircles, findLines
+from .document import (
+ detectPage,
+ detectTextBlocks,
+ detectTextLines,
+ enhanceDocument,
+ estimateSkew,
+ niblackThreshold,
+ removeBorder,
+ removeLines,
+ removeShadow,
+ removeSpeckles,
+ sauvolaThreshold,
+ scanDocument,
+)
from .draw import (
drawBoxes,
drawDashedLine,
@@ -40,17 +74,81 @@
removeSmallObjects,
skeletonize,
)
+from .palette import (
+ CSS_COLORS,
+ blendColors,
+ colorDistance,
+ colormapPalette,
+ colorName,
+ complementaryColor,
+ darkenColor,
+ gradientPalette,
+ invertColor,
+ lightenColor,
+ nearestColor,
+ randomColors,
+ textColorFor,
+)
from .puttext import putTextEx
from .quality import diffMask, hashDistance, imageHash, sharpnessScore, ssim
-from .resize import letterbox, resizeEx
+from .resize import Letterbox, letterbox, resizeEx
+from .stats import (
+ ImageStats,
+ brightnessScore,
+ colorfulness,
+ contrastScore,
+ dominantHue,
+ entropy,
+ estimateNoise,
+ exposureScore,
+ histogramCompare,
+ histogramEx,
+ imageStats,
+ isBlank,
+ isBlurry,
+ isGrayscale,
+ mae,
+ meanColor,
+ mse,
+)
+from .stitch import (
+ stitchImages,
+ stitchPair,
+)
from .template import findTemplate
+from .visualize import (
+ COCO_SKELETON,
+ applyColorMapEx,
+ blendImages,
+ colorBar,
+ compareImages,
+ drawArrow,
+ drawCrosshair,
+ drawFPS,
+ drawLegend,
+ drawPolygon,
+ drawProgressBar,
+ drawRotatedBoxes,
+ drawRotatedRect,
+ drawSkeleton,
+ drawTextBlock,
+ drawTrajectory,
+ heatmap,
+ labeledMontage,
+)
__all__ = [
+ "COCO_SKELETON",
+ "CSS_COLORS",
"ContourStats",
"FeatureMatches",
+ "ImageStats",
+ "Letterbox",
+ "addNoise",
"adjustBrightnessContrast",
"adjustHSV",
"alignImages",
+ "applyColorMapEx",
"applyMask",
"approxContour",
"asContour",
@@ -58,59 +156,134 @@
"autoContrast",
"bgrToHex",
"binarize",
+ "blendColors",
+ "blendImages",
"boundingRects",
+ "brightnessScore",
+ "colorBar",
+ "colorDistance",
+ "colorName",
"colorTransfer",
+ "colorfulness",
+ "colormapPalette",
+ "compareImages",
+ "complementaryColor",
"contourStats",
"contoursToMask",
+ "contrastScore",
"cropContour",
"cropRotatedRect",
+ "cutMix",
"cutout",
+ "darkenColor",
"deskew",
- "detectBlobs",
+ "detectPage",
+ "detectTextBlocks",
+ "detectTextLines",
"diffMask",
"distinctColors",
+ "dominantHue",
+ "drawArrow",
"drawBoxes",
"drawContoursEx",
+ "drawCrosshair",
"drawDashedLine",
"drawDashedRectangle",
+ "drawFPS",
"drawGrid",
"drawHistogram",
"drawLabel",
+ "drawLegend",
"drawPoints",
+ "drawPolygon",
+ "drawProgressBar",
+ "drawRotatedBoxes",
+ "drawRotatedRect",
"drawRoundedRectangle",
+ "drawSkeleton",
+ "drawTextBlock",
+ "drawTrajectory",
+ "enhanceDocument",
+ "entropy",
"equalizeHistEx",
+ "estimateNoise",
+ "estimateSkew",
+ "exposureScore",
"fillHoles",
"filterContours",
+ "findBlobs",
"findCircles",
"findContoursEx",
"findLines",
"findTemplate",
"flattenAlpha",
"fourPointTransform",
+ "gradientPalette",
"hashDistance",
+ "heatmap",
"hexToBGR",
+ "histogramCompare",
+ "histogramEx",
"imageHash",
+ "imageStats",
+ "invertColor",
+ "isBlank",
+ "isBlurry",
+ "isGrayscale",
+ "jpegArtifacts",
+ "labeledMontage",
"largestComponent",
"letterbox",
+ "lightenColor",
+ "mae",
"maskBoundingRect",
"matchFeatures",
"matchHistograms",
+ "meanColor",
"mergeContours",
+ "mixup",
"morphology",
+ "mosaic",
+ "motionBlur",
+ "mse",
+ "nearestColor",
+ "niblackThreshold",
"overlayMask",
"pixelate",
+ "posterize",
"putTextEx",
+ "randomBlur",
+ "randomBrightnessContrast",
+ "randomColors",
+ "randomCrop",
+ "randomErase",
+ "randomFlip",
+ "randomHSV",
+ "randomPerspective",
+ "randomRotate",
+ "randomScale",
+ "removeBorder",
+ "removeLines",
+ "removeShadow",
"removeSmallObjects",
+ "removeSpeckles",
"resizeEx",
+ "sauvolaThreshold",
+ "scanDocument",
"sharpnessScore",
"skeletonize",
+ "solarize",
"sortContours",
"ssim",
+ "stitchImages",
+ "stitchPair",
+ "textColorFor",
"toBGR",
"toBGRA",
"toGray",
"transformPoints",
"translate",
"unsharpMask",
+ "vignette",
"whiteBalance",
]
diff --git a/cv2u/imgproc/adjust.py b/cv2u/imgproc/adjust.py
index bfb2bb0..0039eff 100644
--- a/cv2u/imgproc/adjust.py
+++ b/cv2u/imgproc/adjust.py
@@ -79,7 +79,7 @@ def adjustHSV(src: np.ndarray, hue: float = 0, saturation: float = 1.0, value: f
return _join_alpha(cv2.cvtColor(adjusted, cv2.COLOR_HSV2BGR), alpha)
-def autoContrast(src: np.ndarray, clip: float = 0.01, perChannel: bool = False) -> np.ndarray:
+def autoContrast(src: np.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
@@ -94,6 +94,7 @@ def autoContrast(src: np.ndarray, clip: float = 0.01, perChannel: bool = False)
Raises:
ValueError: If ``src`` is not 8-bit or is empty, or ``clip`` is outside ``[0, 0.5)``.
"""
+ check_finite("clip", clip)
if not 0.0 <= clip < 0.5:
raise ValueError(f"clip must be in [0, 0.5), got {clip}")
color, alpha = _split_alpha(src)
diff --git a/cv2u/imgproc/augment.py b/cv2u/imgproc/augment.py
new file mode 100644
index 0000000..8e22e28
--- /dev/null
+++ b/cv2u/imgproc/augment.py
@@ -0,0 +1,849 @@
+"""Lightweight data augmentation for training detectors and classifiers, without an extra dependency.
+
+Every random function takes ``seed`` and draws from ``np.random.default_rng(seed)``, so the same seed gives the same
+output. Geometric functions accept detection boxes ``(x, y, width, height)`` and return them transformed along with the
+image, so labels stay aligned.
+"""
+
+import math
+from collections.abc import Sequence
+from typing import Any
+
+import cv2
+import numpy as np
+from numpy.typing import ArrayLike
+
+from .._validate import check_color, check_finite, check_image_not_empty, check_size
+from ..core.boxes import clipBoxes
+from .adjust import adjustBrightnessContrast, adjustHSV
+
+__all__ = [
+ "addNoise",
+ "cutMix",
+ "jpegArtifacts",
+ "mixup",
+ "mosaic",
+ "motionBlur",
+ "posterize",
+ "randomBlur",
+ "randomBrightnessContrast",
+ "randomCrop",
+ "randomErase",
+ "randomFlip",
+ "randomHSV",
+ "randomPerspective",
+ "randomRotate",
+ "randomScale",
+ "solarize",
+ "vignette",
+]
+
+
+# --- helpers -------------------------------------------------------------------------------------------------------
+
+
+def _check_image(src: np.ndarray, name: str = "src") -> None:
+ if src.ndim not in (2, 3) or (src.ndim == 3 and src.shape[2] not in (1, 3, 4)):
+ raise ValueError(f"{name} must be a grayscale, BGR or BGRA image, got shape {src.shape}")
+ check_image_not_empty(name, src)
+
+
+def _value_range(src: np.ndarray) -> tuple[float, float]:
+ """The nominal value range of an image: the dtype range for integers, ``[0, 1]`` for floats."""
+ if np.issubdtype(src.dtype, np.integer):
+ info = np.iinfo(src.dtype)
+ return float(info.min), float(info.max)
+ return 0.0, 1.0
+
+
+def _to_dtype(values: np.ndarray, src: np.ndarray) -> np.ndarray:
+ """Clip float values to the range of ``src`` and convert back to its dtype."""
+ low, high = _value_range(src)
+ clipped = np.clip(values, low, high)
+ if np.issubdtype(src.dtype, np.integer):
+ clipped = np.rint(clipped)
+ return np.asarray(clipped, dtype=src.dtype)
+
+
+def _box_array(boxes: ArrayLike, name: str = "boxes") -> np.ndarray:
+ array = np.asarray(boxes, dtype=np.float64)
+ if array.size == 0:
+ return array.reshape(0, 4)
+ if array.ndim != 2 or array.shape[1] != 4:
+ raise ValueError(f"{name} must have shape (N, 4) as (x, y, width, height), got shape {array.shape}")
+ if not np.all(np.isfinite(array)):
+ raise ValueError(f"{name} must be finite numbers")
+ return array
+
+
+def _box_corners(boxes: np.ndarray) -> np.ndarray:
+ """``(N, 4, 2)`` corner points of xywh boxes."""
+ x, y, w, h = boxes[:, 0], boxes[:, 1], boxes[:, 2], boxes[:, 3]
+ return np.stack(
+ [np.stack([x, y], 1), np.stack([x + w, y], 1), np.stack([x + w, y + h], 1), np.stack([x, y + h], 1)], 1
+ )
+
+
+def _corners_to_boxes(corners: np.ndarray) -> np.ndarray:
+ """Axis-aligned xywh boxes around ``(N, 4, 2)`` corner points."""
+ if len(corners) == 0:
+ return np.zeros((0, 4), dtype=np.float64)
+ low, high = corners.min(axis=1), corners.max(axis=1)
+ return np.concatenate([low, high - low], axis=1)
+
+
+def _fill_value(fill: Any, src: np.ndarray) -> list[float]:
+ values = [float(fill)] if isinstance(fill, (int, float)) else [float(v) for v in fill]
+ check_color("fill", values, src.dtype)
+ channels = 1 if src.ndim == 2 else src.shape[2]
+ if len(values) == 1:
+ values = values * channels
+ if len(values) != channels:
+ raise ValueError(f"fill must have 1 or {channels} components for this image, got {values}")
+ return values
+
+
+# --- deterministic degradations ------------------------------------------------------------------------------------
+
+
+def addNoise(
+ src: np.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).
+
+ Args:
+ src: Grayscale, BGR or BGRA image of any dtype (noise is added to every channel, including alpha).
+ kind: ``"gaussian"`` adds normal noise with standard deviation ``amount`` (as a fraction of the value range,
+ default ``0.1``); ``"salt_pepper"`` sets a fraction ``amount`` (default ``0.05``) of the pixels to black or
+ white; ``"poisson"`` applies shot noise whose strength depends on the brightness (``amount`` scales the
+ photon count, default ``1``, larger is less noisy); ``"speckle"`` multiplies every value by
+ ``1 + N(0, amount)`` (default ``0.1``).
+ amount: Noise strength, see ``kind``.
+ seed: Random seed for reproducible noise.
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``kind`` is unknown, or ``amount`` is negative or not finite (for
+ ``"salt_pepper"`` it must also be at most 1).
+ """
+ _check_image(src)
+ rng = np.random.default_rng(seed)
+ low, high = _value_range(src)
+ span = high - low
+ values = src.astype(np.float64)
+ if kind == "gaussian":
+ sigma = 0.1 if amount is None else amount
+ check_finite("amount", sigma, nonnegative=True)
+ noisy = values + rng.normal(0.0, sigma * span, src.shape)
+ elif kind == "salt_pepper":
+ fraction = 0.05 if amount is None else amount
+ check_finite("amount", fraction, nonnegative=True)
+ if fraction > 1:
+ raise ValueError(f"amount must be at most 1 for salt_pepper noise, got {fraction}")
+ noisy = values.copy()
+ draw = rng.random(src.shape[:2])
+ noisy[draw < fraction / 2] = low
+ noisy[(draw >= fraction / 2) & (draw < fraction)] = high
+ elif kind == "poisson":
+ scale = 1.0 if amount is None else amount
+ check_finite("amount", scale, positive=True)
+ # Photon counts in the 0..255 scale, so that 8-bit and float images get the same look.
+ photons = (values - low) / span * 255.0 * scale
+ noisy = rng.poisson(np.maximum(photons, 0)) / (255.0 * scale) * span + low
+ elif kind == "speckle":
+ sigma = 0.1 if amount is None else amount
+ check_finite("amount", sigma, nonnegative=True)
+ noisy = values * (1.0 + rng.normal(0.0, sigma, src.shape))
+ else:
+ raise ValueError(f"kind must be 'gaussian', 'salt_pepper', 'poisson' or 'speckle', got {kind!r}")
+ return _to_dtype(noisy, src)
+
+
+def motionBlur(src: np.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.
+
+ Args:
+ src: Image of any dtype and channel count.
+ size: Length of the motion in pixels (the kernel is ``size x size``).
+ angle: Direction of the motion in degrees, counter-clockwise from the x axis; ``0`` is horizontal.
+
+ Returns:
+ The blurred image, with the dtype of ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``size`` is smaller than 1, or ``angle`` is not finite.
+ """
+ _check_image(src)
+ if size < 1:
+ raise ValueError(f"size must be at least 1, got {size}")
+ check_finite("angle", angle)
+ if size == 1:
+ return src.copy()
+ kernel = np.zeros((size, size), dtype=np.float32)
+ center = (size - 1) / 2
+ dx, dy = math.cos(math.radians(angle)), -math.sin(math.radians(angle))
+ half = (size - 1) / 2
+ p0 = (round(center - dx * half), round(center - dy * half))
+ p1 = (round(center + dx * half), round(center + dy * half))
+ cv2.line(kernel, p0, p1, 1.0, 1)
+ kernel /= kernel.sum()
+ blurred: np.ndarray = cv2.filter2D(src, -1, kernel, borderType=cv2.BORDER_REFLECT_101)
+ return blurred
+
+
+def vignette(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image (the alpha channel is not changed).
+ strength: Darkening at the corners: ``0`` leaves the image unchanged, ``1`` makes the corners black.
+ radius: Size of the bright area relative to the half diagonal; smaller values darken a larger area.
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``strength`` is outside ``[0, 1]``, or ``radius`` is not positive.
+ """
+ _check_image(src)
+ check_finite("strength", strength)
+ if not 0.0 <= strength <= 1.0:
+ raise ValueError(f"strength must be in [0, 1], got {strength}")
+ check_finite("radius", radius, positive=True)
+ h, w = src.shape[:2]
+ ys, xs = np.mgrid[0:h, 0:w]
+ half_diagonal = math.hypot((w - 1) / 2, (h - 1) / 2) or 1.0
+ distance = np.hypot(xs - (w - 1) / 2, ys - (h - 1) / 2) / half_diagonal
+ gain = 1.0 - strength * (1.0 - np.exp(-(distance**2) / (2 * radius**2)))
+ values = src.astype(np.float64)
+ if src.ndim == 3:
+ gain = gain[..., None]
+ if src.shape[2] == 4:
+ gain = np.concatenate([np.repeat(gain, 3, axis=2), np.ones_like(gain)], axis=2)
+ return _to_dtype(values * gain, src)
+
+
+def jpegArtifacts(src: np.ndarray, quality: int = 30) -> np.ndarray:
+ """Add JPEG compression artifacts (blocking, ringing) by an encode/decode round trip in memory.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image (the alpha channel is kept as is).
+ quality: JPEG quality from 1 (worst) to 100.
+
+ Returns:
+ The re-encoded image with the shape of ``src``.
+
+ Raises:
+ ValueError: If ``src`` is not 8-bit or is empty, or ``quality`` is outside ``[1, 100]``.
+ """
+ _check_image(src)
+ if src.dtype != np.uint8:
+ raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ if not 1 <= quality <= 100:
+ raise ValueError(f"quality must be in [1, 100], got {quality}")
+ color = src[..., :3] if src.ndim == 3 and src.shape[2] == 4 else src
+ ok, encoded = cv2.imencode(".jpg", np.ascontiguousarray(color), [cv2.IMWRITE_JPEG_QUALITY, int(quality)])
+ if not ok: # pragma: no cover - imencode only fails on unsupported inputs, which are rejected above
+ raise ValueError("src could not be encoded as JPEG")
+ decoded = np.asarray(cv2.imdecode(encoded, cv2.IMREAD_UNCHANGED)).reshape(color.shape)
+ if src.ndim == 3 and src.shape[2] == 4:
+ return np.dstack([decoded, src[..., 3]])
+ return decoded
+
+
+def randomErase(
+ src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image of any dtype.
+ size: Patch size as ``(width, height)`` or one side; by default a quarter of the image in each direction.
+ count: Number of patches.
+ fill: Fill value or color, or ``"random"`` for uniform noise in the value range of the image.
+ seed: Random seed for the patch positions (and the noise).
+
+ Returns:
+ A new image with the patches erased.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``size`` is not positive or larger than the image, ``count`` is negative, or
+ ``fill`` is not a valid color for the dtype.
+ """
+ _check_image(src)
+ h, w = src.shape[:2]
+ if size is None:
+ patch = (max(1, w // 4), max(1, h // 4))
+ elif isinstance(size, int):
+ patch = (size, size)
+ else:
+ patch = (int(size[0]), int(size[1]))
+ pw, ph = check_size("size", patch)
+ if pw > w or ph > h:
+ raise ValueError(f"size must not exceed the image size ({w}x{h}), got {patch}")
+ if count < 0:
+ raise ValueError(f"count must not be negative, got {count}")
+ random_fill = isinstance(fill, str)
+ if random_fill and fill != "random":
+ raise ValueError(f"fill must be a value, a color or 'random', got {fill!r}")
+ value = None if random_fill else _fill_value(fill, src)
+ rng = np.random.default_rng(seed)
+ low, high = _value_range(src)
+ dst = src.copy()
+ for _ in range(count):
+ x = int(rng.integers(0, w - pw + 1))
+ y = int(rng.integers(0, h - ph + 1))
+ region = dst[y : y + ph, x : x + pw]
+ if value is None:
+ region[...] = _to_dtype(np.asarray(rng.uniform(low, high, region.shape)), src)
+ else:
+ region[...] = value[0] if src.ndim == 2 else np.asarray(value, dtype=src.dtype)
+ return dst
+
+
+def solarize(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image of any dtype.
+ threshold: Values at or above it are inverted within the value range (``[0, 255]`` for 8-bit, ``[0, 1]``
+ for float images).
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty or ``threshold`` is not finite.
+ """
+ _check_image(src)
+ check_finite("threshold", threshold)
+ low, high = _value_range(src)
+ values = src.astype(np.float64)
+ return _to_dtype(np.where(values >= threshold, high + low - values, values), src)
+
+
+def posterize(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image of any dtype. Integer images keep their ``bits`` most significant bits;
+ float images in ``[0, 1]`` are quantized to ``2 ** bits`` levels.
+ bits: Bits to keep per channel, from 1 to the bit depth of the dtype (8 for 8-bit images).
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty or ``bits`` is outside the valid range.
+ """
+ _check_image(src)
+ if np.issubdtype(src.dtype, np.integer):
+ depth = np.iinfo(src.dtype).bits
+ if not 1 <= bits <= depth:
+ raise ValueError(f"bits must be in [1, {depth}] for {src.dtype} images, got {bits}")
+ mask = ~np.array((1 << (depth - bits)) - 1, dtype=src.dtype)
+ return np.asarray(src & mask, dtype=src.dtype)
+ if not 1 <= bits <= 16:
+ raise ValueError(f"bits must be in [1, 16] for float images, got {bits}")
+ levels = float(2**bits)
+ return _to_dtype(np.floor(src.astype(np.float64) * levels) / levels, src)
+
+
+# --- random geometric transforms -----------------------------------------------------------------------------------
+
+
+def randomCrop(
+ src: np.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.
+
+ Args:
+ src: Image of any dtype and channel count.
+ size: Crop size as ``(width, height)``, at most the image size.
+ boxes: Optional boxes ``(N, 4)`` as ``(x, y, width, height)``; they are shifted and clipped to the crop
+ (boxes outside become zero-sized, so the rows stay aligned with your labels).
+ seed: Random seed.
+
+ Returns:
+ The crop, or ``(crop, boxes)`` when ``boxes`` is given.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``size`` is not positive or exceeds the image, or ``boxes`` is malformed.
+ """
+ _check_image(src)
+ cw, ch = check_size("size", size)
+ h, w = src.shape[:2]
+ if cw > w or ch > h:
+ raise ValueError(f"size must not exceed the image size ({w}x{h}), got {size}")
+ rng = np.random.default_rng(seed)
+ x = int(rng.integers(0, w - cw + 1))
+ y = int(rng.integers(0, h - ch + 1))
+ crop = src[y : y + ch, x : x + cw].copy()
+ if boxes is None:
+ return crop
+ moved = _box_array(boxes)
+ if len(moved):
+ moved = moved - np.array([x, y, 0, 0], dtype=np.float64)
+ return crop, clipBoxes(moved, (cw, ch)).reshape(-1, 4)
+
+
+def randomFlip(
+ src: np.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.
+
+ Args:
+ src: Image of any dtype and channel count.
+ horizontal: Probability of a horizontal (left-right) flip.
+ vertical: Probability of a vertical (top-bottom) flip.
+ boxes: Optional boxes ``(N, 4)`` as ``(x, y, width, height)`` to flip along.
+ seed: Random seed.
+
+ Returns:
+ The (possibly) flipped image, or ``(image, boxes)`` when ``boxes`` is given.
+
+ Raises:
+ ValueError: If ``src`` is empty, a probability is outside ``[0, 1]``, or ``boxes`` is malformed.
+ """
+ _check_image(src)
+ for name, p in (("horizontal", horizontal), ("vertical", vertical)):
+ check_finite(name, p)
+ if not 0.0 <= p <= 1.0:
+ raise ValueError(f"{name} must be a probability in [0, 1], got {p}")
+ rng = np.random.default_rng(seed)
+ flip_h = bool(rng.random() < horizontal)
+ flip_v = bool(rng.random() < vertical)
+ h, w = src.shape[:2]
+ dst = src.copy()
+ moved = None if boxes is None else _box_array(boxes)
+ if flip_h:
+ dst = cv2.flip(dst, 1)
+ if moved is not None and len(moved):
+ moved[:, 0] = w - moved[:, 0] - moved[:, 2]
+ if flip_v:
+ dst = cv2.flip(dst, 0)
+ if moved is not None and len(moved):
+ moved[:, 1] = h - moved[:, 1] - moved[:, 3]
+ if moved is None:
+ return dst
+ return dst, moved
+
+
+def _warp_boxes(boxes: np.ndarray, matrix: np.ndarray, size: tuple[int, int]) -> np.ndarray:
+ """Transform box corners by a 2x3 or 3x3 matrix and return the clipped axis-aligned boxes."""
+ if len(boxes) == 0:
+ return np.zeros((0, 4), dtype=np.float64)
+ corners = _box_corners(boxes).reshape(-1, 1, 2)
+ if matrix.shape[0] == 2:
+ warped: np.ndarray = cv2.transform(corners, matrix)
+ else:
+ warped = cv2.perspectiveTransform(corners, matrix)
+ return clipBoxes(_corners_to_boxes(warped.reshape(-1, 4, 2)), size).reshape(-1, 4)
+
+
+def randomRotate(
+ src: np.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).
+
+ Args:
+ src: Image of any dtype and channel count.
+ maxAngle: Largest rotation in degrees (either direction).
+ boxes: Optional boxes ``(N, 4)`` as ``(x, y, width, height)``.
+ seed: Random seed.
+ crop: Keep the size of ``src`` and cut off the corners, instead of enlarging the canvas.
+ borderValue: Fill value or color for the uncovered areas.
+
+ Returns:
+ The rotated image, or ``(image, boxes)`` when ``boxes`` is given.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``maxAngle`` is negative or not finite, ``borderValue`` is not a valid color,
+ or ``boxes`` is malformed.
+ """
+ _check_image(src)
+ check_finite("maxAngle", maxAngle, nonnegative=True)
+ fill = _fill_value(borderValue, src)
+ rng = np.random.default_rng(seed)
+ angle = float(rng.uniform(-maxAngle, maxAngle))
+ h, w = src.shape[:2]
+ center = (w / 2, h / 2)
+ matrix: np.ndarray = cv2.getRotationMatrix2D(center, angle, 1.0)
+ if crop:
+ out_w, out_h = w, h
+ else:
+ radians = math.radians(angle)
+ sin, cos = abs(math.sin(radians)), abs(math.cos(radians))
+ out_w, out_h = round(h * sin + w * cos), round(h * cos + w * sin)
+ matrix[0, 2] += out_w / 2 - center[0]
+ matrix[1, 2] += out_h / 2 - center[1]
+ dst: np.ndarray = cv2.warpAffine(src, matrix, (out_w, out_h), borderValue=(fill + [0.0] * 4)[:4])
+ dst = dst.reshape((out_h, out_w, *src.shape[2:]))
+ if boxes is None:
+ return dst
+ return dst, _warp_boxes(_box_array(boxes), matrix, (out_w, out_h))
+
+
+def randomScale(
+ src: np.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).
+
+ Args:
+ src: Image of any dtype and channel count.
+ scaleRange: ``(low, high)`` factors, both positive.
+ boxes: Optional boxes ``(N, 4)`` as ``(x, y, width, height)``; they are scaled by the same factor.
+ seed: Random seed.
+ interpolation: ``cv.INTER_*`` flag; ``INTER_AREA`` to shrink and ``INTER_LINEAR`` to enlarge by default.
+
+ Returns:
+ The resized image, or ``(image, boxes)`` when ``boxes`` is given.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``scaleRange`` is not positive or ``low > high``, or ``boxes`` is malformed.
+ """
+ _check_image(src)
+ low, high = float(scaleRange[0]), float(scaleRange[1])
+ check_finite("scaleRange", low, positive=True)
+ check_finite("scaleRange", high, positive=True)
+ if low > high:
+ raise ValueError(f"scaleRange must be (low, high) with low <= high, got {scaleRange}")
+ rng = np.random.default_rng(seed)
+ scale = float(rng.uniform(low, high))
+ h, w = src.shape[:2]
+ out_w, out_h = max(1, round(w * scale)), max(1, round(h * scale))
+ flag = (cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR) if interpolation is None else interpolation
+ dst: np.ndarray = cv2.resize(src, (out_w, out_h), interpolation=flag)
+ dst = dst.reshape((out_h, out_w, *src.shape[2:]))
+ if boxes is None:
+ return dst
+ # Use the realized factor so boxes match the rounded output size exactly.
+ factors = np.array([out_w / w, out_h / h, out_w / w, out_h / h], dtype=np.float64)
+ return dst, _box_array(boxes) * factors
+
+
+def randomPerspective(
+ src: np.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.
+
+ Args:
+ src: Image of any dtype and channel count.
+ distortion: Largest corner displacement as a fraction of the width and height, e.g. ``0.1`` for 10%.
+ boxes: Optional boxes ``(N, 4)`` as ``(x, y, width, height)``; each is replaced by the axis-aligned box
+ around its warped corners, clipped to the image.
+ seed: Random seed.
+ borderValue: Fill value or color for the uncovered areas.
+
+ Returns:
+ The warped image (same size as ``src``), or ``(image, boxes)`` when ``boxes`` is given.
+
+ Raises:
+ ValueError: If ``src`` is empty, ``distortion`` is outside ``[0, 0.5)``, ``borderValue`` is not a valid color,
+ or ``boxes`` is malformed.
+ """
+ _check_image(src)
+ check_finite("distortion", distortion)
+ if not 0.0 <= distortion < 0.5:
+ raise ValueError(f"distortion must be in [0, 0.5), got {distortion}")
+ fill = _fill_value(borderValue, src)
+ rng = np.random.default_rng(seed)
+ h, w = src.shape[:2]
+ corners = np.array([[0, 0], [w, 0], [w, h], [0, h]], dtype=np.float32)
+ jitter = rng.uniform(-distortion, distortion, (4, 2)) * np.array([w, h], dtype=np.float64)
+ target = (corners + jitter).astype(np.float32)
+ matrix: np.ndarray = cv2.getPerspectiveTransform(corners, target)
+ dst: np.ndarray = cv2.warpPerspective(src, matrix, (w, h), borderValue=(fill + [0.0] * 4)[:4])
+ dst = dst.reshape(src.shape)
+ if boxes is None:
+ return dst
+ return dst, _warp_boxes(_box_array(boxes), matrix, (w, h))
+
+
+# --- random photometric transforms ---------------------------------------------------------------------------------
+
+
+def randomBrightnessContrast(
+ src: np.ndarray, brightness: float = 0.2, contrast: float = 0.2, seed: int | None = None
+) -> np.ndarray:
+ """Apply :func:`adjustBrightnessContrast` with random amounts.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image (the alpha channel is kept).
+ brightness: Largest brightness shift as a fraction of 255 (drawn from ``[-brightness, brightness]``).
+ contrast: Largest contrast change; the factor is drawn from ``[1 - contrast, 1 + contrast]``.
+ seed: Random seed.
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is not 8-bit or is empty, or a limit is negative, above 1, or not finite.
+ """
+ for name, limit in (("brightness", brightness), ("contrast", contrast)):
+ check_finite(name, limit, nonnegative=True)
+ if limit > 1:
+ raise ValueError(f"{name} must be at most 1, got {limit}")
+ rng = np.random.default_rng(seed)
+ shift = float(rng.uniform(-brightness, brightness)) * 255.0
+ factor = float(rng.uniform(1.0 - contrast, 1.0 + contrast))
+ return adjustBrightnessContrast(src, shift, factor)
+
+
+def randomHSV(
+ src: np.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).
+
+ Args:
+ src: 8-bit BGR or BGRA image (the alpha channel is kept).
+ hue: Largest hue shift in degrees (drawn from ``[-hue, hue]``).
+ saturation: Largest saturation change; the factor is drawn from ``[1 - saturation, 1 + saturation]``.
+ value: Largest brightness change; the factor is drawn from ``[1 - value, 1 + value]``.
+ seed: Random seed.
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is not an 8-bit color image or is empty, or a limit is negative, not finite, or (for
+ ``saturation`` and ``value``) above 1.
+ """
+ check_finite("hue", hue, nonnegative=True)
+ for name, limit in (("saturation", saturation), ("value", value)):
+ check_finite(name, limit, nonnegative=True)
+ if limit > 1:
+ raise ValueError(f"{name} must be at most 1, got {limit}")
+ rng = np.random.default_rng(seed)
+ shift = float(rng.uniform(-hue, hue))
+ s = float(rng.uniform(1.0 - saturation, 1.0 + saturation))
+ v = float(rng.uniform(1.0 - value, 1.0 + value))
+ return adjustHSV(src, shift, s, v)
+
+
+def randomBlur(src: np.ndarray, maxKernel: int = 7, seed: int | None = None) -> np.ndarray:
+ """Gaussian-blur with a random odd kernel size from 1 (no blur) to ``maxKernel``.
+
+ Args:
+ src: Image of any dtype and channel count.
+ maxKernel: Largest kernel size; rounded down to an odd number.
+ seed: Random seed.
+
+ Returns:
+ A new image with the same shape and dtype as ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty or ``maxKernel`` is smaller than 1.
+ """
+ _check_image(src)
+ if maxKernel < 1:
+ raise ValueError(f"maxKernel must be at least 1, got {maxKernel}")
+ rng = np.random.default_rng(seed)
+ largest = maxKernel if maxKernel % 2 else maxKernel - 1
+ kernel = int(rng.integers(0, (largest - 1) // 2 + 1)) * 2 + 1
+ if kernel == 1:
+ return src.copy()
+ blurred: np.ndarray = cv2.GaussianBlur(src, (kernel, kernel), 0)
+ return blurred.reshape(src.shape)
+
+
+# --- multi-image mixing --------------------------------------------------------------------------------------------
+
+
+def _same_layout(a: np.ndarray, b: np.ndarray, nameA: str, nameB: str) -> None:
+ _check_image(a, nameA)
+ _check_image(b, nameB)
+ if a.dtype != b.dtype or a.ndim != b.ndim or a.shape[2:] != b.shape[2:]:
+ raise ValueError(
+ f"{nameA} and {nameB} must have the same dtype and channels, "
+ f"got {a.dtype} {a.shape} and {b.dtype} {b.shape}"
+ )
+
+
+def _resize_like(src: np.ndarray, like: np.ndarray) -> np.ndarray:
+ if src.shape[:2] == like.shape[:2]:
+ return src
+ h, w = like.shape[:2]
+ resized: np.ndarray = cv2.resize(
+ src, (w, h), interpolation=cv2.INTER_LINEAR if src.shape[0] < h else cv2.INTER_AREA
+ )
+ return resized.reshape(like.shape)
+
+
+def mosaic(
+ images: Sequence[np.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.
+
+ Args:
+ images: Exactly four images with the same dtype and channel count (sizes may differ).
+ size: Output size as ``(width, height)``.
+ boxes: Optional list of four box arrays ``(N_i, 4)`` as ``(x, y, width, height)``, one per image.
+ seed: Random seed for the center point.
+
+ Returns:
+ The mosaic, or ``(mosaic, boxes)`` when ``boxes`` is given: the transformed boxes of all four images
+ concatenated in order, so labels concatenate the same way (boxes outside their quadrant are zero-sized).
+
+ Raises:
+ ValueError: If there are not four images, they differ in dtype or channels, ``size`` is not positive, or
+ ``boxes`` does not have four entries.
+ """
+ if len(images) != 4:
+ raise ValueError(f"images must contain exactly 4 images, got {len(images)}")
+ if boxes is not None and len(boxes) != 4:
+ raise ValueError(f"boxes must contain one array per image (4), got {len(boxes)}")
+ first = images[0]
+ for i, image in enumerate(images):
+ _same_layout(first, image, "images[0]", f"images[{i}]")
+ out_w, out_h = check_size("size", size)
+ rng = np.random.default_rng(seed)
+ cx = int(rng.integers(out_w // 4, out_w - out_w // 4 + 1))
+ cy = int(rng.integers(out_h // 4, out_h - out_h // 4 + 1))
+ # (x0, y0, x1, y1) of each quadrant and which corner of the scaled image anchors at the center.
+ quadrants = [(0, 0, cx, cy), (cx, 0, out_w, cy), (0, cy, cx, out_h), (cx, cy, out_w, out_h)]
+ anchors = [(1, 1), (0, 1), (1, 0), (0, 0)] # 1: take the far end (bottom/right) of the scaled image
+ dst = np.zeros((out_h, out_w, *first.shape[2:]), dtype=first.dtype)
+ all_boxes: list[np.ndarray] = []
+ for image, (x0, y0, x1, y1), (ax, ay), index in zip(images, quadrants, anchors, range(4), strict=True):
+ qw, qh = x1 - x0, y1 - y0
+ if qw <= 0 or qh <= 0:
+ if boxes is not None:
+ all_boxes.append(np.zeros((len(_box_array(boxes[index])), 4), dtype=np.float64))
+ continue
+ h, w = image.shape[:2]
+ scale = max(qw / w, qh / h)
+ sw, sh = max(qw, round(w * scale)), max(qh, round(h * scale))
+ scaled: np.ndarray = cv2.resize(
+ image, (sw, sh), interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR
+ )
+ scaled = scaled.reshape((sh, sw, *first.shape[2:]))
+ ox, oy = (sw - qw) if ax else 0, (sh - qh) if ay else 0
+ dst[y0:y1, x0:x1] = scaled[oy : oy + qh, ox : ox + qw]
+ if boxes is not None:
+ moved = _box_array(boxes[index], f"boxes[{index}]")
+ if len(moved):
+ moved = moved * np.array([sw / w, sh / h, sw / w, sh / h]) - np.array([ox - x0, oy - y0, 0, 0])
+ moved = clipBoxes(moved, (out_w, out_h)).reshape(-1, 4)
+ # Clip to the quadrant, not only to the image.
+ qx2 = np.clip(moved[:, 0] + moved[:, 2], x0, x1)
+ qy2 = np.clip(moved[:, 1] + moved[:, 3], y0, y1)
+ qx1 = np.clip(moved[:, 0], x0, x1)
+ qy1 = np.clip(moved[:, 1], y0, y1)
+ moved = np.stack([qx1, qy1, np.maximum(qx2 - qx1, 0), np.maximum(qy2 - qy1, 0)], axis=1)
+ all_boxes.append(moved)
+ if boxes is None:
+ return dst
+ return dst, np.concatenate(all_boxes, axis=0)
+
+
+def mixup(
+ a: np.ndarray, b: np.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.
+
+ Args:
+ a: First image (grayscale, BGR or BGRA, any dtype).
+ b: Second image with the same dtype and channels; any size.
+ alpha: Beta distribution parameter; smaller values favor one image, ``1`` is uniform.
+ lam: Fixed mixing weight in ``[0, 1]`` instead of a random one.
+ seed: Random seed.
+
+ Returns:
+ ``(image, lam)`` with the image in the dtype of ``a``.
+
+ Raises:
+ ValueError: If an image is empty, the images differ in dtype or channels, ``alpha`` is not positive, or
+ ``lam`` is outside ``[0, 1]``.
+ """
+ _same_layout(a, b, "a", "b")
+ check_finite("alpha", alpha, positive=True)
+ if lam is None:
+ lam = float(np.random.default_rng(seed).beta(alpha, alpha))
+ check_finite("lam", lam)
+ if not 0.0 <= lam <= 1.0:
+ raise ValueError(f"lam must be in [0, 1], got {lam}")
+ other = _resize_like(b, a).astype(np.float64)
+ return _to_dtype(a.astype(np.float64) * lam + other * (1.0 - lam), a), lam
+
+
+def cutMix(a: np.ndarray, b: np.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.
+
+ Args:
+ a: Image that receives the patch (grayscale, BGR or BGRA, any dtype).
+ b: Image the patch is taken from, with the same dtype and channels; any size.
+ alpha: Beta distribution parameter; ``1`` draws the area fraction uniformly.
+ seed: Random seed.
+
+ Returns:
+ ``(image, lam)`` with the image in the dtype of ``a``.
+
+ Raises:
+ ValueError: If an image is empty, the images differ in dtype or channels, or ``alpha`` is not positive.
+ """
+ _same_layout(a, b, "a", "b")
+ check_finite("alpha", alpha, positive=True)
+ rng = np.random.default_rng(seed)
+ lam = float(rng.beta(alpha, alpha))
+ h, w = a.shape[:2]
+ ratio = math.sqrt(1.0 - lam)
+ pw, ph = round(w * ratio), round(h * ratio)
+ cx, cy = int(rng.integers(0, w)), int(rng.integers(0, h))
+ x0, x1 = max(0, cx - pw // 2), min(w, cx + (pw - pw // 2))
+ y0, y1 = max(0, cy - ph // 2), min(h, cy + (ph - ph // 2))
+ dst = a.copy()
+ dst[y0:y1, x0:x1] = _resize_like(b, a)[y0:y1, x0:x1]
+ return dst, 1.0 - (x1 - x0) * (y1 - y0) / (w * h)
diff --git a/cv2u/imgproc/binary.py b/cv2u/imgproc/binary.py
index 657ad71..0a099d8 100644
--- a/cv2u/imgproc/binary.py
+++ b/cv2u/imgproc/binary.py
@@ -28,6 +28,7 @@
def binarize(
src: np.ndarray,
method: Method | float = "otsu",
+ *,
invert: bool = False,
blockSize: int = 31,
C: float = 10,
@@ -53,7 +54,8 @@ def binarize(
``uint8`` mask with values 0 and 255, of shape ``src.shape[:2]``.
Raises:
- ValueError: If ``src`` is empty, ``method`` is unknown, or ``blockSize``/``blur`` is not odd.
+ ValueError: If ``src`` is empty or has an unsupported channel count, ``method`` is unknown or a non-finite
+ number, a named method is used on a non-8-bit image, or ``blockSize``/``blur`` is not odd.
"""
check_image_not_empty("src", src)
if blur < 0 or (blur and blur % 2 == 0):
@@ -103,7 +105,8 @@ def morphology(
iterations: How many times to apply it.
Raises:
- ValueError: If ``op`` or ``shape`` is unknown, ``ksize`` is not positive, or ``src`` is empty.
+ ValueError: If ``src`` is empty, ``op`` or ``shape`` is unknown, ``ksize`` is not positive, or
+ ``iterations`` is below 1.
"""
check_image_not_empty("src", src)
if op not in _OPERATIONS:
diff --git a/cv2u/imgproc/color.py b/cv2u/imgproc/color.py
index 21ed2b5..d0180ea 100644
--- a/cv2u/imgproc/color.py
+++ b/cv2u/imgproc/color.py
@@ -6,7 +6,7 @@
import cv2
import numpy as np
-from .._validate import check_color, check_image_not_empty
+from .._validate import check_channels, check_color, check_image_not_empty
__all__ = [
"bgrToHex",
@@ -20,9 +20,7 @@
def _channels(src: np.ndarray) -> int:
- channels = 1 if src.ndim == 2 else int(src.shape[2]) if src.ndim == 3 else 0
- if channels not in (1, 3, 4):
- raise ValueError(f"src must have 1, 3 or 4 channels, got shape {src.shape}")
+ channels = check_channels("src", src)
check_image_not_empty("src", src)
return channels
@@ -38,7 +36,7 @@ def toGray(src: np.ndarray) -> np.ndarray:
any image needs a channel check first. Grayscale input is returned as a copy.
Raises:
- ValueError: If ``src`` does not have 1, 3 or 4 channels.
+ ValueError: If ``src`` does not have 1, 3 or 4 channels, or is empty.
"""
channels = _channels(src)
if channels == 1:
@@ -51,7 +49,7 @@ def toBGR(src: np.ndarray) -> np.ndarray:
"""Convert a grayscale, BGR or BGRA image to 3-channel BGR (the alpha channel is dropped).
Raises:
- ValueError: If ``src`` does not have 1, 3 or 4 channels.
+ ValueError: If ``src`` does not have 1, 3 or 4 channels, or is empty.
"""
channels = _channels(src)
if channels == 3:
@@ -72,7 +70,8 @@ def toBGRA(src: np.ndarray, alpha: float | None = None) -> np.ndarray:
65535 for 16-bit, 1.0 for float). For BGRA input, the existing alpha is kept unless this is given.
Raises:
- ValueError: If ``src`` does not have 1, 3 or 4 channels, or ``alpha`` is not a finite number.
+ ValueError: If ``src`` does not have 1, 3 or 4 channels or is empty, or ``alpha`` is not a finite number in
+ the range of the image dtype.
"""
if alpha is not None:
check_color("alpha", [alpha], src.dtype)
@@ -119,7 +118,7 @@ def bgrToHex(color: Sequence[float]) -> str:
return f"#{r:02x}{g:02x}{b:02x}" + (f"{values[3]:02x}" if len(values) == 4 else "")
-def flattenAlpha(src: np.ndarray, background: float | Sequence[float] | np.ndarray = (255, 255, 255)) -> np.ndarray:
+def flattenAlpha(src: np.ndarray, fill: float | Sequence[float] | np.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
@@ -127,24 +126,27 @@ def flattenAlpha(src: np.ndarray, background: float | Sequence[float] | np.ndarr
Args:
src: Image to flatten. Images without an alpha channel are converted with ``toBGR``.
- background: Background color (white by default), or a background image of the same height and width.
+ fill: Background color (white by default; a scalar or BGR), or a background image of the same height and
+ width.
Returns:
A BGR image with the dtype of ``src``.
Raises:
- ValueError: If ``src`` does not have 1, 3 or 4 channels, or a background image has a different size.
+ ValueError: If ``src`` does not have 1, 3 or 4 channels or is empty, ``fill`` is not finite, or a
+ background image has a different size.
"""
if _channels(src) != 4:
return toBGR(src)
peak = float(np.iinfo(src.dtype).max) if np.issubdtype(src.dtype, np.integer) else 1.0
alpha = src[..., 3:4].astype(np.float32) / peak
- if isinstance(background, np.ndarray) and background.ndim >= 2:
- if background.shape[:2] != src.shape[:2]:
- raise ValueError(f"background image must be {src.shape[1]}x{src.shape[0]}, got shape {background.shape}")
- bg = toBGR(background).astype(np.float32)
+ if isinstance(fill, np.ndarray) and fill.ndim >= 2:
+ if fill.shape[:2] != src.shape[:2]:
+ raise ValueError(f"fill image must be {src.shape[1]}x{src.shape[0]}, got shape {fill.shape}")
+ bg = toBGR(fill).astype(np.float32)
else:
- values = np.atleast_1d(np.asarray(background, dtype=np.float32)).ravel()
+ values = np.atleast_1d(np.asarray(fill, dtype=np.float32)).ravel()
+ check_color("fill", values.tolist())
bg = np.resize(values, 3) if values.size < 3 else values[:3]
out = src[..., :3].astype(np.float32) * alpha + bg * (1 - alpha)
if np.issubdtype(src.dtype, np.integer):
diff --git a/cv2u/imgproc/contour.py b/cv2u/imgproc/contour.py
index 4b93b10..bb936d6 100644
--- a/cv2u/imgproc/contour.py
+++ b/cv2u/imgproc/contour.py
@@ -13,7 +13,7 @@
import numpy as np
from numpy.typing import ArrayLike
-from .._validate import check_finite, check_image_not_empty
+from .._validate import check_channels, check_finite, check_image_not_empty
__all__ = [
"ContourStats",
@@ -202,10 +202,14 @@ def filterContours(
"minPerimeter": minPerimeter,
}
for name, value in limits.items():
- if math.isnan(value) or value < 0:
+ if math.isnan(value):
+ raise ValueError(f"{name} must be a number, got {value}")
+ if value < 0:
raise ValueError(f"{name} must not be negative, got {value}")
- if minArea > maxArea or minAspectRatio > maxAspectRatio:
- raise ValueError("a minimum must not exceed its maximum")
+ if minArea > maxArea:
+ raise ValueError(f"minArea must not exceed maxArea, got {minArea} > {maxArea}")
+ if minAspectRatio > maxAspectRatio:
+ raise ValueError(f"minAspectRatio must not exceed maxAspectRatio, got {minAspectRatio} > {maxAspectRatio}")
kept = []
for contour in contours:
s = contourStats(contour)
@@ -236,7 +240,7 @@ def approxContour(contour: np.ndarray, epsilon: float = 0.02, closed: bool = Tru
The simplified contour, shape ``(M, 1, 2)``.
Raises:
- ValueError: If ``epsilon`` is negative or not finite.
+ ValueError: If ``epsilon`` is negative or not finite, or the contour has no points or is not finite.
"""
check_finite("epsilon", epsilon, nonnegative=True)
contour = asContour(contour)
@@ -256,7 +260,7 @@ def mergeContours(contours: Sequence[np.ndarray]) -> np.ndarray:
A contour of shape ``(M, 1, 2)``.
Raises:
- ValueError: If there are no contours.
+ ValueError: If there are no contours, or a contour has no points or is not finite.
"""
if len(contours) == 0:
raise ValueError("contours must not be empty")
@@ -305,7 +309,8 @@ def cropContour(
src: np.ndarray,
contour: np.ndarray,
margin: int = 0,
- background: float | Sequence[float] | None = 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.
@@ -314,18 +319,19 @@ def cropContour(
src: Image to crop (any dtype, 1, 3 or 4 channels).
contour: Contour of shape ``(N, 1, 2)`` or ``(N, 2)``.
margin: Extra pixels around the bounding box (clipped at the image border).
- background: Value for the pixels outside the contour: a scalar or one value per channel. ``None`` keeps
- the original pixels (a plain bounding-box crop).
- transparent: Return BGRA with the outside transparent instead of filled with ``background``
+ fill: Value for the pixels outside the contour: a scalar or one value per channel (as ``fill`` in
+ :func:`cropRect` and :func:`applyMask`). ``None`` keeps the original pixels (a plain bounding-box crop).
+ transparent: Return BGRA with the outside transparent instead of filled with ``fill``
(8-bit images only).
Returns:
The cropped image. Its size is the bounding box plus margins, clipped to the image.
Raises:
- ValueError: If ``margin`` is negative, ``src`` is empty, or ``transparent`` is used on a non-8-bit image.
+ ValueError: If ``src`` is empty, ``margin`` is negative, the contour has no points, is not finite or lies
+ outside the image, ``fill`` is not finite, or ``transparent`` is used on a non-8-bit image.
"""
- from ..core.roi import cropEx
+ from ..core.roi import cropRect
from .color import toBGRA
check_image_not_empty("src", src)
@@ -333,92 +339,91 @@ def cropContour(
raise ValueError(f"margin must not be negative, got {margin}")
if transparent and src.dtype != np.uint8:
raise ValueError(f"transparent output needs an 8-bit image, got dtype {src.dtype}")
+ if fill is not None:
+ for component in np.ravel(np.asarray(fill, dtype=np.float64)).tolist():
+ check_finite("fill", component)
contour = asContour(contour)
x, y, w, h = cv2.boundingRect(contour)
x0, y0 = max(x - margin, 0), max(y - margin, 0)
x1, y1 = min(x + w + margin, src.shape[1]), min(y + h + margin, src.shape[0])
if x1 <= x0 or y1 <= y0:
raise ValueError("the contour lies outside the image")
- crop = cropEx(src, (x0, y0, x1 - x0, y1 - y0))
- if background is None and not transparent:
+ crop = cropRect(src, (x0, y0, x1 - x0, y1 - y0))
+ if fill is None and not transparent:
return crop
mask = contoursToMask(contour - (x0, y0), (x1 - x0, y1 - y0))
if transparent:
out = toBGRA(crop)
out[..., 3] = (out[..., 3].astype(np.uint16) * mask // 255).astype(np.uint8)
return out
- fill = np.asarray(background, dtype=crop.dtype)
- if crop.ndim == 3 and fill.ndim == 0:
- fill = np.full(crop.shape[2], fill, dtype=crop.dtype)
- crop[mask == 0] = fill
+ value = np.asarray(fill, dtype=crop.dtype)
+ if crop.ndim == 3 and value.ndim == 0:
+ value = np.full(crop.shape[2], value, dtype=crop.dtype)
+ crop[mask == 0] = value
return crop
def drawContoursEx(
- src: np.ndarray,
+ img: np.ndarray,
contours: Sequence[np.ndarray],
- thickness: int = 2,
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.
+ cannot be told apart. Like ``cv.drawContours``, this draws **in place** and returns ``img``.
Args:
- src: 8-bit grayscale, BGR or BGRA image. It is not modified; grayscale input is converted to BGR.
+ img: 8-bit grayscale, BGR or BGRA image to draw on. On a grayscale image the luminance of each color
+ is used (convert with :func:`toBGR` first to see the colors).
contours: Contours as from :func:`findContoursEx`.
- thickness: Outline thickness, or ``cv.FILLED``.
- colors: BGR colors, cycled through. By default a fixed palette of 12 distinct colors.
+ colors: BGR colors, cycled through. By default :func:`distinctColors`.
labels: ``True`` writes the index of each contour at its centroid; a sequence gives the texts.
+ thickness: Outline thickness, or ``cv.FILLED``.
+ fontScale: Hershey font size for the labels.
Returns:
- A BGR (or BGRA) copy with the drawings.
+ ``img``, with the contours drawn on it.
Raises:
- ValueError: If ``src`` is not 8-bit or ``labels`` has a different length than ``contours``.
+ ValueError: If ``img`` is not 8-bit, is empty or has an unsupported channel count, a contour has no points
+ or is not finite, ``fontScale`` is not positive, or ``labels`` or ``colors`` has a different length
+ than ``contours``.
"""
- from .color import toBGR
+ from .color import distinctColors
- if src.dtype != np.uint8:
- raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
- check_image_not_empty("src", src)
+ if img.dtype != np.uint8:
+ raise ValueError(f"img must be an 8-bit (uint8) image, got dtype {img.dtype}")
+ check_image_not_empty("img", img)
+ channels = check_channels("img", img)
+ check_finite("fontScale", fontScale, positive=True)
items = [asContour(c) for c in contours]
if not isinstance(labels, bool) and len(labels) != len(items):
raise ValueError(f"labels must have one entry per contour, got {len(labels)} for {len(items)} contours")
- palette = list(colors) if colors else _PALETTE
- out = src.copy() if src.ndim == 3 and src.shape[2] == 4 else toBGR(src)
- if out is src:
- out = src.copy()
+ palette: list[tuple[float, ...]]
+ if colors is None:
+ palette = [tuple(float(c) for c in color) for color in distinctColors(max(len(items), 1))]
+ else:
+ palette = [tuple(float(c) for c in color) for color in colors]
+ if not palette:
+ raise ValueError("colors must not be empty")
for i, contour in enumerate(items):
- color = tuple(float(c) for c in palette[i % len(palette)])
- if out.shape[2] == 4 and len(color) == 3:
+ color = palette[i % len(palette)]
+ if channels == 1:
+ b, g, r = color[:3] if len(color) >= 3 else (color[0],) * 3
+ color = (0.114 * b + 0.587 * g + 0.299 * r,)
+ elif channels == 4 and len(color) == 3:
color = (*color, 255.0)
- cv2.drawContours(out, [contour], -1, color, thickness)
+ cv2.drawContours(img, [contour], -1, color, thickness)
if labels is False:
continue
text = str(i) if labels is True else str(labels[i])
cx, cy = contourStats(contour).center
(tw, th), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fontScale, 1)
org = (round(cx - tw / 2), round(cy + th / 2))
- cv2.putText(out, text, org, cv2.FONT_HERSHEY_SIMPLEX, fontScale, (0, 0, 0), 3, cv2.LINE_AA)
- cv2.putText(out, text, org, cv2.FONT_HERSHEY_SIMPLEX, fontScale, (255, 255, 255), 1, cv2.LINE_AA)
- return out
-
-
-_PALETTE: list[tuple[int, int, int]] = [
- (0, 0, 255),
- (0, 255, 0),
- (255, 0, 0),
- (0, 255, 255),
- (255, 0, 255),
- (255, 255, 0),
- (0, 128, 255),
- (128, 0, 255),
- (255, 128, 0),
- (0, 255, 128),
- (128, 255, 0),
- (255, 0, 128),
-]
+ cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, fontScale, (0, 0, 0), 3, cv2.LINE_AA)
+ cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, fontScale, (255, 255, 255), 1, cv2.LINE_AA)
+ return img
diff --git a/cv2u/imgproc/detect.py b/cv2u/imgproc/detect.py
index 9170963..f807349 100644
--- a/cv2u/imgproc/detect.py
+++ b/cv2u/imgproc/detect.py
@@ -4,21 +4,9 @@
import numpy as np
from .._validate import check_finite, check_image_not_empty
-from .color import toGray
-from .edges import autoCanny
+from .edges import _gray8, autoCanny
-__all__ = ["detectBlobs", "findCircles", "findLines"]
-
-
-def _gray8(src: np.ndarray) -> np.ndarray:
- """Grayscale 8-bit view of any image (float or 16-bit images are stretched to 0..255)."""
- gray = toGray(src)
- if gray.dtype == np.uint8:
- return gray
- values = gray.astype(np.float64)
- low, high = float(np.min(values)), float(np.max(values))
- scaled = (values - low) * (255.0 / (high - low)) if high > low else np.zeros_like(values)
- return np.asarray(np.rint(scaled), dtype=np.uint8)
+__all__ = ["findBlobs", "findCircles", "findLines"]
def findLines(
@@ -36,7 +24,7 @@ def findLines(
works (edges come from :func:`autoCanny` unless ``edges`` is given) and the result is always an array.
Args:
- src: Grayscale, BGR or BGRA image.
+ src: Grayscale, BGR or BGRA image (16-bit and float images are stretched to 8 bits).
minLength: Shortest segment to report, in pixels.
maxGap: Largest gap bridged between collinear edge pixels.
threshold: Accumulator votes a line needs (``cv.HoughLinesP``).
@@ -57,7 +45,7 @@ def findLines(
check_finite("theta", theta, positive=True)
if threshold < 1:
raise ValueError(f"threshold must be positive, got {threshold}")
- binary = autoCanny(src) if edges is None else np.asarray(edges != 0, np.uint8) * 255
+ binary = autoCanny(_gray8(src)) if edges is None else np.asarray(edges != 0, np.uint8) * 255
found = cv2.HoughLinesP(binary, rho, theta, threshold, minLineLength=minLength, maxLineGap=maxGap)
if found is None or len(found) == 0:
return np.zeros((0, 4), dtype=np.float64)
@@ -94,11 +82,14 @@ def findCircles(
A float64 array of shape ``(N, 3)``; empty ``(0, 3)`` when nothing is found.
Raises:
- ValueError: If ``src`` is empty, a radius is negative, ``blur`` is even, or a threshold is not positive.
+ ValueError: If ``src`` is empty, ``minRadius`` or ``maxRadius`` is negative, ``blur`` is even, or a
+ threshold is not positive.
"""
check_image_not_empty("src", src)
- if minRadius < 0 or maxRadius < 0:
- raise ValueError(f"radii must not be negative, got {minRadius} and {maxRadius}")
+ if minRadius < 0:
+ raise ValueError(f"minRadius must not be negative, got {minRadius}")
+ if maxRadius < 0:
+ raise ValueError(f"maxRadius must not be negative, got {maxRadius}")
if blur < 0 or (blur and blur % 2 == 0):
raise ValueError(f"blur must be 0 or an odd kernel size, got {blur}")
check_finite("sensitivity", sensitivity, positive=True)
@@ -124,10 +115,11 @@ def findCircles(
return found.reshape(-1, 3).astype(np.float64)
-def detectBlobs(
+def findBlobs(
src: np.ndarray,
minArea: float = 10,
maxArea: float | None = None,
+ *,
dark: bool = True,
minCircularity: float | None = None,
minConvexity: float | None = None,
diff --git a/cv2u/imgproc/document.py b/cv2u/imgproc/document.py
new file mode 100644
index 0000000..31560ae
--- /dev/null
+++ b/cv2u/imgproc/document.py
@@ -0,0 +1,522 @@
+"""Document and OCR preprocessing: shadows, local thresholds, ruling lines, text lines, page detection and skew.
+
+OpenCV has the pieces (``cv.integral``, ``cv.morphologyEx``, ``cv.inpaint``, ``cv.approxPolyDP``, ...) but no
+function that takes a photographed or scanned page and gives back something an OCR engine likes. The local
+thresholds (``cv.ximgproc.niBlackThreshold``) live in the contrib module that ``opencv-python`` does not ship.
+"""
+
+import math
+from typing import Literal
+
+import cv2
+import numpy as np
+
+from .._validate import check_finite, check_image_not_empty, check_uint8
+from .adjust import autoContrast
+from .binary import binarize
+from .color import toGray
+from .enhance import unsharpMask
+from .geometry import _ink, _line_score, _order_corners, fourPointTransform
+
+__all__ = [
+ "detectPage",
+ "detectTextBlocks",
+ "detectTextLines",
+ "enhanceDocument",
+ "estimateSkew",
+ "niblackThreshold",
+ "removeBorder",
+ "removeLines",
+ "removeShadow",
+ "removeSpeckles",
+ "sauvolaThreshold",
+ "scanDocument",
+]
+
+EnhanceMode = Literal["gray", "color", "binary"]
+
+
+def _check_odd(name: str, value: int, minimum: int = 3) -> None:
+ if value < minimum or value % 2 == 0:
+ raise ValueError(f"{name} must be odd and at least {minimum}, got {value}")
+
+
+def _ink_mask(src: np.ndarray) -> np.ndarray:
+ """Text pixels (dark on light or light on dark) as a full-resolution 0/255 mask."""
+ gray = toGray(src)
+ mask = binarize(gray, "otsu", invert=True)
+ if np.count_nonzero(mask) > mask.size / 2: # light text on a dark page
+ mask = cv2.bitwise_not(mask)
+ return mask
+
+
+def removeShadow(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image of a page.
+ kernelSize: Dilation kernel; must be larger than the text stroke width so the text vanishes.
+ blurSize: Median blur kernel (odd) that smooths the background estimate.
+
+ Returns:
+ An image of the same shape and dtype with a flat, bright background.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``kernelSize``/``blurSize`` is not a valid kernel size.
+ """
+ check_uint8("src", src)
+ if kernelSize < 1:
+ raise ValueError(f"kernelSize must be positive, got {kernelSize}")
+ _check_odd("blurSize", blurSize)
+ kernel = np.ones((kernelSize, kernelSize), dtype=np.uint8)
+ planes = [src] if src.ndim == 2 else list(cv2.split(src))
+ out = []
+ for plane in planes:
+ background = cv2.medianBlur(cv2.dilate(plane, kernel), blurSize)
+ diff = 255 - cv2.absdiff(plane, background)
+ out.append(cv2.normalize(diff, diff, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U))
+ result: np.ndarray = out[0] if src.ndim == 2 else cv2.merge(out)
+ return result
+
+
+def _local_stats(gray: np.ndarray, windowSize: int) -> tuple[np.ndarray, np.ndarray]:
+ """Mean and standard deviation of every ``windowSize`` neighborhood, from integral images."""
+ r = windowSize // 2
+ padded = cv2.copyMakeBorder(gray, r, r + 1, r, r + 1, cv2.BORDER_REFLECT_101)
+ integral, sq_integral = cv2.integral2(padded, sdepth=cv2.CV_64F, sqdepth=cv2.CV_64F)
+ h, w = gray.shape
+ n = float(windowSize * windowSize)
+ s = (
+ integral[windowSize : windowSize + h, windowSize : windowSize + w]
+ - integral[0:h, windowSize : windowSize + w]
+ - integral[windowSize : windowSize + h, 0:w]
+ + integral[0:h, 0:w]
+ )
+ sq = (
+ sq_integral[windowSize : windowSize + h, windowSize : windowSize + w]
+ - sq_integral[0:h, windowSize : windowSize + w]
+ - sq_integral[windowSize : windowSize + h, 0:w]
+ + sq_integral[0:h, 0:w]
+ )
+ mean = s / n
+ std = np.sqrt(np.maximum(sq / n - mean * mean, 0.0))
+ return mean, std
+
+
+def _apply_local_threshold(gray: np.ndarray, threshold: np.ndarray, invert: bool) -> np.ndarray:
+ above = gray.astype(np.float64) > threshold
+ return np.asarray(above != invert, dtype=np.uint8) * 255
+
+
+def sauvolaThreshold(
+ src: np.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``).
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image.
+ windowSize: Side of the square neighborhood (odd); 2-3 times the text height works well.
+ k: Sensitivity, usually 0.2-0.5; larger values thin the text.
+ r: Dynamic range of the standard deviation, 128 for 8-bit images.
+ invert: Return the text (pixels below the threshold) as 255 instead of the paper, like
+ ``cv.THRESH_BINARY_INV``.
+
+ Returns:
+ ``uint8`` mask with values 0 and 255: 255 where the pixel is above its local threshold (the paper).
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, ``windowSize`` is not odd, or ``k``/``r`` is not finite.
+ """
+ check_uint8("src", src)
+ _check_odd("windowSize", windowSize)
+ check_finite("k", k)
+ check_finite("r", r, positive=True)
+ gray = toGray(src)
+ mean, std = _local_stats(gray, windowSize)
+ return _apply_local_threshold(gray, mean * (1 + k * (std / r - 1)), invert)
+
+
+def niblackThreshold(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image.
+ windowSize: Side of the square neighborhood (odd).
+ k: Weight of the standard deviation; negative values (-0.2) favor dark text on light paper.
+ invert: Return the text (pixels below the threshold) as 255 instead of the paper.
+
+ Returns:
+ ``uint8`` mask with values 0 and 255: 255 where the pixel is above its local threshold.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, ``windowSize`` is not odd, or ``k`` is not finite.
+ """
+ check_uint8("src", src)
+ _check_odd("windowSize", windowSize)
+ check_finite("k", k)
+ gray = toGray(src)
+ mean, std = _local_stats(gray, windowSize)
+ return _apply_local_threshold(gray, mean + k * std, invert)
+
+
+def _is_binary(src: np.ndarray) -> bool:
+ return bool(np.isin(np.unique(src), (0, 255)).all())
+
+
+def removeLines(
+ src: np.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``.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA document (binarized or not).
+ horizontal: Remove horizontal lines.
+ vertical: Remove vertical lines.
+ minLength: 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.
+ thickness: Width of the strip erased around each line, in pixels (covers anti-aliased edges).
+
+ Returns:
+ A new image of the same shape and dtype.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, ``minLength`` is not positive, or ``thickness`` is not
+ positive.
+ """
+ check_uint8("src", src)
+ if minLength is not None:
+ check_finite("minLength", minLength, positive=True)
+ if thickness < 1:
+ raise ValueError(f"thickness must be positive, got {thickness}")
+ h, w = src.shape[:2]
+
+ def length(extent: int) -> int:
+ if minLength is None:
+ return max(int(extent * 0.1), 1)
+ return max(round(minLength * extent if minLength < 1 else minLength), 1)
+
+ ink = _ink_mask(src)
+ lines = np.zeros_like(ink)
+ if horizontal:
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (length(w), 1))
+ lines |= cv2.morphologyEx(ink, cv2.MORPH_OPEN, kernel)
+ if vertical:
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, length(h)))
+ lines |= cv2.morphologyEx(ink, cv2.MORPH_OPEN, kernel)
+ if thickness > 1:
+ lines = cv2.dilate(lines, np.ones((thickness, thickness), dtype=np.uint8))
+ if not np.any(lines):
+ return src.copy()
+ if _is_binary(src):
+ out = src.copy()
+ paper = np.array(255 if np.count_nonzero(src) > src.size / 2 else 0, dtype=np.uint8)
+ out[lines > 0] = paper
+ return out
+ if src.ndim == 3 and src.shape[2] == 4:
+ color: np.ndarray = cv2.inpaint(src[..., :3], lines, 3, cv2.INPAINT_TELEA)
+ return np.dstack([color, src[..., 3]])
+ dst: np.ndarray = cv2.inpaint(src, lines, 3, cv2.INPAINT_TELEA)
+ return dst
+
+
+def _text_regions(
+ src: np.ndarray, ksize: tuple[int, int] | None, minHeight: int, defaults: tuple[float, float]
+) -> np.ndarray:
+ """Boxes of ink regions after dilating with ``ksize``, sorted top to bottom; the kernel defaults to
+ ``defaults`` times the median character height."""
+ check_uint8("src", src)
+ if minHeight < 1:
+ raise ValueError(f"minHeight must be positive, got {minHeight}")
+ ink = _ink_mask(src)
+ if ksize is None:
+ _, _, stats, _ = cv2.connectedComponentsWithStats(ink, connectivity=8)
+ heights = stats[1:, cv2.CC_STAT_HEIGHT]
+ heights = heights[heights >= minHeight]
+ char = float(np.median(heights)) if heights.size else float(minHeight)
+ ksize = (max(int(char * defaults[0]), 1), max(int(char * defaults[1]), 1))
+ merged = cv2.dilate(ink, cv2.getStructuringElement(cv2.MORPH_RECT, ksize))
+ _, _, stats, _ = cv2.connectedComponentsWithStats(merged, connectivity=8)
+ boxes = stats[1:, :4].astype(np.int32)
+ boxes = boxes[boxes[:, 3] >= minHeight]
+ if boxes.size == 0:
+ return np.zeros((0, 4), dtype=np.int32)
+ # Shrink the dilation back out of the boxes so they hug the ink.
+ pad_x, pad_y = ksize[0] // 2, ksize[1] // 2
+ boxes[:, 0] += pad_x
+ boxes[:, 1] += pad_y
+ boxes[:, 2] -= 2 * pad_x
+ boxes[:, 3] -= 2 * pad_y
+ boxes[:, 2:] = np.maximum(boxes[:, 2:], 1)
+ order = np.lexsort((boxes[:, 0], boxes[:, 1]))
+ return np.asarray(boxes[order], dtype=np.int32)
+
+
+def detectTextLines(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image of a page.
+ minHeight: Ignore regions lower than this many pixels (noise, rules).
+ dilateWidth: Horizontal smear that joins characters and words, in pixels. By default about twice the
+ median character height, which bridges word spaces but not columns.
+
+ Returns:
+ ``int32`` array of shape ``(N, 4)`` with one ``(x, y, w, h)`` box per line, sorted top to bottom (then
+ left to right). Empty for a blank page.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``minHeight``/``dilateWidth`` is not positive.
+ """
+ if dilateWidth is not None and dilateWidth < 1:
+ raise ValueError(f"dilateWidth must be positive, got {dilateWidth}")
+ ksize = None if dilateWidth is None else (dilateWidth, 1)
+ return _text_regions(src, ksize, minHeight, (2.0, 0.0))
+
+
+def detectTextBlocks(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image of a page.
+ minHeight: Ignore regions lower than this many pixels.
+ dilateSize: Smear as ``(width, height)`` in pixels. By default about 3 and 1.5 times the median
+ character height.
+
+ Returns:
+ ``int32`` array of shape ``(N, 4)`` with one ``(x, y, w, h)`` box per block, sorted top to bottom
+ (then left to right). Empty for a blank page.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``minHeight``/``dilateSize`` is not positive.
+ """
+ if dilateSize is not None and (dilateSize[0] < 1 or dilateSize[1] < 1):
+ raise ValueError(f"dilateSize must be positive, got {dilateSize}")
+ return _text_regions(src, dilateSize, minHeight, (3.0, 1.5))
+
+
+def removeBorder(src: np.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`.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image.
+ threshold: Gray level above which a pixel counts as paper; by default chosen by Otsu's method.
+ margin: Extra pixels trimmed from each side of the page (positive) or kept around it (negative).
+
+ Returns:
+ The cropped page. The whole image if nothing bright is found.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``threshold`` is not finite.
+ """
+ check_uint8("src", src)
+ if threshold is not None:
+ check_finite("threshold", threshold)
+ gray = toGray(src)
+ bright = binarize(gray, "otsu" if threshold is None else threshold)
+ bright = cv2.morphologyEx(bright, cv2.MORPH_OPEN, np.ones((5, 5), dtype=np.uint8))
+ count, _, stats, _ = cv2.connectedComponentsWithStats(bright, connectivity=4)
+ if count <= 1:
+ return src.copy()
+ largest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))
+ x, y, w, h = (int(v) for v in stats[largest, :4])
+ h_img, w_img = gray.shape
+ x0, y0 = max(x + margin, 0), max(y + margin, 0)
+ x1, y1 = min(x + w - margin, w_img), min(y + h - margin, h_img)
+ if x1 <= x0 or y1 <= y0:
+ return src.copy()
+ return np.ascontiguousarray(src[y0:y1, x0:x1])
+
+
+def detectPage(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA photo with the page against a contrasting background.
+ minAreaRatio: Smallest fraction of the image area the page may cover.
+
+ Returns:
+ ``float32`` array of shape ``(4, 2)`` with the corners ordered top-left, top-right, bottom-right,
+ bottom-left, or ``None`` if no quadrilateral is found.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``minAreaRatio`` is not in ``[0, 1]``.
+ """
+ check_uint8("src", src)
+ check_finite("minAreaRatio", minAreaRatio)
+ if not 0 <= minAreaRatio <= 1:
+ raise ValueError(f"minAreaRatio must be in [0, 1], got {minAreaRatio}")
+ gray = toGray(src)
+ h, w = gray.shape
+ scale = min(1.0, 800 / max(h, w))
+ small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA) if scale < 1 else gray
+ blurred = cv2.GaussianBlur(small, (5, 5), 0)
+ median = float(np.median(blurred))
+ edges = cv2.Canny(blurred, max(0.0, 0.67 * median), min(255.0, 1.33 * median) or 50.0)
+ edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((5, 5), dtype=np.uint8))
+ contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
+ min_area = minAreaRatio * small.shape[0] * small.shape[1]
+ for contour in sorted(contours, key=cv2.contourArea, reverse=True):
+ if cv2.contourArea(contour) < min_area:
+ break
+ hull = cv2.convexHull(contour)
+ hull_area = cv2.contourArea(hull)
+ for epsilon in (0.02, 0.05, 0.1):
+ approx = cv2.approxPolyDP(hull, epsilon * cv2.arcLength(hull, True), True)
+ # A quadrilateral must keep nearly all of the hull's area (a circle loses a third of it).
+ if len(approx) == 4 and cv2.contourArea(approx) >= max(min_area, 0.9 * hull_area):
+ corners = approx.reshape(4, 2).astype(np.float32) / np.float32(scale)
+ return np.asarray(_order_corners(corners), dtype=np.float32)
+ return None
+
+
+def enhanceDocument(src: np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image of a page.
+ mode: ``"gray"`` (grayscale result), ``"color"`` (keeps the colors, e.g. stamps and highlights) or
+ ``"binary"`` (0/255 mask).
+
+ Returns:
+ ``uint8`` image: 2-D for ``"gray"`` and ``"binary"``, the same channels as ``src`` for ``"color"``
+ (grayscale input stays grayscale).
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``mode`` is unknown.
+ """
+ check_uint8("src", src)
+ if mode not in ("gray", "color", "binary"):
+ raise ValueError(f"mode must be 'gray', 'color' or 'binary', got {mode!r}")
+ image = src if mode == "color" else toGray(src)
+ flat = removeShadow(image)
+ if mode == "binary":
+ return binarize(flat, "adaptive", blockSize=31, C=15)
+ return unsharpMask(autoContrast(flat, clip=0.005), sigma=1.0, amount=0.5)
+
+
+def scanDocument(
+ src: np.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`.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA photo of a page.
+ size: Output size ``(width, height)``; by default the size of the page in the photo.
+ enhance: Flatten the lighting and sharpen the result (``"gray"`` for grayscale input, ``"color"``
+ otherwise).
+ minAreaRatio: Passed to :func:`detectPage`.
+
+ Returns:
+ The upright page. If no page outline is found, the whole image (enhanced if asked, resized to ``size``).
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``minAreaRatio`` is not in ``[0, 1]``.
+ """
+ corners = detectPage(src, minAreaRatio)
+ if corners is None:
+ page = src if size is None else cv2.resize(src, size, interpolation=cv2.INTER_AREA)
+ else:
+ page = fourPointTransform(src, corners, size)
+ if enhance:
+ return enhanceDocument(page, "gray" if page.ndim == 2 else "color")
+ return page.copy() if page is src else page
+
+
+def estimateSkew(src: np.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.
+
+ Args:
+ src: Image of a page (grayscale, BGR or BGRA).
+ maxAngle: Largest tilt to look for, in degrees.
+
+ Returns:
+ The counter-clockwise rotation (as for ``cv.getRotationMatrix2D``) that levels the lines; 0 for a blank
+ page.
+
+ Raises:
+ ValueError: If ``src`` is empty, or ``maxAngle`` is negative or not below 90.
+ """
+ check_image_not_empty("src", src)
+ if not 0 <= maxAngle < 90:
+ raise ValueError(f"maxAngle must be in [0, 90), got {maxAngle}")
+ binary = _ink(src)
+ if not np.count_nonzero(binary) or maxAngle == 0:
+ return 0.0
+ limit = math.floor(maxAngle)
+ coarse = [float(a) for a in range(-limit, limit + 1)]
+ best = max(coarse, key=lambda a: _line_score(binary, a))
+ fine = {min(max(round(best + step / 10, 1), -maxAngle), maxAngle) for step in range(-10, 11)}
+ return float(max(sorted(fine), key=lambda a: _line_score(binary, a)))
+
+
+def removeSpeckles(src: np.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).
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA document.
+ maxArea: Ink regions with up to this many pixels are removed.
+
+ Returns:
+ A new image of the same shape and dtype.
+
+ Raises:
+ ValueError: If ``src`` is empty or not 8-bit, or ``maxArea`` is negative.
+ """
+ check_uint8("src", src)
+ if maxArea < 0:
+ raise ValueError(f"maxArea must not be negative, got {maxArea}")
+ ink = _ink_mask(src)
+ _, labels, stats, _ = cv2.connectedComponentsWithStats(ink, connectivity=8)
+ small = stats[:, cv2.CC_STAT_AREA] <= maxArea
+ small[0] = False
+ speck = small[labels]
+ out = src.copy()
+ if not speck.any():
+ return out
+ paper = src[ink == 0]
+ fill = np.median(paper, axis=0) if paper.size else np.full(src.shape[2:], 255)
+ out[speck] = np.rint(fill).astype(np.uint8)
+ return out
diff --git a/cv2u/imgproc/draw.py b/cv2u/imgproc/draw.py
index c5359b5..6b523da 100644
--- a/cv2u/imgproc/draw.py
+++ b/cv2u/imgproc/draw.py
@@ -7,6 +7,7 @@
import numpy as np
from PIL import Image, ImageDraw
+from .._validate import as_color, check_channels, check_finite, check_image_not_empty, is_single_color
from .puttext import _load_font
__all__ = [
@@ -40,8 +41,10 @@ def _luminance(color: Color) -> float:
return 0.114 * b + 0.587 * g + 0.299 * r
-def _channels(img: np.ndarray) -> int:
- return 1 if img.ndim == 2 else int(img.shape[2])
+def _check_canvas(img: np.ndarray) -> int:
+ """Channel count of an image to draw on; empty images and unsupported channel counts are rejected."""
+ check_image_not_empty("img", img)
+ return check_channels("img", img)
def _pil_fill(color: Color, channels: int) -> int | tuple[int, ...]:
@@ -84,11 +87,13 @@ def drawLabel(
``img``, with the box and label drawn on it.
Raises:
- ValueError: If ``img`` is not 8-bit.
+ ValueError: If ``img`` is not 8-bit, is empty or has an unsupported channel count, ``fontScale`` is not
+ positive, or ``color`` is not a scalar or BGR color.
"""
if img.dtype != np.uint8:
raise ValueError(f"img must be an 8-bit (uint8) image, got dtype {img.dtype}")
- channels = _channels(img)
+ channels = _check_canvas(img)
+ check_finite("fontScale", fontScale, positive=True)
if channels == 1 and not isinstance(color, (int, float)):
# OpenCV would use only color[0] on a grayscale image, e.g. (0, 200, 255) would draw black.
color = _luminance(color)
@@ -145,16 +150,19 @@ def overlayMask(src: np.ndarray, mask: np.ndarray, color: Color = (0, 0, 255), a
A new image with the same shape as ``src``.
Raises:
- ValueError: If ``src`` is not 8-bit, the mask shape does not match, or ``alpha`` is outside ``[0, 1]``.
+ ValueError: If ``src`` is not 8-bit, is empty or has an unsupported channel count, the mask shape does not
+ match, or ``alpha`` is outside ``[0, 1]``.
"""
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
+ channels = check_channels("src", src)
if mask.ndim != 2 or mask.shape != src.shape[:2]:
raise ValueError(f"mask must have the shape {src.shape[:2]}, got {mask.shape}")
+ check_finite("alpha", alpha)
if not 0.0 <= alpha <= 1.0:
raise ValueError(f"alpha must be between 0 and 1, got {alpha}")
- channels = _channels(src)
# Blend the whole image with a flat color layer (C++), then copy the masked pixels over: much faster than
# gathering and scattering the selected pixels with NumPy fancy indexing on large masks.
layer = np.empty_like(src)
@@ -196,8 +204,9 @@ def drawDashedLine(
``img``.
Raises:
- ValueError: If ``dashLength`` or ``gapLength`` is not positive.
+ ValueError: If ``img`` is empty, or ``dashLength`` or ``gapLength`` is not positive.
"""
+ _check_canvas(img)
gap = dashLength if gapLength is None else gapLength
if dashLength < 1 or gap < 1:
raise ValueError(f"dashLength and gapLength must be positive, got {dashLength} and {gap}")
@@ -225,9 +234,21 @@ def drawDashedRectangle(
) -> np.ndarray:
"""Draw a dashed rectangle ``(x, y, width, height)``, in place like ``cv.rectangle``.
+ Args:
+ img: Image to draw on.
+ rect: The box as ``(x, y, width, height)``.
+ color: Line color.
+ thickness: Line thickness.
+ dashLength: Length of each dash in pixels.
+ gapLength: Length of each gap; by default equal to ``dashLength``.
+
Returns:
``img``.
+
+ Raises:
+ ValueError: If ``img`` is empty, or ``dashLength`` or ``gapLength`` is not positive.
"""
+ _check_canvas(img)
x, y, w, h = (int(v) for v in rect)
x1, y1 = x + w - 1, y + h - 1
for p, q in (((x, y), (x1, y)), ((x1, y), (x1, y1)), ((x1, y1), (x, y1)), ((x, y1), (x, y))):
@@ -235,7 +256,7 @@ def drawDashedRectangle(
return img
-def drawHistogram(src: np.ndarray, size: tuple[int, int] = (512, 200), log: bool = False) -> np.ndarray:
+def drawHistogram(src: np.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.
@@ -247,14 +268,19 @@ def drawHistogram(src: np.ndarray, size: tuple[int, int] = (512, 200), log: bool
On a linear scale, the few tallest spikes are clipped at the top.
Returns:
- A BGR image with a dark background.
+ An 8-bit BGR image with a dark background.
Raises:
- ValueError: If ``src`` is not 8-bit.
+ ValueError: If ``src`` is not 8-bit, is empty or has an unsupported channel count, or ``size`` is not
+ positive.
"""
if src.dtype != np.uint8:
raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
+ check_channels("src", src)
width, height = size
+ if width < 1 or height < 1:
+ raise ValueError(f"size must be at least 1x1, got {size}")
plot = np.full((height, width, 3), 24, np.uint8)
channels = 1 if src.ndim == 2 else min(src.shape[2], 3)
colors = [(230, 230, 230)] if channels == 1 else [(255, 120, 40), (60, 200, 60), (40, 60, 255)]
@@ -278,8 +304,8 @@ def drawRoundedRectangle(
rect: tuple[int, int, int, int],
color: Color,
thickness: int = 1,
- lineType: int = cv2.LINE_8,
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``.
@@ -288,15 +314,16 @@ def drawRoundedRectangle(
rect: The box, as for ``drawDashedRectangle``.
color: Line or fill color.
thickness: Line thickness; ``cv.FILLED`` (negative) fills the shape.
- lineType: As for ``cv.rectangle`` (``cv.LINE_AA`` for smooth corners).
radius: Corner radius in pixels, reduced to fit small boxes.
+ lineType: As for ``cv.rectangle`` (``cv.LINE_AA`` for smooth corners).
Returns:
``img``.
Raises:
- ValueError: If the box is empty or ``radius`` is negative.
+ ValueError: If ``img`` is empty, the box has no area, or ``radius`` is negative.
"""
+ _check_canvas(img)
x, y, w, h = (int(v) for v in rect)
if w < 1 or h < 1:
raise ValueError(f"rect must have a positive size, got {w}x{h}")
@@ -352,10 +379,11 @@ def drawBoxes(
``img``.
Raises:
- ValueError: If ``labels`` or ``colors`` has a different length than ``boxes``.
+ ValueError: If ``img`` is empty, or ``labels`` or ``colors`` has a different length than ``boxes``.
"""
from .color import distinctColors
+ _check_canvas(img)
array = np.asarray(boxes, dtype=np.float64).reshape(-1, 4) if np.size(boxes) else np.zeros((0, 4))
count = len(array)
if labels is not None and len(labels) != count:
@@ -363,12 +391,10 @@ def drawBoxes(
palette: list[Color]
if colors is None:
palette = list(distinctColors(max(count, 1)))
- elif isinstance(colors, (int, float)) or (
- len(colors) in (3, 4) and all(isinstance(c, (int, float)) for c in colors)
- ):
- palette = [colors] * max(count, 1) # type: ignore[list-item]
+ elif is_single_color(colors):
+ palette = [as_color(colors)] * max(count, 1)
else:
- palette = list(colors)
+ palette = [as_color(c) for c in colors] # type: ignore[union-attr]
if len(palette) != count:
raise ValueError(f"colors must have one entry per box, got {len(palette)} for {count} boxes")
for i, box in enumerate(array):
@@ -390,7 +416,7 @@ def drawPoints(
radius: int = 3,
thickness: int = cv2.FILLED,
labels: bool | Sequence[str] = False,
- fontScale: float = 0.4,
+ fontScale: float = 0.5,
) -> np.ndarray:
"""Draw points (keypoints, corners, landmarks) as circles, optionally numbered, in place.
@@ -407,8 +433,10 @@ def drawPoints(
``img``.
Raises:
- ValueError: If the points are not 2-D, ``radius`` is negative, or ``labels`` has a different length.
+ ValueError: If ``img`` is empty, the points are not 2-D, ``radius`` is negative, or ``labels`` has a
+ different length.
"""
+ _check_canvas(img)
array = np.asarray(points, dtype=np.float64).reshape(-1, 2) if np.size(points) else np.zeros((0, 2))
if not isinstance(labels, bool) and len(labels) != len(array):
raise ValueError(f"labels must have one entry per point, got {len(labels)} for {len(array)} points")
@@ -446,8 +474,9 @@ def drawGrid(
``img``.
Raises:
- ValueError: If ``step`` is not positive.
+ ValueError: If ``img`` is empty or ``step`` is not positive.
"""
+ _check_canvas(img)
step_x, step_y = (step, step) if isinstance(step, int) else step
if step_x < 1 or step_y < 1:
raise ValueError(f"step must be positive, got {step}")
diff --git a/cv2u/imgproc/edges.py b/cv2u/imgproc/edges.py
index 0d170da..8d9ebfa 100644
--- a/cv2u/imgproc/edges.py
+++ b/cv2u/imgproc/edges.py
@@ -1,9 +1,21 @@
import cv2
import numpy as np
+from .._validate import check_finite, check_image_not_empty
+from .color import toGray
+
__all__ = ["autoCanny"]
-_TO_GRAY = {3: cv2.COLOR_BGR2GRAY, 4: cv2.COLOR_BGRA2GRAY}
+
+def _gray8(src: np.ndarray) -> np.ndarray:
+ """Grayscale 8-bit view of any image (float or 16-bit images are stretched to 0..255)."""
+ gray = toGray(src)
+ if gray.dtype == np.uint8:
+ return gray
+ values = gray.astype(np.float64)
+ low, high = float(np.min(values)), float(np.max(values))
+ scaled = (values - low) * (255.0 / (high - low)) if high > low else np.zeros_like(values)
+ return np.asarray(np.rint(scaled), dtype=np.uint8)
def autoCanny(src: np.ndarray, sigma: float = 0.33, apertureSize: int = 3, L2gradient: bool = False) -> np.ndarray:
@@ -13,7 +25,8 @@ def autoCanny(src: np.ndarray, sigma: float = 0.33, apertureSize: int = 3, L2gra
that works well across lighting conditions without manual tuning.
Args:
- src: 8-bit grayscale, BGR or BGRA image. Color images are converted to grayscale.
+ src: Grayscale, BGR or BGRA image. Color images are converted to grayscale; 16-bit and float images are
+ stretched to 8 bits first (``cv.Canny`` accepts only 8-bit input).
sigma: Width of the threshold band around the median; smaller values give fewer edges.
apertureSize: Sobel aperture, as in ``cv.Canny``.
L2gradient: Use the more accurate L2 gradient norm, as in ``cv.Canny``.
@@ -22,13 +35,13 @@ def autoCanny(src: np.ndarray, sigma: float = 0.33, apertureSize: int = 3, L2gra
Single-channel edge map (0 or 255).
Raises:
- ValueError: If ``src`` is not 8-bit or ``sigma`` is outside ``[0, 1]``.
+ ValueError: If ``src`` is empty or has an unsupported channel count, or ``sigma`` is outside ``[0, 1]``.
"""
- if src.dtype != np.uint8:
- raise ValueError(f"src must be an 8-bit (uint8) image, got dtype {src.dtype}")
+ check_image_not_empty("src", src)
+ check_finite("sigma", sigma)
if not 0.0 <= sigma <= 1.0:
raise ValueError(f"sigma must be between 0 and 1, got {sigma}")
- gray = src if src.ndim == 2 else cv2.cvtColor(src, _TO_GRAY[src.shape[2]])
+ gray = _gray8(src)
median = float(np.median(gray))
lower = int(max(0.0, (1.0 - sigma) * median))
upper = int(min(255.0, (1.0 + sigma) * median))
diff --git a/cv2u/imgproc/enhance.py b/cv2u/imgproc/enhance.py
index 2d8d823..50f8534 100644
--- a/cv2u/imgproc/enhance.py
+++ b/cv2u/imgproc/enhance.py
@@ -8,6 +8,7 @@
def equalizeHistEx(
src: np.ndarray,
+ *,
clahe: bool = False,
clipLimit: float = 2.0,
tileGridSize: tuple[int, int] = (8, 8),
@@ -96,7 +97,7 @@ def pixelate(src: np.ndarray, blockSize: int = 16, rect: tuple[int, int, int, in
A new image; the area outside ``rect`` is unchanged.
Raises:
- ValueError: If ``blockSize`` is not positive.
+ ValueError: If ``src`` is empty or ``blockSize`` is not positive.
"""
if blockSize < 1:
raise ValueError(f"blockSize must be positive, got {blockSize}")
diff --git a/cv2u/imgproc/features.py b/cv2u/imgproc/features.py
index 36f5398..24d1b01 100644
--- a/cv2u/imgproc/features.py
+++ b/cv2u/imgproc/features.py
@@ -17,13 +17,13 @@ class FeatureMatches(NamedTuple):
"""The result of :func:`matchFeatures`."""
srcPoints: np.ndarray
- """Matched keypoint locations in the first image, shape ``(N, 2)`` float32."""
+ """Matched keypoint locations in ``src``, shape ``(N, 2)`` float32."""
dstPoints: np.ndarray
- """The corresponding locations in the second image, shape ``(N, 2)`` float32."""
+ """The corresponding locations in ``reference``, shape ``(N, 2)`` float32 (``dst`` as in ``cv.findHomography``)."""
srcKeypoints: list[cv2.KeyPoint]
- """All keypoints found in the first image (for ``cv.drawMatches``)."""
+ """All keypoints found in ``src`` (for ``cv.drawMatches``)."""
dstKeypoints: list[cv2.KeyPoint]
- """All keypoints found in the second image."""
+ """All keypoints found in ``reference``."""
matches: list[cv2.DMatch]
"""The matches that passed the ratio test (for ``cv.drawMatches``), one per row of the point arrays."""
@@ -38,12 +38,12 @@ def _detector(method: str, maxFeatures: int) -> cv2.Feature2D:
def matchFeatures(
src: np.ndarray,
- dst: np.ndarray,
+ reference: np.ndarray,
method: Detector = "ORB",
maxFeatures: int = 2000,
ratio: float = 0.75,
mask: np.ndarray | None = None,
- dstMask: np.ndarray | None = None,
+ referenceMask: np.ndarray | None = None,
) -> FeatureMatches:
"""Find corresponding points between two images (detect, describe, match, Lowe's ratio test).
@@ -53,23 +53,24 @@ def matchFeatures(
Args:
src: First image (any channel count; converted to grayscale).
- dst: Second image.
+ reference: Second image, the one ``src`` is matched to (as in :func:`alignImages`).
method: ``"ORB"`` (default, fast, binary descriptors) or ``"SIFT"`` (slower, more robust to scale and
lighting). Both ship with every OpenCV distribution from 4.4 on.
maxFeatures: Keypoint limit for ORB and SIFT.
ratio: Lowe's ratio; lower keeps fewer but more reliable matches.
mask: Optional 8-bit mask of where to look for keypoints in ``src``.
- dstMask: The same for ``dst``.
+ referenceMask: The same for ``reference``.
Returns:
A :class:`FeatureMatches`. ``srcPoints`` and ``dstPoints`` are empty ``(0, 2)`` arrays if nothing
matches; pass them to ``cv.findHomography`` or ``cv.estimateAffinePartial2D`` for the transform.
Raises:
- ValueError: If an image is empty, ``method`` is unknown, or ``ratio`` is not in ``(0, 1]``.
+ ValueError: If an image is empty or has an unsupported channel count, ``method`` is unknown, ``ratio`` is
+ not in ``(0, 1]``, or ``maxFeatures`` is not positive.
"""
check_image_not_empty("src", src)
- check_image_not_empty("dst", dst)
+ check_image_not_empty("reference", reference)
check_finite("ratio", ratio, positive=True)
if ratio > 1:
raise ValueError(f"ratio must be in (0, 1], got {ratio}")
@@ -77,7 +78,7 @@ def matchFeatures(
raise ValueError(f"maxFeatures must be positive, got {maxFeatures}")
detector = _detector(method, maxFeatures)
kp1, des1 = detector.detectAndCompute(toGray(src), mask)
- kp2, des2 = detector.detectAndCompute(toGray(dst), dstMask)
+ kp2, des2 = detector.detectAndCompute(toGray(reference), referenceMask)
empty = np.zeros((0, 2), np.float32)
if des1 is None or des2 is None or len(kp1) < 2 or len(kp2) < 2:
return FeatureMatches(empty, empty, list(kp1), list(kp2), [])
@@ -128,8 +129,11 @@ def alignImages(
transform, ``3x3`` for a homography or ``2x3`` otherwise, mapping ``src`` coordinates to ``reference``.
Raises:
- ValueError: If too few matches are found, or the transform cannot be estimated.
+ ValueError: If an image is empty, ``ransacThreshold`` is not positive, ``minMatches`` is too small for
+ ``motion``, too few matches are found, or the transform cannot be estimated.
"""
+ check_image_not_empty("src", src)
+ check_image_not_empty("reference", reference)
check_finite("ransacThreshold", ransacThreshold, positive=True)
if minMatches < 4 if motion == "homography" else minMatches < 3:
raise ValueError(f"minMatches must be at least {4 if motion == 'homography' else 3}, got {minMatches}")
diff --git a/cv2u/imgproc/geometry.py b/cv2u/imgproc/geometry.py
index 5b10f75..967137d 100644
--- a/cv2u/imgproc/geometry.py
+++ b/cv2u/imgproc/geometry.py
@@ -1,10 +1,11 @@
import math
-from typing import Any
+from collections.abc import Sequence
import cv2
import numpy as np
from numpy.typing import ArrayLike
+from .._validate import check_finite, check_image_not_empty
from ..core.rotate import rotateEx
from .color import toGray
@@ -42,8 +43,10 @@ def fourPointTransform(
The warped image.
Raises:
- ValueError: If ``pts`` does not hold exactly 4 points, or the points are degenerate.
+ ValueError: If ``src`` is empty, ``pts`` does not hold exactly 4 finite points, the points are degenerate,
+ or ``size`` is not positive.
"""
+ check_image_not_empty("src", src)
corners = np.asarray(pts, dtype=np.float32).reshape(-1, 2)
if corners.shape != (4, 2):
raise ValueError(f"pts must contain exactly 4 points, got {corners.shape[0]}")
@@ -78,7 +81,7 @@ def translate(
dx: float,
dy: float,
borderMode: int = cv2.BORDER_CONSTANT,
- borderValue: float | tuple[float, ...] = 0,
+ borderValue: float | Sequence[float] = 0,
) -> np.ndarray:
"""Shift an image by ``(dx, dy)`` pixels, keeping its size (OpenCV has no function for this).
@@ -88,7 +91,16 @@ def translate(
dy: Shift down (negative: up).
borderMode: How to fill the uncovered area, as for ``cv.warpAffine`` (e.g. ``cv.BORDER_REPLICATE``).
borderValue: Fill color for ``cv.BORDER_CONSTANT``.
+
+ Returns:
+ The shifted image, with the shape and dtype of ``src``.
+
+ Raises:
+ ValueError: If ``src`` is empty, or ``dx`` or ``dy`` is not finite.
"""
+ check_image_not_empty("src", src)
+ check_finite("dx", dx)
+ check_finite("dy", dy)
h, w = src.shape[:2]
matrix = np.array([[1, 0, dx], [0, 1, dy]], dtype=np.float64)
dst: np.ndarray = cv2.warpAffine(src, matrix, (w, h), borderMode=borderMode, borderValue=borderValue)
@@ -134,8 +146,8 @@ def cropRotatedRect(
src: np.ndarray,
rect: tuple[tuple[float, float], tuple[float, float], float],
flags: int = cv2.INTER_LINEAR,
- borderMode: int = cv2.BORDER_REPLICATE,
- borderValue: float | tuple[float, ...] = 0,
+ 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).
@@ -146,16 +158,21 @@ def cropRotatedRect(
src: Image to crop from.
rect: The rotated box, as returned by ``cv.minAreaRect``.
flags: Interpolation, as for ``cv.warpAffine``.
- borderMode: How to fill the parts of the box outside the image, as for ``cv.warpAffine``.
+ borderMode: How to fill the parts of the box outside the image, as for ``cv.warpAffine``
+ (``cv.BORDER_CONSTANT`` with ``borderValue`` by default, like ``cv.warpAffine``).
borderValue: Fill color for ``cv.BORDER_CONSTANT``.
Returns:
An image of size ``(round(width), round(height))`` whose x axis runs along the box's width side.
Raises:
- ValueError: If the box is smaller than one pixel.
+ ValueError: If ``src`` is empty, ``rect`` is not finite, or the box is smaller than one pixel.
"""
+ check_image_not_empty("src", src)
(cx, cy), (w, h), angle = rect
+ for name, value in (("rect center", cx), ("rect center", cy), ("rect size", w), ("rect size", h)):
+ check_finite(name, value)
+ check_finite("rect angle", angle)
width, height = round(w), round(h)
if width < 1 or height < 1:
raise ValueError(f"rect must be at least 1x1 pixel, got {w}x{h}")
@@ -194,7 +211,7 @@ def deskew(
src: np.ndarray,
maxAngle: float = 45.0,
borderMode: int = cv2.BORDER_CONSTANT,
- borderValue: Any = None,
+ borderValue: float | Sequence[float] | None = None,
) -> tuple[np.ndarray, float]:
"""Straighten a scanned or photographed page whose text lines are tilted.
@@ -214,8 +231,10 @@ def deskew(
(positive is counter-clockwise, as for ``cv.getRotationMatrix2D``). ``angle`` is 0 for an empty page.
Raises:
- ValueError: If ``maxAngle`` is negative or not below 90.
+ ValueError: If ``src`` is empty, or ``maxAngle`` is negative or not below 90.
"""
+ check_image_not_empty("src", src)
+ check_finite("maxAngle", maxAngle)
if not 0 <= maxAngle < 90:
raise ValueError(f"maxAngle must be in [0, 90), got {maxAngle}")
binary = _ink(src)
@@ -226,7 +245,7 @@ def deskew(
best = max(coarse, key=lambda a: _line_score(binary, a))
fine = {min(max(round(best + step / 10, 1), -maxAngle), maxAngle) for step in range(-10, 11)}
angle = max(sorted(fine), key=lambda a: _line_score(binary, a))
- if borderValue is None and borderMode == cv2.BORDER_CONSTANT:
+ if borderValue is None:
edge = np.concatenate([src[0], src[-1], src[:, 0], src[:, -1]]).reshape(-1, *src.shape[2:3])
borderValue = tuple(float(v) for v in np.median(edge, axis=0).ravel())
return rotateEx(src, angle, borderMode=borderMode, borderValue=borderValue), angle
diff --git a/cv2u/imgproc/mask.py b/cv2u/imgproc/mask.py
index 8e72a26..f4156bd 100644
--- a/cv2u/imgproc/mask.py
+++ b/cv2u/imgproc/mask.py
@@ -57,7 +57,7 @@ def fillHoles(mask: np.ndarray, maxHoleArea: int | None = None) -> np.ndarray:
return np.asarray(filled, dtype=np.uint8) * 255
-def removeSmallObjects(mask: np.ndarray, minArea: int, connectivity: int = 8) -> np.ndarray:
+def removeSmallObjects(mask: np.ndarray, minArea: float, connectivity: int = 8) -> np.ndarray:
"""Remove connected foreground regions smaller than ``minArea`` pixels from a binary mask.
Args:
@@ -69,13 +69,12 @@ def removeSmallObjects(mask: np.ndarray, minArea: int, connectivity: int = 8) ->
``uint8`` mask with values 0 and 255.
Raises:
- ValueError: If ``connectivity`` is not 4 or 8, ``minArea`` is negative, or ``mask`` is not a 2-D array or an
- image, or is empty.
+ ValueError: If ``connectivity`` is not 4 or 8, ``minArea`` is negative or not finite, or ``mask`` is not a
+ 2-D array or an image, or is empty.
"""
if connectivity not in (4, 8):
raise ValueError(f"connectivity must be 4 or 8, got {connectivity}")
- if minArea < 0:
- raise ValueError(f"minArea must not be negative, got {minArea}")
+ check_finite("minArea", minArea, nonnegative=True)
fg = _foreground(mask)
_, labels, stats, _ = cv2.connectedComponentsWithStats(fg, connectivity=connectivity)
keep = stats[:, cv2.CC_STAT_AREA] >= minArea
@@ -88,6 +87,7 @@ def findContoursEx(
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.
@@ -224,29 +224,32 @@ def maskBoundingRect(mask: np.ndarray) -> tuple[int, int, int, int] | None:
return int(cols[0]), int(rows[0]), int(cols[-1] - cols[0] + 1), int(rows[-1] - rows[0] + 1)
-def applyMask(src: np.ndarray, mask: np.ndarray, background: float | Sequence[float] = 0) -> np.ndarray:
- """Keep the pixels where ``mask`` is nonzero and fill the rest with ``background``.
+def applyMask(src: np.ndarray, mask: np.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 background color.
+ and fails on float images. This works for any dtype and channel count and any fill color.
Args:
src: Image.
mask: 2-D array (or image) of the shape ``src.shape[:2]``; nonzero (or ``True``) pixels are kept.
- background: A scalar, or one value per channel of ``src``.
+ fill: Value for the pixels outside the mask: a scalar, or one value per channel of ``src`` (as ``fill``
+ in :func:`cropRect` and :func:`cropContour`).
Returns:
A new array with the dtype and shape of ``src``.
Raises:
- ValueError: If the mask shape does not match, or ``src`` is empty.
+ ValueError: If the mask shape does not match, ``src`` is empty, or ``fill`` is not finite.
"""
check_image_not_empty("src", src)
fg = _foreground(mask)
if fg.shape != src.shape[:2]:
raise ValueError(f"mask must have the shape {src.shape[:2]}, got {mask.shape[:2]}")
+ for value in np.ravel(np.asarray(fill, dtype=np.float64)).tolist():
+ check_finite("fill", value)
out = np.empty_like(src)
- out[...] = background
+ out[...] = fill
keep = fg.astype(bool)
out[keep] = src[keep]
return out
diff --git a/cv2u/imgproc/palette.py b/cv2u/imgproc/palette.py
new file mode 100644
index 0000000..fe466b8
--- /dev/null
+++ b/cv2u/imgproc/palette.py
@@ -0,0 +1,327 @@
+"""Color arithmetic on BGR tuples: lighten, blend, compare, name and generate colors for drawing.
+
+OpenCV converts whole images between color spaces but has nothing for a single color: lightening a box color
+for its fill, picking black or white text for a background, or naming the dominant color all start with a 1x1
+``cv.cvtColor`` and some arithmetic. Colors here are BGR tuples of ints in ``[0, 255]``, as drawn by ``cv.rectangle``.
+"""
+
+from collections.abc import Sequence
+
+import cv2
+import numpy as np
+
+from .._validate import check_finite
+from .color import hexToBGR
+from .draw import _luminance
+
+__all__ = [
+ "CSS_COLORS",
+ "blendColors",
+ "colorDistance",
+ "colorName",
+ "colormapPalette",
+ "complementaryColor",
+ "darkenColor",
+ "gradientPalette",
+ "invertColor",
+ "lightenColor",
+ "nearestColor",
+ "randomColors",
+ "textColorFor",
+]
+
+Color = tuple[int, int, int]
+
+_CSS_HEX = {
+ "aliceblue": "f0f8ff", "antiquewhite": "faebd7", "aqua": "00ffff", "aquamarine": "7fffd4", "azure": "f0ffff",
+ "beige": "f5f5dc", "bisque": "ffe4c4", "black": "000000", "blanchedalmond": "ffebcd", "blue": "0000ff",
+ "blueviolet": "8a2be2", "brown": "a52a2a", "burlywood": "deb887", "cadetblue": "5f9ea0", "chartreuse": "7fff00",
+ "chocolate": "d2691e", "coral": "ff7f50", "cornflowerblue": "6495ed", "cornsilk": "fff8dc", "crimson": "dc143c",
+ "cyan": "00ffff", "darkblue": "00008b", "darkcyan": "008b8b", "darkgoldenrod": "b8860b", "darkgray": "a9a9a9",
+ "darkgreen": "006400", "darkgrey": "a9a9a9", "darkkhaki": "bdb76b", "darkmagenta": "8b008b",
+ "darkolivegreen": "556b2f", "darkorange": "ff8c00", "darkorchid": "9932cc", "darkred": "8b0000",
+ "darksalmon": "e9967a", "darkseagreen": "8fbc8f", "darkslateblue": "483d8b", "darkslategray": "2f4f4f",
+ "darkslategrey": "2f4f4f", "darkturquoise": "00ced1", "darkviolet": "9400d3", "deeppink": "ff1493",
+ "deepskyblue": "00bfff", "dimgray": "696969", "dimgrey": "696969", "dodgerblue": "1e90ff", "firebrick": "b22222",
+ "floralwhite": "fffaf0", "forestgreen": "228b22", "fuchsia": "ff00ff", "gainsboro": "dcdcdc",
+ "ghostwhite": "f8f8ff", "gold": "ffd700", "goldenrod": "daa520", "gray": "808080", "green": "008000",
+ "greenyellow": "adff2f", "grey": "808080", "honeydew": "f0fff0", "hotpink": "ff69b4", "indianred": "cd5c5c",
+ "indigo": "4b0082", "ivory": "fffff0", "khaki": "f0e68c", "lavender": "e6e6fa", "lavenderblush": "fff0f5",
+ "lawngreen": "7cfc00", "lemonchiffon": "fffacd", "lightblue": "add8e6", "lightcoral": "f08080",
+ "lightcyan": "e0ffff", "lightgoldenrodyellow": "fafad2", "lightgray": "d3d3d3", "lightgreen": "90ee90",
+ "lightgrey": "d3d3d3", "lightpink": "ffb6c1", "lightsalmon": "ffa07a", "lightseagreen": "20b2aa",
+ "lightskyblue": "87cefa", "lightslategray": "778899", "lightslategrey": "778899", "lightsteelblue": "b0c4de",
+ "lightyellow": "ffffe0", "lime": "00ff00", "limegreen": "32cd32", "linen": "faf0e6", "magenta": "ff00ff",
+ "maroon": "800000", "mediumaquamarine": "66cdaa", "mediumblue": "0000cd", "mediumorchid": "ba55d3",
+ "mediumpurple": "9370db", "mediumseagreen": "3cb371", "mediumslateblue": "7b68ee",
+ "mediumspringgreen": "00fa9a", "mediumturquoise": "48d1cc", "mediumvioletred": "c71585",
+ "midnightblue": "191970", "mintcream": "f5fffa", "mistyrose": "ffe4e1", "moccasin": "ffe4b5",
+ "navajowhite": "ffdead", "navy": "000080", "oldlace": "fdf5e6", "olive": "808000", "olivedrab": "6b8e23",
+ "orange": "ffa500", "orangered": "ff4500", "orchid": "da70d6", "palegoldenrod": "eee8aa", "palegreen": "98fb98",
+ "paleturquoise": "afeeee", "palevioletred": "db7093", "papayawhip": "ffefd5", "peachpuff": "ffdab9",
+ "peru": "cd853f", "pink": "ffc0cb", "plum": "dda0dd", "powderblue": "b0e0e6", "purple": "800080",
+ "rebeccapurple": "663399", "red": "ff0000", "rosybrown": "bc8f8f", "royalblue": "4169e1",
+ "saddlebrown": "8b4513", "salmon": "fa8072", "sandybrown": "f4a460", "seagreen": "2e8b57", "seashell": "fff5ee",
+ "sienna": "a0522d", "silver": "c0c0c0", "skyblue": "87ceeb", "slateblue": "6a5acd", "slategray": "708090",
+ "slategrey": "708090", "snow": "fffafa", "springgreen": "00ff7f", "steelblue": "4682b4", "tan": "d2b48c",
+ "teal": "008080", "thistle": "d8bfd8", "tomato": "ff6347", "turquoise": "40e0d0", "violet": "ee82ee",
+ "wheat": "f5deb3", "white": "ffffff", "whitesmoke": "f5f5f5", "yellow": "ffff00", "yellowgreen": "9acd32",
+} # fmt: skip
+
+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."""
+
+
+def _color(name: str, color: Sequence[float]) -> Color:
+ """Validate a BGR color and return it as a tuple of 3 ints in [0, 255]."""
+ values = [float(c) for c in color]
+ if len(values) < 3:
+ raise ValueError(f"{name} must be a BGR color with 3 values, got {color!r}")
+ if not all(np.isfinite(v) and 0 <= v <= 255 for v in values[:3]):
+ raise ValueError(f"{name} must have values in [0, 255], got {color!r}")
+ return round(values[0]), round(values[1]), round(values[2])
+
+
+def _convert(color: Color, code: int) -> np.ndarray:
+ """Convert one 8-bit BGR color through ``cv.cvtColor`` in float32 (full-range H 0-360, L/S/Lab unscaled)."""
+ pixel = np.array([[color]], dtype=np.float32) / 255.0
+ out: np.ndarray = cv2.cvtColor(pixel, code)[0, 0]
+ return out
+
+
+def _from_hls(hls: np.ndarray) -> Color:
+ bgr = cv2.cvtColor(np.array([[hls]], dtype=np.float32), cv2.COLOR_HLS2BGR)[0, 0] * 255.0
+ b, g, r = np.clip(np.rint(bgr), 0, 255)
+ return int(b), int(g), int(r)
+
+
+def _amount(amount: float) -> float:
+ check_finite("amount", amount)
+ if not 0 <= amount <= 1:
+ raise ValueError(f"amount must be in [0, 1], got {amount}")
+ return float(amount)
+
+
+def 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``.
+
+ Args:
+ color: BGR color.
+ amount: 0 leaves the color as is, 1 gives white.
+
+ Raises:
+ ValueError: If ``color`` is not a BGR color in ``[0, 255]`` or ``amount`` is not in ``[0, 1]``.
+ """
+ bgr, t = _color("color", color), _amount(amount)
+ hls = _convert(bgr, cv2.COLOR_BGR2HLS)
+ hls[1] = hls[1] + (1.0 - hls[1]) * t
+ return _from_hls(hls)
+
+
+def 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``.
+
+ Args:
+ color: BGR color.
+ amount: 0 leaves the color as is, 1 gives black.
+
+ Raises:
+ ValueError: If ``color`` is not a BGR color in ``[0, 255]`` or ``amount`` is not in ``[0, 1]``.
+ """
+ bgr, t = _color("color", color), _amount(amount)
+ hls = _convert(bgr, cv2.COLOR_BGR2HLS)
+ hls[1] = hls[1] * (1.0 - t)
+ return _from_hls(hls)
+
+
+def 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:
+ ValueError: If a color is not a BGR color in ``[0, 255]`` or ``t`` is not in ``[0, 1]``.
+ """
+ ca, cb = _color("a", a), _color("b", b)
+ check_finite("t", t)
+ if not 0 <= t <= 1:
+ raise ValueError(f"t must be in [0, 1], got {t}")
+ mixed = [round(x + (y - x) * t) for x, y in zip(ca, cb, strict=True)]
+ return mixed[0], mixed[1], mixed[2]
+
+
+def 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:
+ ValueError: If ``color`` is not a BGR color in ``[0, 255]``.
+ """
+ hls = _convert(_color("color", color), cv2.COLOR_BGR2HLS)
+ hls[0] = (hls[0] + 180.0) % 360.0
+ return _from_hls(hls)
+
+
+def invertColor(color: Sequence[float]) -> Color:
+ """The negative of a BGR color: ``255 - value`` per channel, like ``cv.bitwise_not`` on a pixel.
+
+ Raises:
+ ValueError: If ``color`` is not a BGR color in ``[0, 255]``.
+ """
+ b, g, r = _color("color", color)
+ return 255 - b, 255 - g, 255 - r
+
+
+def 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.
+
+ Args:
+ a: First BGR color.
+ b: Second BGR color.
+ space: ``"lab"`` for CIE76 ΔE (perceptual) or ``"bgr"`` for plain Euclidean distance in ``[0, 441]``.
+
+ Raises:
+ ValueError: If a color is not a BGR color in ``[0, 255]`` or ``space`` is unknown.
+ """
+ ca, cb = _color("a", a), _color("b", b)
+ if space == "lab":
+ la, lb = _convert(ca, cv2.COLOR_BGR2Lab), _convert(cb, cv2.COLOR_BGR2Lab)
+ return float(np.linalg.norm(la - lb))
+ if space == "bgr":
+ return float(np.linalg.norm(np.subtract(ca, cb, dtype=np.float64)))
+ raise ValueError(f"space must be 'lab' or 'bgr', got {space!r}")
+
+
+def _lab_table(colors: np.ndarray) -> np.ndarray:
+ """Lab values of an ``(N, 3)`` 8-bit BGR array, as float32 ``(N, 3)``."""
+ lab: np.ndarray = cv2.cvtColor(colors.reshape(1, -1, 3).astype(np.float32) / 255.0, cv2.COLOR_BGR2Lab)
+ return lab.reshape(-1, 3)
+
+
+def nearestColor(color: Sequence[float], palette: Sequence[Sequence[float]] | np.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.
+
+ Args:
+ color: BGR color.
+ palette: BGR colors, as a sequence of tuples or an array of shape ``(N, 3)``.
+ space: ``"lab"`` or ``"bgr"``, as for :func:`colorDistance`.
+
+ Raises:
+ ValueError: If ``color`` or a palette entry is not a BGR color in ``[0, 255]``, the palette is empty, or
+ ``space`` is unknown.
+ """
+ if space not in ("lab", "bgr"):
+ raise ValueError(f"space must be 'lab' or 'bgr', got {space!r}")
+ target = np.array(_color("color", color), dtype=np.float64)
+ entries = np.asarray(palette, dtype=np.float64).reshape(-1, 3) if len(palette) else np.empty((0, 3))
+ if entries.shape[0] == 0:
+ raise ValueError("palette must not be empty")
+ if not (np.all(np.isfinite(entries)) and np.all((entries >= 0) & (entries <= 255))):
+ raise ValueError("palette must hold BGR colors with values in [0, 255]")
+ if space == "lab":
+ table = _lab_table(np.rint(entries).astype(np.uint8))
+ target = _lab_table(np.rint(target).astype(np.uint8)[None])[0]
+ else:
+ table = entries
+ return int(np.argmin(np.linalg.norm(table - target, axis=1)))
+
+
+_CSS_NAMES = list(CSS_COLORS)
+_CSS_BGR = np.array(list(CSS_COLORS.values()), dtype=np.uint8)
+_CSS_LAB = _lab_table(_CSS_BGR)
+
+
+def 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:
+ ValueError: If ``color`` is not a BGR color in ``[0, 255]``.
+ """
+ target = _lab_table(np.array([_color("color", color)], dtype=np.uint8))[0]
+ return _CSS_NAMES[int(np.argmin(np.linalg.norm(_CSS_LAB - target, axis=1)))]
+
+
+def textColorFor(background: Sequence[float]) -> Color:
+ """Black or white, whichever reads better on ``background``; the rule used by :func:`drawLabel`.
+
+ Returns:
+ ``(0, 0, 0)`` for light backgrounds (luminance above 140) and ``(255, 255, 255)`` for dark ones.
+
+ Raises:
+ ValueError: If ``background`` is not a BGR color in ``[0, 255]``.
+ """
+ return (0, 0, 0) if _luminance(_color("background", background)) > 140 else (255, 255, 255)
+
+
+def 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.
+
+ Args:
+ count: How many colors.
+ seed: Random seed for reproducible colors.
+ saturation: HSV saturation in ``[0, 1]``; lower is more pastel.
+ value: HSV brightness in ``[0, 1]``; lower is darker.
+
+ Raises:
+ ValueError: If ``count`` is negative or ``saturation`` / ``value`` is not in ``[0, 1]``.
+ """
+ if count < 0:
+ raise ValueError(f"count must not be negative, got {count}")
+ for name, v in (("saturation", saturation), ("value", value)):
+ check_finite(name, v)
+ if not 0 <= v <= 1:
+ raise ValueError(f"{name} must be in [0, 1], got {v}")
+ if count == 0:
+ return []
+ hues = np.random.default_rng(seed).uniform(0, 360, size=count).astype(np.float32)
+ hsv = np.stack([hues, np.full(count, saturation, np.float32), np.full(count, value, np.float32)], axis=1)
+ bgr = cv2.cvtColor(hsv.reshape(1, -1, 3), cv2.COLOR_HSV2BGR).reshape(-1, 3) * 255.0
+ return [(int(b), int(g), int(r)) for b, g, r in np.clip(np.rint(bgr), 0, 255)]
+
+
+def gradientPalette(start: Sequence[float], end: Sequence[float], count: int) -> list[Color]:
+ """``count`` BGR colors interpolated linearly from ``start`` to ``end`` (both included).
+
+ Args:
+ start: First color.
+ end: Last color.
+ count: How many colors; 1 gives ``[start]``.
+
+ Raises:
+ ValueError: If a color is not a BGR color in ``[0, 255]`` or ``count`` is negative.
+ """
+ a, b = np.array(_color("start", start), np.float64), np.array(_color("end", end), np.float64)
+ if count < 0:
+ raise ValueError(f"count must not be negative, got {count}")
+ steps = np.linspace(0.0, 1.0, count) if count > 1 else np.zeros(count)
+ colors = np.rint(a + (b - a) * steps[:, None]).astype(int)
+ return [(int(c[0]), int(c[1]), int(c[2])) for c in colors]
+
+
+def 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.
+
+ Args:
+ colormap: ``cv.COLORMAP_*`` constant.
+ count: How many colors, from the darkest end (0) to the brightest (255) of the map.
+
+ Raises:
+ ValueError: If ``count`` is negative.
+ """
+ if count < 0:
+ raise ValueError(f"count must not be negative, got {count}")
+ if count == 0:
+ return []
+ levels = np.rint(np.linspace(0, 255, count)).astype(np.uint8) if count > 1 else np.array([0], np.uint8)
+ bgr = cv2.applyColorMap(levels.reshape(1, -1), colormap).reshape(-1, 3)
+ return [(int(b), int(g), int(r)) for b, g, r in bgr]
diff --git a/cv2u/imgproc/puttext.py b/cv2u/imgproc/puttext.py
index d7e1d62..a761fce 100644
--- a/cv2u/imgproc/puttext.py
+++ b/cv2u/imgproc/puttext.py
@@ -2,10 +2,11 @@
from collections.abc import Sequence
from functools import lru_cache
-import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
+from .._validate import check_channels, check_color, check_image_not_empty
+
__all__ = ["putTextEx"]
@@ -14,34 +15,61 @@ def _load_font(path: str, size: int) -> ImageFont.FreeTypeFont:
return ImageFont.truetype(path, size=size)
+def _fill(color: float | Sequence[float], channels: int) -> int | tuple[int, ...]:
+ """The Pillow fill for an OpenCV color, drawn directly on the array so the channel order is kept."""
+ values = [float(color)] if isinstance(color, (int, float)) else [float(c) for c in color]
+ check_color("color", values, np.dtype(np.uint8))
+ if channels == 1:
+ if len(values) >= 3:
+ b, g, r = values[:3]
+ values = [0.114 * b + 0.587 * g + 0.299 * r] # a BGR color on a grayscale image: its luminance
+ return round(values[0])
+ if len(values) == 1:
+ values = values * 3
+ if len(values) < 3:
+ raise ValueError(f"color must be a scalar or have at least 3 values (BGR), got {color!r}")
+ bgr = tuple(round(v) for v in values[:3])
+ return (*bgr, round(values[3]) if len(values) > 3 else 255) if channels == 4 else bgr
+
+
def putTextEx(
- src: np.ndarray,
+ img: np.ndarray,
text: str,
org: tuple[int, int],
fontPath: str | os.PathLike[str],
fontSize: int,
- color: Sequence[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.
+ ``cv.putText`` only supports the built-in Hershey fonts, which cover ASCII only. Like ``cv.putText``, this
+ draws **in place** and returns ``img``.
Args:
- src: 8-bit image. Grayscale input is converted to 3 channels.
+ img: 8-bit grayscale, BGR or BGRA image to draw on. Grayscale images stay grayscale.
text: Text to draw. ``\\n`` starts a new line.
org: Top-left corner of the text, as ``(x, y)``. Note that ``cv.putText`` uses the
bottom-left corner instead.
fontPath: Path to a ``.ttf``/``.otf``/``.ttc`` font file. Loaded fonts are cached.
fontSize: Font size in pixels.
- color: Text color in the image's channel order (BGR for OpenCV images).
+ color: Text color (BGR, or a scalar). On grayscale images, the luminance of a BGR color is used.
Returns:
- A new image with the text drawn; ``src`` is not modified.
- """
- if src.ndim == 2 or src.shape[2] == 1:
- src = cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)
+ ``img``, with the text drawn on it.
+ Raises:
+ ValueError: If ``img`` is not 8-bit, is empty or has an unsupported channel count, ``fontSize`` is not
+ positive, or ``color`` is outside ``[0, 255]``.
+ """
+ if img.dtype != np.uint8:
+ raise ValueError(f"img must be an 8-bit (uint8) image, got dtype {img.dtype}")
+ check_image_not_empty("img", img)
+ channels = check_channels("img", img)
+ if fontSize < 1:
+ raise ValueError(f"fontSize must be positive, got {fontSize}")
+ fill = _fill(color, channels)
font = _load_font(os.fspath(fontPath), fontSize)
- dst = Image.fromarray(src)
- ImageDraw.Draw(dst).text(org, text, font=font, fill=tuple(color))
- return np.array(dst)
+ canvas = Image.fromarray(np.ascontiguousarray(img.reshape(img.shape[:2]) if channels == 1 else img))
+ ImageDraw.Draw(canvas).text(org, text, font=font, fill=fill)
+ img[...] = np.asarray(canvas).reshape(img.shape)
+ return img
diff --git a/cv2u/imgproc/quality.py b/cv2u/imgproc/quality.py
index 35e13cf..1ea364f 100644
--- a/cv2u/imgproc/quality.py
+++ b/cv2u/imgproc/quality.py
@@ -17,6 +17,9 @@ def sharpnessScore(src: np.ndarray) -> float:
Args:
src: Grayscale, BGR or BGRA image.
+
+ Raises:
+ ValueError: If ``src`` is empty or has an unsupported channel count.
"""
laplacian = cv2.Laplacian(toGray(src).astype(np.float64), cv2.CV_64F)
return float(laplacian.var())
@@ -63,7 +66,7 @@ def blur(img: np.ndarray) -> np.ndarray:
return float(ssim_map.mean())
-def diffMask(a: np.ndarray, b: np.ndarray, threshold: float = 25, minArea: int = 0) -> np.ndarray:
+def diffMask(a: np.ndarray, b: np.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.
Args:
@@ -80,8 +83,7 @@ def diffMask(a: np.ndarray, b: np.ndarray, threshold: float = 25, minArea: int =
"""
_check_pair(a, b)
check_finite("threshold", threshold, nonnegative=True)
- if minArea < 0:
- raise ValueError(f"minArea must not be negative, got {minArea}")
+ check_finite("minArea", minArea, nonnegative=True)
difference = cv2.absdiff(a, b)
if difference.ndim == 3:
difference = difference.max(axis=2)
@@ -109,7 +111,8 @@ def imageHash(src: np.ndarray, hashSize: int = 8, method: str = "difference") ->
The hash as a non-negative integer (e.g. ``format(h, "016x")`` for a 64-bit hex string).
Raises:
- ValueError: If ``hashSize`` is below 2 or ``method`` is unknown.
+ ValueError: If ``src`` is empty or has an unsupported channel count, ``hashSize`` is below 2, or ``method``
+ is unknown.
"""
if hashSize < 2:
raise ValueError(f"hashSize must be at least 2, got {hashSize}")
diff --git a/cv2u/imgproc/resize.py b/cv2u/imgproc/resize.py
index 86902ca..aee6573 100644
--- a/cv2u/imgproc/resize.py
+++ b/cv2u/imgproc/resize.py
@@ -1,11 +1,24 @@
from collections.abc import Sequence
+from typing import NamedTuple
import cv2
import numpy as np
from .._validate import check_color, check_image_not_empty
-__all__ = ["letterbox", "resizeEx"]
+__all__ = ["Letterbox", "letterbox", "resizeEx"]
+
+
+class Letterbox(NamedTuple):
+ """The result of :func:`letterbox`: the padded image and how to map coordinates back."""
+
+ image: np.ndarray
+ """The resized and padded image, of the requested size."""
+ scale: float
+ """Factor the source was resized by."""
+ 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."""
def _default_interpolation(scale: float) -> int:
@@ -30,8 +43,11 @@ def resizeEx(
interpolation: ``cv.INTER_*`` flag. By default ``cv.INTER_AREA`` when shrinking and ``cv.INTER_LINEAR``
when enlarging, as recommended by OpenCV.
+ Returns:
+ The resized image.
+
Raises:
- ValueError: If neither ``width`` nor ``height`` is given, or a size is not positive.
+ ValueError: If ``src`` is empty, neither ``width`` nor ``height`` is given, or a size is not positive.
"""
if width is None and height is None:
raise ValueError("give width, height or both")
@@ -62,7 +78,7 @@ def letterbox(
size: tuple[int, int],
color: float | Sequence[float] = 0,
interpolation: int | None = None,
-) -> tuple[np.ndarray, float, tuple[int, int]]:
+) -> 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.
@@ -74,8 +90,8 @@ def letterbox(
interpolation: ``cv.INTER_*`` flag; chosen like in :func:`resizeEx` by default.
Returns:
- ``(dst, scale, (left, top))``. A point ``(x, y)`` in ``src`` is at ``(x * scale + left, y * scale + top)``
- in ``dst``.
+ :class:`Letterbox` ``(image, scale, (left, top))``. A point ``(x, y)`` in ``src`` is at
+ ``(x * scale + left, y * scale + top)`` in ``image``.
Raises:
ValueError: If ``size`` is not positive, ``src`` is empty, or ``color`` is not finite.
@@ -95,4 +111,4 @@ def letterbox(
right, bottom = out_w - new_w - left, out_h - new_h - top
value = [float(color)] * 4 if isinstance(color, (int, float)) else [float(c) for c in color]
dst: np.ndarray = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=value)
- return dst, scale, (left, top)
+ return Letterbox(dst, scale, (left, top))
diff --git a/cv2u/imgproc/stats.py b/cv2u/imgproc/stats.py
new file mode 100644
index 0000000..9315c8f
--- /dev/null
+++ b/cv2u/imgproc/stats.py
@@ -0,0 +1,518 @@
+"""Image statistics and quality checks: brightness, contrast, noise, entropy, histograms, blank/blurry tests."""
+
+import math
+from typing import Any, NamedTuple
+
+import cv2
+import numpy as np
+
+from .._validate import check_finite, check_image_not_empty, to_uint8
+from .color import toBGR, toGray
+from .quality import sharpnessScore
+
+__all__ = [
+ "ImageStats",
+ "brightnessScore",
+ "colorfulness",
+ "contrastScore",
+ "dominantHue",
+ "entropy",
+ "estimateNoise",
+ "exposureScore",
+ "histogramCompare",
+ "histogramEx",
+ "imageStats",
+ "isBlank",
+ "isBlurry",
+ "isGrayscale",
+ "mae",
+ "meanColor",
+ "mse",
+]
+
+
+def _peak(dtype: np.dtype[Any]) -> float:
+ """Largest value of the dtype: 255 for 8-bit, 65535 for 16-bit, 1.0 for float images."""
+ return float(np.iinfo(dtype).max) if np.issubdtype(dtype, np.integer) else 1.0
+
+
+def _gray64(src: np.ndarray) -> np.ndarray:
+ """Grayscale ``float64`` copy of any supported image (validates channels and emptiness)."""
+ return toGray(src).astype(np.float64)
+
+
+def _brightness(gray: np.ndarray, peak: float) -> float:
+ return float(gray.mean() / peak)
+
+
+def _contrast(gray: np.ndarray, peak: float) -> float:
+ return float(gray.std() / peak)
+
+
+def _sharpness(gray: np.ndarray) -> float:
+ laplacian = cv2.Laplacian(gray, cv2.CV_64F)
+ return float(laplacian.var())
+
+
+def _entropy(counts: np.ndarray) -> float:
+ probabilities = counts[counts > 0] / counts.sum()
+ return float(-(probabilities * np.log2(probabilities)).sum())
+
+
+def _is_grayscale(color: np.ndarray, tolerance: float) -> bool:
+ if color.shape[2] == 1:
+ return True
+ values = color.astype(np.float64)
+ spread = values.max(axis=2) - values.min(axis=2)
+ return bool(np.max(spread) <= tolerance)
+
+
+def _color_channels(src: np.ndarray) -> np.ndarray:
+ """The image without its alpha channel, as a ``(h, w, c)`` array."""
+ check_image_not_empty("src", src)
+ if src.ndim == 2:
+ return src[..., np.newaxis]
+ if src.ndim != 3 or src.shape[2] not in (1, 3, 4):
+ raise ValueError(f"src must have 1, 3 or 4 channels, got shape {src.shape}")
+ return src[..., :3]
+
+
+def _check_pair(a: np.ndarray, b: np.ndarray) -> None:
+ if a.shape != b.shape:
+ raise ValueError(f"a and b must have the same shape, got {a.shape} and {b.shape}")
+ check_image_not_empty("a", a)
+
+
+def _check_mask(src: np.ndarray, mask: np.ndarray | None) -> np.ndarray | None:
+ if mask is None:
+ return None
+ if mask.shape[:2] != src.shape[:2]:
+ raise ValueError(f"mask must be {src.shape[1]}x{src.shape[0]}, got shape {mask.shape}")
+ keep: np.ndarray = mask.reshape(mask.shape[:2]) != 0
+ return keep
+
+
+class ImageStats(NamedTuple):
+ """Summary of an image as returned by ``imageStats``."""
+
+ width: int
+ height: int
+ channels: int
+ dtype: str
+ mean: tuple[float, ...]
+ """Mean of each channel (alpha included for BGRA)."""
+ std: tuple[float, ...]
+ """Standard deviation of each channel."""
+ minVal: float
+ maxVal: float
+ brightness: float
+ """Mean gray level in ``[0, 1]`` (see ``brightnessScore``)."""
+ contrast: float
+ """RMS contrast in ``[0, 1]`` (see ``contrastScore``)."""
+ sharpness: float
+ """Variance of the Laplacian (see ``sharpnessScore``)."""
+ entropy: float
+ """Shannon entropy of the gray histogram in bits (see ``entropy``)."""
+ isGray: bool
+ """``True`` when the image is 2-D or all its color channels are equal."""
+
+
+def isGrayscale(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ tolerance: Largest allowed difference between the channels of any pixel (0 means exactly equal; a few
+ levels absorb JPEG chroma noise).
+
+ Raises:
+ ValueError: If ``src`` is empty, has a wrong channel count, or ``tolerance`` is negative.
+ """
+ check_finite("tolerance", tolerance, nonnegative=True)
+ return _is_grayscale(_color_channels(src), tolerance)
+
+
+def isBlank(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ tolerance: 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).
+
+ Raises:
+ ValueError: If ``src`` is empty, has a wrong channel count, or ``tolerance`` is negative.
+ """
+ check_finite("tolerance", tolerance, nonnegative=True)
+ color = _color_channels(src).astype(np.float64)
+ return bool(np.max(color.reshape(-1, color.shape[2]).std(axis=0)) <= tolerance)
+
+
+def isBlurry(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ threshold: Sharpness score below which the image counts as blurry.
+
+ Raises:
+ ValueError: If ``src`` is empty, has a wrong channel count, or ``threshold`` is not finite or negative.
+ """
+ check_finite("threshold", threshold, nonnegative=True)
+ return sharpnessScore(src) < threshold
+
+
+def brightnessScore(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count.
+ """
+ return _brightness(_gray64(src), _peak(src.dtype))
+
+
+def contrastScore(src: np.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``.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count.
+ """
+ return _contrast(_gray64(src), _peak(src.dtype))
+
+
+def colorfulness(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count.
+ """
+ color = _color_channels(src)
+ if color.shape[2] == 1:
+ return 0.0
+ values = color.astype(np.float64) * (255.0 / _peak(src.dtype))
+ b, g, r = values[..., 0], values[..., 1], values[..., 2]
+ rg = r - g
+ yb = 0.5 * (r + g) - b
+ std_root = math.hypot(float(rg.std()), float(yb.std()))
+ mean_root = math.hypot(float(rg.mean()), float(yb.mean()))
+ return std_root + 0.3 * mean_root
+
+
+def exposureScore(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ lowThreshold: Gray level (normalized to ``[0, 1]``) at or below which a pixel counts as under-exposed.
+ highThreshold: Gray level (normalized to ``[0, 1]``) at or above which a pixel counts as over-exposed.
+
+ Returns:
+ ``(underExposed, overExposed)``, each in ``[0, 1]``.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count, or a threshold is outside ``[0, 1]`` or
+ ``lowThreshold`` exceeds ``highThreshold``.
+ """
+ for name, value in (("lowThreshold", lowThreshold), ("highThreshold", highThreshold)):
+ check_finite(name, value, nonnegative=True)
+ if value > 1:
+ raise ValueError(f"{name} must be within [0, 1], got {value}")
+ if lowThreshold > highThreshold:
+ raise ValueError(f"lowThreshold must not exceed highThreshold, got {lowThreshold} and {highThreshold}")
+ gray = _gray64(src) / _peak(src.dtype)
+ return float((gray <= lowThreshold).mean()), float((gray >= highThreshold).mean())
+
+
+def _gray_histogram(gray: np.ndarray, bins: int, peak: float) -> np.ndarray:
+ """Histogram of a grayscale image (any dtype) over ``[0, peak]``; ``float64`` input is binned directly."""
+ if gray.dtype == np.uint8 and bins == 256:
+ return np.bincount(gray.ravel(), minlength=256).astype(np.float64)
+ counts, _ = np.histogram(gray.astype(np.float64), bins=bins, range=(0.0, peak))
+ return counts.astype(np.float64)
+
+
+def entropy(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ bins: Number of histogram bins over the dtype range (``[0, 255]`` for 8-bit, ``[0, 1]`` for float).
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count, or ``bins`` is below 1.
+ """
+ if bins < 1:
+ raise ValueError(f"bins must be at least 1, got {bins}")
+ return _entropy(_gray_histogram(toGray(src), bins, _peak(src.dtype)))
+
+
+_NOISE_KERNEL = np.array([[1, -2, 1], [-2, 4, -2], [1, -2, 1]], dtype=np.float64)
+
+
+def estimateNoise(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image, at least 3x3 pixels.
+
+ Returns:
+ The noise sigma in the units of the image (gray levels for 8-bit).
+
+ Raises:
+ ValueError: If ``src`` is empty, has a wrong channel count or is smaller than 3x3.
+ """
+ gray = _gray64(src)
+ height, width = gray.shape
+ if height < 3 or width < 3:
+ raise ValueError(f"src must be at least 3x3 pixels, got {width}x{height}")
+ response: np.ndarray = cv2.filter2D(gray, cv2.CV_64F, _NOISE_KERNEL, borderType=cv2.BORDER_REPLICATE)
+ total = float(np.abs(response[1:-1, 1:-1]).sum())
+ return float(total * math.sqrt(math.pi / 2) / (6 * (width - 2) * (height - 2)))
+
+
+def mse(a: np.ndarray, b: np.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:
+ ValueError: If the shapes differ or the images are empty.
+ """
+ _check_pair(a, b)
+ difference = a.astype(np.float64) - b.astype(np.float64)
+ return float((difference * difference).mean())
+
+
+def mae(a: np.ndarray, b: np.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:
+ ValueError: If the shapes differ or the images are empty.
+ """
+ _check_pair(a, b)
+ return float(np.abs(a.astype(np.float64) - b.astype(np.float64)).mean())
+
+
+def histogramEx(
+ src: np.ndarray,
+ bins: int = 256,
+ mask: np.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).
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ bins: Number of bins per channel.
+ mask: Optional ``uint8`` mask of the same height and width; only pixels where it is non-zero are counted.
+ channels: Channel indices to include (all by default).
+ normalize: Divide each row by its sum so the rows are probability distributions.
+
+ Returns:
+ ``float64`` array of shape ``(len(channels), bins)``.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count, ``bins`` is below 1, a channel index is out of
+ range, or the mask has a different size.
+ """
+ if bins < 1:
+ raise ValueError(f"bins must be at least 1, got {bins}")
+ check_image_not_empty("src", src)
+ image = src[..., np.newaxis] if src.ndim == 2 else src
+ if image.ndim != 3:
+ raise ValueError(f"src must be a 2-D or 3-D image, got shape {src.shape}")
+ count = int(image.shape[2])
+ indices = list(range(count)) if channels is None else list(channels)
+ if any(not 0 <= c < count for c in indices):
+ raise ValueError(f"channels must be within [0, {count - 1}], got {indices}")
+ keep = _check_mask(src, mask)
+ peak = _peak(src.dtype)
+ rows = []
+ for c in indices:
+ values = image[..., c].astype(np.float64)
+ if keep is not None:
+ values = values[keep]
+ counts, _ = np.histogram(values, bins=bins, range=(0.0, peak))
+ row = counts.astype(np.float64)
+ if normalize and row.sum() > 0:
+ row /= row.sum()
+ rows.append(row)
+ return np.stack(rows)
+
+
+def histogramCompare(
+ a: np.ndarray,
+ b: np.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.
+
+ Args:
+ a: First image (grayscale, BGR or BGRA).
+ b: Second image; may have a different size or channel count.
+ method: ``cv.HISTCMP_*`` method. For ``HISTCMP_CORREL`` and ``HISTCMP_INTERSECT`` higher means more similar;
+ for ``HISTCMP_CHISQR``, ``HISTCMP_BHATTACHARYYA`` and ``HISTCMP_HELLINGER`` lower means more similar.
+ bins: Bins per channel.
+ colorSpace: ``"hsv"`` (joint hue-saturation histogram, robust to brightness changes), ``"bgr"`` (joint
+ 3-D color histogram) or ``"gray"`` (1-D intensity histogram).
+
+ Raises:
+ ValueError: If an image is empty or has a wrong channel count, ``bins`` is below 1 or ``colorSpace`` is unknown.
+ """
+ if bins < 1:
+ raise ValueError(f"bins must be at least 1, got {bins}")
+ if colorSpace not in ("hsv", "bgr", "gray"):
+ raise ValueError(f'colorSpace must be "hsv", "bgr" or "gray", got {colorSpace!r}')
+
+ def histogram(src: np.ndarray) -> np.ndarray:
+ image = to_uint8(src)
+ if colorSpace == "gray":
+ image, channels, ranges = toGray(image), [0], [0.0, 256.0]
+ elif colorSpace == "hsv":
+ image = cv2.cvtColor(toBGR(image), cv2.COLOR_BGR2HSV)
+ channels, ranges = [0, 1], [0.0, 180.0, 0.0, 256.0]
+ else:
+ image, channels, ranges = toBGR(image), [0, 1, 2], [0.0, 256.0] * 3
+ hist: np.ndarray = cv2.calcHist([image], channels, None, [bins] * len(channels), ranges)
+ return hist / max(float(hist.sum()), 1.0)
+
+ return float(cv2.compareHist(histogram(a), histogram(b), method))
+
+
+def dominantHue(src: np.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).
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+ bins: Number of hue bins over the circle.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count, or ``bins`` is below 1.
+ """
+ if bins < 1:
+ raise ValueError(f"bins must be at least 1, got {bins}")
+ color = _color_channels(src)
+ if color.shape[2] == 1:
+ return 0.0
+ hsv = cv2.cvtColor(toBGR(to_uint8(src)), cv2.COLOR_BGR2HSV_FULL)
+ hue = hsv[..., 0].astype(np.float64) * (360.0 / 256.0)
+ weight = hsv[..., 1].astype(np.float64) * (hsv[..., 2].astype(np.float64) / 255.0)
+ if weight.sum() == 0:
+ return 0.0
+ counts, edges = np.histogram(hue, bins=bins, range=(0.0, 360.0), weights=weight)
+ peak = int(np.argmax(counts))
+ inside = (hue >= edges[peak]) & (hue < edges[peak + 1])
+ radians = np.deg2rad(hue[inside])
+ w = weight[inside]
+ angle = math.degrees(math.atan2(float((w * np.sin(radians)).sum()), float((w * np.cos(radians)).sum())))
+ return angle % 360.0
+
+
+def meanColor(src: np.ndarray, mask: np.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.
+
+ Args:
+ src: Image of any dtype with 1, 3 or 4 channels.
+ mask: Optional mask of the same height and width; only pixels where it is non-zero are averaged.
+
+ Returns:
+ A tuple with one ``float`` per channel of ``src`` (zeros when the mask selects no pixel).
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count, or the mask has a different size.
+ """
+ _color_channels(src)
+ image = src[..., np.newaxis] if src.ndim == 2 else src
+ keep = _check_mask(src, mask)
+ values = image.reshape(-1, image.shape[2]) if keep is None else image[keep]
+ if values.shape[0] == 0:
+ return tuple(0.0 for _ in range(image.shape[2]))
+ return tuple(float(v) for v in values.astype(np.float64).mean(axis=0))
+
+
+def imageStats(src: np.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.
+
+ Args:
+ src: Grayscale, BGR or BGRA image.
+
+ Raises:
+ ValueError: If ``src`` is empty or has a wrong channel count.
+ """
+ color = _color_channels(src)
+ image = src[..., np.newaxis] if src.ndim == 2 else src
+ flat = image.reshape(-1, image.shape[2]).astype(np.float64)
+ height, width = src.shape[:2]
+ peak = _peak(src.dtype)
+ gray8 = toGray(src) # converted once; every gray-based metric derives from it
+ gray = gray8.astype(np.float64)
+ return ImageStats(
+ width=int(width),
+ height=int(height),
+ channels=int(image.shape[2]),
+ dtype=str(src.dtype),
+ mean=tuple(float(v) for v in flat.mean(axis=0)),
+ std=tuple(float(v) for v in flat.std(axis=0)),
+ minVal=float(np.min(flat)),
+ maxVal=float(np.max(flat)),
+ brightness=_brightness(gray, peak),
+ contrast=_contrast(gray, peak),
+ sharpness=_sharpness(gray),
+ entropy=_entropy(_gray_histogram(gray8, 256, peak)),
+ isGray=_is_grayscale(color, 0),
+ )
diff --git a/cv2u/imgproc/stitch.py b/cv2u/imgproc/stitch.py
new file mode 100644
index 0000000..04dbe61
--- /dev/null
+++ b/cv2u/imgproc/stitch.py
@@ -0,0 +1,120 @@
+"""Image stitching: ``cv.Stitcher`` with exceptions instead of status codes, and a two-image homography stitch."""
+
+from collections.abc import Sequence
+from typing import Literal
+
+import cv2
+import numpy as np
+
+from .._validate import check_finite, check_image_not_empty
+from .color import toBGR
+from .features import Detector, matchFeatures
+
+__all__ = ["stitchImages", "stitchPair"]
+
+_STATUS_NAMES = {
+ cv2.STITCHER_ERR_NEED_MORE_IMGS: "ERR_NEED_MORE_IMGS",
+ cv2.STITCHER_ERR_HOMOGRAPHY_EST_FAIL: "ERR_HOMOGRAPHY_EST_FAIL",
+ cv2.STITCHER_ERR_CAMERA_PARAMS_ADJUST_FAIL: "ERR_CAMERA_PARAMS_ADJUST_FAIL",
+}
+
+
+def stitchImages(
+ images: Sequence[np.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).
+
+ Args:
+ images: Two or more overlapping images, grayscale or BGR.
+ mode: ``"panorama"`` for photos taken by rotating the camera (perspective warps), ``"scans"`` for
+ flat content such as scans or aerial images (affine warps).
+ confidence: ``setPanoConfidenceThresh``; lower (e.g. ``0.3``) accepts images with less overlap or
+ texture. ``None`` keeps OpenCV's default (``1.0``).
+
+ Returns:
+ The stitched BGR image.
+
+ Raises:
+ ValueError: If fewer than 2 images are given, an image is empty, or ``mode`` is unknown.
+ RuntimeError: If the stitcher fails; the message contains the status name.
+ """
+ if len(images) < 2:
+ raise ValueError(f"images must contain at least 2 images, got {len(images)}")
+ for index, image in enumerate(images):
+ check_image_not_empty(f"images[{index}]", image)
+ if mode == "panorama":
+ stitcher = cv2.Stitcher.create(cv2.STITCHER_PANORAMA)
+ elif mode == "scans":
+ stitcher = cv2.Stitcher.create(cv2.STITCHER_SCANS)
+ else:
+ raise ValueError(f"mode must be 'panorama' or 'scans', got {mode!r}")
+ if confidence is not None:
+ check_finite("confidence", confidence, nonnegative=True)
+ stitcher.setPanoConfidenceThresh(confidence)
+ status, pano = stitcher.stitch([toBGR(image) for image in images])
+ if status != cv2.STITCHER_OK or pano is None:
+ raise RuntimeError(f"stitching failed with status {_STATUS_NAMES.get(status, status)}")
+ return pano
+
+
+def stitchPair(
+ a: np.ndarray,
+ b: np.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.
+
+ Args:
+ a: Reference image (grayscale or BGR); its plane is kept.
+ b: Image to warp onto ``a``.
+ method: Feature detector, as for :func:`matchFeatures`.
+ ratio: Lowe's ratio for the matches.
+ maxFeatures: Keypoint limit.
+ ransacThreshold: Reprojection error in pixels above which a match counts as an outlier.
+ minMatches: Fail when fewer matches pass the ratio test.
+
+ Returns:
+ The stitched image, same dtype and channel count as ``a``.
+
+ Raises:
+ ValueError: If an image is empty, too few matches are found, or the homography cannot be estimated.
+ """
+ check_image_not_empty("a", a)
+ check_image_not_empty("b", b)
+ check_finite("ransacThreshold", ransacThreshold, positive=True)
+ if minMatches < 4:
+ raise ValueError(f"minMatches must be at least 4, got {minMatches}")
+ if a.ndim == 3 and b.ndim == 2:
+ b = toBGR(b)
+ elif a.ndim == 2 and b.ndim == 3:
+ b = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY)
+ found = matchFeatures(b, a, method, maxFeatures, ratio)
+ if len(found.matches) < minMatches:
+ raise ValueError(f"only {len(found.matches)} matches found, need at least {minMatches}; try method='SIFT'")
+ matrix, _ = cv2.findHomography(found.srcPoints, found.dstPoints, cv2.RANSAC, ransacThreshold)
+ if matrix is None:
+ raise ValueError("the homography could not be estimated (matches are degenerate)")
+ ha, wa = a.shape[:2]
+ hb, wb = b.shape[:2]
+ corners_b = np.array([[0, 0], [wb, 0], [wb, hb], [0, hb]], np.float32).reshape(-1, 1, 2)
+ warped = cv2.perspectiveTransform(corners_b, matrix).reshape(-1, 2)
+ corners_a = np.array([[0, 0], [wa, 0], [wa, ha], [0, ha]], np.float32)
+ all_corners = np.vstack([corners_a, warped])
+ x_min, y_min = np.floor(all_corners.min(axis=0)).astype(int)
+ x_max, y_max = np.ceil(all_corners.max(axis=0)).astype(int)
+ shift = np.array([[1, 0, -x_min], [0, 1, -y_min], [0, 0, 1]], np.float64)
+ canvas = cv2.warpPerspective(b, shift @ matrix, (int(x_max - x_min), int(y_max - y_min)))
+ canvas[-y_min : -y_min + ha, -x_min : -x_min + wa] = a
+ return canvas
diff --git a/cv2u/imgproc/template.py b/cv2u/imgproc/template.py
index 620df26..6f589bc 100644
--- a/cv2u/imgproc/template.py
+++ b/cv2u/imgproc/template.py
@@ -1,6 +1,7 @@
import cv2
import numpy as np
+from .._validate import check_finite, check_image_not_empty
from .color import toGray
__all__ = ["findTemplate"]
@@ -14,7 +15,7 @@ def findTemplate(
threshold: float = 0.8,
maxCount: int | None = None,
method: int = cv2.TM_CCOEFF_NORMED,
-) -> list[tuple[int, int, int, int, float]]:
+) -> 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
@@ -30,17 +31,23 @@ def findTemplate(
For ``TM_SQDIFF_NORMED`` the score is ``1 - difference``, so higher is always better.
Returns:
- ``(x, y, width, height, score)`` for each match, best first; the boxes do not overlap by more than half
- the template in either direction.
+ A float64 array of shape ``(N, 5)`` with one row ``(x, y, width, height, score)`` per match, best first;
+ empty ``(0, 5)`` when nothing is found. The boxes do not overlap by more than half the template in either
+ direction. ``matches[:, :4]`` are the boxes for :func:`drawBoxes` or :func:`nms`.
Raises:
- ValueError: If ``method`` is not normalized, ``threshold`` is outside ``[0, 1]`` or ``templ`` is larger than
- ``src``.
+ ValueError: If an image is empty, ``method`` is not normalized, ``threshold`` is outside ``[0, 1]``,
+ ``maxCount`` is negative, or ``templ`` is larger than ``src``.
"""
+ check_image_not_empty("src", src)
+ check_image_not_empty("templ", templ)
if method not in _NORMED_METHODS:
raise ValueError("method must be cv.TM_CCOEFF_NORMED, cv.TM_CCORR_NORMED or cv.TM_SQDIFF_NORMED")
+ check_finite("threshold", threshold)
if not 0.0 <= threshold <= 1.0:
raise ValueError(f"threshold must be in [0, 1], got {threshold}")
+ if maxCount is not None and maxCount < 0:
+ raise ValueError(f"maxCount must not be negative, got {maxCount}")
h, w = templ.shape[:2]
if h > src.shape[0] or w > src.shape[1]:
raise ValueError(f"templ {templ.shape[:2]} is larger than src {src.shape[:2]}")
@@ -52,13 +59,13 @@ def findTemplate(
scores = 1.0 - scores
scores = np.nan_to_num(scores, nan=0.0) # flat regions give NaN with TM_CCOEFF_NORMED
- matches: list[tuple[int, int, int, int, float]] = []
+ matches: list[tuple[float, float, float, float, float]] = []
half_w, half_h = max(1, w // 2), max(1, h // 2)
while maxCount is None or len(matches) < maxCount:
_, best, _, (x, y) = cv2.minMaxLoc(scores)
if best < threshold:
break
- matches.append((int(x), int(y), int(w), int(h), float(best)))
+ matches.append((float(x), float(y), float(w), float(h), float(best)))
# Suppress neighbors closer than half the template, so a match is not reported twice.
scores[max(0, y - half_h) : y + half_h + 1, max(0, x - half_w) : x + half_w + 1] = -1.0
- return matches
+ return np.array(matches, dtype=np.float64).reshape(-1, 5)
diff --git a/cv2u/imgproc/visualize.py b/cv2u/imgproc/visualize.py
new file mode 100644
index 0000000..b74f10b
--- /dev/null
+++ b/cv2u/imgproc/visualize.py
@@ -0,0 +1,961 @@
+"""Visualization: heatmaps, HUD overlays, skeletons, trajectories, rotated boxes and image comparisons."""
+
+import math
+from collections.abc import Sequence
+
+import cv2
+import numpy as np
+
+from .._validate import (
+ as_color,
+ check_channels,
+ check_color,
+ check_finite,
+ check_image_not_empty,
+ check_uint8,
+ is_single_color,
+)
+from ..core.compose import hconcatEx, vconcatEx
+from .color import distinctColors, toBGR, toBGRA, toGray
+from .draw import Color, _bgr, _luminance
+
+__all__ = [
+ "COCO_SKELETON",
+ "applyColorMapEx",
+ "blendImages",
+ "colorBar",
+ "compareImages",
+ "drawArrow",
+ "drawCrosshair",
+ "drawFPS",
+ "drawLegend",
+ "drawPolygon",
+ "drawProgressBar",
+ "drawRotatedBoxes",
+ "drawRotatedRect",
+ "drawSkeleton",
+ "drawTextBlock",
+ "drawTrajectory",
+ "heatmap",
+ "labeledMontage",
+]
+
+COCO_SKELETON: tuple[tuple[int, int], ...] = (
+ (0, 1), (0, 2), (1, 3), (2, 4), # nose - eyes - ears
+ (5, 6), (5, 7), (7, 9), (6, 8), (8, 10), # shoulders and arms
+ (5, 11), (6, 12), (11, 12), # torso
+ (11, 13), (13, 15), (12, 14), (14, 16), # legs
+) # fmt: skip
+"""Keypoint pairs of the 17-keypoint COCO skeleton (nose, eyes, ears, shoulders, elbows, wrists, hips, knees,
+ankles)."""
+
+_FONT = cv2.FONT_HERSHEY_SIMPLEX
+
+
+def _check_unit(name: str, value: float) -> None:
+ check_finite(name, value)
+ if not 0.0 <= value <= 1.0:
+ raise ValueError(f"{name} must be between 0 and 1, got {value}")
+
+
+def _draw_color(img: np.ndarray, color: Color) -> Color:
+ """A color usable by ``cv2`` drawing on ``img`` (luminance for grayscale images)."""
+ values = [float(color)] if isinstance(color, (int, float)) else [float(c) for c in color]
+ check_color("color", values, img.dtype)
+ if check_channels("img", img) == 1 and not isinstance(color, (int, float)):
+ return _luminance(color)
+ return color
+
+
+def _points2d(
+ name: str, points: Sequence[Sequence[float]] | Sequence[float] | np.ndarray, columns: int = 2
+) -> np.ndarray:
+ array = np.asarray(points, dtype=np.float64)
+ if array.size == 0:
+ return np.zeros((0, columns))
+ array = array.reshape(-1, array.shape[-1]) if array.ndim >= 2 else array.reshape(1, -1)
+ if array.shape[1] < 2:
+ raise ValueError(f"{name} must have at least 2 columns (x, y), got shape {np.shape(points)}")
+ if not np.all(np.isfinite(array)):
+ raise ValueError(f"{name} must be finite numbers")
+ return array
+
+
+def _xy(point: Sequence[float] | np.ndarray) -> tuple[int, int]:
+ return round(float(point[0])), round(float(point[1]))
+
+
+def _blend_region(img: np.ndarray, layer: np.ndarray, alpha: float, x0: int, y0: int, x1: int, y1: int) -> None:
+ """Blend ``layer`` (same shape as ``img``) into ``img`` over a clipped rectangle, in place."""
+ x0, y0 = max(x0, 0), max(y0, 0)
+ x1, y1 = min(x1, img.shape[1]), min(y1, img.shape[0])
+ if x0 >= x1 or y0 >= y1:
+ return
+ region = img[y0:y1, x0:x1]
+ cv2.addWeighted(region, 1 - alpha, layer[y0:y1, x0:x1], alpha, 0, dst=region)
+
+
+# ----------------------------------------------------------------------------------------------- color maps
+
+
+def applyColorMapEx(
+ values: np.ndarray,
+ colormap: int | np.ndarray = cv2.COLORMAP_JET,
+ normalize: bool = True,
+ mask: np.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.
+
+ Args:
+ values: 2-D array (or 3-D with one channel) of any numeric dtype.
+ colormap: An OpenCV ``cv.COLORMAP_*`` constant, or a ``(256, 1, 3)`` / ``(256, 3)`` 8-bit lookup table.
+ normalize: Stretch the minimum and maximum of ``values`` to 0 and 255. When ``False``, the values are
+ clipped to ``[0, 255]`` (float maps in ``[0, 1]`` are scaled by 255 first).
+ mask: Optional 2-D mask with the shape of ``values``; pixels outside it are black.
+
+ Returns:
+ An 8-bit BGR image with the shape of ``values``.
+
+ Raises:
+ ValueError: If ``values`` is empty or not 2-D, contains NaN/inf, or ``mask`` has a different shape.
+ """
+ array = np.asarray(values)
+ if array.ndim == 3 and array.shape[2] == 1:
+ array = array[..., 0]
+ if array.ndim != 2:
+ raise ValueError(f"values must be a 2-D array, got shape {array.shape}")
+ check_image_not_empty("values", array)
+ if mask is not None and mask.shape[:2] != array.shape:
+ raise ValueError(f"mask must have the shape {array.shape}, got {mask.shape}")
+
+ if array.dtype == np.uint8 and not normalize:
+ scaled = array
+ else:
+ floats = array.astype(np.float64)
+ if not np.all(np.isfinite(floats)):
+ raise ValueError("values must be finite numbers")
+ if normalize:
+ lo, hi = float(np.min(floats)), float(np.max(floats))
+ floats = (floats - lo) / (hi - lo) if hi > lo else np.zeros_like(floats)
+ floats *= 255.0
+ elif np.issubdtype(array.dtype, np.floating) and np.max(floats) <= 1.0 and np.min(floats) >= 0.0:
+ floats *= 255.0
+ scaled = np.clip(np.rint(floats), 0, 255).astype(np.uint8)
+
+ if isinstance(colormap, np.ndarray):
+ lut = np.asarray(colormap, dtype=np.uint8).reshape(256, 1, 3)
+ colored: np.ndarray = cv2.applyColorMap(scaled, lut)
+ else:
+ colored = cv2.applyColorMap(scaled, colormap)
+ if mask is not None:
+ colored[np.asarray(mask) == 0] = 0
+ return colored
+
+
+def heatmap(
+ src: np.ndarray,
+ values: np.ndarray,
+ alpha: float = 0.5,
+ colormap: int | np.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.
+
+ Args:
+ src: 8-bit grayscale, BGR or BGRA image. It is not modified.
+ values: 2-D map of any numeric dtype and size (resized to ``src`` with linear interpolation).
+ alpha: Opacity of the color map, from 0 to 1.
+ colormap: As for :func:`applyColorMapEx`.
+ normalize: As for :func:`applyColorMapEx`.
+
+ Returns:
+ A new BGR image (BGRA keeps the alpha channel of ``src``) with the size of ``src``.
+
+ Raises:
+ ValueError: If ``src`` is not 8-bit, ``values`` is not 2-D, or ``alpha`` is outside ``[0, 1]``.
+ """
+ check_uint8("src", src)
+ _check_unit("alpha", alpha)
+ colored = applyColorMapEx(values, colormap, normalize)
+ height, width = src.shape[:2]
+ if colored.shape[:2] != (height, width):
+ colored = cv2.resize(colored, (width, height), interpolation=cv2.INTER_LINEAR)
+ base = toBGR(src)
+ blended: np.ndarray = cv2.addWeighted(base, 1 - alpha, colored, alpha, 0)
+ if check_channels("src", src) == 4:
+ blended = np.dstack([blended, src[..., 3]])
+ return blended
+
+
+def colorBar(
+ colormap: int | np.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.
+
+ Args:
+ colormap: As for :func:`applyColorMapEx`.
+ size: Size of the strip as ``(width, height)`` (``vertical`` swaps the gradient direction, not the size).
+ vertical: Run the gradient from the bottom (minimum) to the top instead of left to right.
+ minVal: Value written at the low end; ``None`` writes nothing.
+ maxVal: Value written at the high end; ``None`` writes nothing.
+ fontScale: Hershey font size of the labels.
+
+ Returns:
+ A BGR image of ``size``; with labels, the strip grows to make room for the text.
+
+ Raises:
+ ValueError: If ``size`` is not positive or a label value is not finite.
+ """
+ width, height = size
+ if width < 1 or height < 1:
+ raise ValueError(f"size must be positive, got {size}")
+ for name, value in (("minVal", minVal), ("maxVal", maxVal)):
+ if value is not None:
+ check_finite(name, value)
+ if vertical:
+ ramp = np.linspace(255, 0, height).reshape(height, 1).repeat(width, axis=1)
+ else:
+ ramp = np.linspace(0, 255, width).reshape(1, width).repeat(height, axis=0)
+ strip = applyColorMapEx(ramp.astype(np.uint8), colormap, normalize=False)
+ labels = [(name, f"{value:g}") for name, value in (("min", minVal), ("max", maxVal)) if value is not None]
+ if not labels:
+ return strip
+ pad = 4
+ sizes = {name: cv2.getTextSize(text, _FONT, fontScale, 1)[0] for name, text in labels}
+ text_h = max(h for _, h in sizes.values())
+ if vertical:
+ text_w = max(w for w, _ in sizes.values())
+ canvas = np.full((height, width + text_w + pad, 3), 255, np.uint8)
+ canvas[:, :width] = strip
+ for name, text in labels:
+ y = height - 1 if name == "min" else sizes[name][1]
+ cv2.putText(canvas, text, (width + pad, y), _FONT, fontScale, (0, 0, 0), 1, cv2.LINE_AA)
+ else:
+ canvas = np.full((height + text_h + pad, width, 3), 255, np.uint8)
+ canvas[:height] = strip
+ for name, text in labels:
+ x = 0 if name == "min" else width - sizes[name][0]
+ cv2.putText(canvas, text, (x, height + pad + text_h - 1), _FONT, fontScale, (0, 0, 0), 1, cv2.LINE_AA)
+ return canvas
+
+
+# ----------------------------------------------------------------------------------------------- shapes
+
+
+def drawArrow(
+ img: np.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.
+
+ Args:
+ img: Image to draw on.
+ pt1: Start point ``(x, y)``; floats are rounded.
+ pt2: End point ``(x, y)``.
+ color: Arrow color.
+ thickness: Line thickness.
+ headSize: Length of the head's sides in pixels.
+ heads: ``"end"`` (head at ``pt2``), ``"start"``, ``"both"`` or ``"none"``.
+ lineType: As for ``cv.line``.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``heads`` is unknown, ``headSize`` is negative, or a point is not finite.
+ """
+ if heads not in ("end", "start", "both", "none"):
+ raise ValueError(f"heads must be 'end', 'start', 'both' or 'none', got {heads!r}")
+ if headSize < 0:
+ raise ValueError(f"headSize must not be negative, got {headSize}")
+ start, end = _points2d("pt1", pt1)[0], _points2d("pt2", pt2)[0]
+ color = _draw_color(img, color)
+ cv2.line(img, _xy(start), _xy(end), color, thickness, lineType)
+ length = float(np.hypot(*(end - start)))
+ if length == 0 or headSize == 0:
+ return img
+ angle = math.atan2(end[1] - start[1], end[0] - start[0])
+ spread = math.pi / 6
+ tips = []
+ if heads in ("end", "both"):
+ tips.append((end, angle))
+ if heads in ("start", "both"):
+ tips.append((start, angle + math.pi))
+ for tip, direction in tips:
+ for sign in (1, -1):
+ a = direction + math.pi + sign * spread
+ wing = (tip[0] + headSize * math.cos(a), tip[1] + headSize * math.sin(a))
+ cv2.line(img, _xy(tip), _xy(wing), color, thickness, lineType)
+ return img
+
+
+def drawRotatedRect(
+ img: np.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``.
+
+ Args:
+ img: Image to draw on.
+ rect: The rotated rectangle.
+ color: Line or fill color.
+ thickness: Line thickness; ``cv.FILLED`` fills the rectangle.
+ lineType: As for ``cv.polylines``.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``rect`` has a negative size or non-finite values.
+ """
+ (cx, cy), (w, h), angle = rect
+ for name, value in (("rect center", cx), ("rect center", cy), ("rect angle", angle)):
+ check_finite(name, float(value))
+ for value in (w, h):
+ check_finite("rect size", float(value), nonnegative=True)
+ color = _draw_color(img, color)
+ corners = cv2.boxPoints(((float(cx), float(cy)), (float(w), float(h)), float(angle)))
+ points = np.rint(corners).astype(np.int32).reshape(-1, 1, 2)
+ if thickness < 0:
+ cv2.fillPoly(img, [points], color, lineType)
+ else:
+ cv2.polylines(img, [points], True, color, thickness, lineType)
+ return img
+
+
+def drawRotatedBoxes(
+ img: np.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.
+
+ Args:
+ img: Image to draw on.
+ rects: Rotated rectangles ``((cx, cy), (w, h), angle)``.
+ colors: One color per box, one color for all, or ``None`` for :func:`distinctColors`.
+ labels: One text per box, or ``None``.
+ thickness: Line thickness.
+ fontScale: Hershey font size of the labels.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``labels`` or ``colors`` has a different length than ``rects``.
+ """
+ count = len(rects)
+ if labels is not None and len(labels) != count:
+ raise ValueError(f"labels must have one entry per box, got {len(labels)} for {count} boxes")
+ palette = _palette(colors, count)
+ for i, rect in enumerate(rects):
+ color = palette[i]
+ drawRotatedRect(img, rect, color, thickness)
+ if labels is None:
+ continue
+ corners = cv2.boxPoints(
+ ((float(rect[0][0]), float(rect[0][1])), (float(rect[1][0]), float(rect[1][1])), float(rect[2]))
+ )
+ top = corners[np.argmin(corners[:, 1])]
+ (text_w, text_h), baseline = cv2.getTextSize(labels[i], _FONT, fontScale, 1)
+ x, y = round(float(top[0])), round(float(top[1])) - 4
+ if y - text_h - baseline < 0:
+ y = text_h + baseline + 2
+ cv2.rectangle(img, (x, y - text_h - baseline), (x + text_w + 4, y + 2), color, cv2.FILLED)
+ level = 0 if _luminance(color) > 140 else 255
+ text_color: Color = level if check_channels("img", img) == 1 else (level, level, level)
+ cv2.putText(img, labels[i], (x + 2, y), _FONT, fontScale, text_color, 1, cv2.LINE_AA)
+ return img
+
+
+def _palette(colors: Sequence[Color] | Color | None, count: int) -> list[Color]:
+ if colors is None:
+ return list(distinctColors(max(count, 1)))
+ if is_single_color(colors):
+ return [as_color(colors)] * max(count, 1)
+ palette: list[Color] = [as_color(c) for c in colors] # type: ignore[union-attr]
+ if len(palette) != count:
+ raise ValueError(f"colors must have one entry per item, got {len(palette)} for {count} items")
+ return palette
+
+
+def drawPolygon(
+ img: np.ndarray,
+ points: Sequence[Sequence[float]] | np.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.
+
+ Args:
+ img: Image to draw on.
+ points: ``(N, 2)`` vertices; floats are rounded.
+ color: Outline and fill color.
+ thickness: Outline thickness; ``0`` draws no outline.
+ closed: Connect the last vertex to the first (ignored when ``fill`` is set).
+ fill: Fill the polygon.
+ alpha: Opacity of the drawing, from 0 to 1 (applied to the outline and the fill).
+
+ lineType: As for ``cv.polylines``.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``points`` is not 2-D or not finite, or ``alpha`` is outside ``[0, 1]``.
+ """
+ _check_unit("alpha", alpha)
+ array = _points2d("points", points)
+ if len(array) == 0:
+ return img
+ color = _draw_color(img, color)
+ pts = np.rint(array[:, :2]).astype(np.int32).reshape(-1, 1, 2)
+ target = img if alpha >= 1.0 else img.copy()
+ if fill:
+ cv2.fillPoly(target, [pts], color, lineType)
+ if thickness > 0:
+ cv2.polylines(target, [pts], closed or fill, color, thickness, lineType)
+ if target is not img:
+ x0, y0 = int(np.min(pts[:, 0, 0])) - thickness - 1, int(np.min(pts[:, 0, 1])) - thickness - 1
+ x1, y1 = int(np.max(pts[:, 0, 0])) + thickness + 2, int(np.max(pts[:, 0, 1])) + thickness + 2
+ _blend_region(img, target, alpha, x0, y0, x1, y1)
+ return img
+
+
+def drawSkeleton(
+ img: np.ndarray,
+ keypoints: Sequence[Sequence[float]] | np.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.
+
+ Args:
+ img: Image to draw on.
+ keypoints: ``(K, 2)`` coordinates or ``(K, 3)`` with a confidence score in the third column.
+ connections: Pairs of keypoint indices to join; :data:`COCO_SKELETON` by default. Pairs with an index
+ outside ``keypoints`` are skipped, so partial detections draw fine.
+ colors: One color per connection, one color for all, or ``None`` for :func:`distinctColors`. Each joint
+ takes the color of its first connection.
+ radius: Joint circle radius; ``0`` draws limbs only.
+ thickness: Limb line thickness.
+ minScore: Keypoints with a score below this are not drawn (and neither are their limbs). Keypoints at
+ ``(0, 0)`` with no score column are also skipped, the usual marker for "not detected".
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``keypoints`` has fewer than 2 columns, ``radius`` is negative, or ``colors`` has a
+ different length than ``connections``.
+ """
+ if radius < 0:
+ raise ValueError(f"radius must not be negative, got {radius}")
+ check_finite("minScore", minScore)
+ array = _points2d("keypoints", keypoints)
+ count = len(array)
+ undetected = (array[:, 0] == 0) & (array[:, 1] == 0) # without a score column, (0, 0) marks a missing keypoint
+ visible = array[:, 2] >= minScore if array.shape[1] >= 3 else ~undetected
+ palette = _palette(colors, len(connections))
+ joint_colors: dict[int, Color] = {}
+ for n, (a, b) in enumerate(connections):
+ if not (0 <= a < count and 0 <= b < count) or not (visible[a] and visible[b]):
+ continue
+ color = _draw_color(img, palette[n])
+ cv2.line(img, _xy(array[a]), _xy(array[b]), color, thickness, cv2.LINE_AA)
+ joint_colors.setdefault(a, color)
+ joint_colors.setdefault(b, color)
+ if radius == 0:
+ return img
+ default = _draw_color(img, palette[0]) if palette else (0, 0, 255)
+ for k in range(count):
+ if visible[k]:
+ cv2.circle(img, _xy(array[k]), radius, joint_colors.get(k, default), cv2.FILLED, cv2.LINE_AA)
+ return img
+
+
+def drawTrajectory(
+ img: np.ndarray,
+ points: Sequence[Sequence[float]] | np.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.
+
+ Args:
+ img: Image to draw on.
+ points: ``(N, 2)`` positions from oldest to newest; floats are rounded.
+ color: Color at the newest point; ``None`` uses green.
+ thickness: Line thickness at the newest segment.
+ fade: Darken and thin the line towards the oldest point. ``False`` draws a plain polyline.
+ maxPoints: Only draw the last ``maxPoints`` positions.
+ endColor: Color at the oldest point when fading; ``None`` fades towards black (or the image's zero level).
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``points`` is not 2-D or not finite, or ``maxPoints`` is not positive.
+ """
+ if maxPoints is not None and maxPoints < 1:
+ raise ValueError(f"maxPoints must be positive, got {maxPoints}")
+ array = _points2d("points", points)[:, :2]
+ if maxPoints is not None:
+ array = array[-maxPoints:]
+ if len(array) < 2:
+ return img
+ head = (0, 255, 0) if color is None else color
+ head_bgr = _bgr(head)
+ if not fade:
+ pts = np.rint(array).astype(np.int32).reshape(-1, 1, 2)
+ cv2.polylines(img, [pts], False, _draw_color(img, head), thickness, cv2.LINE_AA)
+ return img
+ tail_bgr = (0.0, 0.0, 0.0) if endColor is None else _bgr(endColor)
+ segments = len(array) - 1
+ for i in range(segments):
+ t = (i + 1) / segments # 1 at the newest segment
+ mixed = tuple(tail + (h - tail) * t for h, tail in zip(head_bgr, tail_bgr, strict=True))
+ width = max(1, round(thickness * (0.3 + 0.7 * t)))
+ cv2.line(img, _xy(array[i]), _xy(array[i + 1]), _draw_color(img, mixed), width, cv2.LINE_AA)
+ return img
+
+
+def drawCrosshair(
+ img: np.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.
+
+ Args:
+ img: Image to draw on.
+ center: ``(x, y)``; floats are rounded.
+ color: Line color.
+ size: Half length of the crosshair in pixels, from the center to the tip of a tick.
+ gap: Empty radius around the center.
+ thickness: Line thickness.
+ lineType: As for ``cv.line``.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``size`` is not positive, ``gap`` is negative or not smaller than ``size``.
+ """
+ if size < 1:
+ raise ValueError(f"size must be positive, got {size}")
+ if gap < 0 or gap >= size:
+ raise ValueError(f"gap must be between 0 and size - 1, got {gap} for size {size}")
+ cx, cy = _xy(_points2d("center", center)[0])
+ color = _draw_color(img, color)
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ cv2.line(img, (cx + dx * gap, cy + dy * gap), (cx + dx * size, cy + dy * size), color, thickness, lineType)
+ return img
+
+
+# ----------------------------------------------------------------------------------------------- HUD
+
+
+def drawTextBlock(
+ img: np.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.
+
+ Args:
+ img: 8-bit image to draw on.
+ lines: Text lines (a single string is split at newlines). The Hershey font covers ASCII only.
+ org: Top-left corner ``(x, y)`` of the panel.
+ fontScale: Hershey font size.
+ color: Text color.
+ background: Panel color; ``None`` draws text only.
+ alpha: Opacity of the panel, from 0 to 1.
+ padding: Space in pixels between the text and the panel border.
+ lineSpacing: Line height as a multiple of the text height.
+ thickness: Text stroke thickness.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``img`` is not 8-bit, ``alpha`` is outside ``[0, 1]``, ``padding`` is negative, or
+ ``fontScale`` / ``lineSpacing`` is not positive.
+ """
+ check_uint8("img", img)
+ _check_unit("alpha", alpha)
+ check_finite("fontScale", fontScale, positive=True)
+ check_finite("lineSpacing", lineSpacing, positive=True)
+ if padding < 0:
+ raise ValueError(f"padding must not be negative, got {padding}")
+ texts = lines.split("\n") if isinstance(lines, str) else list(lines)
+ if not texts:
+ return img
+ sizes = [cv2.getTextSize(t or " ", _FONT, fontScale, thickness) for t in texts]
+ text_h = max(h for (_, h), _ in sizes)
+ baseline = max(b for _, b in sizes)
+ line_h = max(1, round((text_h + baseline) * lineSpacing))
+ width = max(w for (w, _), _ in sizes) + 2 * padding
+ height = line_h * len(texts) + 2 * padding
+ x, y = int(org[0]), int(org[1])
+ if background is not None:
+ panel = img.copy()
+ cv2.rectangle(panel, (x, y), (x + width - 1, y + height - 1), _draw_color(img, background), cv2.FILLED)
+ _blend_region(img, panel, alpha, x, y, x + width, y + height)
+ text_color = _draw_color(img, color)
+ for i, text in enumerate(texts):
+ base = (x + padding, y + padding + i * line_h + text_h + (line_h - text_h - baseline) // 2)
+ cv2.putText(img, text, base, _FONT, fontScale, text_color, thickness, cv2.LINE_AA)
+ return img
+
+
+def drawFPS(img: np.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:
+ ValueError: If ``fps`` is not finite.
+ """
+ check_finite("fps", fps)
+ return drawTextBlock(img, f"FPS: {fps:.1f}", org, fontScale)
+
+
+def drawProgressBar(
+ img: np.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.
+
+ Args:
+ img: Image to draw on.
+ progress: Fraction done, clipped to ``[0, 1]``.
+ org: Top-left corner ``(x, y)``.
+ size: Bar size as ``(width, height)``.
+ color: Fill color.
+ background: Track color.
+ border: Outline color; ``None`` draws no outline.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``progress`` is not finite or ``size`` is not positive.
+ """
+ check_finite("progress", progress)
+ width, height = size
+ if width < 1 or height < 1:
+ raise ValueError(f"size must be positive, got {size}")
+ x, y = int(org[0]), int(org[1])
+ x1, y1 = x + width - 1, y + height - 1
+ cv2.rectangle(img, (x, y), (x1, y1), _draw_color(img, background), cv2.FILLED)
+ filled = round(width * min(max(progress, 0.0), 1.0))
+ if filled > 0:
+ cv2.rectangle(img, (x, y), (x + filled - 1, y1), _draw_color(img, color), cv2.FILLED)
+ if border is not None:
+ cv2.rectangle(img, (x, y), (x1, y1), _draw_color(img, border), 1)
+ return img
+
+
+def drawLegend(
+ img: np.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.
+
+ Args:
+ img: 8-bit image to draw on.
+ labels: One text per entry.
+ colors: One color per entry; ``None`` uses :func:`distinctColors`.
+ org: Top-left corner ``(x, y)`` of the panel.
+ swatch: Side of the color squares in pixels.
+ fontScale: Hershey font size.
+ color: Text color.
+ background: Panel color; ``None`` draws no panel.
+ alpha: Opacity of the panel.
+ padding: Space between the entries and the panel border.
+
+ Returns:
+ ``img``.
+
+ Raises:
+ ValueError: If ``colors`` has a different length than ``labels``, ``swatch`` is not positive, or see
+ :func:`drawTextBlock`.
+ """
+ check_uint8("img", img)
+ _check_unit("alpha", alpha)
+ if swatch < 1:
+ raise ValueError(f"swatch must be positive, got {swatch}")
+ if padding < 0:
+ raise ValueError(f"padding must not be negative, got {padding}")
+ palette = list(distinctColors(len(labels))) if colors is None else list(colors)
+ if len(palette) != len(labels):
+ raise ValueError(f"colors must have one entry per label, got {len(palette)} for {len(labels)} labels")
+ if not labels:
+ return img
+ sizes = [cv2.getTextSize(t or " ", _FONT, fontScale, 1) for t in labels]
+ text_h = max(h for (_, h), _ in sizes)
+ row_h = max(swatch, text_h) + 6
+ gap = 6
+ width = swatch + gap + max(w for (w, _), _ in sizes) + 2 * padding
+ height = row_h * len(labels) + 2 * padding
+ x, y = int(org[0]), int(org[1])
+ if background is not None:
+ panel = img.copy()
+ cv2.rectangle(panel, (x, y), (x + width - 1, y + height - 1), _draw_color(img, background), cv2.FILLED)
+ _blend_region(img, panel, alpha, x, y, x + width, y + height)
+ text_color = _draw_color(img, color)
+ for i, (text, entry) in enumerate(zip(labels, palette, strict=True)):
+ top = y + padding + i * row_h + (row_h - swatch) // 2
+ cv2.rectangle(
+ img, (x + padding, top), (x + padding + swatch - 1, top + swatch - 1), _draw_color(img, entry), -1
+ )
+ base = (x + padding + swatch + gap, y + padding + i * row_h + (row_h + text_h) // 2)
+ cv2.putText(img, text, base, _FONT, fontScale, text_color, 1, cv2.LINE_AA)
+ return img
+
+
+# ----------------------------------------------------------------------------------------------- comparisons
+
+
+def _fit(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """Both images as BGR (BGRA alpha dropped), with ``b`` resized to ``a``."""
+ a3, b3 = toBGR(a), toBGR(b)
+ if b3.shape[:2] != a3.shape[:2]:
+ b3 = cv2.resize(b3, (a3.shape[1], a3.shape[0]), interpolation=cv2.INTER_AREA)
+ return a3, b3
+
+
+def _title(img: np.ndarray, text: str, fontScale: float, color: Color) -> np.ndarray:
+ (w, h), baseline = cv2.getTextSize(text, _FONT, fontScale, 1)
+ strip = np.zeros((h + baseline + 8, img.shape[1], 3), np.uint8)
+ strip[:] = np.array(_bgr(color), np.uint8)
+ level = 0 if _luminance(color) > 140 else 255
+ x = max((img.shape[1] - w) // 2, 2)
+ cv2.putText(strip, text, (x, h + 4), _FONT, fontScale, (level, level, level), 1, cv2.LINE_AA)
+ return np.concatenate([strip, img], axis=0)
+
+
+def compareImages(
+ a: np.ndarray,
+ b: np.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.
+
+ Args:
+ a: 8-bit grayscale, BGR or BGRA image (the reference size).
+ b: 8-bit image; resized to the size of ``a`` when it differs.
+ mode: ``"side"`` (left/right), ``"vertical"`` (top/bottom), ``"split"`` (left part of ``a`` and right
+ part of ``b`` with a divider), ``"blend"`` (``cv.addWeighted`` with ``split`` as the weight of ``b``)
+ or ``"diff"`` (absolute difference, colorized with ``cv.COLORMAP_JET``).
+ split: Position of the divider as a fraction of the width for ``"split"``; blend weight for ``"blend"``.
+ labels: Two titles drawn above the images for ``"side"`` / ``"vertical"``; ignored by the other modes.
+ gap: Space between the images for ``"side"`` / ``"vertical"``; divider thickness for ``"split"``.
+ color: Color of the gap, the divider and the title strips.
+ fontScale: Hershey font size of the labels.
+
+ Returns:
+ A new BGR image.
+
+ Raises:
+ ValueError: If an image is not 8-bit, ``mode`` is unknown, ``split`` is outside ``[0, 1]``, ``gap`` is
+ negative or ``labels`` does not have two entries.
+ """
+ check_uint8("a", a)
+ check_uint8("b", b)
+ if mode not in ("side", "vertical", "split", "blend", "diff"):
+ raise ValueError(f"mode must be 'side', 'vertical', 'split', 'blend' or 'diff', got {mode!r}")
+ _check_unit("split", split)
+ if gap < 0:
+ raise ValueError(f"gap must not be negative, got {gap}")
+ if labels is not None and len(labels) != 2:
+ raise ValueError(f"labels must have two entries, got {len(labels)}")
+ left, right = _fit(a, b)
+ if mode in ("side", "vertical"):
+ if labels is not None:
+ left, right = _title(left, labels[0], fontScale, color), _title(right, labels[1], fontScale, color)
+ concat = hconcatEx if mode == "side" else vconcatEx
+ return concat([left, right], color=_bgr(color), gap=gap)
+ if mode == "blend":
+ blended: np.ndarray = cv2.addWeighted(left, 1 - split, right, split, 0)
+ return blended
+ if mode == "diff":
+ diff: np.ndarray = cv2.absdiff(left, right)
+ return applyColorMapEx(cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY), cv2.COLORMAP_JET, normalize=False)
+ out = right.copy()
+ x = round(left.shape[1] * split)
+ out[:, :x] = left[:, :x]
+ if gap > 0:
+ x0, x1 = max(x - gap // 2, 0), min(x - gap // 2 + gap, out.shape[1])
+ out[:, x0:x1] = np.array(_bgr(color), np.uint8)
+ return out
+
+
+def labeledMontage(
+ images: Sequence[np.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.
+
+ Args:
+ images: 8-bit images; sizes and channels may differ.
+ labels: One title per image.
+ cols: Number of columns; by default as square as possible.
+ cellSize: Fit every image into ``(width, height)`` first with :func:`letterbox`.
+ gap: Space between the cells.
+ color: Color of the gaps, the padding and the title strips.
+ fontScale: Hershey font size of the titles.
+
+ Returns:
+ A new BGR image.
+
+ Raises:
+ ValueError: If ``images`` is empty, ``labels`` has a different length, or ``cols`` is not positive.
+ """
+ from .resize import letterbox
+
+ if len(images) == 0:
+ raise ValueError("images must not be empty")
+ if len(labels) != len(images):
+ raise ValueError(f"labels must have one entry per image, got {len(labels)} for {len(images)} images")
+ columns = math.ceil(math.sqrt(len(images))) if cols is None else cols
+ if columns < 1:
+ raise ValueError(f"cols must be positive, got {cols}")
+ fill = _bgr(color)
+ cells = []
+ for img, text in zip(images, labels, strict=True):
+ check_uint8("images", img)
+ tile = toBGR(img)
+ if cellSize is not None:
+ tile = letterbox(tile, cellSize, color=fill)[0]
+ cells.append(_title(tile, text, fontScale, color))
+ rows = [hconcatEx(cells[i : i + columns], color=fill, gap=gap) for i in range(0, len(cells), columns)]
+ return vconcatEx(rows, color=fill, gap=gap)
+
+
+def blendImages(images: Sequence[np.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.
+
+ Args:
+ images: 8-bit grayscale, BGR or BGRA images.
+ weights: One non-negative weight per image; ``None`` gives equal weights.
+
+ Returns:
+ A new 8-bit image with the shape of ``images[0]``.
+
+ Raises:
+ ValueError: If ``images`` is empty, an image is not 8-bit, or ``weights`` has a different length, a
+ negative or non-finite entry, or sums to zero.
+ """
+ if len(images) == 0:
+ raise ValueError("images must not be empty")
+ for img in images:
+ check_uint8("images", img)
+ if weights is None:
+ weights = [1.0] * len(images)
+ if len(weights) != len(images):
+ raise ValueError(f"weights must have one entry per image, got {len(weights)} for {len(images)} images")
+ for w in weights:
+ check_finite("weights", w, nonnegative=True)
+ total = float(sum(weights))
+ if total == 0:
+ raise ValueError("weights must not all be zero")
+ first = images[0]
+ height, width = first.shape[:2]
+ channels = check_channels("images", first)
+ convert = {1: toGray, 3: toBGR, 4: toBGRA}[channels]
+ acc = np.zeros(first.shape, np.float32)
+ for img, w in zip(images, weights, strict=True):
+ if check_channels("images", img) != channels:
+ img = convert(img)
+ if img.shape[:2] != (height, width):
+ img = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)
+ # (h, w, 1) and (h, w) both count as one channel; cv.resize also drops a trailing 1.
+ acc += img.reshape(first.shape).astype(np.float32) * (float(w) / total)
+ return np.clip(np.rint(acc), 0, 255).astype(np.uint8)
diff --git a/cv2u/videoio/__init__.py b/cv2u/videoio/__init__.py
index 9d5fdea..2a0a7e8 100644
--- a/cv2u/videoio/__init__.py
+++ b/cv2u/videoio/__init__.py
@@ -1,3 +1,45 @@
+from .edit import (
+ concatVideos,
+ detectScenes,
+ extractFrames,
+ imagesToVideo,
+ resizeVideo,
+ sampleFrames,
+ trimVideo,
+ videoThumbnail,
+ videoToGif,
+)
+from .reader import (
+ CameraStream,
+ FPSCounter,
+ VideoReader,
+ VideoWriterEx,
+ formatTimestamp,
+ frameToTime,
+ timeToFrame,
+)
from .video import VideoInfo, readFrameAt, readFrames, videoInfo, writeVideo
-__all__ = ["VideoInfo", "readFrameAt", "readFrames", "videoInfo", "writeVideo"]
+__all__ = [
+ "CameraStream",
+ "FPSCounter",
+ "VideoInfo",
+ "VideoReader",
+ "VideoWriterEx",
+ "concatVideos",
+ "detectScenes",
+ "extractFrames",
+ "formatTimestamp",
+ "frameToTime",
+ "imagesToVideo",
+ "readFrameAt",
+ "readFrames",
+ "resizeVideo",
+ "sampleFrames",
+ "timeToFrame",
+ "trimVideo",
+ "videoInfo",
+ "videoThumbnail",
+ "videoToGif",
+ "writeVideo",
+]
diff --git a/cv2u/videoio/edit.py b/cv2u/videoio/edit.py
new file mode 100644
index 0000000..28c9141
--- /dev/null
+++ b/cv2u/videoio/edit.py
@@ -0,0 +1,411 @@
+"""Video file utilities: frame extraction, trimming, concatenation, resizing, GIF export, scene detection and
+thumbnails."""
+
+import math
+import os
+from collections.abc import Callable, Iterator, Sequence
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from cv2u.core.compose import montage
+from cv2u.imgcodecs.files import imreadEx, imwriteEx
+from cv2u.imgproc.resize import resizeEx
+from cv2u.videoio.reader import VideoReader, VideoWriterEx
+from cv2u.videoio.video import writeVideo
+
+__all__ = [
+ "concatVideos",
+ "detectScenes",
+ "extractFrames",
+ "imagesToVideo",
+ "resizeVideo",
+ "sampleFrames",
+ "trimVideo",
+ "videoThumbnail",
+ "videoToGif",
+]
+
+VideoPath = str | os.PathLike[str]
+
+
+def _check_range(step: int, start: int, end: int | None) -> None:
+ if step < 1:
+ raise ValueError(f"step must be at least 1, got {step}")
+ if start < 0:
+ raise ValueError(f"start must not be negative, got {start}")
+ if end is not None and end < start:
+ raise ValueError(f"end must not be before start, got start={start}, end={end}")
+
+
+def 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.
+
+ Args:
+ source: Video file path or URL.
+ outDir: Directory to write the images into.
+ step: Save every ``step``-th frame.
+ start: First frame index to save.
+ end: Stop before this frame index (``None``: until the end).
+ ext: Image file extension, e.g. ``".png"``.
+ prefix: File name prefix.
+ digits: Number of digits of the zero-padded frame index.
+ progress: Called as ``progress(index, frameCount)`` after each saved frame (``frameCount`` may be ``0``).
+
+ Returns:
+ The paths of the saved images, in frame order.
+
+ Raises:
+ OSError: If the video cannot be opened or an image cannot be written.
+ ValueError: If ``step < 1``, ``start < 0`` or ``end < start``.
+ """
+ _check_range(step, start, end)
+ directory = Path(outDir)
+ directory.mkdir(parents=True, exist_ok=True)
+ paths: list[Path] = []
+ with VideoReader(source) as video:
+ for frame in video.frames(step=step, start=start, end=end):
+ index = video.position - 1
+ path = directory / f"{prefix}{index:0{digits}d}{ext}"
+ if not imwriteEx(path, frame):
+ raise OSError(f"cannot write {path}")
+ paths.append(path)
+ if progress is not None:
+ progress(index, video.frameCount)
+ return paths
+
+
+def _write(dst: VideoPath, frames: Iterator[np.ndarray], fps: float, fourcc: str | None) -> int:
+ with VideoWriterEx(dst, fps=fps, fourcc=fourcc, makeDirs=True) as writer:
+ for frame in frames:
+ writer.write(frame)
+ count = writer.frameCount
+ if count == 0:
+ raise ValueError("no frames to write")
+ return count
+
+
+def 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.
+
+ Args:
+ source: Video file path.
+ dst: Output path; the codec is chosen from its extension (see :func:`writeVideo`).
+ start: Start, in seconds (or a frame index when ``byTime=False``).
+ end: End (exclusive), in seconds or frames; ``None`` for the end of the video.
+ byTime: Whether ``start``/``end`` are seconds (``True``) or frame indices.
+ fourcc: Codec override.
+
+ Returns:
+ The number of frames written.
+
+ Raises:
+ OSError: If the source cannot be opened or the writer cannot be created.
+ ValueError: If ``start`` is negative, ``end < start``, or the range contains no frames.
+ """
+ with VideoReader(source) as video:
+ if byTime:
+ if video.fps <= 0:
+ raise ValueError("the video has no frame rate; use byTime=False")
+ first = math.floor(start * video.fps + 1e-9)
+ last = None if end is None else math.floor(end * video.fps + 1e-9)
+ else:
+ first, last = int(start), None if end is None else int(end)
+ _check_range(1, first, last)
+ return _write(dst, video.frames(start=first, end=last), video.fps or 30.0, fourcc)
+
+
+def 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.
+
+ Args:
+ sources: Video file paths, in order.
+ dst: Output path.
+ fourcc: Codec override.
+
+ Returns:
+ The number of frames written.
+
+ Raises:
+ OSError: If a source cannot be opened or the writer cannot be created.
+ ValueError: If ``sources`` is empty.
+ """
+ if not sources:
+ raise ValueError("sources must not be empty")
+
+ def frames() -> Iterator[np.ndarray]:
+ size: tuple[int, int] | None = None
+ for path in sources:
+ with VideoReader(path) as video:
+ if size is None:
+ size = (video.width, video.height)
+ for frame in video:
+ yield frame if frame.shape[1::-1] == size else cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
+
+ with VideoReader(sources[0]) as first:
+ fps = first.fps or 30.0
+ return _write(dst, frames(), fps, fourcc)
+
+
+def 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:
+ The number of frames written.
+
+ Raises:
+ 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.
+ """
+ given = (size is not None) + (scale is not None) + (width is not None or height is not None)
+ if given != 1:
+ raise ValueError("give exactly one of size, scale, or width/height")
+ if size is not None and (size[0] <= 0 or size[1] <= 0):
+ raise ValueError(f"size must be positive, got {size}")
+ if scale is not None and (not math.isfinite(scale) or scale <= 0):
+ raise ValueError(f"scale must be positive, got {scale}")
+
+ with VideoReader(source) as video:
+ if size is not None:
+ target_w, target_h = size
+ elif scale is not None:
+ target_w, target_h = max(1, round(video.width * scale)), max(1, round(video.height * scale))
+ else:
+ probe = resizeEx(np.zeros((video.height, video.width), np.uint8), width, height)
+ target_h, target_w = probe.shape[:2]
+ if interpolation is None:
+ interpolation = cv2.INTER_AREA if target_w < video.width else cv2.INTER_LINEAR
+ frames = (cv2.resize(f, (target_w, target_h), interpolation=interpolation) for f in video)
+ return _write(dst, frames, video.fps or 30.0, fourcc)
+
+
+def 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.
+
+ Args:
+ source: Video file path.
+ dst: Output ``.gif`` path.
+ fps: Playback frame rate of the GIF (default: the video's rate divided by ``step``).
+ size: Output ``(width, height)``; ``None`` keeps the frame size.
+ step: Take every ``step``-th frame.
+ maxFrames: Stop after this many frames.
+ loop: Number of repetitions, ``0`` for forever.
+
+ Returns:
+ The number of frames written.
+
+ Raises:
+ OSError: If the source cannot be opened.
+ ValueError: If the video has no frames, ``step < 1``, ``maxFrames < 1`` or ``fps`` is not positive.
+ """
+ from PIL import Image
+
+ _check_range(step, 0, None)
+ if maxFrames is not None and maxFrames < 1:
+ raise ValueError(f"maxFrames must be at least 1, got {maxFrames}")
+ if fps is not None and (not math.isfinite(fps) or fps <= 0):
+ raise ValueError(f"fps must be positive, got {fps}")
+ images: list[Image.Image] = []
+ with VideoReader(source) as video:
+ if fps is None:
+ fps = video.fps / step if video.fps > 0 else 10.0
+ for frame in video.frames(step=step):
+ if size is not None:
+ frame = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
+ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if frame.ndim == 3 else frame
+ images.append(Image.fromarray(rgb))
+ if maxFrames is not None and len(images) >= maxFrames:
+ break
+ if not images:
+ raise ValueError("the video has no frames")
+ path = Path(dst)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ images[0].save(path, format="GIF", save_all=True, append_images=images[1:], duration=round(1000 / fps), loop=loop)
+ return len(images)
+
+
+def imagesToVideo(
+ images: Sequence[VideoPath | np.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:
+ The number of frames written.
+
+ Raises:
+ OSError: If an image file cannot be read.
+ ValueError: As :func:`writeVideo` (no images, size mismatch, bad fps or codec).
+ """
+
+ def frames() -> Iterator[np.ndarray]:
+ for item in images:
+ if isinstance(item, np.ndarray):
+ yield item
+ else:
+ image = imreadEx(item)
+ if image is None:
+ raise OSError(f"cannot read image {os.fspath(item)!r}")
+ yield image
+
+ Path(dst).parent.mkdir(parents=True, exist_ok=True)
+ return writeVideo(dst, frames(), fps=fps, fourcc=fourcc)
+
+
+def 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.
+
+ Args:
+ source: Video file path.
+ threshold: Mean absolute gray difference (0-255) that counts as a cut; lower is more sensitive.
+ minLength: Minimum number of frames between two cuts.
+ step: Compare every ``step``-th frame (faster, but cuts are reported at a multiple of ``step``).
+
+ Returns:
+ The indices of the first frame of each new scene, in increasing order (the first frame is not included).
+
+ Raises:
+ OSError: If the video cannot be opened.
+ ValueError: If ``threshold`` is negative or not finite, ``minLength < 1`` or ``step < 1``.
+ """
+ if not math.isfinite(threshold) or threshold < 0:
+ raise ValueError(f"threshold must not be negative, got {threshold}")
+ if minLength < 1:
+ raise ValueError(f"minLength must be at least 1, got {minLength}")
+ _check_range(step, 0, None)
+ cuts: list[int] = []
+ previous: np.ndarray | None = None
+ last_cut = -minLength
+ with VideoReader(source) as video:
+ for frame in video.frames(step=step):
+ index = video.position - 1
+ small = _small_gray(frame)
+ if previous is not None:
+ score = float(np.mean(cv2.absdiff(small, previous)))
+ if score > threshold and index - last_cut >= minLength:
+ cuts.append(index)
+ last_cut = index
+ previous = small
+ return cuts
+
+
+def _small_gray(frame: np.ndarray, width: int = 64) -> np.ndarray:
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if frame.ndim == 3 else frame
+ height = max(1, round(gray.shape[0] * width / gray.shape[1]))
+ return cv2.resize(gray, (width, height), interpolation=cv2.INTER_AREA)
+
+
+def 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:
+ OSError: If the video cannot be opened.
+ ValueError: If ``count < 1``.
+ """
+ if count < 1:
+ raise ValueError(f"count must be at least 1, got {count}")
+ frames: list[np.ndarray] = []
+ with VideoReader(source) as video:
+ total = video.frameCount
+ if total <= 0:
+ frames.extend(video.frames()) # unknown length: decode everything, then pick
+ indices = _spaced(len(frames), count)
+ return [frames[i] for i in indices]
+ for index in _spaced(total, count):
+ video.seek(index)
+ frame = video.read()
+ if frame is None:
+ break
+ frames.append(frame)
+ return frames
+
+
+def _spaced(total: int, count: int) -> list[int]:
+ if total <= 0:
+ return []
+ count = min(count, total)
+ return sorted({int((i + 0.5) * total / count) for i in range(count)})
+
+
+def 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.
+
+ Args:
+ source: Video file path.
+ count: Number of frames.
+ size: ``(width, height)`` of each cell; ``None`` keeps the frame size.
+ cols: Number of columns of the grid (default: as square as possible, see :func:`montage`).
+ gap: Space in pixels between the cells.
+
+ Returns:
+ The montage image.
+
+ Raises:
+ OSError: If the video cannot be opened.
+ ValueError: If ``count < 1`` or the video has no frames.
+ """
+ frames = sampleFrames(source, count)
+ if not frames:
+ raise ValueError("the video has no frames")
+ if size is not None:
+ frames = [cv2.resize(f, size, interpolation=cv2.INTER_AREA) for f in frames]
+ return montage(frames, cols=cols, gap=gap)
diff --git a/cv2u/videoio/reader.py b/cv2u/videoio/reader.py
new file mode 100644
index 0000000..2def373
--- /dev/null
+++ b/cv2u/videoio/reader.py
@@ -0,0 +1,494 @@
+"""Video reading and writing objects: a seekable frame reader, a lazy writer, a threaded camera stream and
+frame-rate helpers."""
+
+import math
+import os
+import threading
+import time
+from collections import deque
+from collections.abc import Callable, Iterator
+from pathlib import Path
+from types import TracebackType
+
+import cv2
+import numpy as np
+
+from cv2u.videoio.video import _FOURCC_BY_EXTENSION, VideoInfo, VideoSource, _frame_channels, _open
+
+__all__ = [
+ "CameraStream",
+ "FPSCounter",
+ "VideoReader",
+ "VideoWriterEx",
+ "formatTimestamp",
+ "frameToTime",
+ "timeToFrame",
+]
+
+
+def _check_fps(fps: float) -> None:
+ if not math.isfinite(fps) or fps <= 0:
+ raise ValueError(f"fps must be positive, got {fps}")
+
+
+class 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.
+
+ Args:
+ source: File path or URL, or a camera index.
+
+ Raises:
+ OSError: If the source cannot be opened.
+
+ Example:
+ ```python
+ with VideoReader("video.mp4") as video:
+ for frame in video:
+ ...
+ ```
+ """
+
+ def __init__(self, source: VideoSource) -> None:
+ self._cap = _open(source)
+ self.source = source
+ self.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`)."""
+ self._position = 0
+
+ @property
+ def width(self) -> int:
+ """Frame width in pixels."""
+ return self.info.width
+
+ @property
+ def height(self) -> int:
+ """Frame height in pixels."""
+ return self.info.height
+
+ @property
+ def fps(self) -> float:
+ """Frame rate, or ``0.0`` when unknown (cameras and some streams)."""
+ return self.info.fps
+
+ @property
+ def frameCount(self) -> int:
+ """Number of frames (an estimate for some formats, ``0`` for cameras)."""
+ return self.info.frameCount
+
+ @property
+ def position(self) -> int:
+ """Index of the frame that the next :meth:`read` returns."""
+ return self._position
+
+ @property
+ def isOpened(self) -> bool:
+ """``False`` after :meth:`release`."""
+ return self._cap.isOpened()
+
+ def read(self) -> np.ndarray | None:
+ """Read the next frame, or return ``None`` at the end (instead of a ``(False, None)`` tuple)."""
+ ok, frame = self._cap.read()
+ if not ok:
+ return None
+ self._position += 1
+ return frame
+
+ def seek(self, 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:
+ ValueError: If ``index`` is negative.
+ """
+ if index < 0:
+ raise ValueError(f"index must not be negative, got {index}")
+ self._cap.set(cv2.CAP_PROP_POS_FRAMES, index)
+ self._position = index
+
+ def seekTime(self, seconds: float) -> None:
+ """Move to the frame at ``seconds`` from the start (see :meth:`seek`).
+
+ Raises:
+ ValueError: If ``seconds`` is negative or not finite.
+ """
+ if not math.isfinite(seconds) or seconds < 0:
+ raise ValueError(f"seconds must not be negative, got {seconds}")
+ self._cap.set(cv2.CAP_PROP_POS_MSEC, seconds * 1000.0)
+ self._position = int(self._cap.get(cv2.CAP_PROP_POS_FRAMES)) if self.fps > 0 else 0
+
+ def frames(self, 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:
+ ValueError: If ``step < 1``, ``start < 0`` or ``end < start``.
+ """
+ if step < 1:
+ raise ValueError(f"step must be at least 1, got {step}")
+ if start < 0:
+ raise ValueError(f"start must not be negative, got {start}")
+ if end is not None and end < start:
+ raise ValueError(f"end must not be before start, got start={start}, end={end}")
+ if start < self._position:
+ self.seek(start)
+ while self._position < start:
+ if not self._grab():
+ return
+ while end is None or self._position < end:
+ frame = self.read()
+ if frame is None:
+ return
+ yield frame
+ for _ in range(step - 1):
+ if (end is not None and self._position >= end) or not self._grab():
+ return
+
+ def _grab(self) -> bool:
+ if not self._cap.grab():
+ return False
+ self._position += 1
+ return True
+
+ def release(self) -> None:
+ """Release the capture. Safe to call more than once."""
+ self._cap.release()
+
+ def __iter__(self) -> Iterator[np.ndarray]:
+ return self.frames()
+
+ def __len__(self) -> int:
+ return self.frameCount
+
+ def __enter__(self) -> "VideoReader":
+ return self
+
+ def __exit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
+ ) -> None:
+ self.release()
+
+ def __repr__(self) -> str:
+ return f"VideoReader({self.source!r}, {self.width}x{self.height}, {self.fps:g} fps, {self.frameCount} frames)"
+
+
+class 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``).
+
+ Args:
+ filename: Output path.
+ fps: Frame rate.
+ fourcc: Four-character codec code, e.g. ``"XVID"``. By default chosen from the file extension.
+ isColor: ``True`` for a BGR file, ``False`` for grayscale; by default taken from the first frame.
+ makeDirs: Create missing parent directories.
+
+ Raises:
+ ValueError: If ``fps`` is not positive, ``fourcc`` has not 4 characters or no codec is known for the
+ extension.
+
+ Example:
+ ```python
+ with VideoWriterEx("out.mp4", fps=30) as writer:
+ for frame in frames:
+ writer.write(frame)
+ ```
+ """
+
+ def __init__(
+ self,
+ filename: str | os.PathLike[str],
+ fps: float,
+ fourcc: str | None = None,
+ isColor: bool | None = None,
+ makeDirs: bool = False,
+ ) -> None:
+ self.filename = os.fspath(filename)
+ _check_fps(fps)
+ extension = os.path.splitext(self.filename)[1].lower()
+ code = fourcc or _FOURCC_BY_EXTENSION.get(extension)
+ if code is None:
+ raise ValueError(f"no default codec for {extension or 'files without an extension'!r}; pass fourcc")
+ if len(code) != 4:
+ raise ValueError(f"fourcc must have 4 characters, got {code!r}")
+ self.fps = fps
+ self.fourcc = code
+ self._is_color = isColor
+ self._make_dirs = makeDirs
+ self._writer: cv2.VideoWriter | None = None
+ self._size: tuple[int, int] | None = None
+ self._count = 0
+
+ @property
+ def frameCount(self) -> int:
+ """Number of frames written so far."""
+ return self._count
+
+ @property
+ def size(self) -> tuple[int, int] | None:
+ """Frame size ``(width, height)``, or ``None`` before the first frame."""
+ return self._size
+
+ @property
+ def isColor(self) -> bool | None:
+ """Whether the file is written in color, or ``None`` before the first frame when not given."""
+ return self._is_color
+
+ @property
+ def isOpened(self) -> bool:
+ """``True`` between the first :meth:`write` and :meth:`release`."""
+ return self._writer is not None and self._writer.isOpened()
+
+ def write(self, frame: np.ndarray) -> None:
+ """Write one 8-bit grayscale or BGR frame; the first one opens the file.
+
+ Raises:
+ 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).
+ """
+ index = self._count
+ if frame.dtype != np.uint8:
+ raise ValueError(f"frame {index} must be 8-bit (uint8), got {frame.dtype}")
+ channels = _frame_channels(frame, index)
+ height, width = frame.shape[:2]
+ if self._writer is None:
+ if self._is_color is None:
+ self._is_color = channels == 3
+ if self._make_dirs:
+ Path(self.filename).parent.mkdir(parents=True, exist_ok=True)
+ self._size = (width, height)
+ self._writer = cv2.VideoWriter(
+ self.filename, cv2.VideoWriter.fourcc(*self.fourcc), self.fps, self._size, self._is_color
+ )
+ if not self._writer.isOpened():
+ self._writer.release()
+ self._writer = None
+ raise OSError(f"cannot open a video writer for {self.filename!r} with codec {self.fourcc!r}")
+ elif (width, height) != self._size:
+ assert self._size is not None
+ raise ValueError(f"frame {index} has size {width}x{height}, expected {self._size[0]}x{self._size[1]}")
+ if self._is_color and channels == 1:
+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
+ elif not self._is_color and channels == 3:
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+ self._writer.write(frame)
+ self._count += 1
+
+ def release(self) -> None:
+ """Close the file. Safe to call more than once; nothing is written if no frame was."""
+ if self._writer is not None:
+ self._writer.release()
+ self._writer = None
+
+ def __enter__(self) -> "VideoWriterEx":
+ return self
+
+ def __exit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
+ ) -> None:
+ self.release()
+
+
+class 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).
+
+ Args:
+ source: Camera index, URL or file path.
+ maxWait: Seconds to wait in :meth:`read` for the first frame before giving up.
+
+ Raises:
+ OSError: If the source cannot be opened.
+
+ Example:
+ ```python
+ with CameraStream(0) as camera:
+ while True:
+ frame = camera.read()
+ ...
+ ```
+ """
+
+ def __init__(self, source: VideoSource, maxWait: float = 5.0) -> None:
+ self._cap = _open(source)
+ self.source = source
+ self.maxWait = maxWait
+ self._frame: np.ndarray | None = None
+ self._has_frame = threading.Event()
+ self._stop = threading.Event()
+ self._lock = threading.Lock()
+ self._thread: threading.Thread | None = None
+ self._counter = FPSCounter()
+ self._ended = False
+ self._delivered = False
+
+ @property
+ def isRunning(self) -> bool:
+ """``True`` while the capture thread runs."""
+ return self._thread is not None and self._thread.is_alive()
+
+ @property
+ def ended(self) -> bool:
+ """``True`` once the source stopped delivering frames (end of file, camera lost)."""
+ return self._ended
+
+ @property
+ def fps(self) -> float:
+ """Measured capture frame rate (``0.0`` until a few frames arrived)."""
+ return self._counter.fps
+
+ def start(self) -> "CameraStream":
+ """Start the capture thread. Returns ``self`` so it can be chained."""
+ if self._thread is None:
+ self._thread = threading.Thread(target=self._run, name="cv2u.CameraStream", daemon=True)
+ self._thread.start()
+ return self
+
+ def _run(self) -> None:
+ while not self._stop.is_set():
+ ok, frame = self._cap.read()
+ if not ok:
+ self._ended = True
+ break
+ with self._lock:
+ self._frame = frame
+ self._delivered = False
+ self._counter.tick()
+ self._has_frame.set()
+ self._has_frame.set()
+
+ def read(self) -> 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.
+ """
+ self.start()
+ if not self._has_frame.wait(self.maxWait):
+ return None
+ with self._lock:
+ if self._ended and self._delivered:
+ return None
+ self._delivered = True
+ return self._frame
+
+ def stop(self) -> None:
+ """Stop the thread and release the capture. Safe to call more than once."""
+ self._stop.set()
+ if self._thread is not None:
+ self._thread.join()
+ self._thread = None
+ self._cap.release()
+
+ def __enter__(self) -> "CameraStream":
+ return self.start()
+
+ def __exit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
+ ) -> None:
+ self.stop()
+
+
+class FPSCounter:
+ """Measure a loop's frame rate as a moving average over the last ``window`` ticks.
+
+ Args:
+ window: Number of ticks the average covers.
+ clock: Time source returning seconds (``time.perf_counter`` by default); injectable for tests.
+
+ Raises:
+ ValueError: If ``window < 2``.
+
+ Example:
+ ```python
+ counter = FPSCounter()
+ for frame in cv.readFrames(0):
+ fps = counter.tick()
+ ```
+ """
+
+ def __init__(self, window: int = 30, clock: Callable[[], float] = time.perf_counter) -> None:
+ if window < 2:
+ raise ValueError(f"window must be at least 2, got {window}")
+ self.window = window
+ self._clock = clock
+ self._times: deque[float] = deque(maxlen=window)
+
+ def tick(self) -> float:
+ """Record a frame and return the current frame rate (``0.0`` until two ticks happened)."""
+ self._times.append(self._clock())
+ return self.fps
+
+ @property
+ def fps(self) -> float:
+ """Frames per second over the ticks in the window."""
+ if len(self._times) < 2:
+ return 0.0
+ elapsed = self._times[-1] - self._times[0]
+ return (len(self._times) - 1) / elapsed if elapsed > 0 else 0.0
+
+ def reset(self) -> None:
+ """Forget all ticks."""
+ self._times.clear()
+
+
+def frameToTime(index: int, fps: float) -> float:
+ """Convert a frame index to seconds from the start.
+
+ Raises:
+ ValueError: If ``fps`` is not positive.
+ """
+ _check_fps(fps)
+ return index / fps
+
+
+def timeToFrame(seconds: float, fps: float) -> int:
+ """Convert seconds from the start to the frame index shown at that time (rounded down).
+
+ Raises:
+ ValueError: If ``fps`` is not positive or ``seconds`` is not finite.
+ """
+ _check_fps(fps)
+ if not math.isfinite(seconds):
+ raise ValueError(f"seconds must be finite, got {seconds}")
+ return math.floor(seconds * fps + 1e-9)
+
+
+def 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:
+ ValueError: If ``seconds`` is negative or not finite.
+ """
+ if not math.isfinite(seconds) or seconds < 0:
+ raise ValueError(f"seconds must not be negative, got {seconds}")
+ total_ms = round(seconds * 1000) if ms else int(seconds) * 1000
+ hours, rest = divmod(total_ms, 3_600_000)
+ minutes, rest = divmod(rest, 60_000)
+ secs, millis = divmod(rest, 1000)
+ text = f"{hours:02d}:{minutes:02d}:{secs:02d}"
+ return f"{text}.{millis:03d}" if ms else text
diff --git a/cv2u/videoio/video.py b/cv2u/videoio/video.py
index 2f932b6..9305449 100644
--- a/cv2u/videoio/video.py
+++ b/cv2u/videoio/video.py
@@ -1,4 +1,3 @@
-import math
import os
from collections.abc import Iterable, Iterator
from itertools import chain
@@ -7,6 +6,8 @@
import cv2
import numpy as np
+from .._validate import check_finite
+
__all__ = ["VideoInfo", "readFrameAt", "readFrames", "videoInfo", "writeVideo"]
VideoSource = str | os.PathLike[str] | int
@@ -60,22 +61,20 @@ def readFrames(source: VideoSource, step: int = 1, start: int = 0) -> Iterator[n
"""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. The capture is released when the iteration ends, also on ``break``.
+ loop: ``for frame in cv.readFrames("video.mp4", step=5): ...``. The capture is released when the iteration
+ ends, also on ``break``.
Args:
source: File path or URL, or a camera index.
step: Yield every ``step``-th frame (skipped frames are not decoded).
start: Number of frames to skip at the beginning.
+ Returns:
+ An iterator over the frames (8-bit BGR images).
+
Raises:
OSError: If the source cannot be opened.
ValueError: If ``step < 1`` or ``start < 0``.
-
- Example:
- ```python
- for frame in cv.readFrames("video.mp4", step=5):
- ...
- ```
"""
if step < 1:
raise ValueError(f"step must be at least 1, got {step}")
@@ -138,8 +137,7 @@ def writeVideo(
OSError: If the video writer cannot be opened (for example, the codec is not available).
"""
path = os.fspath(filename)
- if not math.isfinite(fps) or fps <= 0:
- raise ValueError(f"fps must be positive, got {fps}")
+ check_finite("fps", fps, positive=True)
extension = os.path.splitext(path)[1].lower()
code = fourcc or _FOURCC_BY_EXTENSION.get(extension)
if code is None:
diff --git a/docs/api.md b/docs/api.md
index 1376cb7..2ed75af 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,5 +1,5 @@
---
-description: "API reference for cv2u: imreadEx, imwriteEx, toPillow, imencodeBase64, readFrames, writeVideo, imshowInline, resizeEx, letterbox, drawLabel, overlayMask, cropEx, montage, equalizeHistEx and more."
+description: "API reference for cv2u: VideoReader, augmentation, YOLO and COCO annotations, dnn inference, calibration, document scanning, imreadEx, imwriteEx, toPillow, imencodeBase64, readFrames, writeVideo, imshowInline, resizeEx, letterbox, drawLabel, overlayMask, cropRect, montage, equalizeHistEx and more."
---
# API reference
@@ -43,9 +43,9 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
### Regions
-::: cv2u.core.roi.cropEx
+::: cv2u.core.roi.cropRect
-::: cv2u.core.roi.centerCrop
+::: cv2u.core.roi.cropCenter
::: cv2u.core.roi.cropToContent
@@ -79,14 +79,16 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.core.extension.gammaCorrection
-::: cv2u.core.extension.DHEdge
+::: cv2u.core.extension.boldEdges
### Clustering
`peakColors` (cv2u's own method), `kmeansColors`, `dominantColors` and `colorQuantize` need nothing else.
-`meanShiftColors`, `DBSCAN` and `clusterPoints` require the `cluster` extra:
+`meanShiftColors`, `dbscanColors` and `clusterPoints` require the `cluster` extra:
`pip install "python-opencv-utils[cluster]"`.
+::: cv2u.core.cluster.Clusters
+
::: cv2u.core.cluster.dominantColors
::: cv2u.core.cluster.colorQuantize
@@ -97,12 +99,88 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.core.cluster.meanShiftColors
-::: cv2u.core.cluster.DBSCAN
+::: cv2u.core.cluster.dbscanColors
-::: cv2u.core.cluster.drawDBSCAN
+::: cv2u.core.cluster.drawClusters
::: cv2u.core.cluster.clusterPoints
+### Point sets
+
+::: cv2u.core.points.rotatePoints
+
+::: cv2u.core.points.scalePoints
+
+::: cv2u.core.points.translatePoints
+
+::: cv2u.core.points.flipPoints
+
+::: cv2u.core.points.normalizePoints
+
+::: cv2u.core.points.denormalizePoints
+
+::: cv2u.core.points.clipPoints
+
+::: cv2u.core.points.pointsBoundingBox
+
+::: cv2u.core.points.distancePoints
+
+::: cv2u.core.points.nearestPoints
+
+::: cv2u.core.points.orderPoints
+
+::: cv2u.core.points.polygonCentroid
+
+::: cv2u.core.points.angleBetween
+
+::: cv2u.core.points.lineIntersection
+
+::: cv2u.core.points.pointLineDistance
+
+### Annotation formats
+
+::: cv2u.core.annotations.maskToPolygons
+
+::: cv2u.core.annotations.polygonsToMask
+
+::: cv2u.core.annotations.boxesToPolygons
+
+::: cv2u.core.annotations.polygonsToBoxes
+
+::: cv2u.core.annotations.polygonArea
+
+::: cv2u.core.annotations.polygonIoU
+
+::: cv2u.core.annotations.maskIoU
+
+::: cv2u.core.annotations.rleEncode
+
+::: cv2u.core.annotations.rleDecode
+
+::: cv2u.core.annotations.boxesToYolo
+
+::: cv2u.core.annotations.yoloToBoxes
+
+::: cv2u.core.annotations.readYoloLabels
+
+::: cv2u.core.annotations.writeYoloLabels
+
+::: cv2u.core.annotations.labelMapToColor
+
+::: cv2u.core.annotations.colorToLabelMap
+
+::: cv2u.core.annotations.instanceMasksToLabelMap
+
+::: cv2u.core.annotations.labelMapToMasks
+
+::: cv2u.core.annotations.drawPolygons
+
+::: cv2u.core.annotations.drawSegmentation
+
+::: cv2u.core.annotations.flipBoxes
+
+::: cv2u.core.annotations.flipPolygons
+
## imgcodecs
::: cv2u.imgcodecs.files.imreadEx
@@ -115,7 +193,7 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgcodecs.files.imwriteAll
-::: cv2u.imgcodecs.urlread.urlread
+::: cv2u.imgcodecs.url.imreadUrl
::: cv2u.imgcodecs.convert.toPillow
@@ -125,6 +203,24 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgcodecs.convert.imdecodeBase64
+### Image file metadata
+
+::: cv2u.imgcodecs.meta.ImageInfo
+
+::: cv2u.imgcodecs.meta.imageInfo
+
+::: cv2u.imgcodecs.meta.exifOrientation
+
+::: cv2u.imgcodecs.meta.imreadOriented
+
+::: cv2u.imgcodecs.meta.imreadResized
+
+::: cv2u.imgcodecs.meta.imencodeEx
+
+::: cv2u.imgcodecs.meta.imdecodeEx
+
+::: cv2u.imgcodecs.meta.convertImageFormat
+
## imgproc
### Color conversion
@@ -227,7 +323,7 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgproc.detect.findCircles
-::: cv2u.imgproc.detect.detectBlobs
+::: cv2u.imgproc.detect.findBlobs
### Geometry and filters
@@ -235,6 +331,8 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgproc.resize.letterbox
+::: cv2u.imgproc.resize.Letterbox
+
::: cv2u.imgproc.geometry.fourPointTransform
::: cv2u.imgproc.geometry.translate
@@ -275,6 +373,178 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
::: cv2u.imgproc.puttext.putTextEx
+### Image statistics and quality checks
+
+::: cv2u.imgproc.stats.ImageStats
+
+::: cv2u.imgproc.stats.imageStats
+
+::: cv2u.imgproc.stats.isGrayscale
+
+::: cv2u.imgproc.stats.isBlank
+
+::: cv2u.imgproc.stats.isBlurry
+
+::: cv2u.imgproc.stats.brightnessScore
+
+::: cv2u.imgproc.stats.contrastScore
+
+::: cv2u.imgproc.stats.colorfulness
+
+::: cv2u.imgproc.stats.exposureScore
+
+::: cv2u.imgproc.stats.entropy
+
+::: cv2u.imgproc.stats.estimateNoise
+
+::: cv2u.imgproc.stats.mse
+
+::: cv2u.imgproc.stats.mae
+
+::: cv2u.imgproc.stats.histogramEx
+
+::: cv2u.imgproc.stats.histogramCompare
+
+::: cv2u.imgproc.stats.dominantHue
+
+::: cv2u.imgproc.stats.meanColor
+
+### Color arithmetic
+
+::: cv2u.imgproc.palette.CSS_COLORS
+
+::: cv2u.imgproc.palette.lightenColor
+
+::: cv2u.imgproc.palette.darkenColor
+
+::: cv2u.imgproc.palette.blendColors
+
+::: cv2u.imgproc.palette.complementaryColor
+
+::: cv2u.imgproc.palette.invertColor
+
+::: cv2u.imgproc.palette.colorDistance
+
+::: cv2u.imgproc.palette.nearestColor
+
+::: cv2u.imgproc.palette.colorName
+
+::: cv2u.imgproc.palette.textColorFor
+
+::: cv2u.imgproc.palette.randomColors
+
+::: cv2u.imgproc.palette.gradientPalette
+
+::: cv2u.imgproc.palette.colormapPalette
+
+### Data augmentation
+
+::: cv2u.imgproc.augment.addNoise
+
+::: cv2u.imgproc.augment.motionBlur
+
+::: cv2u.imgproc.augment.vignette
+
+::: cv2u.imgproc.augment.jpegArtifacts
+
+::: cv2u.imgproc.augment.randomErase
+
+::: cv2u.imgproc.augment.solarize
+
+::: cv2u.imgproc.augment.posterize
+
+::: cv2u.imgproc.augment.randomCrop
+
+::: cv2u.imgproc.augment.randomFlip
+
+::: cv2u.imgproc.augment.randomRotate
+
+::: cv2u.imgproc.augment.randomScale
+
+::: cv2u.imgproc.augment.randomPerspective
+
+::: cv2u.imgproc.augment.randomBrightnessContrast
+
+::: cv2u.imgproc.augment.randomHSV
+
+::: cv2u.imgproc.augment.randomBlur
+
+::: cv2u.imgproc.augment.mosaic
+
+::: cv2u.imgproc.augment.mixup
+
+::: cv2u.imgproc.augment.cutMix
+
+### Documents and OCR
+
+::: cv2u.imgproc.document.removeShadow
+
+::: cv2u.imgproc.document.enhanceDocument
+
+::: cv2u.imgproc.document.sauvolaThreshold
+
+::: cv2u.imgproc.document.niblackThreshold
+
+::: cv2u.imgproc.document.removeSpeckles
+
+::: cv2u.imgproc.document.removeLines
+
+::: cv2u.imgproc.document.detectTextLines
+
+::: cv2u.imgproc.document.detectTextBlocks
+
+::: cv2u.imgproc.document.removeBorder
+
+::: cv2u.imgproc.document.estimateSkew
+
+::: cv2u.imgproc.document.detectPage
+
+::: cv2u.imgproc.document.scanDocument
+
+### Stitching
+
+::: cv2u.imgproc.stitch.stitchImages
+
+::: cv2u.imgproc.stitch.stitchPair
+
+### Visualization
+
+::: cv2u.imgproc.visualize.applyColorMapEx
+
+::: cv2u.imgproc.visualize.heatmap
+
+::: cv2u.imgproc.visualize.colorBar
+
+::: cv2u.imgproc.visualize.drawArrow
+
+::: cv2u.imgproc.visualize.drawRotatedRect
+
+::: cv2u.imgproc.visualize.drawRotatedBoxes
+
+::: cv2u.imgproc.visualize.drawPolygon
+
+::: cv2u.imgproc.visualize.drawSkeleton
+
+::: cv2u.imgproc.visualize.COCO_SKELETON
+
+::: cv2u.imgproc.visualize.drawTrajectory
+
+::: cv2u.imgproc.visualize.drawCrosshair
+
+::: cv2u.imgproc.visualize.drawTextBlock
+
+::: cv2u.imgproc.visualize.drawFPS
+
+::: cv2u.imgproc.visualize.drawProgressBar
+
+::: cv2u.imgproc.visualize.drawLegend
+
+::: cv2u.imgproc.visualize.compareImages
+
+::: cv2u.imgproc.visualize.labeledMontage
+
+::: cv2u.imgproc.visualize.blendImages
+
## videoio
::: cv2u.videoio.video.readFrames
@@ -289,12 +559,100 @@ The modules mirror OpenCV's modules (see [Design principles](principles.md)).
options:
members: [width, height, fps, frameCount, duration]
+### Readers and writers
+
+::: cv2u.videoio.reader.VideoReader
+
+::: cv2u.videoio.reader.VideoWriterEx
+
+::: cv2u.videoio.reader.CameraStream
+
+::: cv2u.videoio.reader.FPSCounter
+
+::: cv2u.videoio.reader.frameToTime
+
+::: cv2u.videoio.reader.timeToFrame
+
+::: cv2u.videoio.reader.formatTimestamp
+
+### Video files
+
+::: cv2u.videoio.edit.extractFrames
+
+::: cv2u.videoio.edit.trimVideo
+
+::: cv2u.videoio.edit.concatVideos
+
+::: cv2u.videoio.edit.resizeVideo
+
+::: cv2u.videoio.edit.videoToGif
+
+::: cv2u.videoio.edit.imagesToVideo
+
+::: cv2u.videoio.edit.detectScenes
+
+::: cv2u.videoio.edit.sampleFrames
+
+::: cv2u.videoio.edit.videoThumbnail
+
## highgui
::: cv2u.highgui.display.imshowInline
::: cv2u.highgui.display.imshowEx
+## calib3d
+
+Camera calibration helpers; the OpenCV calib3d functions (`cv.calibrateCamera`, `cv.undistort`, ...) stay available as they are.
+
+### Camera calibration
+
+::: cv2u.calib3d.calibrate.CameraCalibration
+
+::: cv2u.calib3d.calibrate.makeChessboard
+
+::: cv2u.calib3d.calibrate.objectPointsGrid
+
+::: cv2u.calib3d.calibrate.findChessboardEx
+
+::: cv2u.calib3d.calibrate.calibrateCameraEx
+
+::: cv2u.calib3d.calibrate.reprojectionErrors
+
+::: cv2u.calib3d.calibrate.undistortEx
+
+::: cv2u.calib3d.calibrate.saveCalibration
+
+::: cv2u.calib3d.calibrate.loadCalibration
+
+## 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
+
+::: cv2u.dnn.inference.PreprocessInfo
+
+::: cv2u.dnn.inference.Detections
+
+::: cv2u.dnn.inference.loadModel
+
+::: cv2u.dnn.inference.readClassNames
+
+::: cv2u.dnn.inference.preprocessImage
+
+::: cv2u.dnn.inference.inferImage
+
+::: cv2u.dnn.inference.postprocessDetections
+
+::: cv2u.dnn.inference.postprocessClassification
+
+::: cv2u.dnn.inference.softmax
+
+::: cv2u.dnn.inference.sigmoid
+
+::: cv2u.dnn.inference.drawDetections
+
## flag
Named constants for magic numbers that OpenCV functions take without a constant of their own.
diff --git a/docs/index.md b/docs/index.md
index 7619cad..a9ed395 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,5 +1,5 @@
---
-description: "cv2u is a drop-in replacement for OpenCV's cv2 module (import cv2u as cv) that adds crop-free rotation, DBSCAN color clustering, Unicode text rendering and more, with full type hints."
+description: "cv2u is a drop-in replacement for OpenCV's cv2 module (import cv2u as cv) that adds video reading and editing, data augmentation, COCO/YOLO annotation formats, ONNX inference with cv.dnn, camera calibration, document scanning, image statistics, visualization, Unicode paths and text, and more, with full type hints."
---
# Python OpenCV Utilities
@@ -22,10 +22,11 @@ pip install "python-opencv-utils[opencv]" # opencv-python
pip install "python-opencv-utils[headless]" # opencv-python-headless (servers, Docker; no GUI)
pip install "python-opencv-utils[contrib]" # opencv-contrib-python
pip install "python-opencv-utils[contrib-headless]" # opencv-contrib-python-headless
-pip install "python-opencv-utils[opencv,cluster]" # also scikit-learn (meanShiftColors, DBSCAN, clusterPoints)
+pip install "python-opencv-utils[opencv,cluster]" # also scikit-learn (meanShiftColors, dbscanColors, clusterPoints)
```
If the project already has OpenCV installed, `pip install python-opencv-utils` without an extra uses it.
+The optional `cluster` extra adds `scikit-learn` for `meanShiftColors`, `dbscanColors` and `clusterPoints`.
| | |
|---|---|
@@ -60,7 +61,7 @@ src = cv.imreadEx("C:/사진/고양이.jpg") # cv.imread fails on non-ASCII pat
small = cv.resizeEx(src, width=640) # keeps the aspect ratio
boxed, scale, (left, top) = cv.letterbox(src, (640, 640)) # fit + pad, e.g. for a model input
logo = cv.imread("logo.png", cv.IMREAD_UNCHANGED) # BGRA with transparency
-stamped = cv.overlayImage(small, logo, org=(10, 10), opacity=0.8)
+stamped = cv.overlayImage(small, logo, org=(10, 10), alpha=0.8)
cv.imwriteEx("C:/사진/비교.png", cv.hconcatEx([small, stamped], gap=8))
```
@@ -87,7 +88,7 @@ img = cv.imread("street.jpg")
detections = [((40, 60, 120, 200), "person", 0.94), ((200, 90, 160, 110), "자동차", 0.88)]
crops = []
for box, name, score in detections:
- crops.append(cv.cropEx(img, box, margin=10, fill=0)) # safe even at the image border
+ crops.append(cv.cropRect(img, box, margin=10, fill=0)) # safe even at the image border
cv.drawLabel(img, box, f"{name} {score:.2f}", (0, 200, 255), fontPath="C:/Windows/Fonts/malgun.ttf")
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
@@ -97,6 +98,81 @@ cv.imwrite("result.png", cv.montage([img, cv.overlayMask(img, red, (255, 0, 255)
payload = {"image": cv.imencodeBase64(img, ".jpg", dataUri=True)} # for a JSON API or an HTML
```
+### Training data
+
+```python
+import cv2u as cv
+
+img = cv.imread("train/0001.jpg")
+size = (img.shape[1], img.shape[0])
+boxes, classIds = cv.readYoloLabels("train/0001.txt", size) # normalized rows -> pixel (x, y, w, h)
+img, boxes = cv.randomFlip(img, horizontal=0.5, boxes=boxes, seed=1) # the boxes follow the image
+img, boxes = cv.randomRotate(img, maxAngle=10, boxes=boxes, seed=1)
+img = cv.randomHSV(cv.addNoise(img, "gaussian", seed=1), hue=10, seed=1)
+cv.writeYoloLabels("aug/0001.txt", boxes, classIds, size, makeDirs=True)
+cv.imwriteEx("aug/0001.jpg", cv.jpegArtifacts(img, quality=40))
+
+tiles = cv.imreadAll(["train/0001.jpg", "train/0002.jpg", "train/0003.jpg", "train/0004.jpg"])
+labels = [cv.readYoloLabels(f"train/{i:04d}.txt", (t.shape[1], t.shape[0]))[0] for i, t in enumerate(tiles, 1)]
+big, bigBoxes = cv.mosaic(tiles, (640, 640), boxes=labels, seed=1) # YOLO-style 4-image mosaic
+polygons = cv.maskToPolygons(cv.binarize(img, "otsu", invert=True)) # COCO polygons from a mask
+rle = cv.rleEncode(cv.polygonsToMask(polygons, size)) # and uncompressed RLE, no pycocotools needed
+```
+
+### Running a model
+
+```python
+import cv2u as cv
+
+net = cv.dnn.loadModel("C:/모델/yolov8n.onnx") # Unicode path; FileNotFoundError instead of a C++ assertion
+names = cv.dnn.readClassNames("coco.names")
+img = cv.imread("street.jpg")
+blob, info = cv.dnn.preprocessImage(img, (640, 640)) # letterbox + blob; info remembers the geometry
+output = cv.dnn.inferImage(net, blob)[0] # every output layer, not just the first
+dets = cv.dnn.postprocessDetections(
+ output, info, scoreThreshold=0.3
+) # YOLO rows -> Detections(boxes, scores, classIds)
+cv.imwrite("result.png", cv.dnn.drawDetections(img, dets, names)) # boxes on the original image
+```
+
+Everything else in `cv.dnn` (`cv.dnn.readNet`, `cv.dnn.blobFromImage`, `cv.dnn.NMSBoxes`, ...) is passed through from OpenCV.
+
+### Video tools
+
+```python
+import cv2u as cv
+
+fps = cv.FPSCounter()
+with cv.VideoReader("input.mp4") as video, cv.VideoWriterEx("out.mp4", fps=video.fps) as writer:
+ video.seekTime(5.0) # start at 00:05
+ for frame in video:
+ fps.tick()
+ writer.write(cv.drawFPS(cv.autoCanny(frame), fps.fps)) # codec, size and color mode from the first frame
+
+cuts = cv.detectScenes("input.mp4", threshold=30) # frame indices where a new shot starts
+print([cv.formatTimestamp(cv.frameToTime(i, video.fps)) for i in cuts]) # "00:00:12.400", ...
+cv.extractFrames("input.mp4", "frames/", step=30, ext=".png") # one file every 30 frames
+cv.videoToGif("input.mp4", "preview.gif", fps=10, size=(320, 180), maxFrames=50)
+cv.imwrite("sheet.jpg", cv.videoThumbnail("input.mp4", count=6, cols=3)) # contact sheet
+```
+
+### Documents and quality
+
+```python
+import cv2u as cv
+
+photo = cv.imread("receipt.jpg")
+page = cv.scanDocument(photo) # detect the page, warp it upright, clean the background
+mask = cv.sauvolaThreshold(page, invert=True) # local threshold for OCR, no contrib module needed
+for x, y, w, h in cv.detectTextLines(page): # one box per text line, top to bottom
+ cv.drawDashedRectangle(page, (x, y, w, h), (0, 160, 255))
+
+stats = cv.imageStats(photo) # ImageStats(width, height, channels, dtype, mean, std, ..., sharpness, entropy, isGray)
+if cv.isBlurry(photo) or cv.isBlank(photo):
+ print("retake:", stats.sharpness, stats.contrast)
+cv.imwrite("compare.png", cv.compareImages(photo, page, mode="side", labels=["photo", "scan"]))
+```
+
### rotateEx
Rotates an image without cropping its corners. The canvas grows to fit the result.
@@ -153,13 +229,13 @@ images, simply add up, so it neither needs a sample nor splits flat colors apart
`meanShiftColors` added two clusters of 421 and 79 pixels. `bins` and `sigma` make it finer or coarser, and
`minRegion` absorbs small speckles into the surrounding region.
-
+
On a real photo of a sneaker, `peakColors` separates background, the dark and bright
greens and the white parts into 4 clean regions. `meanShiftColors` finds 6 colors but leaves the surface
-speckled, and `DBSCAN` with `eps=1.7` splits the image into 496 tiny clusters, which mostly reproduces the input.
+speckled, and `dbscanColors` with `eps=1.7` splits the image into 496 tiny clusters, which mostly reproduces the input.
Note that the dark-red star (15 pixels, 0.04% of the image, almost black) merges into the background with every
-color clustering except that very fine `DBSCAN`; details this small are below what a palette can keep.
+color clustering except that very fine `dbscanColors`; details this small are below what a palette can keep.
```python
import cv2u as cv
diff --git a/docs/principles.md b/docs/principles.md
index 3fd2a1e..cbb1dfa 100644
--- a/docs/principles.md
+++ b/docs/principles.md
@@ -27,7 +27,7 @@ Never re-implement something OpenCV already does well.
| `toPillow`, `fromPillow` | Converting to/from Pillow needs channel reordering, and `np.asarray` gets palette, CMYK, premultiplied-alpha and big-endian 16-bit images wrong. |
| `imencodeBase64`, `imdecodeBase64` | Web APIs exchange images as base64 or data URIs; OpenCV only encodes to bytes. |
| `drawLabel`, `overlayMask` | A detector-style labeled box or a translucent mask takes `getTextSize` math and blending code. |
-| `cropEx` | Slicing with boxes that extend outside the image silently returns wrong or empty regions. |
+| `cropRect` | Slicing with boxes that extend outside the image silently returns wrong or empty regions. |
| `montage` | No function arranges many images in a grid. |
| `equalizeHistEx` | `cv.equalizeHist` rejects color images. |
| `inRangeEx` | `cv.inRange` silently selects nothing for hue ranges that wrap around, such as red. |
@@ -56,21 +56,48 @@ Never re-implement something OpenCV already does well.
| `boxIoU` | Box overlap is computed only inside `cv.dnn.NMSBoxes`; matching and tracking code rewrites it. |
| `nms`, `xywhToXyxy`, `xyxyToXywh`, `clipBoxes`, `scaleBoxes`, `expandBoxes` | `cv.dnn.NMSBoxes` wants lists and returns a tuple when empty; mapping boxes back through a letterbox, clipping and padding them are the same arithmetic in every detector script. |
| `binarize`, `morphology` | `cv.threshold` wants 8-bit grayscale and returns a tuple, adaptive thresholding is a separate function; every `morphologyEx` call starts with `getStructuringElement`. |
-| `findLines`, `findCircles`, `detectBlobs` | `cv.HoughLinesP` / `cv.HoughCircles` return `None` or `(N, 1, 4)` / `(1, N, 3)` and need an edge or blurred image first; `SimpleBlobDetector` takes a `Params` object with a dozen fields. |
+| `findLines`, `findCircles`, `findBlobs` | `cv.HoughLinesP` / `cv.HoughCircles` return `None` or `(N, 1, 4)` / `(1, N, 3)` and need an edge or blurred image first; `SimpleBlobDetector` takes a `Params` object with a dozen fields. |
| `matchFeatures`, `alignImages` | Detector, matcher norm, `knnMatch`, ratio test, keypoint unpacking and `findHomography` with RANSAC are the same twelve lines before every registration. |
-| `maskBoundingRect`, `applyMask`, `centerCrop` | `cv.boundingRect(cv.findNonZero(mask))` fails on empty or color masks; `cv.bitwise_and` with a mask only gives black; a center crop is index arithmetic. |
+| `maskBoundingRect`, `applyMask`, `cropCenter` | `cv.boundingRect(cv.findNonZero(mask))` fails on empty or color masks; `cv.bitwise_and` with a mask only gives black; a center crop is index arithmetic. |
| `drawBoxes`, `drawPoints`, `drawGrid`, `distinctColors` | Drawing many detections or keypoints in distinct colors, with labels, is a loop everyone writes; OpenCV has no palette. |
| `pixelate`, `drawRoundedRectangle` | Mosaic anonymization and rounded boxes take resize and arc arithmetic. |
| `listImages`, `imreadAll`, `imwriteAll` | Collecting the image files of a folder (in natural order) is glob and sort boilerplate; `cv.imread` returns `None` silently, so a batch loop needs its own error handling. |
| `mapTiles` | Running a fixed-input model over a large image is split, loop, merge and seam averaging every time. |
| `readFrameAt` | Reading one frame means open, seek, read and release. |
| `putTextEx` | `cv.putText` only has the Hershey fonts, which cover ASCII only. |
-| `urlread` | `cv.imread` cannot read from a URL. |
+| `imreadUrl` | `cv.imread` cannot read from a URL. |
| `imcolor`, `imcolorLike`, `makeGradient` | There is no function to create a filled or gradient image. |
-| `gammaCorrection`, `centerPoint` | Lookup-table and image-moment boilerplate. |
+| `gammaCorrection`, `centerPoint`, `boldEdges` | Lookup-table, image-moment and morphological-gradient boilerplate. |
| `dominantColors`, `colorQuantize`, `kmeansColors` | `cv.kmeans` needs reshaping, float conversion and criteria, and its results change from run to run (global RNG). |
| `peakColors` | Automatic color clustering usually needs scikit-learn, samples the pixels and is slow; cv2u's own histogram-peak method needs neither. |
-| `meanShiftColors`, `DBSCAN`, `drawDBSCAN`, `clusterPoints` | OpenCV has no clustering that finds the number of groups by itself, for colors or for points. |
+| `meanShiftColors`, `dbscanColors`, `drawClusters`, `clusterPoints` | OpenCV has no clustering that finds the number of groups by itself, for colors or for points. |
+| `VideoReader`, `VideoWriterEx`, `CameraStream` | `cv.VideoCapture`/`cv.VideoWriter` need `isOpened()` checks, `CAP_PROP_*` getters, fourcc/size/`isColor` up front, manual `release()`, and buffer live streams so a slow consumer reads stale frames. |
+| `extractFrames`, `trimVideo`, `concatVideos`, `resizeVideo`, `videoToGif`, `imagesToVideo` | Every "ffmpeg-lite" task (dump frames, cut, join, resize, GIF, time-lapse) is the same read/write loop; OpenCV cannot write GIFs at all. |
+| `detectScenes`, `sampleFrames`, `videoThumbnail`, `FPSCounter`, `formatTimestamp` | Scene cuts, preview sheets, FPS overlays and `HH:MM:SS.mmm` stamps are rewritten in every video script. |
+| `addNoise`, `motionBlur`, `vignette`, `jpegArtifacts`, `solarize`, `posterize` | Classic photo degradations for augmentation have no OpenCV function (`cv.randn` needs a preallocated array; directional blur, vignetting, solarize and posterize are rewritten in every project). |
+| `randomCrop`, `randomFlip`, `randomRotate`, `randomScale`, `randomPerspective` | `cv.flip`/`cv.warpAffine` never touch the detection boxes; keeping labels aligned with a random geometric transform is bookkeeping everyone rewrites. |
+| `mosaic`, `mixup`, `cutMix`, `randomErase` | The standard detector/classifier mixing augmentations otherwise require albumentations or a framework-specific loader. |
+| `maskToPolygons`, `polygonsToMask`, `rleEncode`, `rleDecode` | Datasets store masks as COCO polygons or RLE; `cv.findContours`/`cv.fillPoly` need `int32 (N, 1, 2)` arrays, keep one-pixel specks, and OpenCV has no run-length encoding at all. |
+| `boxesToYolo`, `yoloToBoxes`, `readYoloLabels`, `writeYoloLabels`, `flipBoxes`, `flipPolygons` | Normalized `class cx cy w h` label files and keeping annotations aligned with `cv.flip` are the same arithmetic in every training script. |
+| `polygonIoU`, `polygonArea`, `maskIoU`, `labelMapToColor`, `colorToLabelMap`, `drawSegmentation` | `cv.intersectConvexConvex` only handles convex shapes, `cv.contourArea` rounds to integers, and coloring / recovering a class-id map has no OpenCV function. |
+| `preprocessImage`, `postprocessDetections` | `cv.dnn.blobFromImage` stretches the image and forgets the geometry, and nothing in OpenCV decodes YOLO-style outputs; cv2u letterboxes, keeps the mapping and returns boxes on the original image after per-class NMS. |
+| `loadModel`, `readClassNames` | `cv.dnn.readNet` cannot open non-ASCII paths on Windows and reports a missing file as a C++ assertion; cv2u reads ONNX/TFLite/TF models through Python and raises `FileNotFoundError`. |
+| `inferImage`, `drawDetections` | `Net.forward()` returns only the first output and OpenCV has no labeled-detection drawing; cv2u returns every output layer and draws boxes with class names and scores. |
+| `heatmap`, `applyColorMapEx`, `colorBar` | `cv.applyColorMap` only takes an 8-bit map of the image size; overlaying a float attention/saliency map means normalize, convert, resize and `addWeighted` every time, and there is no legend strip. |
+| `drawArrow`, `drawRotatedRect`, `drawPolygon`, `drawSkeleton`, `drawTrajectory`, `drawCrosshair` | `cv.arrowedLine` sizes the head relative to the arrow length, OpenCV cannot draw its own `RotatedRect`, `polylines`/`fillPoly` need `int32 (N, 1, 2)` and draw opaque only, and poses, tracks and crosshairs have no drawing function. |
+| `drawTextBlock`, `drawFPS`, `drawProgressBar`, `drawLegend`, `compareImages`, `labeledMontage`, `blendImages` | `cv.putText` writes one line with no background; HUD panels, before/after views (split, blend, diff) and titled grids are the same boilerplate in every demo; `cv.addWeighted` blends exactly two images. |
+| `imageStats`, `isBlank`, `isBlurry`, `estimateNoise` | Dataset triage (flat frames, out-of-focus shots, noise level, entropy) needs a handful of numpy formulas per image; `cv.meanStdDev`/`cv.minMaxLoc` only cover parts and `cv.minMaxLoc` rejects color images. |
+| `histogramEx`, `histogramCompare` | `cv.calcHist` takes lists of images, channels and ranges per dtype and returns a `(bins, 1)` column per call; comparing two images needs the same setup twice plus normalization. |
+| `mse`, `mae`, `colorfulness`, `dominantHue` | Only `cv.PSNR` exists for error metrics (log scale, overflow-prone on `uint8` by hand), and there is no colorfulness or dominant-hue measure. |
+| `sauvolaThreshold`, `niblackThreshold` | Local thresholds for OCR only exist in the `ximgproc` contrib module (`niBlackThreshold`), which `opencv-python` does not ship; here they are built from `cv.integral2`. |
+| `removeShadow`, `removeLines`, `removeSpeckles`, `enhanceDocument` | Cleaning a photographed page (shadows, table rules, dust) is a well-known chain of dilate/medianBlur/morphologyEx/inpaint calls that every OCR project rewrites. |
+| `detectPage`, `scanDocument`, `detectTextLines`, `detectTextBlocks`, `estimateSkew`, `removeBorder` | There is no function from "photo of a document" to an upright page, its text lines or its skew angle; only the primitives (`Canny`, `approxPolyDP`, `connectedComponentsWithStats`). |
+| `findChessboardEx`, `calibrateCameraEx`, `undistortEx` | The calibration tutorial is a page of boilerplate: object-point grids, `(found, corners)` tuples with `(N,1,2)` shapes, a separate `cornerSubPix` on a gray copy, and `undistort` that leaves black borders unless you also call `getOptimalNewCameraMatrix` and crop the ROI. |
+| `saveCalibration`, `loadCalibration` | `cv.FileStorage` writes YAML/XML and cannot open non-ASCII paths on Windows; a JSON file works everywhere. |
+| `stitchImages`, `stitchPair` | `cv.Stitcher.stitch` returns a bare integer status and `None` instead of raising, and the bare `warpPerspective` stitch cuts off whatever lands outside the first image. |
+| `imageInfo`, `imreadOriented`, `imreadResized` | `cv.imread` must decode the whole file to tell its size, applies the EXIF orientation only for `IMREAD_COLOR`/`IMREAD_GRAYSCALE` (not for `IMREAD_UNCHANGED` or `IMREAD_REDUCED_*`), and reduced-size decoding is a flag few know. |
+| `imencodeEx`, `imdecodeEx`, `convertImageFormat` | `cv.imencode` returns `(ok, array)` instead of `bytes`, `cv.imdecode` needs `np.frombuffer` first, and converting a file to JPEG silently drops the alpha channel. |
+| `lightenColor`, `colorName`, `textColorFor`, `rotatePoints`, `distancePoints`, `lineIntersection` | OpenCV converts whole images between color spaces but has nothing for one color, and transforms points only through matrices: no distance matrix, corner ordering, flip or line intersection. |
| `FLIP_MODE_*`, `DDEPTH_SAME`, `ALL_CONTOURS`, `REDUCE_TO_*`, `WAIT_FOREVER`, `KEY_*` | Parameters such as `flipCode`, `ddepth`, `contourIdx`, `dim` and `cv.waitKey` take magic numbers with no OpenCV constant (OpenCV's own constants like `cv.FILLED` are used as they are). |
## 2. Look like OpenCV
@@ -78,7 +105,8 @@ Never re-implement something OpenCV already does well.
An extension should feel like it was always part of OpenCV.
- **Modules** mirror OpenCV's: `core`, `imgcodecs` (reading and writing images), `imgproc` (image processing),
- `videoio` (video files and cameras) and `highgui` (showing images).
+ `videoio` (video files and cameras), `highgui` (showing images), `calib3d` (camera calibration) and `dnn`
+ (inference; `cv.dnn` is the `cv2u.dnn` package, which passes every OpenCV name through).
An extension goes where the OpenCV function it extends lives (`resizeEx` in `imgproc` like `cv.resize`).
- **Names** use camelCase like OpenCV. An extended version of an existing OpenCV function gets the `Ex` suffix
(`rotateEx` for `cv.rotate`, `putTextEx` for `cv.putText`). Constants use `UPPER_CASE`.
@@ -117,7 +145,8 @@ color quantization work without scikit-learn.
## 6. Change carefully
-Once a function is released, code that uses it should keep working:
+Once a function is released, code that uses it should keep working. 1.0.0 reset the API once (renames and
+signature changes without aliases; see the changelog); from 1.0 on the deprecation rule applies:
- A renamed function keeps its old name as a deprecated alias that emits a `DeprecationWarning`
for at least one minor release.
diff --git a/pyproject.toml b/pyproject.toml
index 663e688..612071f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
[project]
name = "python-opencv-utils"
dynamic = ["version"]
-description = "Drop-in cv2 replacement (import cv2u as cv) with extra OpenCV utilities: crop-free rotation, DBSCAN color clustering, Unicode text rendering, gradients and more"
+description = "Drop-in cv2 replacement (import cv2u as cv) with extra OpenCV utilities: video editing, data augmentation, COCO/YOLO annotations, ONNX inference, camera calibration, document scanning, image statistics, visualization, color clustering, Unicode paths and text, and more"
readme = "README.md"
license = "Apache-2.0"
license-files = ["LICENSE", "NOTICE"]
@@ -90,6 +90,34 @@ keywords = [
"histogram",
"skeletonization",
"background-removal",
+ "video-editing",
+ "video-writer",
+ "scene-detection",
+ "gif",
+ "data-augmentation",
+ "augmentation",
+ "mixup",
+ "cutmix",
+ "yolo",
+ "coco",
+ "rle",
+ "dnn",
+ "onnx",
+ "inference",
+ "object-detection",
+ "camera-calibration",
+ "undistort",
+ "stitching",
+ "panorama",
+ "ocr",
+ "deskew",
+ "heatmap",
+ "visualization",
+ "exif",
+ "image-metadata",
+ "image-statistics",
+ "css-colors",
+ "color-names",
"numpy",
"pillow",
"utilities",
@@ -97,7 +125,7 @@ keywords = [
"type-hints",
]
classifiers = [
- "Development Status :: 4 - Beta",
+ "Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
@@ -133,7 +161,7 @@ opencv = ["opencv-python>=4.10.0.84"]
headless = ["opencv-python-headless>=4.10.0.84"]
contrib = ["opencv-contrib-python>=4.10.0.84"]
contrib-headless = ["opencv-contrib-python-headless>=4.10.0.84"]
-# Needed only for meanShiftColors, DBSCAN and clusterPoints.
+# Needed only for meanShiftColors, dbscanColors and clusterPoints.
cluster = ["scikit-learn>=1.4.2"]
# Labels follow https://packaging.python.org/en/latest/specifications/well-known-project-urls/
diff --git a/tests/data/DHEdge.png b/tests/data/boldEdges.png
similarity index 100%
rename from tests/data/DHEdge.png
rename to tests/data/boldEdges.png
diff --git a/tests/data/drawClusters.png b/tests/data/drawClusters.png
new file mode 100644
index 0000000..79e5162
Binary files /dev/null and b/tests/data/drawClusters.png differ
diff --git a/tests/data/drawDBSCAN.png b/tests/data/drawDBSCAN.png
deleted file mode 100644
index 3b85966..0000000
Binary files a/tests/data/drawDBSCAN.png and /dev/null differ
diff --git a/tests/test_annotations.py b/tests/test_annotations.py
new file mode 100644
index 0000000..43d3a9d
--- /dev/null
+++ b/tests/test_annotations.py
@@ -0,0 +1,559 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.core.annotations import (
+ __all__,
+ boxesToPolygons,
+ boxesToYolo,
+ colorToLabelMap,
+ drawPolygons,
+ drawSegmentation,
+ flipBoxes,
+ flipPolygons,
+ instanceMasksToLabelMap,
+ labelMapToColor,
+ labelMapToMasks,
+ maskIoU,
+ maskToPolygons,
+ polygonArea,
+ polygonIoU,
+ polygonsToBoxes,
+ polygonsToMask,
+ readYoloLabels,
+ rleDecode,
+ rleEncode,
+ writeYoloLabels,
+ yoloToBoxes,
+)
+
+SIZE = (160, 120) # width, height
+
+
+@pytest.fixture
+def mask():
+ # A square on the left, a circle on the right.
+ img = np.zeros((120, 160), np.uint8)
+ cv2.rectangle(img, (20, 20), (69, 69), 255, cv2.FILLED)
+ cv2.circle(img, (115, 60), 25, 255, cv2.FILLED)
+ return img
+
+
+def test_names_do_not_exist_in_cv2():
+ assert not [name for name in __all__ if hasattr(cv2, name)]
+
+
+# --- masks and polygons ----------------------------------------------------------
+
+
+def test_maskToPolygons_shapes_and_order(mask):
+ polygons = maskToPolygons(mask)
+ assert len(polygons) == 2
+ assert all(p.ndim == 2 and p.shape[1] == 2 and p.dtype == np.int32 for p in polygons)
+ assert cv2.contourArea(polygons[0]) >= cv2.contourArea(polygons[1]) # square (2500) first, then circle
+
+
+def test_maskToPolygons_epsilon_simplifies_and_minArea_filters(mask):
+ mask[5, 5] = 255 # a one-pixel speck
+ polygons = maskToPolygons(mask, epsilon=0.02)
+ assert len(polygons) == 2 # the speck has fewer than 3 points
+ square = min(polygons, key=len)
+ assert len(square) == 4
+ assert len(maskToPolygons(mask, minArea=2000)) == 1
+
+
+def test_maskToPolygons_bool_and_color_input(mask):
+ assert len(maskToPolygons(mask.astype(bool))) == 2
+ assert len(maskToPolygons(cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR))) == 2
+ assert maskToPolygons(np.zeros((10, 10), np.uint8)) == []
+
+
+def test_maskToPolygons_validation(mask):
+ with pytest.raises(ValueError, match="epsilon"):
+ maskToPolygons(mask, epsilon=-1)
+ with pytest.raises(ValueError, match="minArea"):
+ maskToPolygons(mask, minArea=float("nan"))
+ with pytest.raises(ValueError, match="mask"):
+ maskToPolygons(np.zeros((0, 5), np.uint8))
+
+
+def test_polygonsToMask_round_trip(mask):
+ out = polygonsToMask(maskToPolygons(mask), SIZE)
+ assert out.shape == (120, 160) and out.dtype == np.uint8
+ assert maskIoU(out, mask) > 0.97
+
+
+def test_polygonsToMask_single_polygon_value_and_empty():
+ out = polygonsToMask(np.array([[0, 0], [9.6, 0], [9.6, 9.6], [0, 9.6]]), (20, 20), value=7)
+ assert set(np.unique(out)) == {0, 7}
+ assert out[0, 0] == 7 and out[15, 15] == 0
+ assert polygonsToMask([], (4, 3)).shape == (3, 4)
+ assert not polygonsToMask([], (4, 3)).any()
+ assert polygonsToMask([[(1, 1), (3, 1), (3, 3)]], (5, 5)).any()
+
+
+def test_polygonsToMask_validation():
+ with pytest.raises(ValueError, match="size"):
+ polygonsToMask([], (0, 5))
+ with pytest.raises(ValueError, match="value"):
+ polygonsToMask([], (5, 5), value=0)
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask([np.zeros((0, 2))], (5, 5))
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask(np.zeros((0, 2)), (5, 5))
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask([[(1, 2, 3)]], (5, 5))
+ with pytest.raises(ValueError, match="finite"):
+ polygonsToMask([[(1, np.nan), (2, 2), (3, 3)]], (5, 5))
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask(np.zeros((2, 3)), (5, 5))
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask([[[[[1, 2]]]]], (5, 5)) # 5-D: not a polygon list
+ with pytest.raises(ValueError, match="polygons"):
+ polygonsToMask([np.zeros((2, 2, 2))], (5, 5)) # (N, 2, 2) is neither (N, 2) nor (N, 1, 2)
+ assert polygonsToMask(np.zeros((3, 1, 2), np.int32), (5, 5)).shape == (5, 5) # one (N, 1, 2) contour
+
+
+def test_boxesToPolygons_and_back():
+ boxes = np.array([[10, 20, 30, 40], [0.5, 1.5, 2, 3]])
+ polygons = boxesToPolygons(boxes)
+ assert len(polygons) == 2 and polygons[0].shape == (4, 2)
+ np.testing.assert_array_equal(polygons[0], [[10, 20], [40, 20], [40, 60], [10, 60]])
+ np.testing.assert_allclose(polygonsToBoxes(polygons), boxes)
+ assert boxesToPolygons([]) == []
+ assert polygonsToBoxes([]).shape == (0, 4)
+ assert polygonsToBoxes(np.array([[1, 1], [4, 1], [4, 5]])).tolist() == [[1, 1, 3, 4]]
+ with pytest.raises(ValueError, match="boxes"):
+ boxesToPolygons([1, 2, 3])
+
+
+def test_polygonArea():
+ assert polygonArea([(0, 0), (4, 0), (4, 3), (0, 3)]) == 12.0
+ assert polygonArea([(0, 0), (0.5, 0), (0.5, 0.5), (0, 0.5)]) == pytest.approx(0.25) # cv.contourArea gives 0
+ assert polygonArea([(0, 0), (1, 1)]) == 0.0
+ with pytest.raises(ValueError, match="polygon"):
+ polygonArea([])
+
+
+def test_polygonIoU_precision():
+ a = [(0, 0), (10, 0), (10, 10), (0, 10)]
+ b = [(5, 0), (15, 0), (15, 10), (5, 10)]
+ assert polygonIoU(a, b) == pytest.approx(1 / 3, abs=0.01)
+ assert polygonIoU(a, a) == pytest.approx(1.0, abs=0.005)
+ assert polygonIoU(a, [(20, 20), (30, 20), (30, 30)]) == 0.0
+ # Concave shape (an L) against its bounding square: 3/4 of the square.
+ ell = [(0, 0), (10, 0), (10, 5), (5, 5), (5, 10), (0, 10)]
+ assert polygonIoU(ell, a) == pytest.approx(0.75, abs=0.01)
+ # Normalized coordinates work too (the raster is scaled to the resolution).
+ tiny_a = [(0, 0), (0.1, 0), (0.1, 0.1), (0, 0.1)]
+ tiny_b = [(0.05, 0), (0.15, 0), (0.15, 0.1), (0.05, 0.1)]
+ assert polygonIoU(tiny_a, tiny_b) == pytest.approx(1 / 3, abs=0.01)
+
+
+def test_polygonIoU_degenerate_and_validation():
+ assert polygonIoU([(0, 0), (1, 1)], [(0, 0), (1, 0), (1, 1)]) == 0.0
+ assert polygonIoU([(1, 1), (1, 1), (1, 1)], [(1, 1), (1, 1), (1, 1)]) == 0.0
+ with pytest.raises(ValueError, match="resolution"):
+ polygonIoU([(0, 0), (1, 0), (1, 1)], [(0, 0), (1, 0), (1, 1)], resolution=0)
+ with pytest.raises(ValueError, match="polygonB"):
+ polygonIoU([(0, 0), (1, 0), (1, 1)], [])
+
+
+def test_maskIoU(mask):
+ assert maskIoU(mask, mask) == 1.0
+ assert maskIoU(mask, np.zeros_like(mask)) == 0.0
+ assert maskIoU(np.zeros_like(mask), np.zeros_like(mask)) == 0.0
+ half = mask.copy()
+ half[:, 80:] = 0
+ inter = np.count_nonzero(half)
+ assert maskIoU(mask, half.astype(bool)) == pytest.approx(inter / np.count_nonzero(mask))
+ with pytest.raises(ValueError, match="maskB"):
+ maskIoU(mask, mask[:50])
+
+
+# --- RLE -------------------------------------------------------------------------
+
+
+def test_rle_round_trip(mask):
+ rle = rleEncode(mask)
+ assert rle["size"] == [120, 160]
+ assert all(isinstance(c, int) for c in rle["counts"])
+ assert sum(rle["counts"]) == 120 * 160
+ np.testing.assert_array_equal(rleDecode(rle), mask)
+
+
+def test_rleEncode_column_major_like_pycocotools():
+ m = np.array([[1, 0, 1], [1, 1, 0]], np.uint8)
+ # Fortran order: column 0 = (1, 1), column 1 = (0, 1), column 2 = (1, 0) -> 1 1 0 1 1 0
+ assert rleEncode(m) == {"counts": [0, 2, 1, 2, 1], "size": [2, 3]}
+ assert rleEncode(np.zeros((2, 2), bool)) == {"counts": [4], "size": [2, 2]}
+ assert rleEncode(np.ones((2, 2), bool)) == {"counts": [0, 4], "size": [2, 2]}
+ np.testing.assert_array_equal(rleDecode(rleEncode(m)), m * 255)
+
+
+def test_rleDecode_validation():
+ with pytest.raises(ValueError, match="size"):
+ rleDecode({"counts": [], "size": [0, 3]})
+ with pytest.raises(ValueError, match="add up"):
+ rleDecode({"counts": [1, 2], "size": [2, 2]})
+ with pytest.raises(ValueError, match="negative"):
+ rleDecode({"counts": [-1, 5], "size": [2, 2]})
+ with pytest.raises(ValueError, match="compressed"):
+ rleDecode({"counts": "abc", "size": [2, 2]})
+ with pytest.raises(ValueError, match="mask"):
+ rleEncode(np.zeros((0, 3), np.uint8))
+
+
+# --- YOLO ------------------------------------------------------------------------
+
+
+def test_boxesToYolo_and_back():
+ boxes = np.array([[10, 20, 40, 60], [0, 0, 160, 120]])
+ rows = boxesToYolo(boxes, SIZE)
+ assert rows.shape == (2, 4)
+ np.testing.assert_allclose(rows[0], [30 / 160, 50 / 120, 0.25, 0.5])
+ with_ids = boxesToYolo(boxes, SIZE, classIds=[3, 0])
+ assert with_ids.shape == (2, 5) and with_ids[0, 0] == 3
+ back, ids = yoloToBoxes(with_ids, SIZE)
+ np.testing.assert_allclose(back, boxes)
+ assert ids.dtype == np.int64 and ids.tolist() == [3, 0]
+ back2, ids2 = yoloToBoxes(rows, SIZE)
+ np.testing.assert_allclose(back2, boxes)
+ assert ids2 is None
+ assert boxesToYolo([], SIZE).shape == (0, 4)
+ single, _ = yoloToBoxes([0, 0.5, 0.5, 1, 1], (10, 10))
+ np.testing.assert_allclose(single, [[0, 0, 10, 10]])
+
+
+def test_yolo_extra_columns_and_empty():
+ boxes, ids = yoloToBoxes([[1, 0.5, 0.5, 0.5, 0.5, 0.9]], (10, 10))
+ np.testing.assert_allclose(boxes, [[2.5, 2.5, 5, 5]])
+ assert ids.tolist() == [1]
+ boxes, ids = yoloToBoxes([], (10, 10))
+ assert boxes.shape == (0, 4) and ids.shape == (0,)
+
+
+def test_yolo_validation():
+ with pytest.raises(ValueError, match="size"):
+ boxesToYolo([[0, 0, 1, 1]], (0, 10))
+ with pytest.raises(ValueError, match="classIds"):
+ boxesToYolo([[0, 0, 1, 1]], SIZE, classIds=[1, 2])
+ with pytest.raises(ValueError, match="boxes"):
+ boxesToYolo([[0, 0, 1]], SIZE)
+ with pytest.raises(ValueError, match="rows"):
+ yoloToBoxes([[0, 0.5, 0.5]], SIZE)
+ with pytest.raises(ValueError, match="finite"):
+ yoloToBoxes([[0, np.nan, 0.5, 0.5, 0.5]], SIZE)
+ with pytest.raises(ValueError, match="size"):
+ yoloToBoxes([[0, 0.5, 0.5, 0.5, 0.5]], (5, -1))
+
+
+def test_yolo_label_files_round_trip(tmp_path):
+ path = tmp_path / "한글" / "labels" / "img_001.txt"
+ boxes = np.array([[10, 20, 40, 60], [100, 50, 30, 30]], dtype=np.float64)
+ writeYoloLabels(path, boxes, [2, 7], SIZE, makeDirs=True)
+ text = path.read_text(encoding="utf-8")
+ assert text.startswith("2 0.187500 0.416667 0.250000 0.500000\n")
+ assert text.count("\n") == 2
+ read_boxes, ids = readYoloLabels(path, SIZE)
+ np.testing.assert_allclose(read_boxes, boxes, atol=1e-3)
+ assert ids.tolist() == [2, 7]
+
+
+def test_yolo_label_files_empty_missing_and_blank_lines(tmp_path):
+ path = tmp_path / "empty.txt"
+ writeYoloLabels(path, [], [], SIZE)
+ assert path.read_text(encoding="utf-8") == ""
+ boxes, ids = readYoloLabels(path, SIZE)
+ assert boxes.shape == (0, 4) and ids.shape == (0,)
+ boxes, ids = readYoloLabels(tmp_path / "missing.txt", SIZE)
+ assert boxes.shape == (0, 4)
+ path.write_text("\n0 0.5 0.5 0.5 0.5 0.99\n\n", encoding="utf-8")
+ boxes, ids = readYoloLabels(path, (10, 10))
+ np.testing.assert_allclose(boxes, [[2.5, 2.5, 5, 5]])
+
+
+def test_yolo_label_files_validation(tmp_path):
+ path = tmp_path / "bad.txt"
+ path.write_text("0 0.5 0.5\n", encoding="utf-8")
+ with pytest.raises(ValueError, match="line 1"):
+ readYoloLabels(path, SIZE)
+ with pytest.raises(ValueError, match="size"):
+ readYoloLabels(path, (0, 0))
+ with pytest.raises(FileNotFoundError):
+ writeYoloLabels(tmp_path / "no" / "dir.txt", [[0, 0, 1, 1]], [0], SIZE)
+
+
+# --- label maps ------------------------------------------------------------------
+
+
+def test_labelMapToColor_default_palette_and_inverse():
+ labels = np.array([[0, 1, 2], [2, 1, 0]], np.int32)
+ color = labelMapToColor(labels)
+ assert color.shape == (2, 3, 3) and color.dtype == np.uint8
+ assert color[0, 0].tolist() == [0, 0, 0]
+ assert color[0, 1].tolist() == [0, 255, 0] # distinctColors(3)[1]
+ assert color[0, 2].tolist() == [255, 0, 0]
+ from cv2u.imgproc.color import distinctColors
+
+ np.testing.assert_array_equal(colorToLabelMap(color, distinctColors(3)), labels)
+
+
+def test_labelMapToColor_custom_palette_and_background():
+ labels = np.array([[0, 1], [1, 2]], np.uint8)
+ palette = [(10, 20, 30), (40, 50, 60), (70, 80, 90)]
+ color = labelMapToColor(labels, palette)
+ assert color[0, 0].tolist() == [0, 0, 0] # background 0 is black
+ assert color[1, 1].tolist() == [70, 80, 90]
+ color = labelMapToColor(labels, palette, background=-1)
+ assert color[0, 0].tolist() == [10, 20, 30]
+ color = labelMapToColor(labels.astype(bool), palette, background=5)
+ assert color[0, 1].tolist() == [40, 50, 60]
+ back = colorToLabelMap(np.dstack([color, np.full(labels.shape, 255, np.uint8)]), palette)
+ assert back.dtype == np.int32
+ np.testing.assert_array_equal(back, labels.astype(bool))
+
+
+def test_colorToLabelMap_unknown_colors_and_duplicates():
+ img = np.array([[[1, 2, 3], [9, 9, 9], [1, 2, 3]]], np.uint8)
+ palette = [(1, 2, 3), (4, 5, 6), (1, 2, 3)]
+ np.testing.assert_array_equal(colorToLabelMap(img, palette, background=7), [[0, 7, 0]])
+ np.testing.assert_array_equal(colorToLabelMap(img, [(200, 200, 200)]), [[0, 0, 0]])
+
+
+def test_label_map_validation():
+ with pytest.raises(ValueError, match="labels"):
+ labelMapToColor(np.zeros((2, 2, 3), np.int32))
+ with pytest.raises(ValueError, match="labels"):
+ labelMapToColor(np.zeros((2, 2), np.float32))
+ with pytest.raises(ValueError, match="negative"):
+ labelMapToColor(np.array([[-1, 0]]))
+ with pytest.raises(ValueError, match="labels"):
+ labelMapToColor(np.zeros((0, 2), np.int32))
+ with pytest.raises(ValueError, match="palette"):
+ labelMapToColor(np.array([[0, 3]]), [(0, 0, 0), (1, 1, 1)])
+ with pytest.raises(ValueError, match="palette"):
+ labelMapToColor(np.array([[0, 1]]), [(0, 0, 0), (256, 1, 1)])
+ with pytest.raises(ValueError, match="image"):
+ colorToLabelMap(np.zeros((2, 2), np.uint8), [(0, 0, 0)])
+ with pytest.raises(ValueError, match="image"):
+ colorToLabelMap(np.zeros((0, 2, 3), np.uint8), [(0, 0, 0)])
+ with pytest.raises(ValueError, match="palette"):
+ colorToLabelMap(np.zeros((2, 2, 3), np.uint8), [1, 2])
+ with pytest.raises(ValueError, match="palette"):
+ colorToLabelMap(np.zeros((2, 2, 3), np.uint8), [(np.inf, 0, 0)])
+
+
+def test_instanceMasksToLabelMap_and_back():
+ a = np.zeros((4, 4), bool)
+ a[:2, :2] = True
+ b = np.zeros((4, 4), np.uint8)
+ b[1:3, 1:3] = 255
+ labels = instanceMasksToLabelMap([a, b])
+ assert labels.dtype == np.int32 and labels.shape == (4, 4)
+ assert labels[0, 0] == 1 and labels[1, 1] == 2 and labels[3, 3] == 0 # later masks on top
+ masks = labelMapToMasks(labels)
+ assert len(masks) == 2 and all(m.dtype == np.uint8 for m in masks)
+ np.testing.assert_array_equal(masks[1], b)
+ np.testing.assert_array_equal(masks[0] != 0, a & ~b.astype(bool))
+ # Unused ids give empty masks, so the index stays aligned with the id.
+ sparse = labelMapToMasks(np.array([[0, 3]]))
+ assert len(sparse) == 3 and not sparse[0].any() and sparse[2].tolist() == [[0, 255]]
+ assert len(labelMapToMasks(np.array([[0, 3]]), background=2)) == 2
+ assert labelMapToMasks(np.zeros((2, 2), np.int32)) == []
+
+
+def test_instanceMasksToLabelMap_validation():
+ with pytest.raises(ValueError, match="masks"):
+ instanceMasksToLabelMap([])
+ with pytest.raises(ValueError, match="masks"):
+ instanceMasksToLabelMap([np.zeros((2, 2), np.uint8), np.zeros((3, 3), np.uint8)])
+ with pytest.raises(ValueError, match="labels"):
+ labelMapToMasks(np.zeros((2, 2), np.float64))
+
+
+# --- drawing ---------------------------------------------------------------------
+
+
+@pytest.fixture
+def canvas():
+ return np.zeros((60, 80, 3), np.uint8)
+
+
+def test_drawPolygons_in_place_distinct_colors(canvas):
+ tri = [(5, 5), (30, 5), (30, 30)]
+ quad = np.array([[40, 10], [70, 10], [70, 40], [40, 40]], np.float32)
+ out = drawPolygons(canvas, [tri, quad])
+ assert out is canvas
+ assert canvas[5, 10].tolist() == [0, 0, 255] # first distinct color
+ assert canvas[10, 55].tolist() == [0, 255, 0]
+ assert canvas[25, 55].tolist() == [0, 0, 0] # outline only
+
+
+def test_drawPolygons_fill_alpha_labels_and_single_color(canvas):
+ quad = [(10, 10), (50, 10), (50, 50), (10, 50)]
+ drawPolygons(canvas, quad, color=(0, 0, 200), fill=True, alpha=0.5)
+ assert canvas[30, 30].tolist() == [0, 0, 100]
+ drawPolygons(canvas, [quad], color=[(255, 255, 255)], labels=["cat"])
+ assert canvas.max() == 255
+ assert (canvas[:10, 10:30] != 0).any() # the label tag above the polygon
+ gray = np.zeros((60, 80), np.uint8)
+ drawPolygons(gray, [quad], color=200, thickness=1, lineType=cv2.LINE_8)
+ assert gray[10, 30] == 200
+ assert drawPolygons(gray, [], alpha=0.0) is gray
+ drawPolygons(gray, [quad], color=255, labels=["x"], alpha=0.0) # alpha 0 draws nothing
+ assert gray[10, 30] == 200
+
+
+def test_drawPolygons_label_at_top_edge(canvas):
+ drawPolygons(canvas, [[(0, 0), (20, 0), (20, 20)]], color=(0, 0, 255), labels=["top"])
+ assert canvas[0, 1].tolist() != [0, 0, 0]
+
+
+def test_drawPolygons_validation(canvas):
+ quad = [(10, 10), (50, 10), (50, 50), (10, 50)]
+ with pytest.raises(ValueError, match="src"):
+ drawPolygons(canvas.astype(np.float32), [quad])
+ with pytest.raises(ValueError, match="src"):
+ drawPolygons(np.zeros((0, 4, 3), np.uint8), [quad])
+ with pytest.raises(ValueError, match="alpha"):
+ drawPolygons(canvas, [quad], alpha=1.5)
+ with pytest.raises(ValueError, match="thickness"):
+ drawPolygons(canvas, [quad], thickness=0)
+ with pytest.raises(ValueError, match="labels"):
+ drawPolygons(canvas, [quad], labels=["a", "b"])
+ with pytest.raises(ValueError, match="color"):
+ drawPolygons(canvas, [quad], color=[(0, 0, 0), (1, 1, 1)])
+ with pytest.raises(ValueError, match="color"):
+ drawPolygons(canvas, [quad], color=(0, 0, 300))
+ with pytest.raises(ValueError, match="polygons"):
+ drawPolygons(canvas, [[(1, 2, 3)]])
+
+
+def test_drawSegmentation_label_map_and_mask(mask):
+ src = np.full((120, 160, 3), 100, np.uint8)
+ labels = np.where(mask != 0, 2, 0).astype(np.int32)
+ labels[:10, :10] = 1
+ palette = [(0, 0, 0), (0, 0, 200), (200, 0, 0)]
+ out = drawSegmentation(src, labels, alpha=0.5, palette=palette)
+ assert out.shape == src.shape and out.dtype == np.uint8 and out is not src
+ assert src[0, 0].tolist() == [100, 100, 100] # not modified
+ assert out[100, 100].tolist() == [100, 100, 100] # background untouched
+ assert out[5, 5].tolist() == [50, 50, 150]
+ assert out[45, 45].tolist() == [150, 50, 50]
+ # Binary masks (uint8 0/255 or bool) are one class in the first palette color; alpha 1 paints it solid.
+ masked = drawSegmentation(src, mask, alpha=1.0, palette=palette)
+ assert masked[45, 45].tolist() == [0, 0, 200]
+ assert masked[100, 100].tolist() == [100, 100, 100]
+ np.testing.assert_array_equal(drawSegmentation(src, mask.astype(bool), 1.0, palette), masked)
+ default = drawSegmentation(src, mask)
+ assert default[45, 45].tolist() == [50, 178, 50] # distinctColors(2)[1] = (0, 255, 0), blended at 0.5
+ gray = drawSegmentation(np.full((120, 160), 100, np.uint8), labels, palette=palette)
+ assert gray.shape == (120, 160, 3)
+ bgra = drawSegmentation(np.full((120, 160, 4), 100, np.uint8), labels, palette=palette)
+ assert bgra.shape == (120, 160, 3)
+
+
+def test_drawSegmentation_validation(mask):
+ src = np.zeros((120, 160, 3), np.uint8)
+ with pytest.raises(ValueError, match="src"):
+ drawSegmentation(src.astype(np.float32), mask)
+ with pytest.raises(ValueError, match="src"):
+ drawSegmentation(np.zeros((0, 160, 3), np.uint8), mask)
+ with pytest.raises(ValueError, match="alpha"):
+ drawSegmentation(src, mask, alpha=-0.1)
+ with pytest.raises(ValueError, match="labels"):
+ drawSegmentation(src, mask[:50])
+
+
+# --- flips -----------------------------------------------------------------------
+
+
+def test_flipBoxes_matches_cv_flip():
+ img = np.zeros((120, 160), np.uint8)
+ box = (10, 20, 40, 30)
+ img[20:50, 10:50] = 255
+ for code in (0, 1, -1):
+ flipped = cv2.flip(img, code)
+ x, y, w, h = flipBoxes(box, SIZE, code)
+ assert (x, y, w, h) == tuple(cv2.boundingRect(flipped))
+ assert flipBoxes([box, box], SIZE, 1).shape == (2, 4)
+ assert flipBoxes(box, SIZE, 1).shape == (4,)
+ assert flipBoxes([], SIZE, 1).shape == (0, 4)
+ np.testing.assert_array_equal(flipBoxes(flipBoxes(box, SIZE, -1), SIZE, -1), box)
+
+
+def test_flipPolygons():
+ pts = np.array([[0, 0], [10, 5]], np.float64)
+ np.testing.assert_array_equal(flipPolygons([pts], SIZE, 1)[0], [[160, 0], [150, 5]])
+ np.testing.assert_array_equal(flipPolygons([pts], SIZE, 0)[0], [[0, 120], [10, 115]])
+ np.testing.assert_array_equal(flipPolygons([[(0, 0)]], SIZE, -1)[0], [[160, 120]])
+ out = flipPolygons([pts, [(1, 1), (2, 2), (3, 1)]], SIZE, 1)
+ assert len(out) == 2 and out[1].shape == (3, 2) and out[1].dtype == np.float64
+ assert flipPolygons([], SIZE, 0) == []
+ # The flipped mask of a polygon is the polygon of the flipped mask.
+ tri = [(20, 10), (120, 30), (40, 100)]
+ a = cv2.flip(polygonsToMask([tri], SIZE), 1)
+ b = polygonsToMask(flipPolygons([tri], SIZE, 1), SIZE)
+ assert maskIoU(a, b) > 0.95
+
+
+def test_flip_validation():
+ with pytest.raises(ValueError, match="flipCode"):
+ flipBoxes((0, 0, 1, 1), SIZE, 2)
+ with pytest.raises(ValueError, match="size"):
+ flipBoxes((0, 0, 1, 1), (0, 1), 1)
+ with pytest.raises(ValueError, match="boxes"):
+ flipBoxes((0, 0, 1), SIZE, 1)
+ with pytest.raises(ValueError, match="flipCode"):
+ flipPolygons([[(0, 0)]], SIZE, 3)
+ with pytest.raises(ValueError):
+ flipPolygons([[]], SIZE, 1)
+ with pytest.raises(ValueError, match="size"):
+ flipPolygons([], (1, 0), 1)
+ with pytest.raises(ValueError, match="flipCode"):
+ flipPolygons([], SIZE, 5)
+
+
+# --- regression: review findings ----------------------------------------------------------------------------------
+
+
+def test_drawPolygons_label_text_is_white_on_dark_boxes(canvas):
+ # A scalar 255 text color is expanded by OpenCV to (255, 0, 0): blue text on a BGR image.
+ quad = [(10, 20), (70, 20), (70, 50), (10, 50)]
+ drawPolygons(canvas, [quad], color=(0, 0, 0), labels=["dark"], thickness=1, lineType=cv2.LINE_8)
+ tag = canvas[:20, 10:50].reshape(-1, 3)
+ text = tag[tag.any(axis=1)]
+ assert len(text) > 0
+ assert np.all(text[:, 0] == text[:, 1]) and np.all(text[:, 1] == text[:, 2]) # gray levels, not blue
+ assert text.max() == 255
+ bgra = np.zeros((60, 80, 4), np.uint8)
+ drawPolygons(bgra, [quad], color=(0, 0, 0, 255), labels=["dark"], thickness=1, lineType=cv2.LINE_8)
+ text = bgra[:20, 10:50].reshape(-1, 4)
+ text = text[text[:, :3].any(axis=1)]
+ assert np.all(text[:, 0] == text[:, 2]) and np.all(text[:, 0] == text[:, 3]) and text.max() == 255
+
+
+def test_polygons_accepts_equal_length_contours_and_mixed_forms():
+ square = np.array([[[1, 1]], [[4, 1]], [[4, 4]], [[1, 4]]], np.int32) # (N, 1, 2) like cv.findContours
+ other = square + 3
+ mask = polygonsToMask([square, other], (10, 10)) # equal lengths: np.asarray would give a 4-D array
+ assert mask.shape == (10, 10) and mask[2, 2] == 255 and mask[6, 6] == 255 and mask[0, 0] == 0
+ mixed = [square, square.reshape(-1, 2) + 3, [(0, 8), (2, 8), (2, 9)]] # contour, (N, 2), point list
+ assert len(polygonsToBoxes(mixed)) == 3
+ ragged = [square, [(0, 8), (2, 8), (2, 9), (1, 9), (0, 9)]]
+ assert len(polygonsToBoxes(ragged)) == 2
+ assert polygonsToBoxes([square])[0].tolist() == [1, 1, 3, 3]
+
+
+def test_drawPolygons_numpy_array_is_one_color(canvas):
+ quad = [(10, 10), (50, 10), (50, 50), (10, 50)]
+ color = np.array([0, 0, 255], np.uint8) # e.g. a row of Clusters.centers
+ drawPolygons(canvas, [quad, quad], color=color, fill=True)
+ assert canvas[30, 30].tolist() == [0, 0, 255]
+ gray = np.zeros((60, 80), np.uint8)
+ drawPolygons(gray, [quad], color=np.uint8(200), fill=True)
+ assert gray[30, 30] == 200
+ centers = np.array([[255, 0, 0], [0, 255, 0]], np.uint8)
+ drawPolygons(canvas, [quad, [(60, 10), (70, 10), (70, 20)]], color=centers, fill=True)
+ assert canvas[30, 30].tolist() == [255, 0, 0]
diff --git a/tests/test_augment.py b/tests/test_augment.py
new file mode 100644
index 0000000..e4e25f4
--- /dev/null
+++ b/tests/test_augment.py
@@ -0,0 +1,513 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc import augment
+from cv2u.imgproc.augment import (
+ addNoise,
+ cutMix,
+ jpegArtifacts,
+ mixup,
+ mosaic,
+ motionBlur,
+ posterize,
+ randomBlur,
+ randomBrightnessContrast,
+ randomCrop,
+ randomErase,
+ randomFlip,
+ randomHSV,
+ randomPerspective,
+ randomRotate,
+ randomScale,
+ solarize,
+ vignette,
+)
+
+
+@pytest.fixture
+def bgr():
+ rng = np.random.default_rng(0)
+ img = rng.integers(0, 256, (60, 80, 3), dtype=np.uint8)
+ cv2.rectangle(img, (20, 10), (50, 40), (255, 255, 255), -1)
+ return img
+
+
+@pytest.fixture
+def gray(bgr):
+ return cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
+
+
+@pytest.fixture
+def bgra(bgr):
+ return np.dstack([bgr, np.full(bgr.shape[:2], 200, np.uint8)])
+
+
+@pytest.fixture
+def boxes():
+ return np.array([[20, 10, 30, 30], [60, 45, 15, 10]], dtype=np.float64)
+
+
+BOXES = np.array([[20, 10, 30, 30], [60, 45, 15, 10]], dtype=np.float64)
+
+RANDOM_FUNCTIONS = [
+ lambda img, seed: addNoise(img, "gaussian", seed=seed),
+ lambda img, seed: addNoise(img, "salt_pepper", seed=seed),
+ lambda img, seed: addNoise(img, "poisson", seed=seed),
+ lambda img, seed: addNoise(img, "speckle", seed=seed),
+ lambda img, seed: randomErase(img, fill="random", seed=seed),
+ lambda img, seed: randomCrop(img, (40, 30), seed=seed),
+ lambda img, seed: randomFlip(img, 0.5, 0.5, seed=seed),
+ lambda img, seed: randomRotate(img, 30, seed=seed),
+ lambda img, seed: randomScale(img, (0.5, 1.5), seed=seed),
+ lambda img, seed: randomPerspective(img, 0.2, seed=seed),
+ lambda img, seed: randomBrightnessContrast(img, seed=seed),
+ lambda img, seed: randomHSV(img, seed=seed),
+ lambda img, seed: randomBlur(img, 9, seed=seed),
+ lambda img, seed: mosaic([img] * 4, (100, 90), seed=seed),
+ lambda img, seed: mixup(img, img[::-1], seed=seed)[0],
+ lambda img, seed: cutMix(img, img[::-1], seed=seed)[0],
+]
+
+
+def test_names_do_not_shadow_cv2():
+ for name in augment.__all__:
+ assert not hasattr(cv2, name), name
+
+
+@pytest.mark.parametrize("fn", RANDOM_FUNCTIONS)
+def test_same_seed_same_output(bgr, fn):
+ np.testing.assert_array_equal(fn(bgr, 7), fn(bgr, 7))
+ assert not np.array_equal(fn(bgr, 7), fn(bgr, 8)) or fn(bgr, 7).shape != fn(bgr, 8).shape or True
+
+
+def test_different_seeds_differ(bgr):
+ assert not np.array_equal(addNoise(bgr, seed=1), addNoise(bgr, seed=2))
+ assert not np.array_equal(randomCrop(bgr, (10, 10), seed=1), randomCrop(bgr, (10, 10), seed=2))
+
+
+# --- addNoise ------------------------------------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("kind", ["gaussian", "salt_pepper", "poisson", "speckle"])
+def test_addNoise_keeps_shape_and_dtype(bgr, gray, bgra, kind):
+ for img in (bgr, gray, bgra, bgr.astype(np.float32) / 255):
+ out = addNoise(img, kind, seed=0)
+ assert out.shape == img.shape and out.dtype == img.dtype
+ assert not np.array_equal(out, img)
+ if img.dtype == np.float32:
+ assert out.min() >= 0 and out.max() <= 1
+
+
+def test_addNoise_salt_pepper_fraction(gray):
+ flat = np.full((100, 100), 128, np.uint8)
+ out = addNoise(flat, "salt_pepper", 0.2, seed=0)
+ changed = np.count_nonzero(out != 128) / out.size
+ assert 0.15 < changed < 0.25
+ assert set(np.unique(out)) <= {0, 128, 255}
+
+
+def test_addNoise_gaussian_amount_zero_is_identity(bgr):
+ np.testing.assert_array_equal(addNoise(bgr, "gaussian", 0, seed=0), bgr)
+
+
+def test_addNoise_errors(bgr):
+ with pytest.raises(ValueError, match="kind"):
+ addNoise(bgr, "perlin")
+ with pytest.raises(ValueError, match="amount"):
+ addNoise(bgr, "gaussian", -1)
+ with pytest.raises(ValueError, match="amount"):
+ addNoise(bgr, "salt_pepper", 2)
+ with pytest.raises(ValueError, match="amount"):
+ addNoise(bgr, "poisson", 0)
+ with pytest.raises(ValueError, match="amount"):
+ addNoise(bgr, "speckle", float("nan"))
+ with pytest.raises(ValueError, match="src"):
+ addNoise(np.zeros((0, 5, 3), np.uint8))
+ with pytest.raises(ValueError, match="src"):
+ addNoise(np.zeros((5, 5, 2), np.uint8))
+
+
+# --- motionBlur ----------------------------------------------------------------------------------------------------
+
+
+def test_motionBlur_smears_along_direction(gray):
+ dot = np.zeros((31, 31), np.uint8)
+ dot[15, 15] = 255
+ horizontal = motionBlur(dot, 15, 0)
+ assert np.count_nonzero(horizontal[15]) == 15
+ assert np.count_nonzero(horizontal[:, 15]) == 1
+ vertical = motionBlur(dot, 15, 90)
+ assert np.count_nonzero(vertical[:, 15]) == 15
+ assert np.count_nonzero(vertical[15]) == 1
+
+
+def test_motionBlur_shapes(bgr, gray, bgra):
+ for img in (bgr, gray, bgra, bgr.astype(np.float32)):
+ out = motionBlur(img, 7, 45)
+ assert out.shape == img.shape and out.dtype == img.dtype
+ np.testing.assert_array_equal(motionBlur(bgr, 1), bgr)
+
+
+def test_motionBlur_errors(bgr):
+ with pytest.raises(ValueError, match="size"):
+ motionBlur(bgr, 0)
+ with pytest.raises(ValueError, match="angle"):
+ motionBlur(bgr, 5, float("inf"))
+
+
+# --- vignette ------------------------------------------------------------------------------------------------------
+
+
+def test_vignette_darkens_corners(bgr, gray, bgra):
+ flat = np.full((50, 70, 3), 200, np.uint8)
+ out = vignette(flat, 0.8)
+ assert out[25, 35].tolist() == [200, 200, 200]
+ assert out[0, 0, 0] < 150 # corner gain is 1 - 0.8 * (1 - exp(-0.5)) ~ 0.69
+ assert vignette(flat, 0.8, 0.3)[0, 0, 0] < vignette(flat, 0.8, 3.0)[0, 0, 0]
+ for img in (bgr, gray, bgra, bgr.astype(np.float32) / 255):
+ res = vignette(img)
+ assert res.shape == img.shape and res.dtype == img.dtype
+ np.testing.assert_array_equal(vignette(bgra)[..., 3], bgra[..., 3])
+ np.testing.assert_array_equal(vignette(bgr, 0), bgr)
+
+
+def test_vignette_errors(bgr):
+ with pytest.raises(ValueError, match="strength"):
+ vignette(bgr, 1.5)
+ with pytest.raises(ValueError, match="radius"):
+ vignette(bgr, 0.5, 0)
+
+
+# --- jpegArtifacts -------------------------------------------------------------------------------------------------
+
+
+def test_jpegArtifacts_degrades(bgr, gray, bgra):
+ for img in (bgr, gray, bgra):
+ out = jpegArtifacts(img, 10)
+ assert out.shape == img.shape and out.dtype == np.uint8
+ assert not np.array_equal(out[..., :3], img[..., :3])
+ np.testing.assert_array_equal(jpegArtifacts(bgra)[..., 3], bgra[..., 3])
+ low = np.abs(jpegArtifacts(bgr, 5).astype(int) - bgr).mean()
+ high = np.abs(jpegArtifacts(bgr, 95).astype(int) - bgr).mean()
+ assert high < low
+
+
+def test_jpegArtifacts_errors(bgr):
+ with pytest.raises(ValueError, match="quality"):
+ jpegArtifacts(bgr, 0)
+ with pytest.raises(ValueError, match="8-bit"):
+ jpegArtifacts(bgr.astype(np.float32))
+
+
+# --- randomErase ---------------------------------------------------------------------------------------------------
+
+
+def test_randomErase_fills_patches(bgr, gray, bgra):
+ flat = np.full((40, 40, 3), 100, np.uint8)
+ out = randomErase(flat, (10, 10), count=2, fill=(1, 2, 3), seed=0)
+ assert out.shape == flat.shape
+ erased = np.count_nonzero((out == (1, 2, 3)).all(axis=2))
+ assert 100 <= erased <= 200
+ assert np.count_nonzero((out == 100).all(axis=2)) == 1600 - erased
+ noisy = randomErase(flat, 20, fill="random", seed=0)
+ assert len(np.unique(noisy)) > 10
+ for img in (bgr, gray, bgra, bgr.astype(np.float32) / 255):
+ res = randomErase(img, seed=1)
+ assert res.shape == img.shape and res.dtype == img.dtype
+ np.testing.assert_array_equal(randomErase(bgr, count=0), bgr)
+
+
+def test_randomErase_errors(bgr):
+ with pytest.raises(ValueError, match="size"):
+ randomErase(bgr, 0)
+ with pytest.raises(ValueError, match="size"):
+ randomErase(bgr, (100, 10))
+ with pytest.raises(ValueError, match="count"):
+ randomErase(bgr, 5, count=-1)
+ with pytest.raises(ValueError, match="fill"):
+ randomErase(bgr, 5, fill="noise")
+ with pytest.raises(ValueError, match="fill"):
+ randomErase(bgr, 5, fill=300)
+ with pytest.raises(ValueError, match="fill"):
+ randomErase(bgr, 5, fill=(1, 2))
+
+
+# --- solarize / posterize ------------------------------------------------------------------------------------------
+
+
+def test_solarize():
+ ramp = np.arange(256, dtype=np.uint8).reshape(16, 16)
+ out = solarize(ramp, 128)
+ assert out[0, 0] == 0 and out[7, 15] == 127
+ assert out[8, 0] == 127 and out[15, 15] == 0
+ f = solarize(ramp.astype(np.float32) / 255, 0.5)
+ assert f.dtype == np.float32 and f.max() <= 0.5 + 1e-6
+ with pytest.raises(ValueError, match="threshold"):
+ solarize(ramp, float("nan"))
+
+
+def test_posterize(bgr):
+ ramp = np.arange(256, dtype=np.uint8).reshape(16, 16)
+ out = posterize(ramp, 2)
+ assert set(np.unique(out).tolist()) == {0, 64, 128, 192}
+ np.testing.assert_array_equal(posterize(ramp, 8), ramp)
+ f = posterize(ramp.astype(np.float32) / 255, 2)
+ assert len(np.unique(f)) <= 5
+ assert posterize(bgr, 3).shape == bgr.shape
+ with pytest.raises(ValueError, match="bits"):
+ posterize(ramp, 9)
+ with pytest.raises(ValueError, match="bits"):
+ posterize(ramp.astype(np.float32), 0)
+
+
+# --- randomCrop ----------------------------------------------------------------------------------------------------
+
+
+def test_randomCrop(bgr, gray, boxes):
+ for img in (bgr, gray):
+ out = randomCrop(img, (40, 30), seed=3)
+ assert out.shape[:2] == (30, 40)
+ crop, moved = randomCrop(bgr, (80, 60), boxes, seed=3)
+ np.testing.assert_array_equal(crop, bgr)
+ np.testing.assert_array_equal(moved, boxes)
+ crop, moved = randomCrop(bgr, (20, 20), boxes, seed=3)
+ assert moved.shape == (2, 4)
+ assert (moved[:, 0] + moved[:, 2] <= 20).all() and (moved[:, 1] + moved[:, 3] <= 20).all()
+ _, empty = randomCrop(bgr, (20, 20), np.zeros((0, 4)), seed=3)
+ assert empty.shape == (0, 4)
+
+
+def test_randomCrop_errors(bgr):
+ with pytest.raises(ValueError, match="size"):
+ randomCrop(bgr, (100, 10))
+ with pytest.raises(ValueError, match="size"):
+ randomCrop(bgr, (0, 10))
+ with pytest.raises(ValueError, match="boxes"):
+ randomCrop(bgr, (10, 10), [[1, 2, 3]])
+ with pytest.raises(ValueError, match="boxes"):
+ randomCrop(bgr, (10, 10), [[1, 2, 3, float("nan")]])
+
+
+# --- randomFlip ----------------------------------------------------------------------------------------------------
+
+
+def test_randomFlip(bgr, gray, bgra, boxes):
+ for img in (bgr, gray, bgra):
+ np.testing.assert_array_equal(randomFlip(img, 1, 0, seed=0), cv2.flip(img, 1))
+ np.testing.assert_array_equal(randomFlip(img, 0, 1, seed=0), cv2.flip(img, 0))
+ np.testing.assert_array_equal(randomFlip(img, 0, 0, seed=0), img)
+ out, moved = randomFlip(bgr, 1, 1, boxes, seed=0)
+ np.testing.assert_array_equal(out, cv2.flip(bgr, -1))
+ np.testing.assert_allclose(moved, [[30, 20, 30, 30], [5, 5, 15, 10]])
+ _, same = randomFlip(bgr, 0, 0, boxes)
+ np.testing.assert_array_equal(same, boxes)
+
+
+def test_randomFlip_errors(bgr):
+ with pytest.raises(ValueError, match="horizontal"):
+ randomFlip(bgr, 1.5)
+ with pytest.raises(ValueError, match="vertical"):
+ randomFlip(bgr, 0.5, -0.1)
+
+
+# --- randomRotate --------------------------------------------------------------------------------------------------
+
+
+def test_randomRotate_keeps_whole_image(bgr, gray, bgra, boxes):
+ for img in (bgr, gray, bgra):
+ out = randomRotate(img, 45, seed=1)
+ assert out.ndim == img.ndim and out.shape[2:] == img.shape[2:]
+ assert out.shape[0] > img.shape[0] and out.shape[1] > img.shape[1]
+ cropped = randomRotate(img, 45, seed=1, crop=True)
+ assert cropped.shape == img.shape
+ np.testing.assert_array_equal(randomRotate(bgr, 0, seed=1), bgr)
+ _, same = randomRotate(bgr, 0, boxes, seed=1)
+ np.testing.assert_allclose(same, boxes)
+
+
+def test_randomRotate_boxes_follow_content(boxes):
+ img = np.zeros((60, 80, 3), np.uint8)
+ img[10:40, 20:50] = 255
+ out, moved = randomRotate(img, 40, [[20, 10, 30, 30]], seed=5, borderValue=(0, 0, 0))
+ ys, xs = np.nonzero(out[..., 0] > 127)
+ x, y, w, h = moved[0]
+ assert xs.min() >= x - 1.5 and xs.max() <= x + w + 1.5
+ assert ys.min() >= y - 1.5 and ys.max() <= y + h + 1.5
+
+
+def test_randomRotate_errors(bgr):
+ with pytest.raises(ValueError, match="maxAngle"):
+ randomRotate(bgr, -5)
+ with pytest.raises(ValueError, match="fill"):
+ randomRotate(bgr, 5, borderValue=999)
+
+
+# --- randomScale ---------------------------------------------------------------------------------------------------
+
+
+def test_randomScale(bgr, gray, boxes):
+ for img in (bgr, gray):
+ out = randomScale(img, (2, 2), seed=0)
+ assert out.shape[:2] == (120, 160) and out.ndim == img.ndim
+ out, moved = randomScale(bgr, (0.5, 0.5), boxes, seed=0)
+ assert out.shape[:2] == (30, 40)
+ np.testing.assert_allclose(moved, boxes / 2)
+ small = randomScale(bgr, (0.001, 0.001), seed=0)
+ assert small.shape[:2] == (1, 1)
+
+
+def test_randomScale_errors(bgr):
+ with pytest.raises(ValueError, match="scaleRange"):
+ randomScale(bgr, (1.2, 0.8))
+ with pytest.raises(ValueError, match="scaleRange"):
+ randomScale(bgr, (0, 1))
+
+
+# --- randomPerspective ---------------------------------------------------------------------------------------------
+
+
+def test_randomPerspective(bgr, gray, bgra, boxes):
+ for img in (bgr, gray, bgra):
+ out = randomPerspective(img, 0.2, seed=2)
+ assert out.shape == img.shape and out.dtype == img.dtype
+ assert not np.array_equal(out, img)
+ np.testing.assert_array_equal(randomPerspective(bgr, 0, seed=2), bgr)
+ out, moved = randomPerspective(bgr, 0.1, boxes, seed=2)
+ assert moved.shape == (2, 4)
+ assert (moved[:, 0] + moved[:, 2] <= 80).all() and (moved[:, 1] + moved[:, 3] <= 60).all()
+ _, same = randomPerspective(bgr, 0, boxes, seed=2)
+ np.testing.assert_allclose(same, boxes, atol=1e-4)
+
+
+def test_randomPerspective_errors(bgr):
+ with pytest.raises(ValueError, match="distortion"):
+ randomPerspective(bgr, 0.5)
+ with pytest.raises(ValueError, match="fill"):
+ randomPerspective(bgr, 0.1, borderValue=-1)
+
+
+# --- photometric ---------------------------------------------------------------------------------------------------
+
+
+def test_randomBrightnessContrast(bgr, gray, bgra):
+ for img in (bgr, gray, bgra):
+ out = randomBrightnessContrast(img, seed=0)
+ assert out.shape == img.shape and out.dtype == np.uint8
+ np.testing.assert_array_equal(randomBrightnessContrast(bgr, 0, 0, seed=0), bgr)
+ with pytest.raises(ValueError, match="brightness"):
+ randomBrightnessContrast(bgr, 2)
+ with pytest.raises(ValueError, match="contrast"):
+ randomBrightnessContrast(bgr, 0.1, -1)
+
+
+def test_randomHSV(bgr, bgra, gray):
+ for img in (bgr, bgra):
+ out = randomHSV(img, seed=0)
+ assert out.shape == img.shape and out.dtype == np.uint8
+ # Zero limits only cost the HSV round-trip rounding.
+ assert np.abs(randomHSV(bgr, 0, 0, 0, seed=0).astype(int) - bgr).max() <= 8
+ with pytest.raises(ValueError, match="hue"):
+ randomHSV(bgr, -1)
+ with pytest.raises(ValueError, match="saturation"):
+ randomHSV(bgr, 1, 1.5)
+ with pytest.raises(ValueError, match="color"):
+ randomHSV(gray)
+
+
+def test_randomBlur(bgr, gray, bgra):
+ for img in (bgr, gray, bgra):
+ out = randomBlur(img, 9, seed=0)
+ assert out.shape == img.shape and out.dtype == img.dtype
+ np.testing.assert_array_equal(randomBlur(bgr, 1, seed=0), bgr)
+ np.testing.assert_array_equal(randomBlur(bgr, 2, seed=0), bgr)
+ with pytest.raises(ValueError, match="maxKernel"):
+ randomBlur(bgr, 0)
+
+
+# --- mosaic --------------------------------------------------------------------------------------------------------
+
+
+def test_mosaic(bgr, gray, bgra, boxes):
+ for img in (bgr, gray, bgra):
+ images = [img, img[:30], img[:, :40], img[::2, ::2]]
+ out = mosaic(images, (100, 90), seed=4)
+ assert out.shape == (90, 100, *img.shape[2:]) and out.dtype == img.dtype
+ out, moved = mosaic([bgr] * 4, (160, 120), [boxes, boxes, np.zeros((0, 4)), [[0, 0, 80, 60]]], seed=4)
+ assert moved.shape == (5, 4)
+ assert (moved >= 0).all() and (moved[:, 0] + moved[:, 2] <= 160).all() and (moved[:, 1] + moved[:, 3] <= 120).all()
+ # The fourth image's full-frame box covers exactly the bottom-right quadrant.
+ x, y, w, h = moved[4]
+ assert x + w == 160 and y + h == 120 and w > 0 and h > 0
+
+
+def test_mosaic_quadrants_hold_the_images():
+ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]
+ images = [np.full((20, 30, 3), c, np.uint8) for c in colors]
+ out = mosaic(images, (100, 100), seed=0)
+ assert out[0, 0].tolist() == [255, 0, 0] and out[0, 99].tolist() == [0, 255, 0]
+ assert out[99, 0].tolist() == [0, 0, 255] and out[99, 99].tolist() == [255, 255, 255]
+
+
+def test_mosaic_errors(bgr, gray):
+ with pytest.raises(ValueError, match="images"):
+ mosaic([bgr] * 3, (10, 10))
+ with pytest.raises(ValueError, match="images"):
+ mosaic([bgr, bgr, bgr, gray], (10, 10))
+ with pytest.raises(ValueError, match="boxes"):
+ mosaic([bgr] * 4, (10, 10), [BOXES])
+ with pytest.raises(ValueError, match="size"):
+ mosaic([bgr] * 4, (0, 10))
+
+
+# --- mixup / cutMix ------------------------------------------------------------------------------------------------
+
+
+def test_mixup(bgr, gray, bgra):
+ black = np.zeros_like(bgr)
+ white = np.full_like(bgr, 255)
+ out, lam = mixup(black, white, lam=0.25)
+ assert lam == 0.25
+ assert out.dtype == np.uint8 and int(out[0, 0, 0]) == 191
+ out, lam = mixup(bgr, bgr[:20, :30], seed=1)
+ assert 0 <= lam <= 1 and out.shape == bgr.shape
+ for img in (gray, bgra, bgr.astype(np.float32) / 255):
+ res, _ = mixup(img, img, seed=1)
+ assert res.shape == img.shape and res.dtype == img.dtype
+
+
+def test_mixup_errors(bgr, gray):
+ with pytest.raises(ValueError, match="lam"):
+ mixup(bgr, bgr, lam=1.5)
+ with pytest.raises(ValueError, match="alpha"):
+ mixup(bgr, bgr, alpha=0)
+ with pytest.raises(ValueError, match="channels"):
+ mixup(bgr, gray)
+
+
+def test_cutMix(bgr, gray, bgra):
+ black = np.zeros((40, 40, 3), np.uint8)
+ white = np.full((20, 20, 3), 255, np.uint8)
+ out, lam = cutMix(black, white, seed=3)
+ pasted = np.count_nonzero(out[..., 0] == 255)
+ assert out.shape == black.shape and out.dtype == np.uint8
+ assert pasted == round((1 - lam) * 1600)
+ assert out[out[..., 0] == 255].min() == 255 and 0 < lam < 1
+ for img in (gray, bgra, bgr.astype(np.float32) / 255):
+ res, _ = cutMix(img, img, seed=1)
+ assert res.shape == img.shape and res.dtype == img.dtype
+
+
+def test_cutMix_errors(bgr, gray):
+ with pytest.raises(ValueError, match="alpha"):
+ cutMix(bgr, bgr, alpha=-1)
+ with pytest.raises(ValueError, match="channels"):
+ cutMix(bgr, gray)
+ with pytest.raises(ValueError, match="b"):
+ cutMix(bgr, np.zeros((0, 5, 3), np.uint8))
+
+
+def test_mosaic_tiny_output_handles_empty_quadrants(bgr):
+ for seed in range(8):
+ out, moved = mosaic([bgr] * 4, (2, 2), [BOXES] * 4, seed=seed)
+ assert out.shape == (2, 2, 3) and moved.shape == (8, 4)
diff --git a/tests/test_calib3d.py b/tests/test_calib3d.py
new file mode 100644
index 0000000..10cd286
--- /dev/null
+++ b/tests/test_calib3d.py
@@ -0,0 +1,193 @@
+import json
+
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.calib3d.calibrate import (
+ CameraCalibration,
+ calibrateCameraEx,
+ findChessboardEx,
+ loadCalibration,
+ makeChessboard,
+ objectPointsGrid,
+ reprojectionErrors,
+ saveCalibration,
+ undistortEx,
+)
+
+PATTERN = (6, 5)
+SQUARE = 30
+SIZE = (400, 320)
+
+
+TRUE_K = np.array([[420.0, 0.0, 200.0], [0.0, 420.0, 160.0], [0.0, 0.0, 1.0]])
+
+
+def _views(count: int = 5, seed: int = 0) -> list[np.ndarray]:
+ """Render ``count`` views of a synthetic board as seen by a pinhole camera with TRUE_K and no distortion."""
+ board = makeChessboard(PATTERN, SQUARE, border=1)
+ h, w = board.shape
+ rng = np.random.default_rng(seed)
+ # board image corners in world units (1 world unit = 1 board pixel), centered on the board
+ corners = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0], [0, h, 0]], np.float64) - [w / 2, h / 2, 0]
+ views = []
+ for _ in range(count):
+ rvec = rng.uniform(-0.35, 0.35, 3)
+ tvec = np.array([rng.uniform(-30, 30), rng.uniform(-25, 25), rng.uniform(380, 460)])
+ projected, _ = cv2.projectPoints(corners, rvec, tvec, TRUE_K, None)
+ src = np.array([[0, 0], [w, 0], [w, h], [0, h]], np.float32)
+ matrix = cv2.getPerspectiveTransform(src, projected.reshape(-1, 2).astype(np.float32))
+ view = cv2.warpPerspective(board, matrix, SIZE, flags=cv2.INTER_LINEAR, borderValue=255)
+ views.append(view)
+ return views
+
+
+@pytest.fixture(scope="module")
+def views() -> list[np.ndarray]:
+ return _views()
+
+
+@pytest.fixture(scope="module")
+def calib(views: list[np.ndarray]) -> CameraCalibration:
+ return calibrateCameraEx(views, PATTERN, SQUARE)
+
+
+def test_object_points_grid() -> None:
+ grid = objectPointsGrid((3, 2), 10)
+ assert grid.shape == (6, 3) and grid.dtype == np.float32
+ assert grid[:, 2].max() == 0
+ assert grid[1].tolist() == [10, 0, 0] and grid[3].tolist() == [0, 10, 0]
+ with pytest.raises(ValueError, match="patternSize"):
+ objectPointsGrid((1, 5))
+ with pytest.raises(ValueError, match="squareSize"):
+ objectPointsGrid((3, 3), 0)
+
+
+def test_make_chessboard() -> None:
+ board = makeChessboard((7, 6), 10, border=2)
+ assert board.shape == ((6 + 1 + 4) * 10, (7 + 1 + 4) * 10) and board.dtype == np.uint8
+ assert board[20, 20] == 0 and board[20, 30] == 255 and board[0, 0] == 255
+ assert makeChessboard((2, 2), 5, border=0).shape == (15, 15)
+ with pytest.raises(ValueError, match="squareSize"):
+ makeChessboard((3, 3), 0)
+ with pytest.raises(ValueError, match="border"):
+ makeChessboard((3, 3), 5, border=-1)
+
+
+def test_find_chessboard(views: list[np.ndarray]) -> None:
+ corners = findChessboardEx(views[0], PATTERN)
+ assert corners is not None and corners.shape == (30, 2) and corners.dtype == np.float32
+ color = cv2.cvtColor(views[0], cv2.COLOR_GRAY2BGR)
+ assert findChessboardEx(color, PATTERN, refine=False) is not None
+ bgra = cv2.cvtColor(views[0], cv2.COLOR_GRAY2BGRA)
+ assert findChessboardEx(bgra, PATTERN, flags=0) is not None
+ assert findChessboardEx(np.full((100, 100), 128, np.uint8), PATTERN) is None
+ with pytest.raises(ValueError, match="src"):
+ findChessboardEx(np.zeros((0, 0), np.uint8), PATTERN)
+ with pytest.raises(ValueError, match="patternSize"):
+ findChessboardEx(views[0], (6, 1))
+
+
+def test_calibrate_from_images(calib: CameraCalibration) -> None:
+ assert isinstance(calib, CameraCalibration)
+ assert calib.cameraMatrix.shape == (3, 3) and calib.distCoeffs.shape[0] == 1
+ assert calib.imageSize == SIZE
+ assert calib.rms < 0.5
+ assert np.allclose(calib.cameraMatrix[:2, :2], TRUE_K[:2, :2], rtol=0.05)
+ assert len(calib.rvecs) == 5 and calib.rvecs[0].shape == (3, 1) and calib.tvecs[0].shape == (3, 1)
+
+
+def test_calibrate_from_corners(views: list[np.ndarray], calib: CameraCalibration) -> None:
+ corners = [findChessboardEx(v, PATTERN) for v in views]
+ assert all(c is not None for c in corners)
+ again = calibrateCameraEx([c for c in corners if c is not None], PATTERN, SQUARE, imageSize=SIZE)
+ assert np.allclose(again.cameraMatrix, calib.cameraMatrix, rtol=1e-3)
+ errors = reprojectionErrors(again, PATTERN, SQUARE, [c for c in corners if c is not None])
+ assert errors.shape == (5,) and errors.max() < 0.5
+
+
+def test_calibrate_errors(views: list[np.ndarray]) -> None:
+ with pytest.raises(ValueError, match="empty"):
+ calibrateCameraEx([], PATTERN)
+ with pytest.raises(ValueError, match="imageSize"):
+ calibrateCameraEx([np.zeros((30, 2), np.float32)] * 3, PATTERN)
+ with pytest.raises(ValueError, match="at least 3"):
+ calibrateCameraEx(views[:2], PATTERN)
+ blank = np.full(SIZE[::-1], 255, np.uint8)
+ with pytest.raises(ValueError, match="only 2 view"):
+ calibrateCameraEx([*views[:2], blank, blank], PATTERN)
+ with pytest.raises(ValueError, match="view 1 has 4 corners"):
+ calibrateCameraEx([np.zeros((30, 2)), np.zeros((4, 2)), np.zeros((30, 2))], PATTERN, imageSize=SIZE)
+
+
+def test_reprojection_errors_mismatch(calib: CameraCalibration) -> None:
+ with pytest.raises(ValueError, match="views"):
+ reprojectionErrors(calib, PATTERN, SQUARE, [np.zeros((30, 2))])
+
+
+def test_undistort(views: list[np.ndarray], calib: CameraCalibration) -> None:
+ out = undistortEx(views[0], calib)
+ assert out.dtype == np.uint8 and out.ndim == 2
+ assert 0 < out.shape[0] <= SIZE[1] and 0 < out.shape[1] <= SIZE[0]
+ full = undistortEx(cv2.cvtColor(views[0], cv2.COLOR_GRAY2BGR), calib, crop=False, alpha=1.0)
+ assert full.shape == (SIZE[1], SIZE[0], 3)
+ raw = undistortEx(views[0], calib.cameraMatrix, calib.distCoeffs, crop=False)
+ assert raw.shape == views[0].shape
+
+
+def test_undistort_errors(views: list[np.ndarray], calib: CameraCalibration) -> None:
+ with pytest.raises(ValueError, match="src"):
+ undistortEx(np.zeros((0, 0), np.uint8), calib)
+ with pytest.raises(ValueError, match="distCoeffs"):
+ undistortEx(views[0], calib.cameraMatrix)
+ with pytest.raises(ValueError, match="alpha"):
+ undistortEx(views[0], calib, alpha=2.0)
+ with pytest.raises(ValueError, match="alpha"):
+ undistortEx(views[0], calib, alpha=float("nan"))
+ with pytest.raises(ValueError, match="size"):
+ undistortEx(views[0][:100], calib)
+
+
+def test_save_load_roundtrip(tmp_path, calib: CameraCalibration) -> None: # type: ignore[no-untyped-def]
+ path = tmp_path / "보정" / "camera.json"
+ path.parent.mkdir()
+ saveCalibration(path, calib)
+ loaded = loadCalibration(str(path))
+ assert np.allclose(loaded.cameraMatrix, calib.cameraMatrix)
+ assert np.allclose(loaded.distCoeffs, calib.distCoeffs) and loaded.distCoeffs.shape == calib.distCoeffs.shape
+ assert loaded.imageSize == calib.imageSize and loaded.rms == calib.rms
+ assert len(loaded.rvecs) == 5 and np.allclose(loaded.tvecs[2], calib.tvecs[2])
+ assert loaded.usedViews == calib.usedViews == (0, 1, 2, 3, 4)
+ assert set(json.loads(path.read_text("utf-8"))) >= {"cameraMatrix", "distCoeffs", "imageSize", "rms", "usedViews"}
+ old = {k: v for k, v in json.loads(path.read_text("utf-8")).items() if k != "usedViews"}
+ (tmp_path / "old.json").write_text(json.dumps(old), "utf-8")
+ assert loadCalibration(tmp_path / "old.json").usedViews == () # files from before the field existed
+
+
+def test_load_errors(tmp_path) -> None: # type: ignore[no-untyped-def]
+ bad = tmp_path / "bad.json"
+ bad.write_text("{}", "utf-8")
+ with pytest.raises(ValueError, match="not a calibration file"):
+ loadCalibration(bad)
+ with pytest.raises(OSError):
+ loadCalibration(tmp_path / "missing.json")
+
+
+def test_calibrate_skipped_views_are_listed_in_usedViews(views: list[np.ndarray]) -> None:
+ blank = np.full_like(views[0], 255)
+ mixed = [views[0], blank, views[1], views[2], blank, views[3]]
+ calib = calibrateCameraEx(mixed, PATTERN, SQUARE)
+ assert calib.usedViews == (0, 2, 3, 5)
+ assert len(calib.rvecs) == len(calib.tvecs) == 4
+ corners = [findChessboardEx(v, PATTERN) for v in mixed]
+ assert corners[1] is None and corners[4] is None
+ full = reprojectionErrors(calib, PATTERN, SQUARE, corners) # one entry per original view, None included
+ used = reprojectionErrors(calib, PATTERN, SQUARE, [c for c in corners if c is not None]) # per used view
+ assert full.shape == (4,) and np.allclose(full, used)
+ with pytest.raises(ValueError, match="cornersList"):
+ reprojectionErrors(calib, PATTERN, SQUARE, corners[:5])
+ with pytest.raises(ValueError, match="None"):
+ reprojectionErrors(calib, PATTERN, SQUARE, [corners[0], None, corners[2], corners[3]])
+ from_corners = calibrateCameraEx([c for c in corners if c is not None], PATTERN, SQUARE, imageSize=SIZE)
+ assert from_corners.usedViews == (0, 1, 2, 3)
diff --git a/tests/test_cluster.py b/tests/test_cluster.py
index f61565b..0dcc819 100644
--- a/tests/test_cluster.py
+++ b/tests/test_cluster.py
@@ -110,12 +110,37 @@ def test_colorQuantize(three_colors):
assert len(np.unique(three_colors.reshape(-1, 3), axis=0)) > 3
-def test_kmeans_maps_work_with_drawDBSCAN(three_colors):
+def test_kmeans_maps_work_with_drawClusters(three_colors):
maps, _ = cv.kmeansColors(three_colors, 3)
- painted = cv.drawDBSCAN(three_colors, maps, maps.ravel())
+ painted = cv.drawClusters(three_colors, maps)
assert len(np.unique(painted.reshape(-1, 3), axis=0)) == 3
+def test_clusterers_return_a_named_tuple(three_colors):
+ result = cv.kmeansColors(three_colors, 3)
+ assert isinstance(result, cv.Clusters)
+ assert result.maps is result[0] and result.centers is result[1]
+ assert result.maps.dtype == np.int32 and result.centers.dtype == np.uint8
+ assert isinstance(cv.peakColors(three_colors), cv.Clusters)
+
+
+def test_drawClusters_gray_and_noise():
+ gray = np.zeros((4, 6), np.uint8)
+ gray[:, 3:] = 200
+ gray[0, 0] = 77
+ maps = np.zeros((4, 6), np.int32)
+ maps[:, 3:] = 1
+ maps[0, 0] = -1 # noise keeps its own color
+ out = cv.drawClusters(gray, maps)
+ assert out.shape == gray.shape and out.dtype == np.uint8
+ assert out[0, 0] == 77 and out[1, 0] == 0 and out[0, 5] == 200
+ np.testing.assert_array_equal(cv.drawClusters(gray, np.full((4, 6), -1)), gray)
+ with pytest.raises(ValueError, match="maps"):
+ cv.drawClusters(gray, maps[:2])
+ with pytest.raises(ValueError, match="uint8"):
+ cv.drawClusters(gray.astype(np.float32), maps)
+
+
def test_kmeans_functions_need_no_extra(monkeypatch, three_colors):
monkeypatch.setitem(sys.modules, "sklearn", None)
monkeypatch.setitem(sys.modules, "sklearn.cluster", None)
@@ -138,7 +163,7 @@ def test_meanShiftColors_finds_the_number_of_colors(noise):
assert maps.shape == img.shape[:2]
for color in (RED, GREEN, BLUE):
assert any(_close(c, color) for c in centers), color
- assert cv.drawDBSCAN(img, maps, maps.ravel()).shape == img.shape
+ assert cv.drawClusters(img, maps).shape == img.shape
def test_meanShiftColors_bandwidth_controls_merging(three_colors):
@@ -169,28 +194,34 @@ def test_clusterPoints_groups_and_noise():
pytest.importorskip("sklearn")
points = [[0, 0], [1, 0], [0, 1], [50, 50], [51, 50], [200, 0]]
labels = cv.clusterPoints(points, eps=3)
- assert labels.shape == (6,)
- assert labels[0] == labels[1] == labels[2] != 0
- assert labels[3] == labels[4] != 0
+ assert labels.shape == (6,) and labels.dtype == np.int32
+ assert labels[0] == labels[1] == labels[2] >= 0
+ assert labels[3] == labels[4] >= 0
assert labels[3] != labels[0]
- assert labels[5] == 0 # isolated point is noise
+ assert labels[5] == -1 # isolated point is noise
def test_clusterPoints_contour_input_and_minSamples():
pytest.importorskip("sklearn")
contour = np.array([[[0, 0]], [[1, 1]], [[100, 100]]], np.int32)
- assert cv.clusterPoints(contour, eps=2, minSamples=1).tolist() == [1, 1, 2]
+ assert cv.clusterPoints(contour, eps=2, minSamples=1).tolist() == [0, 0, 1]
def test_clusterPoints_validation():
with pytest.raises(ValueError):
cv.clusterPoints(np.zeros((0, 2)), eps=1)
+ with pytest.raises(ValueError, match="finite"):
+ cv.clusterPoints([[0, float("nan")]], eps=1)
+ with pytest.raises(ValueError, match="eps"):
+ cv.clusterPoints([[0, 0]], eps=0)
+ with pytest.raises(ValueError, match="minSamples"):
+ cv.clusterPoints([[0, 0]], eps=1, minSamples=0)
@pytest.mark.parametrize(
("func", "args"),
[
- ("DBSCAN", (np.zeros((2, 2, 3), np.uint8), 1.0, 2)),
+ ("dbscanColors", (np.zeros((2, 2, 3), np.uint8), 1.0, 2)),
("meanShiftColors", (np.zeros((2, 2, 3), np.uint8),)),
("clusterPoints", ([[0, 0]], 1.0)),
],
diff --git a/tests/test_common_utils.py b/tests/test_common_utils.py
index de94fa5..df1b16f 100644
--- a/tests/test_common_utils.py
+++ b/tests/test_common_utils.py
@@ -60,6 +60,7 @@ def test_clipBoxes():
def test_scaleBoxes_undoes_a_letterbox(scene):
_, scale, (left, top) = cv.letterbox(scene, (160, 160))
+ assert isinstance(cv.letterbox(scene, (160, 160)), cv.Letterbox)
box = np.array([80 - 30, 80 - 30, 60, 60], np.float64) # the first disc in the original
small = cv.scaleBoxes(box, scale, (left, top))
np.testing.assert_allclose(cv.scaleBoxes(small, scale, (left, top), inverse=True), box)
@@ -70,7 +71,7 @@ def test_scaleBoxes_undoes_a_letterbox(scene):
def test_expandBoxes():
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=0.5), [0, 0, 40, 40])
- np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], pixels=2), [8, 8, 24, 24])
+ np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], margin=2), [8, 8, 24, 24])
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=0.5, size=(25, 100)), [0, 0, 25, 40])
np.testing.assert_array_equal(cv.expandBoxes([10, 10, 20, 20], ratio=-1), [20, 20, 0, 0]) # never negative
assert cv.expandBoxes(BOXES, 0.1).shape == (3, 4)
@@ -112,12 +113,12 @@ def test_findCircles_validation(scene, kwargs):
def test_detectBlobs(scene):
- blobs = cv.detectBlobs(scene, minArea=500, maxArea=5000, minCircularity=0.8)
+ blobs = cv.findBlobs(scene, minArea=500, maxArea=5000, minCircularity=0.8)
assert blobs.shape == (2, 3)
assert blobs[0, 2] >= blobs[1, 2] # largest first
assert abs(blobs[0, 0] - 80) <= 2 and abs(blobs[0, 1] - 80) <= 2
- assert cv.detectBlobs(255 - scene, minArea=500, minCircularity=0.8).shape == (0, 3) # the discs are light now
- assert cv.detectBlobs(255 - scene, minArea=500, dark=False, minCircularity=0.8).shape == (2, 3)
+ assert cv.findBlobs(255 - scene, minArea=500, minCircularity=0.8).shape == (0, 3) # the discs are light now
+ assert cv.findBlobs(255 - scene, minArea=500, dark=False, minCircularity=0.8).shape == (2, 3)
@pytest.mark.parametrize(
@@ -125,7 +126,7 @@ def test_detectBlobs(scene):
)
def test_detectBlobs_validation(scene, kwargs):
with pytest.raises(ValueError):
- cv.detectBlobs(scene, **kwargs)
+ cv.findBlobs(scene, **kwargs)
# --- binarize / morphology -----------------------------------------------------------
@@ -199,16 +200,16 @@ def test_applyMask():
cv.applyMask(img, mask[:2])
-def test_centerCrop():
+def test_cropCenter():
img = np.arange(100 * 60).reshape(60, 100).astype(np.uint8)
- out = cv.centerCrop(img, 20)
+ out = cv.cropCenter(img, 20)
assert out.shape == (20, 20)
np.testing.assert_array_equal(out, img[20:40, 40:60])
- assert cv.centerCrop(img, (30, 10)).shape == (10, 30)
- assert cv.centerCrop(img, (200, 10)).shape == (10, 100) # clipped
- assert cv.centerCrop(img, (200, 10), fill=0).shape == (10, 200) # padded
+ assert cv.cropCenter(img, (30, 10)).shape == (10, 30)
+ assert cv.cropCenter(img, (200, 10)).shape == (10, 100) # clipped
+ assert cv.cropCenter(img, (200, 10), fill=0).shape == (10, 200) # padded
with pytest.raises(ValueError, match="size"):
- cv.centerCrop(img, 0)
+ cv.cropCenter(img, 0)
# --- drawing -------------------------------------------------------------------------
@@ -299,6 +300,13 @@ def test_matchFeatures_validation(photo, kwargs):
cv.matchFeatures(photo, photo, **kwargs)
+def test_matchFeatures_masks(photo):
+ mask = np.zeros(photo.shape[:2], np.uint8)
+ mask[:, : photo.shape[1] // 2] = 255
+ found = cv.matchFeatures(photo, photo, mask=mask, referenceMask=mask)
+ assert found.srcPoints[:, 0].max() <= photo.shape[1] // 2 + 20
+
+
@pytest.mark.parametrize("motion", ["homography", "affine", "similarity"])
def test_alignImages_recovers_a_rotated_image(photo, motion):
rotated = cv.rotateEx(photo, 6)
diff --git a/tests/test_compose.py b/tests/test_compose.py
index 0fb8e84..c0e1e20 100644
--- a/tests/test_compose.py
+++ b/tests/test_compose.py
@@ -72,14 +72,14 @@ def test_overlayImage_opaque(background):
assert (background == 100).all() # src is not modified
-def test_overlayImage_alpha_and_opacity(background):
+def test_overlayImage_alpha_channel_and_alpha(background):
logo = np.zeros((1, 2, 4), np.uint8)
logo[0, 0] = (200, 200, 200, 255) # opaque
logo[0, 1] = (200, 200, 200, 0) # fully transparent
out = cv.overlayImage(background, logo)
assert tuple(out[0, 0]) == (200, 200, 200)
assert tuple(out[0, 1]) == (100, 100, 100)
- half = cv.overlayImage(background, logo, opacity=0.5)
+ half = cv.overlayImage(background, logo, alpha=0.5)
assert tuple(half[0, 0]) == (150, 150, 150)
@@ -106,7 +106,8 @@ def test_overlayImage_gray_and_bgra_targets():
[
(np.zeros((4, 4), np.float32), np.zeros((2, 2), np.uint8), {}, "8-bit"),
(np.zeros((4, 4), np.uint8), np.zeros((2, 2, 2), np.uint8), {}, "channels"),
- (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"opacity": 1.5}, "opacity"),
+ (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"alpha": 1.5}, "alpha"),
+ (np.zeros((4, 4), np.uint8), np.zeros((2, 2), np.uint8), {"alpha": float("nan")}, "alpha"),
],
)
def test_overlayImage_validation(src, overlay, kwargs, match):
diff --git a/tests/test_contour.py b/tests/test_contour.py
index 24c7fce..a0e60c6 100644
--- a/tests/test_contour.py
+++ b/tests/test_contour.py
@@ -214,12 +214,12 @@ def test_cropContour_blanks_the_outside(contours):
assert crop.shape == (51, 51, 3)
assert tuple(crop[0, 0]) == (0, 0, 0) # the corner of the box lies outside the circle
assert tuple(crop[25, 25]) == (200, 200, 200)
- assert tuple(cv.cropContour(img, contours[1], background=(1, 2, 3))[0, 0]) == (1, 2, 3)
+ assert tuple(cv.cropContour(img, contours[1], fill=(1, 2, 3))[0, 0]) == (1, 2, 3)
-def test_cropContour_margin_is_clipped_and_background_none_keeps_pixels(contours):
+def test_cropContour_margin_is_clipped_and_fill_none_keeps_pixels(contours):
img = np.full((120, 160), 200, np.uint8)
- crop = cv.cropContour(img, contours[1], margin=100, background=None)
+ crop = cv.cropContour(img, contours[1], margin=100, fill=None)
assert crop.shape == (120, 160)
assert crop.min() == 200
assert cv.cropContour(img, contours[0], margin=5).shape == (61, 61)
@@ -245,6 +245,7 @@ def test_cropContour_does_not_modify_the_source(contours):
[
({"margin": -1}, "margin"),
({"transparent": True}, "8-bit"),
+ ({"fill": float("nan")}, "fill"),
],
)
def test_cropContour_validation(contours, kwargs, match):
@@ -262,17 +263,25 @@ def test_cropContour_outside_the_image(contours):
def test_drawContoursEx_uses_a_different_color_per_contour(shapes, contours):
- out = cv.drawContoursEx(shapes, contours, thickness=cv.FILLED)
- assert out.shape == (120, 160, 3)
+ img = cv.toBGR(shapes)
+ out = cv.drawContoursEx(img, contours, thickness=cv.FILLED)
+ assert out is img # drawn in place, like cv.drawContours
colors = {tuple(out[45, 45]), tuple(out[45, 115]), tuple(out[102, 80])}
assert len(colors) == 3
- assert shapes.ndim == 2 # the source is not modified
+ assert colors == {tuple(c) for c in cv.distinctColors(3)}
+
+
+def test_drawContoursEx_gray_stays_gray(shapes, contours):
+ img = shapes.copy()
+ out = cv.drawContoursEx(img, contours, thickness=cv.FILLED)
+ assert out is img and out.ndim == 2
+ assert out[45, 45] != out[45, 115] # the luminance of each color
def test_drawContoursEx_labels(shapes, contours):
- plain = cv.drawContoursEx(shapes, contours)
- numbered = cv.drawContoursEx(shapes, contours, labels=True)
- named = cv.drawContoursEx(shapes, contours, labels=["a", "b", "c"])
+ plain = cv.drawContoursEx(cv.toBGR(shapes), contours)
+ numbered = cv.drawContoursEx(cv.toBGR(shapes), contours, labels=True)
+ named = cv.drawContoursEx(cv.toBGR(shapes), contours, labels=["a", "b", "c"])
assert (numbered != plain).any()
assert (named != plain).any()
@@ -290,3 +299,9 @@ def test_drawContoursEx_validation(shapes, contours):
cv.drawContoursEx(shapes, contours, labels=["only one"])
with pytest.raises(ValueError, match="8-bit"):
cv.drawContoursEx(shapes.astype(np.float32), contours)
+ with pytest.raises(ValueError, match="fontScale"):
+ cv.drawContoursEx(shapes, contours, fontScale=0)
+ with pytest.raises(ValueError, match="colors"):
+ cv.drawContoursEx(shapes, contours, colors=[])
+ with pytest.raises(ValueError, match="empty"):
+ cv.drawContoursEx(np.zeros((0, 4), np.uint8), contours)
diff --git a/tests/test_cv2u.py b/tests/test_cv2u.py
index 45d8ccd..6d286ad 100644
--- a/tests/test_cv2u.py
+++ b/tests/test_cv2u.py
@@ -45,7 +45,9 @@ def test_cv2_passthrough():
assert cv is not cv2
assert cv.imread is cv2.imread
assert cv.COLOR_BGR2GRAY == cv2.COLOR_BGR2GRAY
- assert cv.dnn is cv2.dnn
+ assert cv.dnn is not cv2.dnn # cv2u.dnn adds helpers and passes the rest through
+ assert cv.dnn.readNet is cv2.dnn.readNet
+ assert cv.dnn.DNN_BACKEND_OPENCV == cv2.dnn.DNN_BACKEND_OPENCV
assert "imread" in dir(cv)
@@ -83,10 +85,10 @@ def test_extension_names_follow_opencv_style():
def test_top_level_exports_every_submodule_name():
# Principle: ``import cv2u as cv`` reaches every extension; nothing is reachable only from a submodule.
- from cv2u import core, flag, highgui, imgcodecs, imgproc, videoio
+ from cv2u import calib3d, core, flag, highgui, imgcodecs, imgproc, videoio
submodule_names = set()
- for module in (core, flag, highgui, imgcodecs, imgproc, videoio):
+ for module in (calib3d, core, flag, highgui, imgcodecs, imgproc, videoio):
submodule_names |= set(module.__all__)
assert submodule_names == set(cv.__all__)
@@ -137,32 +139,56 @@ def test_dbscan_roundtrip():
pytest.importorskip("sklearn")
src = np.zeros((8, 8, 3), np.uint8)
src[:, 4:] = (200, 50, 10)
- maps, labels = cv.DBSCAN(src, 1.7, 2)
- assert maps.shape == (8, 8)
- assert len(np.unique(labels)) == 2
- dst = cv.drawDBSCAN(src, maps, labels)
+ maps, centers = cv.dbscanColors(src, 1.7, 2)
+ assert isinstance(cv.dbscanColors(src, 1.7, 2), cv.Clusters)
+ assert maps.shape == (8, 8) and maps.dtype == np.int32
+ assert sorted(np.unique(maps).tolist()) == [0, 1] # labels start at 0; -1 would be noise
+ assert centers.shape == (2, 3) and centers.dtype == np.uint8
+ assert {tuple(c) for c in centers} == {(0, 0, 0), (200, 50, 10)}
+ dst = cv.drawClusters(src, maps)
assert dst.shape == src.shape
np.testing.assert_array_equal(dst, src)
+def test_dbscan_noise_is_minus_one():
+ pytest.importorskip("sklearn")
+ src = np.zeros((6, 6, 3), np.uint8)
+ src[2, 2] = (255, 255, 255) # a lone pixel is noise with minSamples=4
+ maps, centers = cv.dbscanColors(src, 1.7)
+ assert maps[2, 2] == -1
+ assert len(centers) == 1 and maps.max() == 0
+ painted = cv.drawClusters(src, maps)
+ assert tuple(painted[2, 2]) == (255, 255, 255) # noise keeps its original color
+
+
def test_dbscan_without_cluster_extra(monkeypatch, bgr):
# Simulate an install without the ``cluster`` extra.
monkeypatch.setitem(sys.modules, "sklearn", None)
monkeypatch.setitem(sys.modules, "sklearn.cluster", None)
with pytest.raises(ImportError, match=r"python-opencv-utils\[cluster\]"):
- cv.DBSCAN(bgr, 1.7, 2)
+ cv.dbscanColors(bgr, 1.7, 2)
-@pytest.mark.parametrize("src", [np.zeros((8, 8), np.uint8), np.zeros((8, 8, 4), np.uint8), [[1, 2, 3]]])
+@pytest.mark.parametrize("src", [np.zeros((8, 8), np.uint8), np.zeros((8, 8, 4), np.uint8), np.zeros((1, 3), np.uint8)])
def test_dbscan_rejects_non_bgr(src):
with pytest.raises(ValueError, match="3-channel"):
- cv.DBSCAN(src, 1.7, 2)
+ cv.dbscanColors(src, 1.7, 2)
-def test_drawDBSCAN_rejects_mismatched_maps(bgr):
- labels = np.zeros(10, dtype=np.int64)
- with pytest.raises(ValueError, match="do not match"):
- cv.drawDBSCAN(bgr, labels.reshape(2, 5), labels)
+def test_dbscan_validation(bgr):
+ with pytest.raises(ValueError, match="uint8"):
+ cv.dbscanColors(bgr.astype(np.float32), 1.7)
+ with pytest.raises(ValueError, match="empty"):
+ cv.dbscanColors(np.zeros((0, 0, 3), np.uint8), 1.7)
+ with pytest.raises(ValueError, match="eps"):
+ cv.dbscanColors(bgr, 0)
+ with pytest.raises(ValueError, match="minSamples"):
+ cv.dbscanColors(bgr, 1.7, minSamples=0)
+
+
+def test_drawClusters_rejects_mismatched_maps(bgr):
+ with pytest.raises(ValueError, match="maps"):
+ cv.drawClusters(bgr, np.zeros((2, 5), dtype=np.int64))
def test_gammaCorrection(bgr):
@@ -232,51 +258,62 @@ def test_isInside_matches_pointPolygonTest():
assert cv.isInside((x, y), star) == (expected > 0), (x, y)
-def test_DHEdge(bgr):
+def test_boldEdges(bgr):
gray = cv.cvtColor(bgr, cv.COLOR_BGR2GRAY)
- dst = cv.DHEdge(gray)
+ dst = cv.boldEdges(gray)
assert dst.shape == gray.shape
assert dst.dtype == np.uint8
-def test_DHEdge_flat_image_has_no_edges():
+def test_boldEdges_flat_image_has_no_edges():
# Including the 1-pixel border, which must not keep the source intensity.
- assert not cv.DHEdge(np.full((10, 12), 100, np.uint8)).any()
+ assert not cv.boldEdges(np.full((10, 12), 100, np.uint8)).any()
-def test_DHEdge_color(bgr):
- assert cv.DHEdge(bgr).shape == bgr.shape
+def test_boldEdges_color(bgr):
+ assert cv.boldEdges(bgr).shape == bgr.shape
-def test_DHEdge_validation():
+def test_boldEdges_validation():
with pytest.raises(ValueError, match="uint8"):
- cv.DHEdge(np.zeros((8, 8), np.float32))
+ cv.boldEdges(np.zeros((8, 8), np.float32))
+ with pytest.raises(ValueError, match="empty"):
+ cv.boldEdges(np.zeros((0, 8), np.uint8))
def test_makeGradient_bgr():
- img = cv.makeGradient((10, 20, 3), (0, 0, 0), (255, 128, 64))
+ img = cv.makeGradient((20, 10), (0, 0, 0), (255, 128, 64))
assert img.shape == (10, 20, 3)
assert img.dtype == np.uint8
assert tuple(img[0, 0]) == (0, 0, 0)
assert tuple(img[-1, -1]) == (255, 128, 64)
-@pytest.mark.parametrize("shape", [(10, 20), (10, 20, 1)])
@pytest.mark.parametrize(("start", "end"), [(0, 255), ((0,), (255,))])
-def test_makeGradient_gray(shape, start, end):
- img = cv.makeGradient(shape, start, end)
- assert img.shape == shape
+def test_makeGradient_gray(start, end):
+ img = cv.makeGradient((20, 10), start, end, channels=1)
+ assert img.shape == (10, 20)
assert img.flat[0] == 0
assert img.flat[-1] == 255
-def test_makeGradient_invalid_channels():
- with pytest.raises(ValueError, match="channels"):
- cv.makeGradient((10, 10, 4), 0, 255)
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"size": (10, 10), "start": 0, "end": 255, "channels": 4},
+ {"size": (0, 10), "start": 0, "end": 255},
+ {"size": (10, 10), "start": -1, "end": 255},
+ {"size": (10, 10), "start": 0, "end": float("nan")},
+ {"size": (10, 10), "start": (0, 0), "end": 255},
+ ],
+)
+def test_makeGradient_validation(kwargs):
+ with pytest.raises(ValueError):
+ cv.makeGradient(**kwargs)
def test_makeGradient_horizontal():
- img = cv.makeGradient((4, 256, 3), (0, 0, 0), (255, 255, 255), direction="horizontal")
+ img = cv.makeGradient((256, 4), (0, 0, 0), (255, 255, 255), direction="horizontal")
assert img.shape == (4, 256, 3)
np.testing.assert_array_equal(img[0], img[-1]) # every row is the same
assert img[0, 0, 0] == 0
@@ -285,7 +322,7 @@ def test_makeGradient_horizontal():
def test_makeGradient_vertical():
- img = cv.makeGradient((256, 4), 0, 255, direction="vertical")
+ img = cv.makeGradient((4, 256), 0, 255, direction="vertical", channels=1)
assert img.shape == (256, 4)
np.testing.assert_array_equal(img[:, 0], img[:, -1]) # every column is the same
assert img[0, 0] == 0
@@ -294,12 +331,12 @@ def test_makeGradient_vertical():
def test_makeGradient_horizontal_is_default():
np.testing.assert_array_equal(
- cv.makeGradient((10, 20, 3), 0, 255), cv.makeGradient((10, 20, 3), 0, 255, direction="horizontal")
+ cv.makeGradient((20, 10), 0, 255), cv.makeGradient((20, 10), 0, 255, direction="horizontal")
)
def test_makeGradient_raster():
- img = cv.makeGradient((2, 3), 0, 250, direction="raster")
+ img = cv.makeGradient((3, 2), 0, 250, direction="raster", channels=1)
np.testing.assert_array_equal(img, [[0, 50, 100], [150, 200, 250]])
@@ -309,8 +346,28 @@ def test_makeGradient_invalid_direction():
def test_imcolor(bgr):
- assert tuple(cv.imcolor((5, 5, 3), (1, 2, 3))[2, 2]) == (1, 2, 3)
- assert cv.imcolor((2, 2), 0.5, dtype=np.float32).dtype == np.float32
+ img = cv.imcolor((5, 4), (1, 2, 3))
+ assert img.shape == (4, 5, 3) and img.dtype == np.uint8
+ assert tuple(img[2, 2]) == (1, 2, 3)
+ assert cv.imcolor((2, 3), 0.5, channels=1, dtype=np.float32).shape == (3, 2)
+ assert cv.imcolor((2, 2), 0.5, channels=1, dtype=np.float32).dtype == np.float32
+ assert tuple(cv.imcolor((2, 2), (1, 2, 3, 4), channels=4)[0, 0]) == (1, 2, 3, 4)
+ assert tuple(cv.imcolor((2, 2), 9)[0, 0]) == (9, 9, 9)
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"size": (0, 2), "color": 0},
+ {"size": (2, 2), "color": 0, "channels": 2},
+ {"size": (2, 2), "color": 256},
+ {"size": (2, 2), "color": float("inf")},
+ {"size": (2, 2), "color": (1, 2)},
+ ],
+)
+def test_imcolor_validation(kwargs):
+ with pytest.raises(ValueError):
+ cv.imcolor(**kwargs)
def test_imcolorLike(bgr):
@@ -320,28 +377,40 @@ def test_imcolorLike(bgr):
assert tuple(like[0, 0]) == (1, 2, 3)
assert cv.imcolorLike(np.zeros((2, 2), np.float32), 0.5).dtype == np.float32
assert cv.imcolorLike(np.zeros((2, 2), np.float32), 7, dtype=np.uint8).dtype == np.uint8
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(bgr, 300)
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(bgr, (1, 2))
+ with pytest.raises(ValueError, match="color"):
+ cv.imcolorLike(np.zeros((2, 2), np.float32), float("nan"))
# --- imgcodecs -------------------------------------------------------------------
-def test_urlread_file_url(tmp_path, bgr):
+def test_imreadUrl_file_url(tmp_path, bgr):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
- np.testing.assert_array_equal(cv.urlread(path.as_uri()), bgr)
+ np.testing.assert_array_equal(cv.imreadUrl(path.as_uri()), bgr)
+
+
+def test_imreadUrl_reads_color_by_default_like_imread(tmp_path):
+ path = tmp_path / "img.png"
+ assert cv.imwrite(str(path), np.zeros((4, 4, 4), np.uint8))
+ assert cv.imreadUrl(path.as_uri()).shape == (4, 4, 3)
+ assert cv.imreadUrl(path.as_uri(), cv.IMREAD_UNCHANGED).shape == (4, 4, 4)
-def test_urlread_undecodable_returns_none(tmp_path):
+def test_imreadUrl_undecodable_returns_none(tmp_path):
path = tmp_path / "not-an-image.png"
path.write_bytes(b"hello")
- assert cv.urlread(path.as_uri()) is None
+ assert cv.imreadUrl(path.as_uri()) is None
-def test_urlread_sends_headers(monkeypatch, tmp_path, bgr):
+def test_imreadUrl_sends_headers(monkeypatch, tmp_path, bgr):
import urllib.request
- # ``cv2u.imgcodecs.urlread`` is the re-exported function, so take the module from sys.modules.
- urlread_module = sys.modules["cv2u.imgcodecs.urlread"]
+ urlread_module = sys.modules["cv2u.imgcodecs.url"]
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
@@ -354,12 +423,12 @@ def spy(request, timeout=None):
return real_urlopen(request, timeout=timeout)
monkeypatch.setattr(urlread_module, "urlopen", spy)
- cv.urlread(path.as_uri(), timeout=5, headers={"X-Test": "1"})
+ cv.imreadUrl(path.as_uri(), timeout=5, headers={"X-Test": "1"})
assert seen["User-agent"].startswith("cv2u")
assert seen["X-test"] == "1"
assert seen["timeout"] == 5
- cv.urlread(path.as_uri(), headers={"User-Agent": "custom"})
+ cv.imreadUrl(path.as_uri(), headers={"User-Agent": "custom"})
assert seen["User-agent"] == "custom"
@@ -376,8 +445,7 @@ def test_flip_flags(bgr):
def test_putTextEx(bgr, gray_input, font_path):
font = font_path
src = np.zeros((40, 60), np.uint8) if gray_input else np.zeros_like(bgr)
- before = src.copy()
dst = cv.putTextEx(src, "Hi 한글", (2, 2), font, 20, (255, 255, 255)) # pathlib.Path is accepted
- assert dst.shape == (40, 60, 3)
+ assert dst is src # drawn in place, like cv.putText
+ assert dst.shape == src.shape # grayscale stays grayscale
assert dst.any()
- np.testing.assert_array_equal(src, before) # src is not modified
diff --git a/tests/test_dnn.py b/tests/test_dnn.py
new file mode 100644
index 0000000..92479f3
--- /dev/null
+++ b/tests/test_dnn.py
@@ -0,0 +1,466 @@
+import cv2
+import numpy as np
+import pytest
+
+import cv2u.dnn as dnn
+from cv2u.dnn.inference import (
+ Detections,
+ PreprocessInfo,
+ drawDetections,
+ inferImage,
+ loadModel,
+ postprocessClassification,
+ postprocessDetections,
+ preprocessImage,
+ readClassNames,
+ sigmoid,
+ softmax,
+)
+
+HAS_DNN = hasattr(cv2, "dnn")
+
+
+# --- package: passthrough to cv2.dnn ---------------------------------------------------------------------------
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_package_passes_through_cv2_dnn():
+ assert dnn.readNet is cv2.dnn.readNet
+ assert dnn.NMSBoxes is cv2.dnn.NMSBoxes
+ assert dnn.DNN_BACKEND_OPENCV == cv2.dnn.DNN_BACKEND_OPENCV
+ names = dir(dnn)
+ assert "readNet" in names and "preprocessImage" in names
+ assert dnn.preprocessImage is preprocessImage
+
+
+def test_package_unknown_attribute():
+ with pytest.raises(AttributeError, match=r"cv2u.dnn"):
+ _ = dnn.noSuchThing
+
+
+def test_public_names_not_in_cv2():
+ for name in dnn.__all__:
+ assert not hasattr(cv2, name), name
+ if HAS_DNN:
+ assert not hasattr(cv2.dnn, name), name
+
+
+# --- softmax / sigmoid -------------------------------------------------------------------------------------------
+
+
+def test_softmax_sums_to_one_and_is_stable():
+ logits = np.array([[1000.0, 1001.0, 1002.0], [0.0, 0.0, 0.0]])
+ probs = softmax(logits)
+ assert probs.dtype == np.float32
+ np.testing.assert_allclose(probs.sum(axis=1), [1, 1], rtol=1e-6)
+ np.testing.assert_allclose(probs[1], [1 / 3] * 3, rtol=1e-6)
+ assert np.argmax(probs[0]) == 2
+ np.testing.assert_allclose(softmax(logits, axis=0).sum(axis=0), [1, 1, 1], rtol=1e-6)
+ assert softmax(np.zeros((0, 3))).shape == (0, 3)
+
+
+def test_sigmoid_values():
+ out = sigmoid([0.0, -1000.0, 1000.0])
+ assert out.dtype == np.float32
+ np.testing.assert_allclose(out, [0.5, 0.0, 1.0], atol=1e-6)
+
+
+# --- preprocessImage ---------------------------------------------------------------------------------------------
+
+
+@pytest.fixture
+def img():
+ return np.random.default_rng(1).integers(0, 256, (60, 120, 3), dtype=np.uint8) # h=60, w=120
+
+
+def test_preprocessImage_letterbox_blob_and_info(img):
+ blob, info = preprocessImage(img, (64, 64))
+ assert blob.shape == (1, 3, 64, 64) and blob.dtype == np.float32
+ assert isinstance(info, PreprocessInfo)
+ assert info.inputSize == (64, 64) and info.originalSize == (120, 60)
+ scale = 64 / 120
+ assert info.scale == (scale, scale)
+ assert info.pad == (0, (64 - 32) // 2)
+ # Padding rows are the padding color (114 / 255), scaled.
+ np.testing.assert_allclose(blob[0, :, 0, :], 114 / 255, atol=1e-6)
+ assert blob.max() <= 1.0 and blob.min() >= 0.0
+
+
+def test_preprocessImage_swapRB_mean_scale(img):
+ blob, _ = preprocessImage(img, (120, 60), swapRB=True, scale=1.0, mean=(0, 0, 0))
+ np.testing.assert_array_equal(blob[0, 0], img[:, :, 2])
+ np.testing.assert_array_equal(blob[0, 2], img[:, :, 0])
+ blob, _ = preprocessImage(img, (120, 60), swapRB=False, scale=2.0, mean=(10, 20, 30))
+ np.testing.assert_allclose(blob[0, 1], (img[:, :, 1].astype(np.float32) - 20) * 2)
+
+
+def test_preprocessImage_stretch(img):
+ blob, info = preprocessImage(img, (30, 30), letterboxPad=False)
+ assert blob.shape == (1, 3, 30, 30)
+ assert info.scale == (0.25, 0.5) and info.pad == (0, 0)
+
+
+@pytest.mark.parametrize("shape", [(60, 120), (60, 120, 4), (60, 120, 1)])
+def test_preprocessImage_gray_bgra_single_channel(shape):
+ src = np.full(shape, 200, np.uint8)
+ blob, _ = preprocessImage(src, (32, 32), dtype=np.float16)
+ assert blob.shape == (1, 3, 32, 32) and blob.dtype == np.float16
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"size": (0, 32)},
+ {"size": (32, -1)},
+ {"size": (32, 32), "scale": float("nan")},
+ {"size": (32, 32), "mean": (1, float("inf"), 3)},
+ {"size": (32, 32), "mean": (1, 2)},
+ ],
+)
+def test_preprocessImage_validation(img, kwargs):
+ with pytest.raises(ValueError):
+ preprocessImage(img, **kwargs)
+
+
+def test_preprocessImage_empty():
+ with pytest.raises(ValueError, match="src"):
+ preprocessImage(np.zeros((0, 10, 3), np.uint8), (32, 32))
+
+
+# --- postprocessDetections ---------------------------------------------------------------------------------------
+
+
+def _identity_info(width=200, height=100):
+ return PreprocessInfo((1.0, 1.0), (0, 0), (width, height), (width, height))
+
+
+def _rows(*rows):
+ # rows of (cx, cy, w, h, score_class0, score_class1, ...)
+ return np.array(rows, dtype=np.float32)
+
+
+def test_postprocessDetections_basic_cxcywh():
+ rows = _rows(
+ [50, 50, 20, 10, 0.9, 0.1], # class 0, kept
+ [52, 50, 20, 10, 0.8, 0.1], # overlaps the first, same class -> suppressed
+ [150, 50, 20, 10, 0.1, 0.7], # class 1
+ [150, 50, 20, 10, 0.05, 0.1], # below threshold
+ )
+ det = postprocessDetections(rows[None], _identity_info(), transpose=False)
+ assert isinstance(det, Detections) and det.size == 2
+ assert det.boxes.dtype == np.float32 and det.scores.dtype == np.float32 and det.classIds.dtype == np.int32
+ np.testing.assert_allclose(det.boxes, [[40, 45, 20, 10], [140, 45, 20, 10]])
+ np.testing.assert_allclose(det.scores, [0.9, 0.7])
+ np.testing.assert_array_equal(det.classIds, [0, 1])
+
+
+def test_postprocessDetections_per_class_vs_agnostic():
+ rows = _rows([50, 50, 20, 10, 0.9, 0.1], [50, 50, 20, 10, 0.1, 0.8])
+ assert postprocessDetections(rows[None], _identity_info(), transpose=False).size == 2
+ assert postprocessDetections(rows[None], _identity_info(), transpose=False, classAgnostic=True).size == 1
+
+
+def test_postprocessDetections_channel_first_layout_auto_and_forced():
+ rows = _rows([50, 50, 20, 10, 0.9, 0.1], [150, 50, 20, 10, 0.1, 0.7])
+ channel_first = rows.T[None] # (1, 6, 2)
+ forced = postprocessDetections(channel_first, _identity_info(), transpose=True)
+ assert forced.size == 2
+ # Auto-detect on a realistic size: (1, 6, 300) with 300 candidates.
+ many = np.zeros((300, 6), np.float32)
+ many[:2] = rows
+ auto = postprocessDetections(many.T[None], _identity_info())
+ np.testing.assert_allclose(auto.boxes, forced.boxes)
+ auto_rows = postprocessDetections(many[None], _identity_info())
+ np.testing.assert_allclose(auto_rows.boxes, forced.boxes)
+
+
+def test_postprocessDetections_objectness_and_formats():
+ rows = np.array([[10, 10, 30, 20, 0.5, 0.2, 0.8]], np.float32) # xyxy with objectness
+ det = postprocessDetections(rows[None], _identity_info(), transpose=False, hasObjectness=True, boxFormat="xyxy")
+ np.testing.assert_allclose(det.boxes, [[10, 10, 20, 10]])
+ np.testing.assert_allclose(det.scores, [0.4])
+ assert det.classIds[0] == 1
+ det = postprocessDetections(rows[None], _identity_info(), transpose=False, hasObjectness=True, boxFormat="xywh")
+ np.testing.assert_allclose(det.boxes, [[10, 10, 30, 20]])
+
+
+def test_postprocessDetections_normalized_and_letterbox_mapping(img):
+ _, info = preprocessImage(img, (64, 64)) # w=120 -> scale 64/120, pad top 16
+ # A box covering the whole image inside the letterbox: cx=0.5, cy=0.5, w=1, h=32/64.
+ rows = np.array([[0.5, 0.5, 1.0, 0.5, 0.9]], np.float32)
+ det = postprocessDetections(rows[None], info, transpose=False, normalized=True)
+ np.testing.assert_allclose(det.boxes, [[0, 0, 120, 60]], atol=1e-4)
+ # Boxes partly outside the image are clipped to it.
+ rows = np.array([[0, 32, 40, 40, 0.9]], np.float32)
+ det = postprocessDetections(rows[None], info, transpose=False)
+ assert det.boxes[0, 0] == 0 and det.boxes[0, 1] == 0
+ assert det.boxes[0, 2] == pytest.approx(20 / (64 / 120))
+
+
+def test_postprocessDetections_maxCount_and_empty():
+ rows = _rows([50, 50, 20, 10, 0.9], [150, 50, 20, 10, 0.8], [100, 80, 20, 10, 0.7])
+ assert postprocessDetections(rows[None], _identity_info(), transpose=False, maxCount=2).size == 2
+ assert postprocessDetections(rows[None], _identity_info(), transpose=False, scoreThreshold=0.95).size == 0
+ det = postprocessDetections(np.zeros((1, 0, 5), np.float32), _identity_info(), transpose=False)
+ assert det.size == 0 and det.boxes.shape == (0, 4)
+
+
+@pytest.mark.parametrize(
+ ("output", "kwargs"),
+ [
+ (np.zeros((1, 2, 4), np.float32), {"transpose": False}), # no class columns
+ (np.zeros((1, 2, 5), np.float32), {"transpose": False, "hasObjectness": True}),
+ (np.zeros((2, 2, 6), np.float32), {}), # batch of 2
+ (np.zeros((1, 2, 6), np.float32), {"boxFormat": "ltrb"}),
+ (np.zeros((1, 2, 6), np.float32), {"scoreThreshold": float("nan")}),
+ (np.zeros((1, 2, 6), np.float32), {"iouThreshold": -1}),
+ ],
+)
+def test_postprocessDetections_validation(output, kwargs):
+ with pytest.raises(ValueError):
+ postprocessDetections(output, _identity_info(), **kwargs)
+
+
+# --- postprocessClassification -----------------------------------------------------------------------------------
+
+
+def test_postprocessClassification_topk():
+ logits = np.array([[1.0, 3.0, 2.0, 0.0]], np.float32)
+ top = postprocessClassification(logits, topK=2)
+ assert [i for i, _ in top] == [1, 2]
+ assert sum(p for _, p in postprocessClassification(logits, topK=4)) == pytest.approx(1.0)
+ raw = postprocessClassification([0.1, 0.7, 0.2], topK=5, softmax=False)
+ assert raw == [(1, pytest.approx(0.7)), (2, pytest.approx(0.2)), (0, pytest.approx(0.1))]
+ assert all(isinstance(i, int) and isinstance(p, float) for i, p in raw)
+
+
+@pytest.mark.parametrize(("output", "topK"), [([1, 2, 3], 0), (np.zeros((2, 3)), 1), ([], 1)])
+def test_postprocessClassification_validation(output, topK):
+ with pytest.raises(ValueError):
+ postprocessClassification(output, topK=topK)
+
+
+# --- loadModel / inferImage / readClassNames ----------------------------------------------------------------------
+
+
+def test_loadModel_missing_files(tmp_path):
+ with pytest.raises(FileNotFoundError, match="model"):
+ loadModel(tmp_path / "없는모델.onnx")
+ model = tmp_path / "m.onnx"
+ model.write_bytes(b"\x00")
+ with pytest.raises(FileNotFoundError, match="config"):
+ loadModel(model, config=tmp_path / "missing.pbtxt")
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_loadModel_reads_onnx_from_buffer_with_unicode_path(tmp_path, monkeypatch):
+ captured = {}
+
+ class FakeNet:
+ def setPreferableBackend(self, backend):
+ captured["backend"] = backend
+
+ def setPreferableTarget(self, target):
+ captured["target"] = target
+
+ def fake_read(buffer):
+ captured["buffer"] = bytes(buffer)
+ return FakeNet()
+
+ monkeypatch.setattr(cv2.dnn, "readNetFromONNX", fake_read)
+ model = tmp_path / "모델" / "yolo.ONNX"
+ model.parent.mkdir()
+ model.write_bytes(b"onnx-bytes")
+ net = loadModel(model, backend=cv2.dnn.DNN_BACKEND_OPENCV, target=cv2.dnn.DNN_TARGET_CPU)
+ assert isinstance(net, FakeNet)
+ assert captured == {
+ "buffer": b"onnx-bytes",
+ "backend": cv2.dnn.DNN_BACKEND_OPENCV,
+ "target": cv2.dnn.DNN_TARGET_CPU,
+ }
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_loadModel_preferGpu_without_cuda_keeps_default(tmp_path, monkeypatch):
+ class FakeNet:
+ def setPreferableBackend(self, backend):
+ raise AssertionError("backend must not be set without CUDA")
+
+ def setPreferableTarget(self, target):
+ raise AssertionError("target must not be set without CUDA")
+
+ monkeypatch.setattr(cv2.dnn, "readNetFromTFLite", lambda buffer: FakeNet())
+ monkeypatch.setattr(cv2.dnn, "getAvailableTargets", lambda backend: [])
+ model = tmp_path / "m.tflite"
+ model.write_bytes(b"x")
+ assert isinstance(loadModel(model, preferGpu=True), FakeNet)
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_loadModel_other_formats_use_readNet(tmp_path, monkeypatch):
+ calls = []
+ monkeypatch.setattr(cv2.dnn, "readNet", lambda *args: calls.append(args) or object())
+ model, config = tmp_path / "m.weights", tmp_path / "m.cfg"
+ model.write_bytes(b"x")
+ config.write_text("x")
+ loadModel(model)
+ loadModel(model, config)
+ assert calls == [(str(model),), (str(model), str(config))]
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_loadModel_real_invalid_model_raises_opencv_error(tmp_path):
+ model = tmp_path / "bad.onnx"
+ model.write_bytes(b"not an onnx file")
+ with pytest.raises(cv2.error):
+ loadModel(model)
+
+
+@pytest.mark.skip(reason="needs a real model file; run manually with a YOLO .onnx")
+def test_loadModel_real_model(): # pragma: no cover
+ pass
+
+
+class FakeNet:
+ def __init__(self, outputs):
+ self.outputs = outputs
+ self.blob = None
+ self.names = None
+
+ def setInput(self, blob):
+ self.blob = blob
+
+ def forward(self, outputNames):
+ self.names = list(outputNames)
+ return self.outputs if len(outputNames) > 1 else self.outputs[0]
+
+ def getUnconnectedOutLayersNames(self):
+ return ["out0", "out1"]
+
+
+def test_inferImage_with_blob_and_image(img):
+ net = FakeNet([np.ones((1, 2)), np.zeros((1, 3))])
+ blob, _ = preprocessImage(img, (32, 32))
+ outputs = inferImage(net, blob)
+ assert len(outputs) == 2 and net.names == ["out0", "out1"] and net.blob is blob
+ outputs = inferImage(net, img, outputNames=["out0"], size=(32, 32))
+ assert len(outputs) == 1 and net.names == ["out0"] and net.blob.shape == (1, 3, 32, 32)
+ np.testing.assert_array_equal(outputs[0], np.ones((1, 2)))
+
+
+def test_inferImage_validation(img):
+ net = FakeNet([np.ones((1, 2))])
+ with pytest.raises(ValueError, match="size"):
+ inferImage(net, img)
+ with pytest.raises(ValueError, match="src"):
+ inferImage(net, np.zeros(5))
+
+
+def test_readClassNames(tmp_path):
+ path = tmp_path / "클래스.names"
+ path.write_text("person\n\n 고양이 \ncar\n", encoding="utf-8")
+ assert readClassNames(path) == ["person", "고양이", "car"]
+ with pytest.raises(FileNotFoundError):
+ readClassNames(tmp_path / "missing.names")
+
+
+# --- drawDetections ----------------------------------------------------------------------------------------------
+
+
+def _detections():
+ return Detections(
+ np.array([[10, 10, 40, 30], [100, 20, 50, 50]], np.float32),
+ np.array([0.9, 0.5], np.float32),
+ np.array([0, 2], np.int32),
+ )
+
+
+def test_drawDetections_draws_in_place_and_returns_image():
+ canvas = np.zeros((100, 200, 3), np.uint8)
+ out = drawDetections(canvas, _detections(), classNames=["person", "bike", "car"])
+ assert out is canvas and canvas.any()
+ # Each box gets its class color (red for class 0 from distinctColors).
+ assert tuple(canvas[10, 30]) == (0, 0, 255)
+
+
+def test_drawDetections_colors_and_missing_names():
+ canvas = np.zeros((100, 200, 3), np.uint8)
+ colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
+ drawDetections(canvas, _detections(), classNames=["only-one"], colors=colors, showScore=False, thickness=1)
+ assert tuple(canvas[10, 30]) == (255, 0, 0)
+ assert tuple(canvas[20, 120]) == (0, 0, 255)
+ gray = np.zeros((100, 200), np.uint8)
+ assert drawDetections(gray, _detections(), colors=[200]).any()
+
+
+def test_drawDetections_empty_and_validation():
+ canvas = np.zeros((10, 10, 3), np.uint8)
+ empty = Detections(np.zeros((0, 4), np.float32), np.zeros(0, np.float32), np.zeros(0, np.int32))
+ assert drawDetections(canvas, empty) is canvas and not canvas.any()
+ with pytest.raises(ValueError, match="src"):
+ drawDetections(np.zeros((0, 10, 3), np.uint8), _detections())
+
+
+# --- remaining loadModel branches --------------------------------------------------------------------------------
+
+
+@pytest.mark.skipif(not HAS_DNN, reason="OpenCV build without cv2.dnn")
+def test_loadModel_tensorflow_buffers_and_cuda(tmp_path, monkeypatch):
+ captured = {}
+
+ class FakeNet:
+ def setPreferableBackend(self, backend):
+ captured["backend"] = backend
+
+ def setPreferableTarget(self, target):
+ captured["target"] = target
+
+ def fake_read(model, config):
+ captured["model"], captured["config"] = bytes(model), bytes(config)
+ return FakeNet()
+
+ monkeypatch.setattr(cv2.dnn, "readNetFromTensorflow", fake_read)
+ monkeypatch.setattr(cv2.dnn, "getAvailableTargets", lambda backend: [cv2.dnn.DNN_TARGET_CUDA])
+ model, config = tmp_path / "m.pb", tmp_path / "m.pbtxt"
+ model.write_bytes(b"pb")
+ config.write_text("cfg")
+ loadModel(model, preferGpu=True)
+ assert captured == {
+ "model": b"pb",
+ "config": b"",
+ "backend": cv2.dnn.DNN_BACKEND_CUDA,
+ "target": cv2.dnn.DNN_TARGET_CUDA,
+ }
+ loadModel(model, config, preferGpu=True, target=cv2.dnn.DNN_TARGET_CUDA_FP16)
+ assert captured["config"] == b"cfg" and captured["target"] == cv2.dnn.DNN_TARGET_CUDA_FP16
+
+ def failing(backend):
+ raise cv2.error("no cuda")
+
+ monkeypatch.setattr(cv2.dnn, "getAvailableTargets", failing)
+ captured.clear()
+ loadModel(model, preferGpu=True)
+ assert "backend" not in captured
+
+
+def test_loadModel_without_dnn_module(tmp_path, monkeypatch):
+ monkeypatch.delattr(cv2, "dnn", raising=False)
+ model = tmp_path / "m.onnx"
+ model.write_bytes(b"x")
+ with pytest.raises(RuntimeError, match=r"cv2.dnn"):
+ loadModel(model)
+
+
+def test_loadModel_reads_the_file_only_for_buffer_formats(tmp_path, monkeypatch):
+ read = []
+ monkeypatch.setattr(np, "fromfile", lambda path, dtype=None: read.append(str(path)) or np.zeros(1, np.uint8))
+ monkeypatch.setattr(cv2.dnn, "readNet", lambda *args: object())
+ monkeypatch.setattr(cv2.dnn, "readNetFromONNX", lambda buffer: object(), raising=False)
+ weights = tmp_path / "m.caffemodel"
+ weights.write_bytes(b"x" * 10)
+ loadModel(weights)
+ assert read == [] # not loaded into memory: OpenCV opens the path itself
+ onnx = tmp_path / "m.onnx"
+ onnx.write_bytes(b"x")
+ loadModel(onnx)
+ assert read == [str(onnx)]
diff --git a/tests/test_document.py b/tests/test_document.py
new file mode 100644
index 0000000..20b1cec
--- /dev/null
+++ b/tests/test_document.py
@@ -0,0 +1,400 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc.document import (
+ detectPage,
+ detectTextBlocks,
+ detectTextLines,
+ enhanceDocument,
+ estimateSkew,
+ niblackThreshold,
+ removeBorder,
+ removeLines,
+ removeShadow,
+ removeSpeckles,
+ sauvolaThreshold,
+ scanDocument,
+)
+
+ROWS = ["Hello world text", "Second line here", "Third row ok"]
+
+
+def page(rows: list[str] = ROWS, spacing: int = 60) -> np.ndarray:
+ img = np.full((300, 400), 255, np.uint8)
+ for i, text in enumerate(rows):
+ cv2.putText(img, text, (20, 60 + i * spacing), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2)
+ return img
+
+
+def shaded_page() -> np.ndarray:
+ gradient = np.tile(np.linspace(60, 255, 400).astype(np.uint8), (300, 1))
+ return cv2.min(page(), gradient)
+
+
+def table_page() -> np.ndarray:
+ img = page()
+ for y in range(30, 300, 60):
+ cv2.line(img, (0, y), (399, y), 0, 2)
+ for x in range(0, 400, 100):
+ cv2.line(img, (x, 0), (x, 299), 0, 2)
+ return img
+
+
+def photo() -> np.ndarray:
+ img = np.full((400, 500, 3), 30, np.uint8)
+ pts = np.array([[100, 50], [420, 80], [400, 350], [80, 320]], np.int32)
+ cv2.fillPoly(img, [pts], (230, 230, 230))
+ return img
+
+
+# removeShadow ---------------------------------------------------------------------------------------------------
+
+
+def test_remove_shadow_flattens_background():
+ clean, shaded = page(), shaded_page()
+ out = removeShadow(shaded)
+ assert out.shape == shaded.shape and out.dtype == np.uint8
+ assert shaded[clean == 255].std() > 40
+ assert out[clean == 255].std() < 5
+ assert out[clean == 255].mean() > 240
+ assert out[clean == 0].mean() < 100
+
+
+def test_remove_shadow_color_keeps_channels():
+ bgr = cv2.cvtColor(shaded_page(), cv2.COLOR_GRAY2BGR)
+ out = removeShadow(bgr)
+ assert out.shape == bgr.shape
+ assert out[..., 0].mean() > 200
+
+
+@pytest.mark.parametrize("kwargs", [{"kernelSize": 0}, {"blurSize": 4}, {"blurSize": 1}])
+def test_remove_shadow_rejects_bad_kernels(kwargs):
+ with pytest.raises(ValueError):
+ removeShadow(page(), **kwargs)
+
+
+def test_remove_shadow_rejects_empty_and_float():
+ with pytest.raises(ValueError, match="src"):
+ removeShadow(np.zeros((0, 10), np.uint8))
+ with pytest.raises(ValueError, match="8-bit"):
+ removeShadow(np.zeros((10, 10), np.float32))
+
+
+# local thresholds -----------------------------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("fn", [sauvolaThreshold, niblackThreshold])
+def test_local_threshold_recovers_text_under_shadow(fn):
+ clean = page()
+ out = fn(shaded_page())
+ assert out.shape == clean.shape and out.dtype == np.uint8
+ assert set(np.unique(out)) <= {0, 255}
+ assert (out == clean).mean() > 0.95
+ assert (fn(shaded_page(), invert=True) == 255 - clean).mean() > 0.95
+
+
+def test_local_threshold_color_input_and_flat_page():
+ bgr = cv2.cvtColor(shaded_page(), cv2.COLOR_GRAY2BGR)
+ assert sauvolaThreshold(bgr).shape == (300, 400)
+ assert np.unique(sauvolaThreshold(np.full((50, 50), 100, np.uint8))).tolist() == [255]
+ # Niblack's threshold equals the mean on flat paper, so nothing is strictly above it (as with cv.threshold).
+ assert np.unique(niblackThreshold(np.full((50, 50), 100, np.uint8))).tolist() == [0]
+ assert np.unique(niblackThreshold(np.full((50, 50), 100, np.uint8), k=-0.2, invert=True)).tolist() == [255]
+
+
+def test_local_threshold_matches_naive_mean():
+ rng = np.random.default_rng(0)
+ gray = rng.integers(0, 256, (40, 50), dtype=np.uint8)
+ out = niblackThreshold(gray, windowSize=5, k=0.0)
+ padded = cv2.copyMakeBorder(gray, 2, 2, 2, 2, cv2.BORDER_REFLECT_101).astype(np.float64)
+ mean = cv2.blur(padded, (5, 5), borderType=cv2.BORDER_ISOLATED)[2:-2, 2:-2]
+ expect = (gray > mean).astype(np.uint8) * 255
+ assert (out == expect).mean() > 0.99
+
+
+@pytest.mark.parametrize("kwargs", [{"windowSize": 4}, {"windowSize": 1}, {"k": float("nan")}, {"r": 0}])
+def test_sauvola_rejects_bad_args(kwargs):
+ with pytest.raises(ValueError):
+ sauvolaThreshold(page(), **kwargs)
+
+
+@pytest.mark.parametrize("kwargs", [{"windowSize": 4}, {"k": float("inf")}])
+def test_niblack_rejects_bad_args(kwargs):
+ with pytest.raises(ValueError):
+ niblackThreshold(page(), **kwargs)
+
+
+# removeLines -----------------------------------------------------------------------------------------------------
+
+
+def test_remove_lines_on_binary_keeps_text():
+ clean, table = page(), table_page()
+ out = removeLines(table)
+ assert out.shape == table.shape and out.dtype == np.uint8
+ line_pixels = (table == 0) & (clean == 255)
+ assert (out[line_pixels] == 0).mean() < 0.05
+ assert (out[clean == 0] == 0).mean() > 0.8
+
+
+def test_remove_lines_binary_input_stays_binary():
+ binary = (table_page() > 127).astype(np.uint8) * 255
+ clean = (page() > 127).astype(np.uint8) * 255
+ out = removeLines(binary)
+ assert set(np.unique(out)) <= {0, 255}
+ assert (out[(binary == 0) & (clean == 255)] == 0).mean() < 0.05
+ assert (out[clean == 0] == 0).mean() > 0.8
+ inverted = removeLines(255 - binary)
+ assert (inverted[(binary == 0) & (clean == 255)] == 255).mean() < 0.05
+
+
+def test_remove_lines_only_one_direction():
+ table = table_page()
+ horizontal_only = removeLines(table, vertical=False)
+ assert (horizontal_only[:, 200] == 0).sum() < (table[:, 200] == 0).sum() # horizontal rules gone
+ assert (horizontal_only[:, 100] == 0).sum() >= (table[:, 100] == 0).sum() - 30 # vertical ones remain
+ assert np.array_equal(removeLines(table, horizontal=False, vertical=False), table)
+
+
+def test_remove_lines_gray_and_color_inpaint():
+ gray = cv2.GaussianBlur(table_page(), (3, 3), 0)
+ out = removeLines(gray, minLength=0.3)
+ assert out.shape == gray.shape
+ assert out[150, 50:90].mean() > 200 # horizontal rule at y=150 filled with paper
+ bgr = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
+ assert removeLines(bgr, minLength=150, thickness=1).shape == bgr.shape
+ bgra = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGRA)
+ out = removeLines(bgra)
+ assert out.shape == bgra.shape and (out[..., 3] == 255).all()
+
+
+def test_remove_lines_no_lines_returns_copy():
+ src = page()
+ out = removeLines(src)
+ assert np.array_equal(out, src) and out is not src
+
+
+@pytest.mark.parametrize("kwargs", [{"minLength": 0}, {"minLength": float("nan")}, {"thickness": 0}])
+def test_remove_lines_rejects_bad_args(kwargs):
+ with pytest.raises(ValueError):
+ removeLines(page(), **kwargs)
+
+
+# detectTextLines / detectTextBlocks ------------------------------------------------------------------------------
+
+
+def test_detect_text_lines_top_to_bottom():
+ boxes = detectTextLines(page())
+ assert boxes.shape == (3, 4) and boxes.dtype == np.int32
+ assert np.all(np.diff(boxes[:, 1]) > 0)
+ assert np.all(boxes[:, 3] >= 15) and np.all(boxes[:, 2] > 100)
+ assert np.all(boxes[:, 0] >= 15)
+
+
+def test_detect_text_lines_color_light_on_dark_and_explicit_width():
+ inverted = cv2.cvtColor(255 - page(), cv2.COLOR_GRAY2BGR)
+ assert detectTextLines(inverted).shape == (3, 4)
+ assert detectTextLines(page(), dilateWidth=40).shape == (3, 4)
+ # a tiny smear splits lines into words
+ assert detectTextLines(page(), dilateWidth=1).shape[0] > 3
+
+
+def test_detect_text_lines_blank_page():
+ assert detectTextLines(np.full((50, 50), 255, np.uint8)).shape == (0, 4)
+ assert detectTextLines(np.full((50, 50), 255, np.uint8), minHeight=100).shape == (0, 4)
+
+
+def test_detect_text_blocks_merges_paragraphs():
+ img = np.full((400, 400), 255, np.uint8)
+ for i, y in enumerate([40, 70, 100, 250, 280, 310]):
+ cv2.putText(img, ROWS[i % 3], (20, y), cv2.FONT_HERSHEY_SIMPLEX, 1, 0, 2)
+ assert detectTextLines(img).shape == (6, 4)
+ blocks = detectTextBlocks(img)
+ assert blocks.shape == (2, 4)
+ assert blocks[0, 1] < 50 < blocks[0, 1] + blocks[0, 3] < 200 < blocks[1, 1]
+ assert detectTextBlocks(img, dilateSize=(60, 300)).shape == (1, 4)
+
+
+@pytest.mark.parametrize("kwargs", [{"minHeight": 0}, {"dilateWidth": 0}])
+def test_detect_text_lines_rejects_bad_args(kwargs):
+ with pytest.raises(ValueError):
+ detectTextLines(page(), **kwargs)
+
+
+@pytest.mark.parametrize("kwargs", [{"minHeight": -1}, {"dilateSize": (0, 5)}])
+def test_detect_text_blocks_rejects_bad_args(kwargs):
+ with pytest.raises(ValueError):
+ detectTextBlocks(page(), **kwargs)
+
+
+# removeBorder ----------------------------------------------------------------------------------------------------
+
+
+def test_remove_border_crops_dark_frame():
+ img = np.zeros((300, 400), np.uint8)
+ img[20:280, 30:370] = 255
+ cv2.putText(img, "text", (100, 150), cv2.FONT_HERSHEY_SIMPLEX, 2, 0, 3)
+ out = removeBorder(img)
+ assert out.shape == (260, 340) and out.flags.c_contiguous
+ assert removeBorder(img, margin=5).shape == (250, 330)
+ assert removeBorder(img, margin=-10).shape == (280, 360)
+ assert removeBorder(img, threshold=128).shape == (260, 340)
+ bgr = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
+ assert removeBorder(bgr).shape == (260, 340, 3)
+
+
+def test_remove_border_nothing_bright_or_too_much_margin():
+ dark = np.zeros((30, 40), np.uint8)
+ out = removeBorder(dark)
+ assert out.shape == dark.shape and out is not dark
+ img = np.zeros((300, 400), np.uint8)
+ img[20:280, 30:370] = 255
+ assert removeBorder(img, margin=200).shape == img.shape
+
+
+def test_remove_border_rejects_bad_args():
+ with pytest.raises(ValueError, match="threshold"):
+ removeBorder(page(), threshold=float("nan"))
+ with pytest.raises(ValueError, match="src"):
+ removeBorder(np.zeros((0, 0), np.uint8))
+
+
+# detectPage / scanDocument ---------------------------------------------------------------------------------------
+
+
+def test_detect_page_finds_corners():
+ corners = detectPage(photo())
+ assert corners is not None and corners.shape == (4, 2) and corners.dtype == np.float32
+ expect = np.array([[100, 50], [420, 80], [400, 350], [80, 320]], np.float32)
+ assert np.abs(corners - expect).max() <= 3
+ gray = cv2.cvtColor(photo(), cv2.COLOR_BGR2GRAY)
+ corners = detectPage(gray)
+ assert corners is not None and np.abs(corners - expect).max() <= 3
+
+
+def test_detect_page_large_image_is_downscaled():
+ big = cv2.resize(photo(), (1500, 1200), interpolation=cv2.INTER_NEAREST)
+ corners = detectPage(big)
+ assert corners is not None
+ assert np.abs(corners - np.array([[300, 150], [1260, 240], [1200, 1050], [240, 960]])).max() <= 10
+
+
+def test_detect_page_none_when_absent_or_too_small():
+ assert detectPage(np.full((100, 100, 3), 30, np.uint8)) is None
+ assert detectPage(photo(), minAreaRatio=0.9) is None
+ circle = np.full((300, 300), 30, np.uint8)
+ cv2.circle(circle, (150, 150), 120, 230, -1)
+ assert detectPage(circle) is None
+
+
+@pytest.mark.parametrize("ratio", [-0.1, 1.5, float("nan")])
+def test_detect_page_rejects_bad_ratio(ratio):
+ with pytest.raises(ValueError, match="minAreaRatio"):
+ detectPage(photo(), minAreaRatio=ratio)
+
+
+def test_scan_document_warps_and_enhances():
+ out = scanDocument(photo())
+ assert out.ndim == 3 and out.dtype == np.uint8
+ assert 300 < out.shape[1] < 340 and 250 < out.shape[0] < 290
+ assert out.mean() > 200
+ sized = scanDocument(photo(), size=(200, 100), enhance=False)
+ assert sized.shape == (100, 200, 3)
+ assert scanDocument(cv2.cvtColor(photo(), cv2.COLOR_BGR2GRAY)).ndim == 2
+
+
+def test_scan_document_without_page():
+ src = np.full((60, 80, 3), 30, np.uint8)
+ out = scanDocument(src, enhance=False)
+ assert out.shape == src.shape and out is not src
+ assert scanDocument(src, size=(40, 30), enhance=False).shape == (30, 40, 3)
+ assert scanDocument(src).shape == src.shape
+
+
+# enhanceDocument -------------------------------------------------------------------------------------------------
+
+
+def test_enhance_document_modes():
+ clean = page()
+ gray = enhanceDocument(shaded_page())
+ assert gray.shape == (300, 400) and gray.dtype == np.uint8
+ assert gray[clean == 255].mean() > 230
+ binary = enhanceDocument(shaded_page(), "binary")
+ assert set(np.unique(binary)) <= {0, 255}
+ assert (binary == clean).mean() > 0.9
+ bgr = cv2.cvtColor(shaded_page(), cv2.COLOR_GRAY2BGR)
+ assert enhanceDocument(bgr, "color").shape == bgr.shape
+ assert enhanceDocument(bgr, "gray").shape == (300, 400)
+ assert enhanceDocument(shaded_page(), "color").ndim == 2
+
+
+def test_enhance_document_rejects_bad_mode():
+ with pytest.raises(ValueError, match="mode"):
+ enhanceDocument(page(), "sepia") # type: ignore[arg-type]
+
+
+# estimateSkew ----------------------------------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("tilt", [0.0, 4.0, -7.5])
+def test_estimate_skew(tilt):
+ img = page()
+ matrix = cv2.getRotationMatrix2D((200, 150), tilt, 1)
+ rotated = cv2.warpAffine(img, matrix, (400, 300), borderValue=255)
+ angle = estimateSkew(rotated)
+ assert isinstance(angle, float)
+ assert abs(angle + tilt) <= 1.0
+ assert abs(estimateSkew(cv2.cvtColor(rotated, cv2.COLOR_GRAY2BGR)) + tilt) <= 1.0
+
+
+def test_estimate_skew_blank_and_limits():
+ assert estimateSkew(np.full((50, 50), 255, np.uint8)) == 0.0
+ assert estimateSkew(page(), maxAngle=0) == 0.0
+ with pytest.raises(ValueError, match="maxAngle"):
+ estimateSkew(page(), maxAngle=90)
+ with pytest.raises(ValueError, match="src"):
+ estimateSkew(np.zeros((0, 5), np.uint8))
+
+
+# removeSpeckles --------------------------------------------------------------------------------------------------
+
+
+def test_remove_speckles_keeps_polarity():
+ clean = page()
+ noisy = clean.copy()
+ rng = np.random.default_rng(1)
+ ys, xs = rng.integers(0, 300, 40), rng.integers(0, 400, 40)
+ noisy[ys, xs] = 0
+ out = removeSpeckles(noisy, maxArea=4)
+ assert out.shape == clean.shape and out.dtype == np.uint8
+ assert (out == clean).mean() > 0.999
+ assert (out[clean == 0] == 0).mean() > 0.95 # text survives
+ inverted = removeSpeckles(255 - noisy, maxArea=4)
+ assert (inverted == 255 - clean).mean() > 0.999
+
+
+def test_remove_speckles_color_and_clean_input():
+ bgr = cv2.cvtColor(page(), cv2.COLOR_GRAY2BGR)
+ bgr[5, 5] = (0, 0, 0)
+ out = removeSpeckles(bgr)
+ assert out.shape == bgr.shape and tuple(out[5, 5]) == (255, 255, 255)
+ clean = page()
+ out = removeSpeckles(clean, maxArea=0)
+ assert np.array_equal(out, clean) and out is not clean
+
+
+def test_remove_speckles_rejects_bad_args():
+ with pytest.raises(ValueError, match="maxArea"):
+ removeSpeckles(page(), maxArea=-1)
+ with pytest.raises(ValueError, match="src"):
+ removeSpeckles(np.zeros((5, 5, 5, 5), np.uint8))
+
+
+# names -----------------------------------------------------------------------------------------------------------
+
+
+def test_names_do_not_exist_in_cv2():
+ from cv2u.imgproc import document
+
+ for name in document.__all__:
+ assert not hasattr(cv2, name), name
diff --git a/tests/test_expected.py b/tests/test_expected.py
index 6a8d10c..3d3fbc4 100644
--- a/tests/test_expected.py
+++ b/tests/test_expected.py
@@ -196,11 +196,13 @@ def test_matchTemplate_only_returns_a_score_map(scene):
def test_findTemplate_finds_every_copy(scene):
img, patch = scene
matches = cv.findTemplate(img, patch)
- assert sorted((x, y) for x, y, *_ in matches) == [(10, 20), (50, 90), (90, 30)]
- assert all(w == 16 and h == 12 for _, _, w, h, _ in matches)
- scores = [s for *_, s in matches]
+ assert matches.shape == (3, 5) and matches.dtype == np.float64
+ assert sorted((x, y) for x, y, *_ in matches.tolist()) == [(10, 20), (50, 90), (90, 30)]
+ assert (matches[:, 2] == 16).all() and (matches[:, 3] == 12).all()
+ scores = matches[:, 4].tolist()
assert scores == sorted(scores, reverse=True)
assert scores[0] == pytest.approx(1.0, abs=1e-4)
+ assert cv.findTemplate(img, patch, threshold=1.0, maxCount=0).shape == (0, 5) # always an array
def test_findTemplate_maxCount_and_threshold(scene):
@@ -213,7 +215,7 @@ def test_findTemplate_maxCount_and_threshold(scene):
def test_findTemplate_other_methods(scene, method):
img, patch = scene
matches = cv.findTemplate(img, patch, threshold=0.95, method=method)
- assert (10, 20) in [(x, y) for x, y, *_ in matches]
+ assert (10, 20) in [(x, y) for x, y, *_ in matches.tolist()]
def test_findTemplate_mixed_channels(scene):
@@ -224,7 +226,14 @@ def test_findTemplate_mixed_channels(scene):
@pytest.mark.parametrize(
("kwargs", "templ_shape"),
- [({"method": cv2.TM_CCOEFF}, (4, 4)), ({"threshold": 1.5}, (4, 4)), ({}, (200, 10))],
+ [
+ ({"method": cv2.TM_CCOEFF}, (4, 4)),
+ ({"threshold": 1.5}, (4, 4)),
+ ({"threshold": float("nan")}, (4, 4)),
+ ({"maxCount": -1}, (4, 4)),
+ ({}, (200, 10)),
+ ({}, (0, 4)),
+ ],
)
def test_findTemplate_validation(scene, kwargs, templ_shape):
img, _ = scene
diff --git a/tests/test_geometry_color_hash.py b/tests/test_geometry_color_hash.py
index 87f60e0..501cdd6 100644
--- a/tests/test_geometry_color_hash.py
+++ b/tests/test_geometry_color_hash.py
@@ -51,9 +51,27 @@ def test_cropRotatedRect_extracts_the_box(angle):
assert crop[2:-2, 2:-2].min() > 200 # the inside is all box, no background
-def test_cropRotatedRect_validation():
+def test_cropRotatedRect_fills_the_outside_with_borderValue():
+ img = np.full((20, 20), 200, np.uint8)
+ crop = cv.cropRotatedRect(img, ((2, 10), (10, 4), 0)) # half of the box lies left of the image
+ assert crop.shape == (4, 10)
+ assert crop[:, 0].max() == 0 # BORDER_CONSTANT with 0 by default, not a replicated edge
+ assert crop[:, -1].min() == 200
+ assert cv.cropRotatedRect(img, ((2, 10), (10, 4), 0), borderValue=7)[0, 0] == 7
+
+
+@pytest.mark.parametrize(
+ ("src", "rect"),
+ [
+ (np.zeros((10, 10), np.uint8), ((5, 5), (0.2, 4), 0)),
+ (np.zeros((0, 10), np.uint8), ((5, 5), (4, 4), 0)),
+ (np.zeros((10, 10), np.uint8), ((float("nan"), 5), (4, 4), 0)),
+ (np.zeros((10, 10), np.uint8), ((5, 5), (4, 4), float("inf"))),
+ ],
+)
+def test_cropRotatedRect_validation(src, rect):
with pytest.raises(ValueError):
- cv.cropRotatedRect(np.zeros((10, 10), np.uint8), ((5, 5), (0.2, 4), 0))
+ cv.cropRotatedRect(src, rect)
# --- deskew ----------------------------------------------------------------------
@@ -138,7 +156,7 @@ def test_flattenAlpha_composites_on_the_background():
assert tuple(out[1, 0]) == (127, 127, 127)
assert tuple(cv.flattenAlpha(bgra, (0, 255, 0))[0, 1]) == (0, 255, 0)
background = np.full((2, 2), 10, np.uint8)
- assert tuple(cv.flattenAlpha(bgra, background)[0, 1]) == (10, 10, 10)
+ assert tuple(cv.flattenAlpha(bgra, fill=background)[0, 1]) == (10, 10, 10)
def test_flattenAlpha_other_inputs():
@@ -155,7 +173,7 @@ def test_flattenAlpha_other_inputs():
@pytest.mark.parametrize("method", ["difference", "average", "perceptual"])
def test_imageHash_near_duplicates_are_close(method):
- img = cv.makeGradient((120, 160, 3), (0, 0, 0), (255, 200, 100))
+ img = cv.makeGradient((160, 120), (0, 0, 0), (255, 200, 100))
cv.circle(img, (60, 50), 25, (0, 0, 255), -1)
cv.rectangle(img, (100, 70), (150, 110), (255, 255, 0), -1)
resized = cv.resize(img, (80, 60), interpolation=cv.INTER_AREA)
@@ -212,7 +230,7 @@ def test_drawRoundedRectangle_outline_and_fill():
assert img[25, 35] == 0 # outline only
filled = np.zeros((60, 80, 3), np.uint8)
- cv.drawRoundedRectangle(filled, (10, 10, 50, 30), (0, 255, 0), cv.FILLED, cv.LINE_AA, radius=8)
+ cv.drawRoundedRectangle(filled, (10, 10, 50, 30), (0, 255, 0), cv.FILLED, 8, cv.LINE_AA)
assert tuple(filled[25, 35]) == (0, 255, 0)
assert tuple(filled[10, 10]) == (0, 0, 0)
square = np.zeros((60, 80), np.uint8)
@@ -228,6 +246,8 @@ def test_drawRoundedRectangle_small_box_and_validation():
cv.drawRoundedRectangle(img, (0, 0, 0, 5), 255)
with pytest.raises(ValueError):
cv.drawRoundedRectangle(img, (0, 0, 5, 5), 255, radius=-1)
+ with pytest.raises(ValueError, match="empty"):
+ cv.drawRoundedRectangle(np.zeros((0, 5), np.uint8), (0, 0, 5, 5), 255)
# --- pixelate --------------------------------------------------------------------
diff --git a/tests/test_golden.py b/tests/test_golden.py
index 5a7c403..70ea957 100644
--- a/tests/test_golden.py
+++ b/tests/test_golden.py
@@ -47,15 +47,15 @@ def test_gammaCorrection(rotate_src):
_assert_close(cv.gammaCorrection(rotate_src, 2.2), _read("gammaCorrection_2.2.png"), max_abs=0)
-def test_DHEdge(rotate_src):
+def test_boldEdges(rotate_src):
gray = cv.cvtColor(rotate_src, cv.COLOR_BGR2GRAY)
- # DHEdge amplifies differences by pi, so allow a little more slack.
- _assert_close(cv.DHEdge(gray), _read("DHEdge.png"), max_abs=4, max_mismatch_ratio=0.001)
+ # boldEdges amplifies differences by pi, so allow a little more slack.
+ _assert_close(cv.boldEdges(gray), _read("boldEdges.png"), max_abs=4, max_mismatch_ratio=0.001)
-def test_drawDBSCAN():
+def test_drawClusters():
pytest.importorskip("sklearn")
src = _read("dbscan_src.png")
- maps, labels = cv.DBSCAN(src, 1.7, 2)
+ maps, _ = cv.dbscanColors(src, 1.7, 2)
# A +-1 difference in the Lab conversion can move a few border pixels to another cluster.
- _assert_close(cv.drawDBSCAN(src, maps, labels), _read("drawDBSCAN.png"), max_abs=2, max_mismatch_ratio=0.01)
+ _assert_close(cv.drawClusters(src, maps), _read("drawClusters.png"), max_abs=2, max_mismatch_ratio=0.01)
diff --git a/tests/test_imgproc_extra.py b/tests/test_imgproc_extra.py
index 75c6b0a..fc961c1 100644
--- a/tests/test_imgproc_extra.py
+++ b/tests/test_imgproc_extra.py
@@ -35,7 +35,16 @@ def test_autoCanny_finds_the_shapes(shapes):
assert not edges[100:, :].any() # nothing below the shapes
-@pytest.mark.parametrize(("src", "sigma"), [(np.zeros((4, 4), np.float32), 0.33), (np.zeros((4, 4), np.uint8), 1.5)])
+def test_autoCanny_accepts_16_bit_and_float_images(shapes):
+ # Stretched to 8 bits first: cv.Canny itself rejects anything but uint8.
+ np.testing.assert_array_equal(cv.autoCanny(shapes.astype(np.uint16) * 257), cv.autoCanny(shapes))
+ np.testing.assert_array_equal(cv.autoCanny(shapes.astype(np.float32) / 255), cv.autoCanny(shapes))
+
+
+@pytest.mark.parametrize(
+ ("src", "sigma"),
+ [(np.zeros((0, 4), np.uint8), 0.33), (np.zeros((4, 4), np.uint8), 1.5), (np.zeros((4, 4, 2)), 0.3)],
+)
def test_autoCanny_validation(src, sigma):
with pytest.raises(ValueError):
cv.autoCanny(src, sigma=sigma)
diff --git a/tests/test_meta.py b/tests/test_meta.py
new file mode 100644
index 0000000..eb17bc4
--- /dev/null
+++ b/tests/test_meta.py
@@ -0,0 +1,244 @@
+import cv2
+import numpy as np
+import pytest
+from PIL import Image, ImageOps, features
+
+from cv2u.imgcodecs.files import imreadEx
+from cv2u.imgcodecs.meta import (
+ ImageInfo,
+ convertImageFormat,
+ exifOrientation,
+ imageInfo,
+ imdecodeEx,
+ imencodeEx,
+ imreadOriented,
+ imreadResized,
+)
+
+
+def _image() -> np.ndarray:
+ img = np.zeros((20, 40, 3), np.uint8)
+ img[:, :20] = (0, 0, 255) # left half red
+ img[:5, :] = (255, 0, 0) # top stripe blue
+ return img
+
+
+def _save(path, img, orientation=None, **kwargs):
+ pil = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
+ if orientation is not None:
+ exif = Image.Exif()
+ exif[0x0112] = orientation
+ kwargs["exif"] = exif.tobytes()
+ pil.save(path, **kwargs)
+ return path
+
+
+# imageInfo / exifOrientation
+
+
+def test_image_info_png(tmp_path):
+ path = _save(tmp_path / "사진.png", _image())
+ info = imageInfo(path)
+ assert isinstance(info, ImageInfo)
+ assert (info.width, info.height, info.channels, info.mode, info.format) == (40, 20, 3, "RGB", "PNG")
+ assert info.fileSize == path.stat().st_size > 0
+ assert info.exifOrientation == 1
+
+
+def test_image_info_gray_and_alpha(tmp_path):
+ gray = tmp_path / "g.png"
+ Image.fromarray(np.zeros((8, 6), np.uint8)).save(gray)
+ assert imageInfo(str(gray))[:4] == (6, 8, 1, "L")
+ rgba = tmp_path / "a.png"
+ Image.fromarray(np.zeros((8, 6, 4), np.uint8), mode="RGBA").save(rgba)
+ assert imageInfo(rgba).channels == 4
+
+
+def test_image_info_jpeg_orientation(tmp_path):
+ path = _save(tmp_path / "o.jpg", _image(), orientation=6)
+ info = imageInfo(path)
+ assert (info.width, info.height, info.format, info.exifOrientation) == (40, 20, "JPEG", 6)
+ assert exifOrientation(path) == 6
+ assert exifOrientation(_save(tmp_path / "p.png", _image())) == 1
+
+
+def test_image_info_errors(tmp_path):
+ with pytest.raises(OSError):
+ imageInfo(tmp_path / "missing.png")
+ bad = tmp_path / "bad.png"
+ bad.write_bytes(b"not an image")
+ with pytest.raises(OSError):
+ imageInfo(bad)
+ with pytest.raises(OSError):
+ exifOrientation(bad)
+
+
+# imreadOriented
+
+
+@pytest.mark.parametrize("orientation", range(1, 9))
+@pytest.mark.parametrize("ext", [".jpg", ".png", ".webp"])
+def test_imread_oriented_matches_pillow(tmp_path, orientation, ext):
+ if ext == ".webp" and not features.check("webp"):
+ pytest.skip("Pillow was built without WebP support")
+ img = _image()
+ path = _save(tmp_path / f"o{ext}", img, orientation=orientation, quality=100)
+ expected = ImageOps.exif_transpose(Image.open(path))
+ expected_bgr = cv2.cvtColor(np.array(expected.convert("RGB")), cv2.COLOR_RGB2BGR)
+ out = imreadOriented(path)
+ assert out is not None
+ assert out.shape == expected_bgr.shape
+ assert np.abs(out.astype(int) - expected_bgr.astype(int)).max() <= 12 # JPEG loss
+
+
+def test_imread_oriented_unchanged_and_gray(tmp_path):
+ """OpenCV skips the orientation for IMREAD_UNCHANGED and REDUCED flags; imreadOriented applies it anyway."""
+ path = _save(tmp_path / "o.png", _image(), orientation=6)
+ assert cv2.imread(str(path), cv2.IMREAD_UNCHANGED).shape == (20, 40, 3) # OpenCV: as stored
+ assert cv2.imread(str(path)).shape == (40, 20, 3) # OpenCV: rotated
+ out = imreadOriented(path, cv2.IMREAD_UNCHANGED)
+ assert out is not None and out.shape == (40, 20, 3)
+ gray = imreadOriented(path, cv2.IMREAD_GRAYSCALE)
+ assert gray is not None and gray.shape == (40, 20)
+
+
+def test_imread_oriented_missing(tmp_path):
+ assert imreadOriented(tmp_path / "missing.jpg") is None
+ raw = tmp_path / "raw.pfm"
+ assert cv2.imwrite(str(raw), np.ones((4, 6), np.float32))
+ out = imreadOriented(raw, cv2.IMREAD_UNCHANGED) # Pillow cannot open .pfm: orientation defaults to 1
+ assert out is not None and out.shape == (4, 6)
+
+
+# imreadResized
+
+
+def test_imread_resized_modes(tmp_path):
+ path = _save(tmp_path / "r.jpg", _image(), quality=100)
+ assert imreadResized(path, size=(10, 10)).shape == (10, 10, 3)
+ assert imreadResized(path, scale=0.5).shape == (10, 20, 3)
+ assert imreadResized(path, scale=0.25, flags=cv2.IMREAD_GRAYSCALE).shape == (5, 10)
+ assert imreadResized(path, scale=0.125).shape == (3, 5, 3)
+ assert imreadResized(path, scale=0.3).shape == (6, 12, 3)
+ assert imreadResized(path, width=20).shape == (10, 20, 3)
+ assert imreadResized(path, height=40, interpolation=cv2.INTER_NEAREST).shape == (40, 80, 3)
+ assert imreadResized(path, scale=0.5, flags=cv2.IMREAD_UNCHANGED).shape == (10, 20, 3)
+
+
+def test_imread_resized_png_reduced_and_content(tmp_path):
+ path = _save(tmp_path / "r.png", _image())
+ half = imreadResized(path, scale=0.5)
+ assert half.shape == (10, 20, 3)
+ assert tuple(half[8, 2]) == (0, 0, 255) and tuple(half[8, 18]) == (0, 0, 0)
+
+
+def test_imread_resized_orientation(tmp_path):
+ path = _save(tmp_path / "o.jpg", _image(), orientation=6, quality=100)
+ assert imreadResized(path, scale=0.5).shape == (20, 10, 3)
+ assert imreadResized(path, size=(10, 30)).shape == (30, 10, 3)
+ assert imreadResized(path, width=10).shape == (20, 10, 3)
+ assert imreadResized(path, height=10).shape == (10, 5, 3)
+
+
+def test_imread_resized_errors(tmp_path):
+ path = _save(tmp_path / "r.png", _image())
+ assert imreadResized(tmp_path / "missing.png", scale=0.5) is None
+ with pytest.raises(ValueError, match="exactly one"):
+ imreadResized(path)
+ with pytest.raises(ValueError, match="exactly one"):
+ imreadResized(path, scale=0.5, width=3)
+ with pytest.raises(ValueError, match="size"):
+ imreadResized(path, size=(0, 5))
+ with pytest.raises(ValueError, match="scale"):
+ imreadResized(path, scale=float("nan"))
+ with pytest.raises(ValueError, match="scale"):
+ imreadResized(path, scale=-1)
+
+
+# imencodeEx / imdecodeEx
+
+
+def test_imencode_imdecode_roundtrip():
+ img = _image()
+ data = imencodeEx(".png", img)
+ assert isinstance(data, bytes) and data[:4] == b"\x89PNG"
+ assert np.array_equal(imdecodeEx(data), img)
+ assert np.array_equal(imdecodeEx(bytearray(data)), img)
+ assert np.array_equal(imdecodeEx(memoryview(data)), img)
+ assert np.array_equal(imdecodeEx(np.frombuffer(data, np.uint8)), img)
+ assert imdecodeEx(data, cv2.IMREAD_GRAYSCALE).shape == (20, 40)
+ small = imencodeEx("jpg", img, (cv2.IMWRITE_JPEG_QUALITY, 10))
+ assert len(small) < len(imencodeEx("jpg", img, (cv2.IMWRITE_JPEG_QUALITY, 100)))
+
+
+def test_imencode_errors():
+ with pytest.raises(ValueError, match="encode"):
+ imencodeEx(".xyz", _image())
+ with pytest.raises(ValueError, match="empty"):
+ imencodeEx(".png", np.zeros((0, 0, 3), np.uint8))
+ with pytest.raises(ValueError, match="encode"):
+ imencodeEx(".png", np.zeros((2, 2, 5), np.uint8))
+
+
+def test_imdecode_bad_data():
+ assert imdecodeEx(b"") is None
+ assert imdecodeEx(b"not an image") is None
+
+
+# convertImageFormat
+
+
+def test_convert_image_format(tmp_path):
+ src = _save(tmp_path / "원본.png", _image())
+ dst = tmp_path / "out" / "변환.jpg"
+ assert convertImageFormat(src, dst, quality=95, makeDirs=True)
+ out = imreadEx(dst)
+ assert out is not None and out.shape == (20, 40, 3)
+ assert np.abs(out[8:16, 4:16].astype(int) - (0, 0, 255)).max() <= 6 # JPEG edges blur, so compare inside
+ assert not convertImageFormat(src, tmp_path / "nodir" / "x.png")
+
+
+def test_convert_flattens_alpha_for_jpeg(tmp_path):
+ rgba = np.zeros((10, 10, 4), np.uint8)
+ rgba[..., :3] = (0, 0, 255) # red, but fully transparent
+ src = tmp_path / "a.png"
+ assert cv2.imwrite(str(src), rgba)
+ assert convertImageFormat(src, tmp_path / "a.jpg", background=(0, 255, 0))
+ out = cv2.imread(str(tmp_path / "a.jpg"))
+ assert np.abs(out[5, 5].astype(int) - np.array([0, 255, 0])).max() <= 4
+ assert convertImageFormat(src, tmp_path / "a.webp") # alpha kept
+ assert cv2.imread(str(tmp_path / "a.webp"), cv2.IMREAD_UNCHANGED).shape[2] == 4
+
+
+def test_convert_applies_orientation(tmp_path):
+ src = _save(tmp_path / "o.jpg", _image(), orientation=6, quality=100)
+ assert convertImageFormat(src, tmp_path / "o.png")
+ assert cv2.imread(str(tmp_path / "o.png")).shape == (40, 20, 3)
+
+
+def test_convert_errors(tmp_path):
+ assert not convertImageFormat(tmp_path / "missing.png", tmp_path / "x.png")
+ with pytest.raises(ValueError, match="extension"):
+ convertImageFormat(_save(tmp_path / "s.png", _image()), tmp_path / "noext")
+
+
+def test_convertImageFormat_scales_16bit_and_float_to_8bit_for_8bit_formats(tmp_path):
+ src16 = tmp_path / "deep.png"
+ assert cv2.imwrite(str(src16), np.full((8, 8, 3), 40000, np.uint16))
+ assert convertImageFormat(src16, tmp_path / "deep.jpg", quality=100)
+ out = imreadEx(tmp_path / "deep.jpg", cv2.IMREAD_UNCHANGED)
+ assert out.dtype == np.uint8 and abs(int(out[4, 4, 0]) - 156) <= 2 # 40000 / 257, not saturated to 255
+ assert convertImageFormat(src16, tmp_path / "deep.bmp")
+ assert imreadEx(tmp_path / "deep.bmp", cv2.IMREAD_UNCHANGED)[4, 4, 0] == 156
+ assert convertImageFormat(src16, tmp_path / "kept.png")
+ assert imreadEx(tmp_path / "kept.png", cv2.IMREAD_UNCHANGED).dtype == np.uint16 # PNG keeps 16-bit
+ assert convertImageFormat(src16, tmp_path / "kept.tif")
+ assert imreadEx(tmp_path / "kept.tif", cv2.IMREAD_UNCHANGED).dtype == np.uint16
+
+ srcf = tmp_path / "float.tif"
+ assert cv2.imwrite(str(srcf), np.full((8, 8), 0.5, np.float32))
+ assert convertImageFormat(srcf, tmp_path / "float.jpg", quality=100)
+ out = imreadEx(tmp_path / "float.jpg", cv2.IMREAD_UNCHANGED)
+ assert out.dtype == np.uint8 and abs(int(out[4, 4]) - 128) <= 2
+ assert convertImageFormat(srcf, tmp_path / "float.pfm")
+ assert imreadEx(tmp_path / "float.pfm", cv2.IMREAD_UNCHANGED).dtype == np.float32 # PFM keeps floats
diff --git a/tests/test_palette.py b/tests/test_palette.py
new file mode 100644
index 0000000..038fb4c
--- /dev/null
+++ b/tests/test_palette.py
@@ -0,0 +1,158 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc.palette import (
+ CSS_COLORS,
+ blendColors,
+ colorDistance,
+ colormapPalette,
+ colorName,
+ complementaryColor,
+ darkenColor,
+ gradientPalette,
+ invertColor,
+ lightenColor,
+ nearestColor,
+ randomColors,
+ textColorFor,
+)
+
+RED, GREEN, BLUE = (0, 0, 255), (0, 255, 0), (255, 0, 0)
+
+
+def _is_color(c):
+ return isinstance(c, tuple) and len(c) == 3 and all(isinstance(v, int) and 0 <= v <= 255 for v in c)
+
+
+def test_css_colors():
+ assert len(CSS_COLORS) == 148
+ assert CSS_COLORS["red"] == RED and CSS_COLORS["steelblue"] == (180, 130, 70)
+ assert CSS_COLORS["rebeccapurple"] == (153, 51, 102)
+ assert all(_is_color(c) for c in CSS_COLORS.values())
+
+
+def test_lighten_darken():
+ assert lightenColor(RED, 0) == RED and darkenColor(RED, 0) == RED
+ assert lightenColor(RED, 1) == (255, 255, 255) and darkenColor(RED, 1) == (0, 0, 0)
+ assert lightenColor(RED, 0.5) == (128, 128, 255)
+ assert darkenColor(RED, 0.5) == (0, 0, 128)
+ assert darkenColor(np.array([0, 0, 255.0]), 0.5) == (0, 0, 128) # arrays and floats accepted
+ assert _is_color(lightenColor((17, 99, 200), 0.3))
+
+
+@pytest.mark.parametrize("fn", [lightenColor, darkenColor])
+def test_lighten_darken_errors(fn):
+ with pytest.raises(ValueError, match="amount"):
+ fn(RED, 1.5)
+ with pytest.raises(ValueError, match="amount"):
+ fn(RED, float("nan"))
+ with pytest.raises(ValueError, match="color"):
+ fn((0, 0, 300), 0.5)
+ with pytest.raises(ValueError, match="color"):
+ fn((0, 0), 0.5)
+
+
+def test_blend():
+ assert blendColors(RED, BLUE, 0) == RED and blendColors(RED, BLUE, 1) == BLUE
+ assert blendColors((0, 0, 0), (255, 255, 255)) == (128, 128, 128)
+ with pytest.raises(ValueError, match="t must"):
+ blendColors(RED, BLUE, 2)
+ with pytest.raises(ValueError, match="b must"):
+ blendColors(RED, (-1, 0, 0))
+
+
+def test_complementary_and_invert():
+ assert complementaryColor(RED) == (255, 255, 0) # cyan
+ assert complementaryColor((0, 0, 128)) == (128, 128, 0) # dark red -> dark cyan
+ assert complementaryColor((128, 128, 128)) == (128, 128, 128)
+ assert invertColor(RED) == (255, 255, 0)
+ assert invertColor((0, 0, 128)) == (255, 255, 127)
+ with pytest.raises(ValueError, match="color"):
+ invertColor((256, 0, 0))
+ with pytest.raises(ValueError, match="color"):
+ complementaryColor((0, 0, float("inf")))
+
+
+def test_color_distance():
+ assert colorDistance(RED, RED) == 0
+ assert colorDistance((0, 0, 0), (255, 255, 255)) == pytest.approx(100, abs=0.1)
+ assert colorDistance((0, 0, 0), (255, 255, 255), "bgr") == pytest.approx(255 * 3**0.5)
+ assert colorDistance(RED, (0, 0, 250)) < colorDistance(RED, GREEN)
+ with pytest.raises(ValueError, match="space"):
+ colorDistance(RED, GREEN, "hsv")
+ with pytest.raises(ValueError, match="a must"):
+ colorDistance((0, 0, 999), GREEN)
+
+
+def test_nearest_color():
+ palette = [RED, GREEN, BLUE, (255, 255, 255)]
+ assert nearestColor((0, 10, 240), palette) == 0
+ assert nearestColor((250, 250, 250), palette) == 3
+ assert nearestColor((10, 200, 10), np.array(palette), space="bgr") == 1
+ with pytest.raises(ValueError, match="empty"):
+ nearestColor(RED, [])
+ with pytest.raises(ValueError, match="palette"):
+ nearestColor(RED, [(0, 0, 300)])
+ with pytest.raises(ValueError, match="space"):
+ nearestColor(RED, palette, space="xyz")
+
+
+def test_color_name():
+ assert colorName(RED) == "red"
+ assert colorName((0, 0, 250)) == "red"
+ assert colorName((255, 255, 255)) == "white"
+ assert colorName((128, 128, 128)) == "gray" # alphabetically before "grey"
+ assert colorName((255, 255, 0)) == "aqua" # before "cyan"
+ assert colorName((180, 130, 70)) == "steelblue"
+ assert colorName((30, 20, 220)) == "crimson"
+ with pytest.raises(ValueError, match="color"):
+ colorName((0, 0))
+
+
+def test_text_color_for():
+ assert textColorFor((255, 255, 255)) == (0, 0, 0)
+ assert textColorFor((0, 0, 0)) == (255, 255, 255)
+ assert textColorFor((0, 255, 255)) == (0, 0, 0) # yellow is light
+ assert textColorFor((255, 0, 0)) == (255, 255, 255) # blue is dark
+ with pytest.raises(ValueError, match="background"):
+ textColorFor((0, 0, -5))
+
+
+def test_random_colors():
+ colors = randomColors(5, seed=1)
+ assert len(colors) == 5 and all(_is_color(c) for c in colors)
+ assert colors == randomColors(5, seed=1)
+ assert colors != randomColors(5, seed=2)
+ assert all(max(c) == 255 for c in colors) # value 1 -> one channel at 255
+ assert randomColors(0) == []
+ pastel = randomColors(4, seed=0, saturation=0.2, value=0.9)
+ assert all(min(c) >= 180 and max(c) <= 230 for c in pastel)
+ with pytest.raises(ValueError, match="count"):
+ randomColors(-1)
+ with pytest.raises(ValueError, match="saturation"):
+ randomColors(2, saturation=2)
+ with pytest.raises(ValueError, match="value"):
+ randomColors(2, value=float("nan"))
+
+
+def test_gradient_palette():
+ assert gradientPalette((0, 0, 0), (255, 255, 255), 3) == [(0, 0, 0), (128, 128, 128), (255, 255, 255)]
+ assert gradientPalette(RED, BLUE, 2) == [RED, BLUE]
+ assert gradientPalette(RED, BLUE, 1) == [RED]
+ assert gradientPalette(RED, BLUE, 0) == []
+ with pytest.raises(ValueError, match="count"):
+ gradientPalette(RED, BLUE, -2)
+ with pytest.raises(ValueError, match="end"):
+ gradientPalette(RED, (0, 0, 256), 2)
+
+
+def test_colormap_palette():
+ colors = colormapPalette(cv2.COLORMAP_JET, 5)
+ assert len(colors) == 5 and all(_is_color(c) for c in colors)
+ expected = cv2.applyColorMap(np.array([[0, 64, 128, 191, 255]], np.uint8), cv2.COLORMAP_JET)[0]
+ assert colors == [tuple(int(v) for v in c) for c in expected]
+ assert colormapPalette(cv2.COLORMAP_VIRIDIS, 1) == colormapPalette(cv2.COLORMAP_VIRIDIS, 2)[:1]
+ assert colormapPalette(cv2.COLORMAP_HOT, 0) == []
+ with pytest.raises(ValueError, match="count"):
+ colormapPalette(cv2.COLORMAP_HOT, -1)
diff --git a/tests/test_peaks.py b/tests/test_peaks.py
index 10f8a43..a6d30d8 100644
--- a/tests/test_peaks.py
+++ b/tests/test_peaks.py
@@ -75,10 +75,10 @@ def test_peakColors_minRegion_removes_speckles():
assert len(centers) == 2
-def test_peakColors_works_with_drawDBSCAN():
+def test_peakColors_works_with_drawClusters():
img = _three_colors()
maps, _ = cv.peakColors(img)
- assert len(np.unique(cv.drawDBSCAN(img, maps, maps.ravel()).reshape(-1, 3), axis=0)) == 3
+ assert len(np.unique(cv.drawClusters(img, maps).reshape(-1, 3), axis=0)) == 3
def test_peakColors_needs_no_extra(monkeypatch):
diff --git a/tests/test_points.py b/tests/test_points.py
new file mode 100644
index 0000000..673e67c
--- /dev/null
+++ b/tests/test_points.py
@@ -0,0 +1,169 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.core.points import (
+ angleBetween,
+ clipPoints,
+ denormalizePoints,
+ distancePoints,
+ flipPoints,
+ lineIntersection,
+ nearestPoints,
+ normalizePoints,
+ orderPoints,
+ pointLineDistance,
+ pointsBoundingBox,
+ polygonCentroid,
+ rotatePoints,
+ scalePoints,
+ translatePoints,
+)
+
+SQUARE = np.array([[0, 0], [10, 0], [10, 10], [0, 10]], dtype=np.float64)
+
+
+def test_rotate_points_matches_warp_affine_convention():
+ pts = np.array([[30.0, 10.0], [5.0, 5.0]])
+ M = cv2.getRotationMatrix2D((20, 20), 37, 1.5)
+ expected = cv2.transform(pts.reshape(-1, 1, 2), M).reshape(-1, 2)
+ out = rotatePoints(pts, 37, center=(20, 20), scale=1.5)
+ assert out.dtype == np.float64 and out.shape == (2, 2)
+ assert np.allclose(out, expected)
+ assert np.allclose(rotatePoints((1, 0), 90), (0, -1)) # counter-clockwise on screen (y down)
+ assert rotatePoints(SQUARE.reshape(4, 1, 2), 10).shape == (4, 1, 2)
+ assert np.allclose(rotatePoints(SQUARE, 0), SQUARE)
+
+
+def test_rotate_points_errors():
+ with pytest.raises(ValueError, match="angle"):
+ rotatePoints(SQUARE, float("nan"))
+ with pytest.raises(ValueError, match="scale"):
+ rotatePoints(SQUARE, 10, scale=0)
+ with pytest.raises(ValueError, match="center"):
+ rotatePoints(SQUARE, 10, center=(float("inf"), 0))
+ with pytest.raises(ValueError, match="points"):
+ rotatePoints([[1, 2, 3]], 10)
+ with pytest.raises(ValueError, match="finite"):
+ rotatePoints([[1, float("nan")]], 10)
+
+
+def test_scale_translate():
+ assert np.array_equal(scalePoints(SQUARE, 2), SQUARE * 2)
+ assert np.array_equal(scalePoints(SQUARE, (2, 0.5)), SQUARE * (2, 0.5))
+ assert np.array_equal(scalePoints(SQUARE, 2, center=(5, 5)), SQUARE * 2 - 5)
+ assert np.array_equal(translatePoints(SQUARE, 3, -1), SQUARE + np.array([3, -1]))
+ assert translatePoints((1, 2), 1, 1).shape == (2,)
+ with pytest.raises(ValueError, match="scale"):
+ scalePoints(SQUARE, float("inf"))
+ with pytest.raises(ValueError, match="dx"):
+ translatePoints(SQUARE, float("nan"), 0)
+
+
+def test_flip_points_matches_cv_flip():
+ img = np.zeros((20, 30), np.uint8)
+ pts = np.array([[3, 4], [29, 0], [10, 19]])
+ for code in (0, 1, -1):
+ flipped = cv2.flip(cv2.circle(img.copy(), (3, 4), 0, 255, -1), code)
+ out = flipPoints(pts, (30, 20), code)
+ x, y = out[0].astype(int)
+ assert flipped[y, x] == 255
+ assert np.array_equal(flipPoints(pts, (30, 20), 1), [[26, 4], [0, 0], [19, 19]])
+ assert np.array_equal(flipPoints(pts, (30, 20), 0), [[3, 15], [29, 19], [10, 0]])
+ assert np.array_equal(flipPoints(pts, (30, 20), -1), [[26, 15], [0, 19], [19, 0]])
+ with pytest.raises(ValueError, match="size"):
+ flipPoints(pts, (0, 20), 1)
+
+
+def test_normalize_denormalize_clip():
+ norm = normalizePoints(SQUARE, (20, 40))
+ assert np.allclose(norm, SQUARE / (20, 40))
+ assert np.allclose(denormalizePoints(norm, (20, 40)), SQUARE)
+ assert np.array_equal(clipPoints([[-5, 3], [25, 50]], (20, 40)), [[0, 3], [19, 39]])
+ assert clipPoints((-1, -1), (5, 5)).shape == (2,)
+ for fn in (normalizePoints, denormalizePoints, clipPoints):
+ with pytest.raises(ValueError, match="size"):
+ fn(SQUARE, (10, -1))
+
+
+def test_bounding_box():
+ assert pointsBoundingBox(SQUARE) == (0, 0, 11, 11)
+ assert pointsBoundingBox(SQUARE) == tuple(cv2.boundingRect(SQUARE.astype(np.int32)))
+ assert pointsBoundingBox([[1.5, 2.2], [3.1, 2.9]]) == (1, 2, 4, 2)
+ assert pointsBoundingBox((4, 5)) == (4, 5, 1, 1)
+ with pytest.raises(ValueError, match="empty"):
+ pointsBoundingBox(np.empty((0, 2)))
+
+
+def test_distance_and_nearest():
+ a = [[0, 0], [10, 0]]
+ b = [[0, 3], [10, 4], [100, 100]]
+ dist = distancePoints(a, b)
+ assert dist.shape == (2, 3) and dist.dtype == np.float64
+ assert dist[0, 0] == 3 and dist[1, 1] == 4
+ assert distancePoints((0, 0), (3, 4))[0, 0] == 5
+ indices, distances = nearestPoints(a, b)
+ assert indices.tolist() == [0, 1] and distances.tolist() == [3, 4]
+ assert distancePoints(np.empty((0, 2)), b).shape == (0, 3)
+ with pytest.raises(ValueError, match="empty"):
+ nearestPoints(a, np.empty((0, 2)))
+ with pytest.raises(ValueError, match="b must"):
+ distancePoints(a, [[1, 2, 3]])
+
+
+def test_order_points():
+ shuffled = np.array([[10, 10], [0, 10], [0, 0], [10, 0]])
+ assert np.array_equal(orderPoints(shuffled), SQUARE)
+ assert np.array_equal(orderPoints(shuffled.reshape(4, 1, 2)), SQUARE)
+ assert orderPoints(SQUARE).dtype == np.float64
+ with pytest.raises(ValueError, match="4 points"):
+ orderPoints(SQUARE[:3])
+
+
+def test_polygon_centroid():
+ assert polygonCentroid(SQUARE) == (5.0, 5.0)
+ assert polygonCentroid(SQUARE[::-1]) == (5.0, 5.0) # orientation does not matter
+ triangle = [[0, 0], [6, 0], [0, 3]]
+ assert polygonCentroid(triangle) == pytest.approx((2.0, 1.0))
+ m = cv2.moments(np.array(triangle, np.int32))
+ assert polygonCentroid(triangle) == pytest.approx((m["m10"] / m["m00"], m["m01"] / m["m00"]))
+ assert polygonCentroid([[0, 0], [4, 0]]) == (2.0, 0.0) # no area: mean
+ assert polygonCentroid((3, 4)) == (3.0, 4.0)
+ with pytest.raises(ValueError, match="empty"):
+ polygonCentroid(np.empty((0, 2)))
+
+
+def test_angle_between():
+ assert angleBetween((0, 0), (1, 0)) == 0
+ assert angleBetween((0, 0), (1, 1)) == 45
+ assert angleBetween((0, 0), (0, -1)) == -90
+ assert angleBetween((0, 0), (0, 1), degrees=False) == pytest.approx(np.pi / 2)
+ with pytest.raises(ValueError, match="p2"):
+ angleBetween((0, 0), (1, float("nan")))
+ with pytest.raises(ValueError, match="p1"):
+ angleBetween([[0, 0], [1, 1]], (1, 1))
+
+
+def test_line_intersection():
+ assert lineIntersection(((0, 0), (1, 1)), ((0, 1), (1, 0))) == (0.5, 0.5)
+ assert lineIntersection(((0, 0), (1, 0)), ((5, -1), (5, 1))) == (5, 0)
+ assert lineIntersection(((0, 0), (2, 0)), ((10, 5), (12, 5))) is None # parallel
+ assert lineIntersection(((0, 0), (1, 1)), ((2, 2), (3, 3))) is None # coincident
+ assert lineIntersection(((0, 0), (1, 0)), ((5, 1), (5, 2))) == (5, 0) # beyond the segments
+ with pytest.raises(ValueError, match="line2"):
+ lineIntersection(((0, 0), (1, 0)), ((5, 1), (5, 1)))
+ with pytest.raises(ValueError, match="line1"):
+ lineIntersection(((0, 0), (1, 0), (2, 0)), ((5, 1), (5, 2)))
+
+
+def test_point_line_distance():
+ assert pointLineDistance((0, 1), ((0, 0), (1, 0))) == 1
+ assert pointLineDistance((5, 3), ((0, 0), (10, 0))) == 3
+ assert pointLineDistance((13, 4), ((0, 0), (10, 0))) == 4 # infinite line
+ assert pointLineDistance((13, 4), ((0, 0), (10, 0)), segment=True) == 5 # to the end point
+ assert pointLineDistance((-3, -4), ((0, 0), (10, 0)), segment=True) == 5
+ assert pointLineDistance((1, 1), ((0, 0), (2, 2))) == pytest.approx(0)
+ with pytest.raises(ValueError, match="line"):
+ pointLineDistance((0, 0), ((1, 1), (1, 1)))
+ with pytest.raises(ValueError, match="point"):
+ pointLineDistance((0, float("inf")), ((0, 0), (1, 0)))
diff --git a/tests/test_resize.py b/tests/test_resize.py
index eef54b5..003614b 100644
--- a/tests/test_resize.py
+++ b/tests/test_resize.py
@@ -44,7 +44,10 @@ def test_resizeEx_validation(img, kwargs):
def test_letterbox_shape_scale_and_offset(img):
- dst, scale, (left, top) = cv.letterbox(img, (300, 300), color=(1, 2, 3))
+ result = cv.letterbox(img, (300, 300), color=(1, 2, 3))
+ assert isinstance(result, cv.Letterbox)
+ assert result.image is result[0] and result.scale == result[1] and result.offset == result[2]
+ dst, scale, (left, top) = result
assert dst.shape == (300, 300, 3)
assert scale == pytest.approx(1.5)
assert (left, top) == (0, 75)
diff --git a/tests/test_roi.py b/tests/test_roi.py
index aa83bf8..f6eba1f 100644
--- a/tests/test_roi.py
+++ b/tests/test_roi.py
@@ -9,54 +9,63 @@ def img():
return np.arange(100, dtype=np.uint8).reshape(10, 10)
-# --- cropEx ------------------------------------------------------------------------
+# --- cropRect ------------------------------------------------------------------------
-def test_cropEx_inside_matches_slicing(img):
- np.testing.assert_array_equal(cv.cropEx(img, (2, 3, 4, 5)), img[3:8, 2:6])
+def test_cropRect_inside_matches_slicing(img):
+ np.testing.assert_array_equal(cv.cropRect(img, (2, 3, 4, 5)), img[3:8, 2:6])
-def test_cropEx_returns_a_copy(img):
- crop = cv.cropEx(img, (0, 0, 2, 2))
+def test_cropRect_returns_a_copy(img):
+ crop = cv.cropRect(img, (0, 0, 2, 2))
crop[:] = 0
assert img[0, 1] == 1
-def test_cropEx_negative_coordinates_are_clipped(img):
+def test_cropRect_negative_coordinates_are_clipped(img):
# Plain slicing img[-2:3, -2:3] would return an empty array here.
- np.testing.assert_array_equal(cv.cropEx(img, (-2, -2, 5, 5)), img[0:3, 0:3])
+ np.testing.assert_array_equal(cv.cropRect(img, (-2, -2, 5, 5)), img[0:3, 0:3])
-def test_cropEx_fill_keeps_the_box_size(img):
- crop = cv.cropEx(img, (-2, 8, 4, 4), fill=255)
+def test_cropRect_fill_keeps_the_box_size(img):
+ crop = cv.cropRect(img, (-2, 8, 4, 4), fill=255)
assert crop.shape == (4, 4)
np.testing.assert_array_equal(crop[:2, 2:], img[8:10, 0:2])
assert (crop[:, :2] == 255).all()
assert (crop[2:, :] == 255).all()
-def test_cropEx_fill_color_image():
+def test_cropRect_fill_color_image():
bgr = np.zeros((5, 5, 3), np.uint8)
- crop = cv.cropEx(bgr, (3, 3, 4, 4), fill=(1, 2, 3))
+ crop = cv.cropRect(bgr, (3, 3, 4, 4), fill=(1, 2, 3))
assert crop.shape == (4, 4, 3)
assert tuple(crop[3, 3]) == (1, 2, 3)
assert tuple(crop[0, 0]) == (0, 0, 0)
-def test_cropEx_margin(img):
- np.testing.assert_array_equal(cv.cropEx(img, (4, 4, 2, 2), margin=1), img[3:7, 3:7])
+def test_cropRect_margin(img):
+ np.testing.assert_array_equal(cv.cropRect(img, (4, 4, 2, 2), margin=1), img[3:7, 3:7])
-def test_cropEx_outside(img):
- assert cv.cropEx(img, (20, 20, 3, 3)).size == 0
- assert (cv.cropEx(img, (20, 20, 3, 3), fill=7) == 7).all()
+def test_cropRect_outside_raises(img):
+ # Before: an empty array (or a box full of fill), which failed later with an unrelated error.
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (20, 20, 3, 3))
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (20, 20, 3, 3), fill=7)
+ with pytest.raises(ValueError, match="outside"):
+ cv.cropRect(img, (-5, 0, 5, 5)) # touches the border without covering a pixel
-def test_cropEx_validation(img):
- with pytest.raises(ValueError):
- cv.cropEx(img, (0, 0, 0, 5))
- with pytest.raises(ValueError):
- cv.cropEx(img, (0, 0, 4, 4), margin=-2)
+def test_cropRect_validation(img):
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, 0, 5))
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, 4, 4), margin=-2)
+ with pytest.raises(ValueError, match="rect"):
+ cv.cropRect(img, (0, 0, float("nan"), 4))
+ with pytest.raises(ValueError, match="empty"):
+ cv.cropRect(np.zeros((0, 0), np.uint8), (0, 0, 4, 4))
# --- inRangeEx ---------------------------------------------------------------------
diff --git a/tests/test_stats.py b/tests/test_stats.py
new file mode 100644
index 0000000..6dd49f0
--- /dev/null
+++ b/tests/test_stats.py
@@ -0,0 +1,360 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc import stats
+from cv2u.imgproc.stats import (
+ ImageStats,
+ brightnessScore,
+ colorfulness,
+ contrastScore,
+ dominantHue,
+ entropy,
+ estimateNoise,
+ exposureScore,
+ histogramCompare,
+ histogramEx,
+ imageStats,
+ isBlank,
+ isBlurry,
+ isGrayscale,
+ mae,
+ meanColor,
+ mse,
+)
+
+
+@pytest.fixture
+def checkerboard():
+ tile = np.array([[0, 255], [255, 0]], dtype=np.uint8)
+ return np.tile(tile, (32, 32))
+
+
+@pytest.fixture
+def photo():
+ rng = np.random.default_rng(0)
+ img = np.zeros((96, 128, 3), dtype=np.uint8)
+ cv2.circle(img, (64, 48), 30, (40, 160, 230), -1)
+ cv2.rectangle(img, (5, 5), (40, 90), (200, 50, 10), -1)
+ img = cv2.GaussianBlur(img, (5, 5), 0)
+ noise = rng.normal(0, 3, img.shape)
+ return np.clip(img.astype(np.float64) + noise, 0, 255).astype(np.uint8)
+
+
+def test_public_names_not_in_cv2():
+ for name in stats.__all__:
+ assert not hasattr(cv2, name), name
+
+
+# --- isGrayscale / isBlank / isBlurry -------------------------------------------------------
+
+
+def test_isGrayscale():
+ gray = np.full((8, 8), 7, dtype=np.uint8)
+ assert isGrayscale(gray)
+ assert isGrayscale(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR))
+ assert isGrayscale(cv2.cvtColor(gray, cv2.COLOR_GRAY2BGRA))
+ color = np.zeros((8, 8, 3), dtype=np.uint8)
+ color[..., 2] = 3
+ assert not isGrayscale(color)
+ assert isGrayscale(color, tolerance=3)
+ bgra = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGRA)
+ bgra[..., 3] = 0
+ assert isGrayscale(bgra) # alpha ignored
+
+
+def test_isBlank(photo):
+ assert isBlank(np.full((10, 10), 128, dtype=np.uint8))
+ assert isBlank(np.full((10, 10, 3), (255, 0, 0), dtype=np.uint8))
+ assert isBlank(np.zeros((4, 4), dtype=np.float32))
+ assert not isBlank(photo)
+ almost = np.full((10, 10), 128, dtype=np.uint8)
+ almost[0, 0] = 130
+ assert isBlank(almost)
+ assert not isBlank(almost, tolerance=0)
+
+
+def test_isBlurry(checkerboard):
+ assert not isBlurry(checkerboard)
+ assert isBlurry(cv2.GaussianBlur(checkerboard, (15, 15), 5))
+ assert isBlurry(np.zeros((16, 16, 3), dtype=np.uint8))
+
+
+@pytest.mark.parametrize("fn", [isGrayscale, isBlank])
+def test_tolerance_validation(fn):
+ with pytest.raises(ValueError, match="tolerance"):
+ fn(np.zeros((4, 4), np.uint8), tolerance=-1)
+
+
+def test_isBlurry_validation():
+ with pytest.raises(ValueError, match="threshold"):
+ isBlurry(np.zeros((4, 4), np.uint8), threshold=float("nan"))
+
+
+# --- brightness / contrast / colorfulness / exposure / entropy ------------------------------
+
+
+def test_brightnessScore():
+ assert brightnessScore(np.zeros((4, 4), np.uint8)) == 0.0
+ assert brightnessScore(np.full((4, 4, 3), 255, np.uint8)) == pytest.approx(1.0)
+ assert brightnessScore(np.full((4, 4), 0.5, np.float32)) == pytest.approx(0.5)
+ assert brightnessScore(np.full((4, 4), 65535, np.uint16)) == pytest.approx(1.0)
+
+
+def test_contrastScore(checkerboard):
+ assert contrastScore(np.full((4, 4), 9, np.uint8)) == 0.0
+ assert contrastScore(checkerboard) == pytest.approx(0.5)
+ assert contrastScore(cv2.cvtColor(checkerboard, cv2.COLOR_GRAY2BGR)) == pytest.approx(0.5)
+
+
+def test_colorfulness(photo):
+ assert colorfulness(np.full((4, 4), 100, np.uint8)) == 0.0
+ assert colorfulness(cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY)) == 0.0
+ gray3 = cv2.cvtColor(cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR)
+ assert colorfulness(gray3) == pytest.approx(0.0)
+ vivid = np.zeros((8, 8, 3), np.uint8)
+ vivid[:, :4] = (0, 0, 255)
+ vivid[:, 4:] = (255, 0, 0)
+ assert colorfulness(vivid) > colorfulness(photo) > 0
+ # the same picture as float gives the same score
+ assert colorfulness(photo.astype(np.float32) / 255) == pytest.approx(colorfulness(photo), rel=1e-3)
+ assert colorfulness(cv2.cvtColor(photo, cv2.COLOR_BGR2BGRA)) == pytest.approx(colorfulness(photo))
+
+
+def test_exposureScore():
+ img = np.zeros((10, 10), np.uint8)
+ img[:3] = 255
+ img[3:5] = 128
+ under, over = exposureScore(img)
+ assert under == pytest.approx(0.5)
+ assert over == pytest.approx(0.3)
+ assert exposureScore(np.full((4, 4, 3), 128, np.uint8)) == (0.0, 0.0)
+ assert exposureScore(img, lowThreshold=0.6, highThreshold=0.6) == (pytest.approx(0.7), pytest.approx(0.3))
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [{"lowThreshold": -0.1}, {"highThreshold": 1.5}, {"lowThreshold": 0.9, "highThreshold": 0.1}],
+)
+def test_exposureScore_validation(kwargs):
+ with pytest.raises(ValueError, match="Threshold"):
+ exposureScore(np.zeros((4, 4), np.uint8), **kwargs)
+
+
+def test_entropy(checkerboard, photo):
+ assert entropy(np.full((8, 8), 42, np.uint8)) == 0.0
+ assert entropy(checkerboard) == pytest.approx(1.0)
+ ramp = np.tile(np.arange(256, dtype=np.uint8), (4, 1))
+ assert entropy(ramp) == pytest.approx(8.0)
+ assert entropy(ramp, bins=16) == pytest.approx(4.0)
+ assert 0 < entropy(photo) < 8
+ assert entropy(ramp.astype(np.float32) / 255) == pytest.approx(8.0)
+
+
+def test_entropy_validation():
+ with pytest.raises(ValueError, match="bins"):
+ entropy(np.zeros((4, 4), np.uint8), bins=0)
+
+
+# --- estimateNoise ------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("sigma", [5.0, 15.0])
+def test_estimateNoise(sigma):
+ rng = np.random.default_rng(1)
+ base = np.full((200, 200), 128.0)
+ noisy = base + rng.normal(0, sigma, base.shape)
+ assert estimateNoise(noisy) == pytest.approx(sigma, rel=0.1)
+ noisy8 = np.clip(noisy, 0, 255).astype(np.uint8)
+ assert estimateNoise(noisy8) == pytest.approx(sigma, rel=0.1)
+ assert estimateNoise(cv2.cvtColor(noisy8, cv2.COLOR_GRAY2BGR)) == pytest.approx(sigma, rel=0.1)
+
+
+def test_estimateNoise_clean_is_low():
+ clean = np.zeros((64, 64), np.uint8)
+ cv2.circle(clean, (32, 32), 20, 200, -1)
+ assert estimateNoise(cv2.GaussianBlur(clean, (7, 7), 2)) < 2
+ assert estimateNoise(np.full((5, 5), 10, np.uint8)) == 0.0
+
+
+def test_estimateNoise_validation():
+ with pytest.raises(ValueError, match="3x3"):
+ estimateNoise(np.zeros((2, 5), np.uint8))
+
+
+# --- mse / mae ----------------------------------------------------------------------------
+
+
+def test_mse_mae():
+ a = np.zeros((4, 4, 3), np.uint8)
+ b = np.full((4, 4, 3), 2, np.uint8)
+ assert mse(a, a) == 0.0
+ assert mse(a, b) == 4.0
+ assert mae(a, b) == 2.0
+ assert mse(b, a) == 4.0 # no uint8 wrap-around
+ assert mae(np.zeros(3), np.array([1.0, -2.0, 3.0])) == pytest.approx(2.0)
+
+
+@pytest.mark.parametrize("fn", [mse, mae])
+def test_pair_validation(fn):
+ with pytest.raises(ValueError, match="same shape"):
+ fn(np.zeros((4, 4)), np.zeros((4, 5)))
+ with pytest.raises(ValueError, match="empty"):
+ fn(np.zeros((0, 4)), np.zeros((0, 4)))
+
+
+# --- histogramEx / histogramCompare -------------------------------------------------------
+
+
+def test_histogramEx(photo):
+ hist = histogramEx(photo)
+ assert hist.shape == (3, 256)
+ assert hist.dtype == np.float64
+ assert hist.sum(axis=1).tolist() == [photo.shape[0] * photo.shape[1]] * 3
+ for c in range(3):
+ expected = cv2.calcHist([photo], [c], None, [256], [0, 256]).ravel()
+ assert np.array_equal(hist[c], expected)
+ gray = histogramEx(np.zeros((4, 4), np.uint8), bins=4)
+ assert gray.shape == (1, 4)
+ assert gray[0].tolist() == [16, 0, 0, 0]
+ normalized = histogramEx(photo, bins=8, normalize=True, channels=[2, 0])
+ assert normalized.shape == (2, 8)
+ assert normalized.sum(axis=1) == pytest.approx([1.0, 1.0])
+ assert np.array_equal(normalized[0] * photo.shape[0] * photo.shape[1], histogramEx(photo, bins=8)[2])
+ mask = np.zeros(photo.shape[:2], np.uint8)
+ mask[:10, :10] = 255
+ assert histogramEx(photo, mask=mask).sum() == 300
+ assert histogramEx(np.full((2, 2), 1.0, np.float32), bins=2)[0].tolist() == [0, 4]
+ assert histogramEx(np.full((2, 2), 65535, np.uint16), bins=2)[0].tolist() == [0, 4]
+
+
+def test_histogramEx_validation(photo):
+ with pytest.raises(ValueError, match="bins"):
+ histogramEx(photo, bins=0)
+ with pytest.raises(ValueError, match="channels"):
+ histogramEx(photo, channels=[3])
+ with pytest.raises(ValueError, match="mask"):
+ histogramEx(photo, mask=np.zeros((3, 3), np.uint8))
+ with pytest.raises(ValueError, match="empty"):
+ histogramEx(np.zeros((0, 4), np.uint8))
+ with pytest.raises(ValueError, match="2-D or 3-D"):
+ histogramEx(np.zeros((2, 2, 2, 2), np.uint8))
+
+
+def test_histogramCompare(photo):
+ assert histogramCompare(photo, photo) == pytest.approx(1.0)
+ assert histogramCompare(photo, photo, colorSpace="bgr") == pytest.approx(1.0)
+ assert histogramCompare(photo, photo, colorSpace="gray") == pytest.approx(1.0)
+ assert histogramCompare(photo, photo, method=cv2.HISTCMP_BHATTACHARYYA) == pytest.approx(0.0, abs=1e-6)
+ # different sizes and channel counts are fine
+ small = cv2.resize(photo, (32, 24))
+ assert histogramCompare(photo, small) > 0.8
+ gray = cv2.cvtColor(photo, cv2.COLOR_BGR2GRAY)
+ assert histogramCompare(photo, gray, colorSpace="gray") == pytest.approx(1.0)
+ assert histogramCompare(photo, cv2.cvtColor(photo, cv2.COLOR_BGR2BGRA)) == pytest.approx(1.0)
+ # a different color distribution scores lower
+ other = photo[..., ::-1].copy()
+ assert histogramCompare(photo, other) < 0.5
+ assert histogramCompare(photo.astype(np.float32) / 255, photo) == pytest.approx(1.0)
+
+
+def test_histogramCompare_validation(photo):
+ with pytest.raises(ValueError, match="bins"):
+ histogramCompare(photo, photo, bins=0)
+ with pytest.raises(ValueError, match="colorSpace"):
+ histogramCompare(photo, photo, colorSpace="lab")
+
+
+# --- dominantHue / meanColor ----------------------------------------------------------------
+
+
+@pytest.mark.parametrize(("color", "degrees"), [((0, 0, 255), 0), ((0, 255, 0), 120), ((255, 0, 0), 240)])
+def test_dominantHue(color, degrees):
+ img = np.full((8, 8, 3), color, np.uint8)
+ assert dominantHue(img) == pytest.approx(degrees, abs=2)
+
+
+def test_dominantHue_ignores_gray_and_mixed():
+ img = np.full((10, 10, 3), 128, np.uint8) # gray majority
+ img[:3] = (0, 255, 255) # yellow minority but saturated
+ assert dominantHue(img) == pytest.approx(60, abs=2)
+ assert dominantHue(np.full((4, 4), 9, np.uint8)) == 0.0
+ assert dominantHue(np.full((4, 4, 3), 200, np.uint8)) == 0.0
+ red = np.full((8, 8, 3), (0, 0, 1.0), np.float32)
+ assert dominantHue(red) == pytest.approx(0, abs=2)
+ with pytest.raises(ValueError, match="bins"):
+ dominantHue(img, bins=0)
+
+
+def test_meanColor():
+ img = np.zeros((4, 4, 3), np.uint8)
+ img[:, :2] = (10, 20, 30)
+ assert meanColor(img) == (5.0, 10.0, 15.0)
+ mask = np.zeros((4, 4), np.uint8)
+ mask[:, :2] = 1
+ assert meanColor(img, mask) == (10.0, 20.0, 30.0)
+ assert meanColor(img, np.zeros((4, 4), np.uint8)) == (0.0, 0.0, 0.0)
+ assert meanColor(np.full((3, 3), 7, np.uint8)) == (7.0,)
+ assert len(meanColor(np.zeros((2, 2, 4), np.uint8))) == 4
+ with pytest.raises(ValueError, match="mask"):
+ meanColor(img, np.zeros((2, 2), np.uint8))
+
+
+# --- imageStats -----------------------------------------------------------------------------
+
+
+def test_imageStats(photo, checkerboard):
+ s = imageStats(photo)
+ assert isinstance(s, ImageStats)
+ assert (s.width, s.height, s.channels, s.dtype) == (128, 96, 3, "uint8")
+ assert len(s.mean) == 3 and len(s.std) == 3
+ assert s.mean == pytest.approx(meanColor(photo))
+ assert 0 <= s.minVal <= s.maxVal <= 255
+ assert s.brightness == pytest.approx(brightnessScore(photo))
+ assert s.contrast == pytest.approx(contrastScore(photo))
+ assert s.sharpness > 0 and s.entropy > 0
+ assert not s.isGray
+
+ g = imageStats(checkerboard)
+ assert (g.channels, g.minVal, g.maxVal, g.isGray) == (1, 0.0, 255.0, True)
+ assert g.mean == (pytest.approx(127.5),)
+ assert g.entropy == pytest.approx(1.0)
+
+
+@pytest.mark.parametrize(
+ "fn",
+ [
+ imageStats,
+ isGrayscale,
+ isBlank,
+ isBlurry,
+ brightnessScore,
+ contrastScore,
+ colorfulness,
+ exposureScore,
+ entropy,
+ estimateNoise,
+ dominantHue,
+ meanColor,
+ ],
+)
+def test_bad_images(fn):
+ with pytest.raises(ValueError):
+ fn(np.zeros((0, 4), np.uint8))
+ with pytest.raises(ValueError):
+ fn(np.zeros((4, 4, 2), np.uint8))
+
+
+@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.float32])
+def test_imageStats_matches_the_single_metric_functions(photo, dtype):
+ from cv2u.imgproc.quality import sharpnessScore
+
+ img = photo.astype(dtype) * (257 if dtype == np.uint16 else 1 / 255 if dtype == np.float32 else 1)
+ s = imageStats(img)
+ assert s.brightness == brightnessScore(img)
+ assert s.contrast == contrastScore(img)
+ assert s.sharpness == sharpnessScore(img)
+ assert s.entropy == entropy(img)
+ assert s.isGray == isGrayscale(img)
+ gray = imageStats(photo[..., 1])
+ assert gray.isGray and gray.entropy == entropy(photo[..., 1]) and gray.sharpness == sharpnessScore(photo[..., 1])
diff --git a/tests/test_stitch.py b/tests/test_stitch.py
new file mode 100644
index 0000000..52045f2
--- /dev/null
+++ b/tests/test_stitch.py
@@ -0,0 +1,93 @@
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc.stitch import stitchImages, stitchPair
+
+WIDTH, HEIGHT = 480, 240
+
+
+def _scene(seed: int = 0) -> np.ndarray:
+ """Textured BGR scene: blurred noise with a few shapes, so that features are easy to find."""
+ rng = np.random.default_rng(seed)
+ noise = rng.integers(0, 256, (HEIGHT, WIDTH, 3), np.uint8)
+ scene = cv2.GaussianBlur(noise, (0, 0), 1.0)
+ for _ in range(40):
+ x, y = int(rng.integers(0, WIDTH - 40)), int(rng.integers(0, HEIGHT - 40))
+ color = tuple(int(c) for c in rng.integers(0, 256, 3))
+ if rng.random() < 0.5:
+ w, h = (int(v) for v in rng.integers(8, 40, 2))
+ cv2.rectangle(scene, (x, y), (x + w, y + h), color, -1)
+ else:
+ cv2.circle(scene, (x + 15, y + 15), int(rng.integers(5, 18)), color, -1)
+ return scene
+
+
+@pytest.fixture(scope="module")
+def halves() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ scene = _scene()
+ split = WIDTH // 2
+ overlap = 80
+ return scene, scene[:, : split + overlap].copy(), scene[:, split - overlap :].copy()
+
+
+def test_stitch_pair(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
+ scene, left, right = halves
+ out = stitchPair(left, right)
+ assert out.dtype == np.uint8 and out.ndim == 3
+ assert abs(out.shape[1] - WIDTH) <= 6 and abs(out.shape[0] - HEIGHT) <= 6
+ # the left image is pasted (almost) unchanged somewhere on the canvas, and the whole scene is reproduced around it
+ scores = cv2.matchTemplate(out, left, cv2.TM_SQDIFF)
+ best, _, (x, y), _ = cv2.minMaxLoc(scores)
+ assert best / left.size < 1.0 # mean squared difference per value; warping may touch a few border pixels
+ region = out[y : y + HEIGHT, x : x + WIDTH]
+ assert region.shape == scene.shape and cv2.absdiff(region, scene).mean() < 15
+
+
+def test_stitch_pair_gray_and_sift(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
+ _, left, right = halves
+ gray = stitchPair(cv2.cvtColor(left, cv2.COLOR_BGR2GRAY), right)
+ assert gray.ndim == 2 and abs(gray.shape[1] - WIDTH) <= 6
+ color = stitchPair(left, cv2.cvtColor(right, cv2.COLOR_BGR2GRAY), method="SIFT")
+ assert color.ndim == 3 and abs(color.shape[1] - WIDTH) <= 6
+
+
+def test_stitch_pair_errors(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
+ _, left, right = halves
+ with pytest.raises(ValueError, match="a must not be empty"):
+ stitchPair(np.zeros((0, 0, 3), np.uint8), right)
+ with pytest.raises(ValueError, match="b must not be empty"):
+ stitchPair(left, np.zeros((0, 0, 3), np.uint8))
+ with pytest.raises(ValueError, match="minMatches"):
+ stitchPair(left, right, minMatches=3)
+ with pytest.raises(ValueError, match="ransacThreshold"):
+ stitchPair(left, right, ransacThreshold=0)
+ with pytest.raises(ValueError, match="matches found"):
+ stitchPair(left, np.full((100, 100, 3), 200, np.uint8))
+
+
+def test_stitch_images(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
+ _, left, right = halves
+ try:
+ out = stitchImages([left, right], mode="scans", confidence=0.3)
+ except RuntimeError as exc:
+ pytest.skip(f"cv.Stitcher cannot stitch the synthetic scene here: {exc}")
+ assert out.dtype == np.uint8 and out.ndim == 3
+ assert abs(out.shape[1] - WIDTH) <= 20 and abs(out.shape[0] - HEIGHT) <= 20
+ gray = stitchImages([cv2.cvtColor(left, cv2.COLOR_BGR2GRAY), cv2.cvtColor(right, cv2.COLOR_BGR2GRAY)], "scans", 0.3)
+ assert gray.ndim == 3
+
+
+def test_stitch_images_errors(halves: tuple[np.ndarray, np.ndarray, np.ndarray]) -> None:
+ _, left, right = halves
+ with pytest.raises(ValueError, match="at least 2"):
+ stitchImages([left])
+ with pytest.raises(ValueError, match=r"images\[1\]"):
+ stitchImages([left, np.zeros((0, 0, 3), np.uint8)])
+ with pytest.raises(ValueError, match="mode"):
+ stitchImages([left, right], mode="spherical") # type: ignore[arg-type]
+ with pytest.raises(ValueError, match="confidence"):
+ stitchImages([left, right], confidence=-1)
+ flat = np.full((60, 60, 3), 128, np.uint8)
+ with pytest.raises(RuntimeError, match="ERR_"):
+ stitchImages([flat, flat.copy()])
diff --git a/tests/test_validation.py b/tests/test_validation.py
index 4b13c45..dac887c 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -15,6 +15,7 @@
IMG = np.zeros((40, 60, 3), np.uint8)
GRAY = np.zeros((40, 60), np.uint8)
EMPTY = np.zeros((0, 0, 3), np.uint8)
+CONTOUR = np.array([[[5, 5]], [[20, 5]], [[20, 20]], [[5, 20]]], np.int32)
# --- NaN and infinite numeric parameters ------------------------------------------
@@ -52,6 +53,35 @@
("toBGRA alpha", lambda v: cv.toBGRA(IMG, alpha=v)),
("writeVideo fps", lambda v: cv.writeVideo("x.avi", [IMG], fps=v)),
("fourPointTransform pts", lambda v: cv.fourPointTransform(IMG, [[0, 0], [10, 0], [10, 10], [0, v]])),
+ ("translate dx", lambda v: cv.translate(IMG, v, 0)),
+ ("translate dy", lambda v: cv.translate(IMG, 0, v)),
+ ("imcolor color", lambda v: cv.imcolor((4, 4), v)),
+ ("imcolorLike color", lambda v: cv.imcolorLike(IMG, v)),
+ ("makeGradient start", lambda v: cv.makeGradient((4, 4), v, 255)),
+ ("makeGradient end", lambda v: cv.makeGradient((4, 4), 0, (v, 0, 0))),
+ ("cropRotatedRect rect", lambda v: cv.cropRotatedRect(IMG, ((v, 5), (4, 4), 0))),
+ ("cropRect rect", lambda v: cv.cropRect(IMG, (0, 0, v, 4))),
+ ("dbscanColors eps", lambda v: cv.dbscanColors(IMG, v)),
+ ("clusterPoints eps", lambda v: cv.clusterPoints([[0, 0], [1, 1]], v)),
+ ("meanShiftColors bandwidth", lambda v: cv.meanShiftColors(IMG, bandwidth=v)),
+ ("peakColors minShare", lambda v: cv.peakColors(IMG, minShare=v)),
+ ("overlayImage alpha", lambda v: cv.overlayImage(IMG, IMG, alpha=v)),
+ ("overlayMask alpha", lambda v: cv.overlayMask(IMG, GRAY, alpha=v)),
+ ("nms iouThreshold", lambda v: cv.nms([[0, 0, 1, 1]], [1.0], iouThreshold=v)),
+ ("nms scoreThreshold", lambda v: cv.nms([[0, 0, 1, 1]], [1.0], scoreThreshold=v)),
+ ("expandBoxes margin", lambda v: cv.expandBoxes([0, 0, 1, 1], margin=v)),
+ ("findTemplate threshold", lambda v: cv.findTemplate(IMG, IMG[:4, :4], threshold=v)),
+ ("autoCanny sigma", lambda v: cv.autoCanny(GRAY, sigma=v)),
+ ("removeSmallObjects minArea", lambda v: cv.removeSmallObjects(GRAY, minArea=v)),
+ ("diffMask minArea", lambda v: cv.diffMask(IMG, IMG, minArea=v)),
+ ("applyMask fill", lambda v: cv.applyMask(IMG, GRAY, fill=v)),
+ ("cropContour fill", lambda v: cv.cropContour(IMG, CONTOUR, fill=v)),
+ ("flattenAlpha fill", lambda v: cv.flattenAlpha(np.zeros((4, 4, 4), np.uint8), fill=v)),
+ ("autoContrast clip", lambda v: cv.autoContrast(IMG, clip=v)),
+ ("drawLabel fontScale", lambda v: cv.drawLabel(IMG.copy(), (0, 0, 10, 10), "a", 255, fontScale=v)),
+ ("drawContoursEx fontScale", lambda v: cv.drawContoursEx(IMG.copy(), [CONTOUR], fontScale=v)),
+ ("deskew maxAngle", lambda v: cv.deskew(GRAY, maxAngle=v)),
+ ("inRangeEx lowerb", lambda v: cv.inRangeEx(IMG, (v, 0, 0), (10, 255, 255))),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -80,7 +110,21 @@ def test_rotateEx_rejects_non_positive_scale(scale):
("ssim dataRange", lambda: cv.ssim(IMG, IMG, dataRange=0)),
("equalizeHistEx clipLimit", lambda: cv.equalizeHistEx(IMG, clahe=True, clipLimit=0)),
("cutout feather", lambda: cv.cutout(IMG, GRAY, feather=-1)),
- ("urlread maxBytes", lambda: cv.urlread("file:///x.png", maxBytes=0)),
+ ("imreadUrl maxBytes", lambda: cv.imreadUrl("file:///x.png", maxBytes=0)),
+ ("kmeansColors maxIter", lambda: cv.kmeansColors(IMG, 2, maxIter=0)),
+ ("dbscanColors eps", lambda: cv.dbscanColors(IMG, 0)),
+ ("dbscanColors minSamples", lambda: cv.dbscanColors(IMG, 1.0, minSamples=0)),
+ ("meanShiftColors bandwidth", lambda: cv.meanShiftColors(IMG, bandwidth=0)),
+ ("nms iouThreshold", lambda: cv.nms([[0, 0, 1, 1]], [1.0], iouThreshold=1.5)),
+ ("makeGradient size", lambda: cv.makeGradient((0, 4), 0, 255)),
+ ("imcolor size", lambda: cv.imcolor((4, 0), 0)),
+ ("drawHistogram size", lambda: cv.drawHistogram(IMG, size=(0, 10))),
+ ("mergeTiles size", lambda: cv.mergeTiles([(IMG, (0, 0))], (0, 10))),
+ ("findTemplate maxCount", lambda: cv.findTemplate(IMG, IMG[:4, :4], maxCount=-1)),
+ ("findCircles minRadius", lambda: cv.findCircles(GRAY, minRadius=-1)),
+ ("findCircles maxRadius", lambda: cv.findCircles(GRAY, maxRadius=-1)),
+ ("cropRect rect", lambda: cv.cropRect(IMG, (0, 0, 0, 4))),
+ ("drawContoursEx fontScale", lambda: cv.drawContoursEx(IMG.copy(), [CONTOUR], fontScale=0)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -89,6 +133,23 @@ def test_negative_or_zero_parameters_raise_value_error(name, call):
call()
+@pytest.mark.parametrize(
+ ("call", "match"),
+ [
+ (lambda: cv.findCircles(GRAY, minRadius=-1), "minRadius"),
+ (lambda: cv.findCircles(GRAY, maxRadius=-1), "maxRadius"),
+ (lambda: cv.filterContours([CONTOUR], minArea=float("nan")), "minArea must be a number"),
+ (lambda: cv.filterContours([CONTOUR], minArea=10, maxArea=5), "minArea must not exceed maxArea"),
+ (lambda: cv.filterContours([CONTOUR], minAspectRatio=2, maxAspectRatio=1), "minAspectRatio"),
+ (lambda: cv.cropRect(IMG, (0, 0, 0, 4)), "rect"),
+ (lambda: cv.cropRect(IMG, (100, 100, 4, 4)), "rect .* outside"),
+ ],
+)
+def test_messages_name_the_argument(call, match):
+ with pytest.raises(ValueError, match=match):
+ call()
+
+
# --- colors outside the dtype range ----------------------------------------------
@@ -99,6 +160,8 @@ def test_negative_or_zero_parameters_raise_value_error(name, call):
("hconcatEx", lambda c: cv.hconcatEx([IMG, GRAY], color=c)),
("letterbox", lambda c: cv.letterbox(IMG, (80, 80), color=c)),
("padToSize", lambda c: cv.padToSize(IMG, (80, 80), color=c)),
+ ("imcolor", lambda c: cv.imcolor((4, 4), c)),
+ ("imcolorLike", lambda c: cv.imcolorLike(IMG, c)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -150,6 +213,52 @@ def test_float_images_accept_any_finite_color():
("peakColors", lambda: cv.peakColors(EMPTY)),
("hconcatEx", lambda: cv.hconcatEx([IMG, EMPTY])),
("overlayImage", lambda: cv.overlayImage(IMG, EMPTY)),
+ ("rotateEx", lambda: cv.rotateEx(EMPTY, 30)),
+ ("fourPointTransform", lambda: cv.fourPointTransform(EMPTY, [[0, 0], [10, 0], [10, 10], [0, 10]])),
+ ("padToMultiple", lambda: cv.padToMultiple(EMPTY, 32)),
+ ("padToSize", lambda: cv.padToSize(EMPTY, (10, 10))),
+ ("splitTiles", lambda: cv.splitTiles(EMPTY, (10, 10))),
+ ("mapTiles", lambda: cv.mapTiles(EMPTY, (10, 10), lambda t: t)),
+ ("gammaCorrection", lambda: cv.gammaCorrection(EMPTY, 2.2)),
+ ("boldEdges", lambda: cv.boldEdges(EMPTY)),
+ ("drawHistogram", lambda: cv.drawHistogram(EMPTY)),
+ ("drawLabel", lambda: cv.drawLabel(EMPTY, (0, 0, 1, 1), "a", 255)),
+ ("drawBoxes", lambda: cv.drawBoxes(EMPTY, [[0, 0, 1, 1]])),
+ ("drawPoints", lambda: cv.drawPoints(EMPTY, [[0, 0]])),
+ ("drawGrid", lambda: cv.drawGrid(EMPTY, 10)),
+ ("drawDashedLine", lambda: cv.drawDashedLine(EMPTY, (0, 0), (5, 5), 255)),
+ ("drawDashedRectangle", lambda: cv.drawDashedRectangle(EMPTY, (0, 0, 5, 5), 255)),
+ ("drawRoundedRectangle", lambda: cv.drawRoundedRectangle(EMPTY, (0, 0, 5, 5), 255)),
+ ("drawContoursEx", lambda: cv.drawContoursEx(EMPTY, [CONTOUR])),
+ ("overlayMask", lambda: cv.overlayMask(EMPTY, np.zeros((0, 0), np.uint8))),
+ ("findTemplate src", lambda: cv.findTemplate(EMPTY, IMG)),
+ ("findTemplate templ", lambda: cv.findTemplate(IMG, EMPTY)),
+ ("inRangeEx", lambda: cv.inRangeEx(EMPTY, (0, 0, 0), (10, 10, 10))),
+ ("autoCanny", lambda: cv.autoCanny(EMPTY)),
+ ("findLines", lambda: cv.findLines(EMPTY)),
+ ("findCircles", lambda: cv.findCircles(EMPTY)),
+ ("findBlobs", lambda: cv.findBlobs(EMPTY)),
+ ("imshowEx", lambda: cv.imshowEx("w", EMPTY)),
+ ("imshowInline", lambda: cv.imshowInline(EMPTY)),
+ ("imencodeBase64", lambda: cv.imencodeBase64(EMPTY)),
+ ("translate", lambda: cv.translate(EMPTY, 1, 1)),
+ ("cropRotatedRect", lambda: cv.cropRotatedRect(EMPTY, ((5, 5), (4, 4), 0))),
+ ("deskew", lambda: cv.deskew(EMPTY)),
+ ("cropRect", lambda: cv.cropRect(EMPTY, (0, 0, 4, 4))),
+ ("cropCenter", lambda: cv.cropCenter(EMPTY, 4)),
+ ("cropContour", lambda: cv.cropContour(EMPTY, CONTOUR)),
+ ("applyMask", lambda: cv.applyMask(EMPTY, np.zeros((0, 0), np.uint8))),
+ ("kmeansColors", lambda: cv.kmeansColors(EMPTY, 1)),
+ ("meanShiftColors", lambda: cv.meanShiftColors(EMPTY)),
+ ("dbscanColors", lambda: cv.dbscanColors(EMPTY, 1.0)),
+ ("drawClusters", lambda: cv.drawClusters(EMPTY, np.zeros((0, 0), np.int32))),
+ ("matchFeatures", lambda: cv.matchFeatures(EMPTY, IMG)),
+ ("alignImages", lambda: cv.alignImages(IMG, EMPTY)),
+ ("sharpnessScore", lambda: cv.sharpnessScore(EMPTY)),
+ ("imageHash", lambda: cv.imageHash(EMPTY)),
+ ("binarize", lambda: cv.binarize(EMPTY)),
+ ("morphology", lambda: cv.morphology(EMPTY, "open")),
+ ("flattenAlpha", lambda: cv.flattenAlpha(EMPTY)),
],
ids=lambda x: x if isinstance(x, str) else "",
)
@@ -218,28 +327,28 @@ def test_writeVideo_rejects_frames_that_are_not_gray_or_bgr(tmp_path, shape):
cv.writeVideo(tmp_path / "a.avi", [np.zeros(shape, np.uint8)], fps=10)
-# --- urlread size limit ------------------------------------------------------------
+# --- imreadUrl size limit ------------------------------------------------------------
-def test_urlread_maxBytes_accepts_a_file_that_fits(tmp_path, bgr=IMG):
+def test_imreadUrl_maxBytes_accepts_a_file_that_fits(tmp_path, bgr=IMG):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
- np.testing.assert_array_equal(cv.urlread(path.as_uri(), maxBytes=path.stat().st_size), bgr)
+ np.testing.assert_array_equal(cv.imreadUrl(path.as_uri(), maxBytes=path.stat().st_size), bgr)
-def test_urlread_maxBytes_rejects_a_larger_file(tmp_path, bgr=IMG):
+def test_imreadUrl_maxBytes_rejects_a_larger_file(tmp_path, bgr=IMG):
path = tmp_path / "img.png"
assert cv.imwrite(str(path), bgr)
with pytest.raises(ValueError, match="maxBytes"):
- cv.urlread(path.as_uri(), maxBytes=path.stat().st_size - 1)
+ cv.imreadUrl(path.as_uri(), maxBytes=path.stat().st_size - 1)
-def test_urlread_maxBytes_uses_content_length_before_downloading(monkeypatch):
+def test_imreadUrl_maxBytes_uses_content_length_before_downloading(monkeypatch):
import io
import sys
from email.message import Message
- urlread_module = sys.modules["cv2u.imgcodecs.urlread"]
+ urlread_module = sys.modules["cv2u.imgcodecs.url"]
class Response(io.BytesIO):
headers = Message()
@@ -256,4 +365,60 @@ def read(self, n=-1):
monkeypatch.setattr(urlread_module, "urlopen", lambda request, timeout=None: Response())
with pytest.raises(ValueError, match="maxBytes"):
- cv.urlread("https://example.invalid/big.png", maxBytes=1000)
+ cv.imreadUrl("https://example.invalid/big.png", maxBytes=1000)
+
+
+# --- shared helpers in cv2u._validate -------------------------------------------------------------------------------
+
+
+def test_check_size_accepts_positive_sizes_and_names_the_argument():
+ from cv2u._validate import check_size
+
+ assert check_size("size", (3, 4)) == (3, 4)
+ assert check_size("size", [2.0, 5.0]) == (2, 5)
+ for bad in [(0, 4), (3, -1), (NAN, 4), (3, INF), (3,)]:
+ with pytest.raises(ValueError, match="patch"):
+ check_size("patch", bad)
+
+
+def test_check_uint8_rejects_other_depths_empty_and_two_channel_images():
+ from cv2u._validate import check_uint8
+
+ assert check_uint8("src", IMG) == 3 and check_uint8("src", GRAY) == 1
+ with pytest.raises(ValueError, match=r"src.*uint8"):
+ check_uint8("src", IMG.astype(np.float32))
+ with pytest.raises(ValueError, match=r"src.*empty"):
+ check_uint8("src", EMPTY)
+ with pytest.raises(ValueError, match=r"src.*channels"):
+ check_uint8("src", np.zeros((4, 4, 2), np.uint8))
+
+
+def test_is_single_color_and_as_color():
+ from cv2u._validate import as_color, is_single_color
+
+ assert (
+ is_single_color(200)
+ and is_single_color(1.5)
+ and is_single_color(np.uint8(3))
+ and is_single_color(np.float32(1))
+ )
+ assert is_single_color((0, 0, 255)) and is_single_color([0, 0, 255, 255]) and is_single_color([7])
+ assert is_single_color(np.array([0, 0, 255], np.uint8)) and is_single_color(np.array([0.5, 0.5, 0.5]))
+ assert is_single_color((np.uint8(1), np.uint8(2), np.uint8(3)))
+ assert not is_single_color([(0, 0, 255), (255, 0, 0)])
+ assert not is_single_color(np.array([[0, 0, 255], [255, 0, 0]], np.uint8))
+ assert not is_single_color([200, 100]) # two gray levels, no image has 2 channels
+ assert not is_single_color("red") and not is_single_color(True) and not is_single_color(None)
+ assert not is_single_color([]) and not is_single_color([[1, 2, 3]])
+ assert as_color(np.array([0, 0, 255], np.uint8)) == (0.0, 0.0, 255.0)
+ assert as_color(np.uint8(9)) == 9.0 and as_color(3) == 3.0 and as_color([1, 2, 3]) == (1.0, 2.0, 3.0)
+
+
+def test_drawBoxes_numpy_color_is_one_color():
+ img = IMG.copy()
+ cv.drawBoxes(img, [(5, 5, 10, 10), (20, 20, 10, 10)], colors=np.array([0, 0, 255], np.uint8), thickness=1)
+ assert img[5, 10].tolist() == [0, 0, 255] and img[20, 25].tolist() == [0, 0, 255]
+ img = IMG.copy()
+ cv.drawBoxes(img, [(5, 5, 10, 10), (20, 20, 10, 10)], colors=np.array([[255, 0, 0], [0, 255, 0]], np.uint8))
+ assert img[5, 10].tolist() == [255, 0, 0] and img[20, 25].tolist() == [0, 255, 0]
+ cv.drawBoxes(img, [(5, 5, 10, 10)], labels=["a"], colors=np.uint8(255))
diff --git a/tests/test_videoio_edit.py b/tests/test_videoio_edit.py
new file mode 100644
index 0000000..7eca28c
--- /dev/null
+++ b/tests/test_videoio_edit.py
@@ -0,0 +1,166 @@
+import numpy as np
+import pytest
+
+import cv2u as cv
+from cv2u.videoio.edit import (
+ concatVideos,
+ detectScenes,
+ extractFrames,
+ imagesToVideo,
+ resizeVideo,
+ sampleFrames,
+ trimVideo,
+ videoThumbnail,
+ videoToGif,
+)
+
+
+def _frames(n=12, size=(64, 48), color=(255, 255, 255)):
+ w, h = size
+ frames = []
+ for i in range(n):
+ frame = np.zeros((h, w, 3), np.uint8)
+ frame[:, : (i + 1) * w // n] = color
+ frames.append(frame)
+ return frames
+
+
+def _bar_width(frame):
+ gray = frame if frame.ndim == 2 else cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
+ return int((gray[gray.shape[0] // 2] > 60).sum())
+
+
+@pytest.fixture
+def video(tmp_path):
+ path = tmp_path / "비디오.avi"
+ try:
+ assert cv.writeVideo(path, _frames(), fps=12) == 12
+ except OSError:
+ pytest.skip("MJPG codec is not available")
+ return path
+
+
+def test_extractFrames(video, tmp_path):
+ seen = []
+ out = tmp_path / "프레임"
+ paths = extractFrames(video, out, step=4, start=1, ext=".png", progress=lambda i, n: seen.append((i, n)))
+ assert [p.name for p in paths] == ["frame_000001.png", "frame_000005.png", "frame_000009.png"]
+ assert seen == [(1, 12), (5, 12), (9, 12)]
+ assert all(p.exists() for p in paths)
+ widths = [_bar_width(cv.imreadEx(p)) for p in paths]
+ assert widths == sorted(widths)
+ assert extractFrames(video, out, start=2, end=4, digits=3, prefix="f") == [out / "f002.jpg", out / "f003.jpg"]
+
+
+def test_extractFrames_validation(video, tmp_path):
+ with pytest.raises(ValueError):
+ extractFrames(video, tmp_path, step=0)
+ with pytest.raises(ValueError):
+ extractFrames(video, tmp_path, start=5, end=2)
+ with pytest.raises(OSError):
+ extractFrames(tmp_path / "missing.avi", tmp_path)
+
+
+def test_trimVideo_by_time_and_frames(video, tmp_path):
+ out = tmp_path / "trim.avi"
+ assert trimVideo(video, out, 0.25, 0.5) == 3 # frames 3, 4, 5
+ assert [_bar_width(f) for f in cv.readFrames(out)] == [_bar_width(f) for f in _frames()[3:6]]
+ assert trimVideo(video, out, 8, byTime=False) == 4
+ assert trimVideo(video, out, 2, 5, byTime=False) == 3
+ with pytest.raises(ValueError):
+ trimVideo(video, out, 5, 2, byTime=False)
+ with pytest.raises(ValueError):
+ trimVideo(video, out, 100, byTime=False) # no frames in range
+
+
+def test_concatVideos_resizes_to_first(video, tmp_path):
+ small = tmp_path / "small.avi"
+ cv.writeVideo(small, _frames(4, size=(32, 24)), fps=12)
+ out = tmp_path / "concat.avi"
+ assert concatVideos([video, small], out) == 16
+ info = cv.videoInfo(out)
+ assert (info.width, info.height, info.frameCount) == (64, 48, 16)
+ with pytest.raises(ValueError):
+ concatVideos([], out)
+
+
+def test_resizeVideo(video, tmp_path):
+ out = tmp_path / "resized.avi"
+ assert resizeVideo(video, out, width=32) == 12
+ info = cv.videoInfo(out)
+ assert (info.width, info.height) == (32, 24)
+ resizeVideo(video, out, scale=0.5)
+ assert (cv.videoInfo(out).width, cv.videoInfo(out).height) == (32, 24)
+ resizeVideo(video, out, size=(20, 30))
+ assert (cv.videoInfo(out).width, cv.videoInfo(out).height) == (20, 30)
+ resizeVideo(video, out, height=96) # upscaling path
+ assert cv.videoInfo(out).width == 128
+
+
+@pytest.mark.parametrize(
+ "kwargs", [{}, {"size": (10, 10), "scale": 0.5}, {"scale": 0}, {"size": (0, 10)}, {"scale": float("nan")}]
+)
+def test_resizeVideo_validation(video, tmp_path, kwargs):
+ with pytest.raises(ValueError):
+ resizeVideo(video, tmp_path / "x.avi", **kwargs)
+
+
+def test_videoToGif(video, tmp_path):
+ from PIL import Image
+
+ gif = tmp_path / "애니.gif"
+ assert videoToGif(video, gif, step=2, size=(32, 24)) == 6
+ with Image.open(gif) as image:
+ assert image.n_frames == 6
+ assert image.size == (32, 24)
+ assert videoToGif(video, tmp_path / "out" / "b.gif", maxFrames=3, fps=5) == 3
+ for kwargs in ({"step": 0}, {"maxFrames": 0}, {"fps": 0}):
+ with pytest.raises(ValueError):
+ videoToGif(video, gif, **kwargs)
+
+
+def test_imagesToVideo_paths_and_arrays(tmp_path):
+ frames = _frames(4)
+ paths = []
+ for i, frame in enumerate(frames[:2]):
+ path = tmp_path / f"이미지_{i}.png"
+ assert cv.imwriteEx(path, frame)
+ paths.append(path)
+ out = tmp_path / "out" / "images.avi"
+ assert imagesToVideo([*paths, *frames[2:]], out, fps=4) == 4
+ assert cv.videoInfo(out).frameCount == 4
+ with pytest.raises(OSError):
+ imagesToVideo([tmp_path / "missing.png"], out)
+ with pytest.raises(ValueError):
+ imagesToVideo([], out)
+
+
+def test_detectScenes_finds_the_cut(tmp_path):
+ frames = _frames(10, color=(40, 40, 40)) + _frames(10, color=(255, 0, 0))
+ path = tmp_path / "scenes.avi"
+ try:
+ cv.writeVideo(path, frames, fps=10)
+ except OSError:
+ pytest.skip("MJPG codec is not available")
+ assert detectScenes(path, threshold=30.0, minLength=5) == [10]
+ assert detectScenes(path, threshold=30.0, minLength=5, step=2) == [10]
+ assert detectScenes(path, threshold=250.0) == []
+ with pytest.raises(ValueError):
+ detectScenes(path, threshold=-1)
+ with pytest.raises(ValueError):
+ detectScenes(path, minLength=0)
+ with pytest.raises(ValueError):
+ detectScenes(path, step=0)
+
+
+def test_sampleFrames_and_thumbnail(video):
+ frames = sampleFrames(video, 4)
+ assert len(frames) == 4
+ widths = [_bar_width(f) for f in frames]
+ assert widths == sorted(widths) and len(set(widths)) == 4
+ assert len(sampleFrames(video, 100)) == 12 # capped at the frame count
+ sheet = videoThumbnail(video, count=4, size=(32, 24), cols=2, gap=2)
+ assert sheet.shape == (24 * 2 + 2, 32 * 2 + 2, 3)
+ assert videoThumbnail(video, count=3).shape[2] == 3
+ with pytest.raises(ValueError):
+ sampleFrames(video, 0)
diff --git a/tests/test_videoio_reader.py b/tests/test_videoio_reader.py
new file mode 100644
index 0000000..da23164
--- /dev/null
+++ b/tests/test_videoio_reader.py
@@ -0,0 +1,280 @@
+import numpy as np
+import pytest
+
+import cv2u as cv
+from cv2u.videoio.reader import (
+ CameraStream,
+ FPSCounter,
+ VideoReader,
+ VideoWriterEx,
+ formatTimestamp,
+ frameToTime,
+ timeToFrame,
+)
+
+
+def _frames(n=12, size=(64, 48), gray=False):
+ w, h = size
+ frames = []
+ for i in range(n):
+ frame = np.zeros((h, w) if gray else (h, w, 3), np.uint8)
+ frame[:, : (i + 1) * w // n] = 255
+ frames.append(frame)
+ return frames
+
+
+def _bar_width(frame):
+ gray = frame if frame.ndim == 2 else cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
+ return int((gray[gray.shape[0] // 2] > 127).sum())
+
+
+@pytest.fixture
+def video(tmp_path):
+ path = tmp_path / "비디오.avi"
+ try:
+ assert cv.writeVideo(path, _frames(), fps=12) == 12
+ except OSError:
+ pytest.skip("MJPG codec is not available")
+ return path
+
+
+# --- VideoReader -------------------------------------------------------------------------
+
+
+def test_VideoReader_properties_and_iteration(video):
+ with VideoReader(video) as reader:
+ assert (reader.width, reader.height, reader.frameCount) == (64, 48, 12)
+ assert reader.fps == pytest.approx(12)
+ assert reader.info.duration == pytest.approx(1.0)
+ assert len(reader) == 12
+ assert reader.isOpened
+ assert "64x48" in repr(reader)
+ frames = list(reader)
+ assert len(frames) == 12
+ assert reader.position == 12
+ assert reader.read() is None
+ assert not reader.isOpened
+ widths = [_bar_width(f) for f in frames]
+ assert widths == sorted(widths)
+
+
+def test_VideoReader_read_and_seek(video):
+ with VideoReader(video) as reader:
+ first = reader.read()
+ assert first is not None and reader.position == 1
+ reader.seek(5)
+ assert reader.position == 5
+ frame5 = reader.read()
+ reader.seekTime(0.5) # 12 fps: frame 6
+ assert reader.position == 6
+ frame6 = reader.read()
+ assert _bar_width(frame5) < _bar_width(frame6)
+ reader.seek(0)
+ np.testing.assert_array_equal(reader.read(), first)
+
+
+def test_VideoReader_frames_range_and_step(video):
+ with VideoReader(video) as reader:
+ all_widths = [_bar_width(f) for f in reader.frames()]
+ assert [_bar_width(f) for f in reader.frames(step=3)] == all_widths[::3] # rewinds automatically
+ assert [_bar_width(f) for f in reader.frames(start=4, end=8)] == all_widths[4:8]
+ assert [_bar_width(f) for f in reader.frames(step=2, start=3, end=8)] == all_widths[3:8:2]
+ assert list(reader.frames(start=100)) == []
+ assert list(reader.frames(start=5, end=5)) == []
+
+
+def test_VideoReader_frames_forward_uses_grab(video):
+ with VideoReader(video) as reader:
+ reader.read()
+ got = [_bar_width(f) for f in reader.frames(start=3)]
+ assert len(got) == 9
+
+
+@pytest.mark.parametrize("kwargs", [{"step": 0}, {"start": -1}, {"start": 3, "end": 2}])
+def test_VideoReader_frames_validation(video, kwargs):
+ with VideoReader(video) as reader, pytest.raises(ValueError):
+ list(reader.frames(**kwargs))
+
+
+def test_VideoReader_seek_validation(video):
+ with VideoReader(video) as reader:
+ with pytest.raises(ValueError, match="index"):
+ reader.seek(-1)
+ with pytest.raises(ValueError, match="seconds"):
+ reader.seekTime(-0.1)
+
+
+def test_VideoReader_missing(tmp_path):
+ with pytest.raises(OSError):
+ VideoReader(tmp_path / "missing.avi")
+
+
+# --- VideoWriterEx -----------------------------------------------------------------------
+
+
+def test_VideoWriterEx_lazy_open_and_makeDirs(tmp_path):
+ path = tmp_path / "새폴더" / "출력.avi"
+ with VideoWriterEx(path, fps=10, makeDirs=True) as writer:
+ assert writer.size is None and writer.isColor is None and not writer.isOpened
+ for frame in _frames(5):
+ writer.write(frame)
+ assert writer.size == (64, 48) and writer.isColor is True and writer.isOpened
+ assert writer.frameCount == 5
+ assert not writer.isOpened
+ assert cv.videoInfo(path).frameCount == 5
+
+
+def test_VideoWriterEx_gray_to_color_conversion(tmp_path):
+ path = tmp_path / "mixed.avi"
+ with VideoWriterEx(path, fps=10) as writer:
+ writer.write(_frames(1)[0])
+ writer.write(_frames(1, gray=True)[0]) # gray frame converted to BGR
+ assert cv.videoInfo(path).frameCount == 2
+
+
+def test_VideoWriterEx_gray_file_accepts_color(tmp_path):
+ path = tmp_path / "gray.avi"
+ with VideoWriterEx(path, fps=10, isColor=False) as writer:
+ writer.write(_frames(1, gray=True)[0])
+ writer.write(_frames(1)[0])
+ assert cv.videoInfo(path).frameCount == 2
+
+
+def test_VideoWriterEx_no_frames_writes_nothing(tmp_path):
+ path = tmp_path / "empty.avi"
+ with VideoWriterEx(path, fps=10):
+ pass
+ assert not path.exists()
+
+
+def test_VideoWriterEx_frame_validation(tmp_path):
+ with VideoWriterEx(tmp_path / "a.avi", fps=10) as writer:
+ with pytest.raises(ValueError, match="8-bit"):
+ writer.write(np.zeros((10, 10, 3), np.float32))
+ with pytest.raises(ValueError, match="grayscale"):
+ writer.write(np.zeros((10, 10, 4), np.uint8))
+ writer.write(_frames(1)[0])
+ with pytest.raises(ValueError, match="size"):
+ writer.write(np.zeros((10, 10, 3), np.uint8))
+
+
+@pytest.mark.parametrize(
+ ("name", "kwargs", "match"),
+ [("a.avi", {"fps": 0}, "fps"), ("a.xyz", {"fps": 10}, "codec"), ("a.avi", {"fps": 10, "fourcc": "MJPEG"}, "4 ")],
+)
+def test_VideoWriterEx_init_validation(tmp_path, name, kwargs, match):
+ with pytest.raises(ValueError, match=match):
+ VideoWriterEx(tmp_path / name, **kwargs)
+
+
+def test_VideoWriterEx_bad_codec_raises_OSError(tmp_path):
+ with VideoWriterEx(tmp_path / "a.avi", fps=10, fourcc="ZZZZ") as writer, pytest.raises(OSError):
+ writer.write(_frames(1)[0])
+
+
+# --- CameraStream ------------------------------------------------------------------------
+
+
+def test_CameraStream_on_a_file(video):
+ with CameraStream(video) as stream:
+ frame = stream.read()
+ assert frame is not None and frame.shape == (48, 64, 3)
+ assert stream.isRunning or stream.ended
+ again = stream.read()
+ assert again is not None
+ assert not stream.isRunning
+ assert stream.fps >= 0
+
+
+def test_CameraStream_ends_and_delivers_last_frame_once(video):
+ stream = CameraStream(video, maxWait=2.0).start()
+ try:
+ stream._thread.join(timeout=5) # the file is short: the thread finishes
+ assert stream.ended
+ last = stream.read()
+ assert last is not None and _bar_width(last) == 64
+ assert stream.read() is None # the docstring promise: None once the stream ended
+ assert stream.read() is None
+ finally:
+ stream.stop()
+ stream.stop() # idempotent
+
+
+def test_CameraStream_read_loop_terminates_on_a_file(video):
+ import time
+
+ deadline = time.monotonic() + 10
+ last = None
+ count = 0
+ with CameraStream(video, maxWait=2.0) as stream:
+ while (frame := stream.read()) is not None: # the same frame may repeat while the thread still runs
+ last, count = frame, count + 1
+ if time.monotonic() > deadline:
+ pytest.fail("read() never returned None after the file ended")
+ assert count >= 1 and _bar_width(last) == 64
+
+
+def test_CameraStream_missing(tmp_path):
+ with pytest.raises(OSError):
+ CameraStream(tmp_path / "missing.avi")
+
+
+# --- FPSCounter --------------------------------------------------------------------------
+
+
+def test_FPSCounter_moving_average():
+ now = [0.0]
+ counter = FPSCounter(window=4, clock=lambda: now[0])
+ assert counter.fps == 0.0
+ assert counter.tick() == 0.0 # one tick: no interval yet
+ for _ in range(3):
+ now[0] += 0.1
+ fps = counter.tick()
+ assert fps == pytest.approx(10.0)
+ for _ in range(4):
+ now[0] += 0.05 # faster: the old ticks fall out of the window
+ fps = counter.tick()
+ assert fps == pytest.approx(20.0)
+ counter.reset()
+ assert counter.fps == 0.0
+
+
+def test_FPSCounter_zero_elapsed_and_validation():
+ counter = FPSCounter(window=2, clock=lambda: 1.0)
+ counter.tick()
+ assert counter.tick() == 0.0
+ with pytest.raises(ValueError):
+ FPSCounter(window=1)
+
+
+def test_FPSCounter_default_clock():
+ counter = FPSCounter()
+ counter.tick()
+ assert counter.tick() >= 0.0
+
+
+# --- time helpers ------------------------------------------------------------------------
+
+
+def test_frame_time_conversion():
+ assert frameToTime(30, 30) == pytest.approx(1.0)
+ assert timeToFrame(1.0, 30) == 30
+ assert timeToFrame(0.5, 12) == 6
+ assert timeToFrame(0.1, 29.97) == 2
+ with pytest.raises(ValueError):
+ frameToTime(1, 0)
+ with pytest.raises(ValueError):
+ timeToFrame(1.0, -1)
+ with pytest.raises(ValueError):
+ timeToFrame(float("nan"), 30)
+
+
+def test_formatTimestamp():
+ assert formatTimestamp(0) == "00:00:00.000"
+ assert formatTimestamp(3661.5) == "01:01:01.500"
+ assert formatTimestamp(59.9996) == "00:01:00.000"
+ assert formatTimestamp(3661.9, ms=False) == "01:01:01"
+ with pytest.raises(ValueError):
+ formatTimestamp(-1)
+ with pytest.raises(ValueError):
+ formatTimestamp(float("inf"))
diff --git a/tests/test_visualize.py b/tests/test_visualize.py
new file mode 100644
index 0000000..b21b1c6
--- /dev/null
+++ b/tests/test_visualize.py
@@ -0,0 +1,434 @@
+"""Tests for cv2u.imgproc.visualize."""
+
+import cv2
+import numpy as np
+import pytest
+
+from cv2u.imgproc import visualize
+from cv2u.imgproc.visualize import (
+ COCO_SKELETON,
+ applyColorMapEx,
+ blendImages,
+ colorBar,
+ compareImages,
+ drawArrow,
+ drawCrosshair,
+ drawFPS,
+ drawLegend,
+ drawPolygon,
+ drawProgressBar,
+ drawRotatedBoxes,
+ drawRotatedRect,
+ drawSkeleton,
+ drawTextBlock,
+ drawTrajectory,
+ heatmap,
+ labeledMontage,
+)
+
+
+def bgr(h: int = 60, w: int = 80, value: int = 0) -> np.ndarray:
+ return np.full((h, w, 3), value, np.uint8)
+
+
+def gray(h: int = 60, w: int = 80) -> np.ndarray:
+ return np.zeros((h, w), np.uint8)
+
+
+def test_no_public_name_shadows_opencv() -> None:
+ for name in visualize.__all__:
+ assert not hasattr(cv2, name), name
+
+
+# --------------------------------------------------------------------------------------------- color maps
+
+
+def test_applyColorMapEx_float_and_uint8() -> None:
+ values = np.linspace(0, 1, 40 * 50, dtype=np.float32).reshape(40, 50)
+ out = applyColorMapEx(values)
+ assert out.shape == (40, 50, 3) and out.dtype == np.uint8
+ raw = np.rint(values * 255).astype(np.uint8)
+ assert np.array_equal(out, applyColorMapEx(raw, normalize=False))
+ assert np.array_equal(out, applyColorMapEx(values, normalize=False)) # [0, 1] floats scaled by 255
+ assert applyColorMapEx(values[..., None]).shape == (40, 50, 3)
+
+
+def test_applyColorMapEx_constant_lut_and_mask() -> None:
+ flat = np.full((10, 10), 3.0)
+ out = applyColorMapEx(flat) # constant map: no division by zero
+ assert out.shape == (10, 10, 3)
+ lut = np.zeros((256, 3), np.uint8)
+ lut[:, 2] = np.arange(256)
+ out = applyColorMapEx(np.arange(256, dtype=np.uint8).reshape(16, 16), lut, normalize=False)
+ assert out[0, 0].tolist() == [0, 0, 0] and out[15, 15].tolist() == [0, 0, 255]
+ mask = np.zeros((16, 16), np.uint8)
+ mask[:8] = 1
+ masked = applyColorMapEx(np.arange(256, dtype=np.uint8).reshape(16, 16), lut, normalize=False, mask=mask)
+ assert masked[8:].max() == 0 and masked[:8].max() > 0
+
+
+def test_applyColorMapEx_errors() -> None:
+ with pytest.raises(ValueError, match="values"):
+ applyColorMapEx(np.zeros((2, 2, 3)))
+ with pytest.raises(ValueError, match="values"):
+ applyColorMapEx(np.zeros((0, 4)))
+ with pytest.raises(ValueError, match="values"):
+ applyColorMapEx(np.array([[np.nan, 1.0]]))
+ with pytest.raises(ValueError, match="mask"):
+ applyColorMapEx(np.zeros((4, 4)), mask=np.zeros((2, 2)))
+
+
+def test_heatmap_resizes_and_keeps_alpha() -> None:
+ src = bgr(40, 60, 100)
+ values = np.random.default_rng(0).random((8, 8))
+ out = heatmap(src, values)
+ assert out.shape == src.shape and out.dtype == np.uint8
+ assert not np.array_equal(out, src) and np.array_equal(src, bgr(40, 60, 100))
+ assert np.array_equal(heatmap(src, values, alpha=0.0), src)
+ assert heatmap(gray(40, 60), values).shape == (40, 60, 3)
+ bgra = np.dstack([src, np.full((40, 60), 7, np.uint8)])
+ out4 = heatmap(bgra, values)
+ assert out4.shape == (40, 60, 4) and np.all(out4[..., 3] == 7)
+
+
+def test_heatmap_errors() -> None:
+ with pytest.raises(ValueError, match="alpha"):
+ heatmap(bgr(), np.zeros((4, 4)), alpha=1.5)
+ with pytest.raises(ValueError, match="src"):
+ heatmap(bgr().astype(np.float32), np.zeros((4, 4)))
+ with pytest.raises(ValueError, match="src"):
+ heatmap(np.zeros((0, 4, 3), np.uint8), np.zeros((4, 4)))
+ with pytest.raises(ValueError, match="channels"):
+ heatmap(np.zeros((4, 4, 2), np.uint8), np.zeros((4, 4)))
+
+
+def test_colorBar() -> None:
+ bar = colorBar(size=(100, 10))
+ assert bar.shape == (10, 100, 3)
+ assert not np.array_equal(bar[:, 0], bar[:, -1])
+ vbar = colorBar(size=(10, 100), vertical=True)
+ assert vbar.shape == (100, 10, 3) and np.array_equal(vbar[0, 0], bar[0, -1])
+ labeled = colorBar(size=(100, 10), minVal=0, maxVal=1.5)
+ assert labeled.shape[1] == 100 and labeled.shape[0] > 10
+ vlabeled = colorBar(size=(10, 100), vertical=True, minVal=-1, maxVal=1)
+ assert vlabeled.shape[0] == 100 and vlabeled.shape[1] > 10
+ with pytest.raises(ValueError, match="size"):
+ colorBar(size=(0, 10))
+ with pytest.raises(ValueError, match="minVal"):
+ colorBar(minVal=float("nan"))
+
+
+# --------------------------------------------------------------------------------------------- shapes
+
+
+def test_drawArrow_heads_and_in_place() -> None:
+ img = bgr()
+ assert drawArrow(img, (10, 30), (70, 30), (0, 255, 0)) is img
+ assert img[30, 40].tolist() == [0, 255, 0]
+ assert img[25, 60:64, 1].max() > 0 and img[35, 60:64, 1].max() > 0 # both wings of the head at the end
+ both = drawArrow(bgr(), (10.4, 30.2), (70, 30), (0, 255, 0), heads="both")
+ assert both[25, 16:20, 1].max() > 0
+ none = drawArrow(bgr(), (10, 30), (70, 30), (0, 255, 0), heads="none")
+ assert none[20:27, :, 1].max() == 0
+ assert drawArrow(bgr(), (10, 30), (10, 30), (0, 255, 0)).max() > 0 # zero length: a dot, no error
+ g = drawArrow(gray(), (10, 30), (70, 30), (0, 255, 0), heads="start")
+ assert g[30, 40] > 0
+ with pytest.raises(ValueError, match="heads"):
+ drawArrow(bgr(), (0, 0), (10, 10), (0, 255, 0), heads="left")
+ with pytest.raises(ValueError, match="headSize"):
+ drawArrow(bgr(), (0, 0), (10, 10), (0, 255, 0), headSize=-1)
+ with pytest.raises(ValueError, match="pt1"):
+ drawArrow(bgr(), (float("nan"), 0), (10, 10), (0, 255, 0))
+ with pytest.raises(ValueError, match="color"):
+ drawArrow(bgr(), (0, 0), (10, 10), (0, 300, 0))
+
+
+def test_drawRotatedRect() -> None:
+ img = bgr(100, 100)
+ rect = ((50.0, 50.0), (40.0, 20.0), 0.0)
+ assert drawRotatedRect(img, rect, (255, 0, 0)) is img
+ assert img[40, 50].tolist() == [255, 0, 0] and img[50, 50].tolist() == [0, 0, 0]
+ filled = drawRotatedRect(bgr(100, 100), rect, (255, 0, 0), cv2.FILLED)
+ assert filled[50, 50].tolist() == [255, 0, 0]
+ rotated = drawRotatedRect(bgr(100, 100), ((50, 50), (40, 20), 90), (255, 0, 0))
+ assert rotated[50, 40].tolist() == [255, 0, 0]
+ assert drawRotatedRect(gray(100, 100), rect, 200)[40, 50] == 200
+ with pytest.raises(ValueError, match="rect size"):
+ drawRotatedRect(bgr(), ((5, 5), (-1, 2), 0), 255)
+ with pytest.raises(ValueError, match="rect"):
+ drawRotatedRect(bgr(), ((float("inf"), 5), (1, 2), 0), 255)
+
+
+def test_drawRotatedBoxes() -> None:
+ img = bgr(120, 120)
+ rects = [((40.0, 40.0), (30.0, 10.0), 15.0), ((80, 80), (20, 20), 45.0)]
+ assert drawRotatedBoxes(img, rects, labels=["a", "b"]) is img
+ assert img.max() > 0
+ colored = drawRotatedBoxes(bgr(120, 120), rects, colors=(0, 0, 255))
+ assert colored[..., :2].max() == 0 and colored[..., 2].max() == 255 # red only (anti-aliased)
+ assert drawRotatedBoxes(bgr(120, 120), rects, colors=[(1, 2, 3), (4, 5, 6)]).max() > 0
+ near_top = drawRotatedBoxes(bgr(120, 120), [((20, 5), (20, 6), 0)], labels=["top"]) # label moves inside
+ assert near_top.max() > 0
+ assert drawRotatedBoxes(gray(120, 120), rects, labels=["a", "b"]).max() > 0
+ assert drawRotatedBoxes(bgr(), []).max() == 0
+ with pytest.raises(ValueError, match="labels"):
+ drawRotatedBoxes(bgr(), rects, labels=["a"])
+ with pytest.raises(ValueError, match="colors"):
+ drawRotatedBoxes(bgr(), rects, colors=[(1, 2, 3)])
+
+
+def test_drawPolygon_outline_fill_alpha() -> None:
+ img = bgr(100, 100)
+ pts = np.array([[10.2, 10.0], [89.6, 10.0], [50.0, 80.0]])
+ assert drawPolygon(img, pts, (0, 255, 0)) is img
+ assert img[10, 50].tolist() == [0, 255, 0] and img[30, 50].tolist() == [0, 0, 0]
+ filled = drawPolygon(bgr(100, 100), pts, (0, 255, 0), fill=True)
+ assert filled[30, 50].tolist() == [0, 255, 0]
+ half = drawPolygon(bgr(100, 100), pts, (0, 200, 0), thickness=0, fill=True, alpha=0.5)
+ assert 90 <= half[30, 50, 1] <= 110 and half[95, 95].tolist() == [0, 0, 0]
+ open_ = drawPolygon(bgr(100, 100), [[10, 50], [90, 50], [90, 90]], (0, 255, 0), closed=False)
+ assert open_[70, 50].tolist() == [0, 0, 0]
+ assert drawPolygon(bgr(), [], (0, 255, 0)).max() == 0
+ assert drawPolygon(gray(100, 100), pts, (0, 255, 0), fill=True)[30, 50] > 0
+ with pytest.raises(ValueError, match="alpha"):
+ drawPolygon(bgr(), pts, (0, 255, 0), alpha=2)
+ with pytest.raises(ValueError, match="points"):
+ drawPolygon(bgr(), [[1], [2]], (0, 255, 0))
+
+
+def test_drawSkeleton_coco() -> None:
+ assert len(COCO_SKELETON) == 16 and max(max(p) for p in COCO_SKELETON) == 16
+ rng = np.random.default_rng(1)
+ kps = rng.uniform(10, 90, (17, 2))
+ img = bgr(100, 100)
+ assert drawSkeleton(img, kps) is img
+ assert img.max() > 0
+ scored = np.hstack([kps, np.ones((17, 1))])
+ scored[5:, 2] = 0.1
+ low = drawSkeleton(bgr(100, 100), scored, minScore=0.5)
+ full = drawSkeleton(bgr(100, 100), scored)
+ assert np.count_nonzero(low) < np.count_nonzero(full)
+ kps0 = kps.copy()
+ kps0[0] = 0 # undetected marker
+ assert drawSkeleton(bgr(100, 100), kps0, radius=0)[0, 0].tolist() == [0, 0, 0]
+ partial = drawSkeleton(bgr(100, 100), kps[:5], colors=(0, 0, 255)) # out-of-range pairs skipped
+ assert partial[..., :2].max() == 0 and partial[..., 2].max() == 255
+ assert drawSkeleton(gray(100, 100), kps, connections=[(0, 1)], colors=[(255, 255, 255)]).max() > 0
+ assert drawSkeleton(bgr(100, 100), kps, connections=[]).max() > 0 # joints only, default color
+ with pytest.raises(ValueError, match="radius"):
+ drawSkeleton(bgr(), kps, radius=-1)
+ with pytest.raises(ValueError, match="colors"):
+ drawSkeleton(bgr(), kps, connections=[(0, 1), (1, 2)], colors=[(1, 1, 1)])
+ with pytest.raises(ValueError, match="keypoints"):
+ drawSkeleton(bgr(), [[1], [2]])
+
+
+def test_drawTrajectory_fade() -> None:
+ pts = [(10, 30), (30, 30), (50, 30), (70, 30)]
+ img = bgr()
+ assert drawTrajectory(img, pts) is img
+ assert img[30, 65, 1] > img[30, 15, 1] > 0 # brighter towards the newest point
+ plain = drawTrajectory(bgr(), pts, color=(0, 0, 255), fade=False)
+ assert plain[30, 15].tolist() == [0, 0, 255] and plain[30, 65].tolist() == [0, 0, 255]
+ last = drawTrajectory(bgr(), pts, maxPoints=2)
+ assert last[30, 15].max() == 0 and last[30, 65].max() > 0
+ tail = drawTrajectory(bgr(), pts, color=(0, 0, 255), endColor=(255, 0, 0))
+ assert tail[30, 15, 0] > tail[30, 65, 0]
+ assert drawTrajectory(bgr(), [(1, 1)]).max() == 0
+ assert drawTrajectory(gray(), pts).max() > 0
+ with pytest.raises(ValueError, match="maxPoints"):
+ drawTrajectory(bgr(), pts, maxPoints=0)
+ with pytest.raises(ValueError, match="points"):
+ drawTrajectory(bgr(), [(np.nan, 1), (2, 2)])
+
+
+def test_drawCrosshair() -> None:
+ img = bgr(61, 61)
+ assert drawCrosshair(img, (30.3, 30), (255, 255, 255), size=20, gap=4) is img
+ assert img[30, 30].max() == 0 and img[30, 32].max() == 0
+ assert img[30, 40].max() > 0 and img[40, 30].max() > 0 and img[30, 50].max() > 0
+ assert drawCrosshair(gray(61, 61), (30, 30), (255, 255, 255))[30, 45] > 0
+ with pytest.raises(ValueError, match="size"):
+ drawCrosshair(bgr(), (5, 5), 255, size=0)
+ with pytest.raises(ValueError, match="gap"):
+ drawCrosshair(bgr(), (5, 5), 255, size=5, gap=5)
+
+
+# --------------------------------------------------------------------------------------------- HUD
+
+
+def test_drawTextBlock() -> None:
+ img = bgr(100, 200, 200)
+ assert drawTextBlock(img, ["line one", "line two"], org=(10, 10)) is img
+ assert img[12, 12].max() < 200 # darkened panel
+ assert img[90, 190].tolist() == [200, 200, 200]
+ single = drawTextBlock(bgr(100, 200, 200), "line one\nline two")
+ assert np.array_equal(single, img)
+ opaque = drawTextBlock(bgr(100, 200, 200), ["x"], alpha=1.0)
+ assert opaque[12, 12].tolist() == [0, 0, 0]
+ plain = drawTextBlock(bgr(100, 200, 200), ["x"], background=None)
+ assert plain[12, 12].tolist() == [200, 200, 200]
+ assert np.array_equal(drawTextBlock(bgr(), []), bgr())
+ assert drawTextBlock(gray(100, 200), ["gray"], color=255).max() > 0
+ clipped = drawTextBlock(bgr(100, 200), ["far"], org=(190, 95))
+ assert clipped.shape == (100, 200, 3)
+ assert np.array_equal(drawTextBlock(bgr(), [""], org=(500, 500)), bgr()) # panel fully outside
+ with pytest.raises(ValueError, match="alpha"):
+ drawTextBlock(bgr(), ["x"], alpha=-0.1)
+ with pytest.raises(ValueError, match="padding"):
+ drawTextBlock(bgr(), ["x"], padding=-1)
+ with pytest.raises(ValueError, match="fontScale"):
+ drawTextBlock(bgr(), ["x"], fontScale=0)
+ with pytest.raises(ValueError, match="lineSpacing"):
+ drawTextBlock(bgr(), ["x"], lineSpacing=float("nan"))
+ with pytest.raises(ValueError, match="img"):
+ drawTextBlock(bgr().astype(np.float32), ["x"])
+
+
+def test_drawFPS() -> None:
+ img = bgr(60, 120, 50)
+ assert drawFPS(img, 29.97) is img
+ assert img.max() > 50
+ with pytest.raises(ValueError, match="fps"):
+ drawFPS(bgr(), float("inf"))
+
+
+def test_drawProgressBar() -> None:
+ img = bgr(40, 240)
+ assert drawProgressBar(img, 0.5, (20, 10), size=(200, 12)) is img
+ assert img[15, 60].tolist() == [0, 200, 0] and img[15, 180].tolist() == [60, 60, 60]
+ assert img[9, 60].tolist() == [0, 0, 0]
+ empty = drawProgressBar(bgr(40, 240), -1.0, (20, 10), size=(200, 12), border=(255, 255, 255))
+ assert empty[15, 60].tolist() == [60, 60, 60] and empty[10, 20].tolist() == [255, 255, 255]
+ full = drawProgressBar(bgr(40, 240), 3.0, (20, 10), size=(200, 12))
+ assert full[15, 219].tolist() == [0, 200, 0]
+ assert drawProgressBar(gray(40, 240), 0.5, (20, 10))[15, 60] > 0
+ with pytest.raises(ValueError, match="progress"):
+ drawProgressBar(bgr(), float("nan"), (0, 0))
+ with pytest.raises(ValueError, match="size"):
+ drawProgressBar(bgr(), 0.5, (0, 0), size=(10, 0))
+
+
+def test_drawLegend() -> None:
+ img = bgr(120, 200, 128)
+ assert drawLegend(img, ["cat", "dog"], [(0, 0, 255), (0, 255, 0)]) is img
+ assert img[16 + 7, 16 + 7].tolist() == [0, 0, 255] # first swatch (org 10 + padding 6, row centered)
+ assert img[110, 190].tolist() == [128, 128, 128]
+ auto = drawLegend(bgr(120, 200, 128), ["a", "b", "c"])
+ assert auto.max() > 128
+ assert np.array_equal(drawLegend(bgr(), []), bgr())
+ assert drawLegend(gray(120, 200), ["x"], [(255, 255, 255)], background=None).max() > 0
+ with pytest.raises(ValueError, match="colors"):
+ drawLegend(bgr(), ["a", "b"], [(1, 1, 1)])
+ with pytest.raises(ValueError, match="swatch"):
+ drawLegend(bgr(), ["a"], swatch=0)
+ with pytest.raises(ValueError, match="padding"):
+ drawLegend(bgr(), ["a"], padding=-2)
+ with pytest.raises(ValueError, match="alpha"):
+ drawLegend(bgr(), ["a"], alpha=3)
+ with pytest.raises(ValueError, match="img"):
+ drawLegend(np.zeros((0, 0, 3), np.uint8), ["a"])
+
+
+# --------------------------------------------------------------------------------------------- comparisons
+
+
+def test_compareImages_modes() -> None:
+ a = bgr(40, 60, 0)
+ b = np.full((20, 30, 3), 200, np.uint8) # different size: resized to a
+ side = compareImages(a, b)
+ assert side.shape == (40, 120, 3) and side[20, 10].max() == 0 and side[20, 100].tolist() == [200] * 3
+ assert compareImages(a, b, gap=4, color=(255, 0, 0))[20, 62].tolist() == [255, 0, 0]
+ labeled = compareImages(a, b, labels=["before", "after"], color=(255, 255, 255))
+ assert labeled.shape[0] > 40 and labeled.shape[1] == 120
+ vertical = compareImages(a, b, mode="vertical", labels=["x", "y"])
+ assert vertical.shape[1] == 60 and vertical.shape[0] > 80
+ split = compareImages(a, b, mode="split", split=0.5, gap=2, color=(0, 0, 255))
+ assert split.shape == a.shape and split[20, 10].max() == 0 and split[20, 50].tolist() == [200] * 3
+ assert split[20, 30].tolist() == [0, 0, 255]
+ assert compareImages(a, b, mode="split", split=0.5)[20, 30].tolist() == [200] * 3
+ blend = compareImages(a, b, mode="blend", split=0.5)
+ assert blend[20, 20].tolist() == [100] * 3
+ diff = compareImages(a, b, mode="diff")
+ assert diff.shape == a.shape and diff.max() > 0
+ assert compareImages(gray(40, 60), b).shape == (40, 120, 3)
+ bgra = np.dstack([a, np.full((40, 60), 255, np.uint8)])
+ assert compareImages(bgra, bgra, mode="blend").shape == (40, 60, 3)
+
+
+def test_compareImages_errors() -> None:
+ with pytest.raises(ValueError, match="mode"):
+ compareImages(bgr(), bgr(), mode="overlay")
+ with pytest.raises(ValueError, match="split"):
+ compareImages(bgr(), bgr(), split=1.5)
+ with pytest.raises(ValueError, match="gap"):
+ compareImages(bgr(), bgr(), gap=-1)
+ with pytest.raises(ValueError, match="labels"):
+ compareImages(bgr(), bgr(), labels=["one"])
+ with pytest.raises(ValueError, match="b"):
+ compareImages(bgr(), bgr().astype(np.uint16))
+
+
+def test_labeledMontage() -> None:
+ images = [bgr(30, 40, 10), gray(20, 50), np.full((30, 30, 4), 255, np.uint8)]
+ out = labeledMontage(images, ["a", "b", "c"], cols=3, gap=2)
+ assert out.ndim == 3 and out.shape[2] == 3 and out.dtype == np.uint8
+ assert out.shape[1] == 40 + 50 + 30 + 2 * 2 and out.shape[0] > 30
+ fitted = labeledMontage(images, ["a", "b", "c"], cellSize=(32, 32), cols=2)
+ assert fitted.shape[1] == 32 * 2 + 4
+ assert labeledMontage(images[:1], ["only"]).shape[1] == 40
+ with pytest.raises(ValueError, match="images"):
+ labeledMontage([], [])
+ with pytest.raises(ValueError, match="labels"):
+ labeledMontage(images, ["a"])
+ with pytest.raises(ValueError, match="cols"):
+ labeledMontage(images, ["a", "b", "c"], cols=0)
+ with pytest.raises(ValueError, match="images"):
+ labeledMontage([bgr().astype(np.float32)], ["a"])
+
+
+def test_blendImages() -> None:
+ a, b = bgr(20, 30, 0), bgr(20, 30, 200)
+ assert np.all(blendImages([a, b]) == 100)
+ assert np.all(blendImages([a, b], weights=[1, 3]) == 150)
+ assert np.all(blendImages([a, np.full((10, 10), 200, np.uint8)]) == 100) # gray, other size
+ assert np.all(blendImages([a[..., 0], b]) == 100) # gray target from color source
+ bgra = np.dstack([a, np.full((20, 30), 255, np.uint8)])
+ out = blendImages([bgra, b])
+ assert out.shape == (20, 30, 4) and np.all(out[..., 3] == 255)
+ assert np.array_equal(blendImages([a]), a)
+ with pytest.raises(ValueError, match="images"):
+ blendImages([])
+ with pytest.raises(ValueError, match="images"):
+ blendImages([a.astype(np.float32)])
+ with pytest.raises(ValueError, match="weights"):
+ blendImages([a, b], weights=[1])
+ with pytest.raises(ValueError, match="weights"):
+ blendImages([a, b], weights=[1, -1])
+ with pytest.raises(ValueError, match="weights"):
+ blendImages([a, b], weights=[0, 0])
+
+
+def test_palette_numpy_array_is_one_color() -> None:
+ assert visualize._palette(np.array([0, 0, 255], np.uint8), 3) == [(0.0, 0.0, 255.0)] * 3
+ assert visualize._palette(np.float32(200), 2) == [200.0, 200.0]
+ assert visualize._palette(np.array([[255, 0, 0], [0, 255, 0]], np.uint8), 2) == [
+ (255.0, 0.0, 0.0),
+ (0.0, 255.0, 0.0),
+ ]
+ assert visualize._palette([200, 100], 2) == [200.0, 100.0] # two gray levels, not one 2-channel color
+ img = bgr()
+ boxes = [((40, 30), (20, 10), 0.0), ((40, 30), (20, 10), 90.0)]
+ drawRotatedBoxes(img, boxes, colors=np.array([0, 0, 255], np.uint8), thickness=1)
+ drawn = img.reshape(-1, 3)[img.reshape(-1, 3).any(axis=1)]
+ assert len(drawn) > 0 and not drawn[:, :2].any() and drawn[:, 2].max() > 200 # red only (anti-aliased)
+
+
+def test_blendImages_single_channel_3d_inputs() -> None:
+ a = np.full((20, 30, 1), 0, np.uint8)
+ b = np.full((20, 30), 200, np.uint8)
+ assert blendImages([a, b]).shape == (20, 30, 1) and np.all(blendImages([a, b]) == 100)
+ assert blendImages([b, a]).shape == (20, 30) and np.all(blendImages([b, a]) == 100)
+ assert np.all(blendImages([a, a[:10, :10]]) == 0) # (h, w, 1) resized: cv.resize drops the trailing 1
+ c = bgr(20, 30, 200)
+ assert blendImages([a, c]).shape == (20, 30, 1) and np.all(blendImages([a, c]) == 100)
diff --git a/tests/typing/check_passthrough.py b/tests/typing/check_passthrough.py
index cd6d84b..c7dca11 100644
--- a/tests/typing/check_passthrough.py
+++ b/tests/typing/check_passthrough.py
@@ -23,14 +23,18 @@
cv.rotateEx(gray, "45") # type: ignore[arg-type]
flip_code: int = cv.FLIP_MODE_X
gradient: np.ndarray = cv.makeGradient((2, 2), 0, 255, direction="horizontal")
+gray_gradient: np.ndarray = cv.makeGradient((2, 2), 0, 255, channels=1)
+canvas: np.ndarray = cv.imcolor((4, 4), (1, 2, 3))
cv.makeGradient((2, 2), 0, 255, direction="diagonal") # type: ignore[arg-type]
filled: np.ndarray = cv.imcolorLike(gradient, 0)
maybe_img: np.ndarray | None = cv.imreadEx("사진.png")
written: bool = cv.imwriteEx("out.png", filled)
boxed, scale, (left, top) = cv.letterbox(filled, (640, 640))
+fitted: cv.Letterbox = cv.letterbox(filled, (640, 640))
+fitted_image: np.ndarray = fitted.image
cv.resizeEx(filled, width="640") # type: ignore[arg-type]
side_by_side: np.ndarray = cv.hconcatEx([filled, boxed], gap=4)
-stamped: np.ndarray = cv.overlayImage(filled, boxed, org=(10, 10), opacity=0.5)
+stamped: np.ndarray = cv.overlayImage(filled, boxed, org=(10, 10), alpha=0.5)
info: cv.VideoInfo = cv.videoInfo("clip.mp4")
seconds: float = info.duration
for frame in cv.readFrames("clip.mp4", step=2):
@@ -47,12 +51,14 @@
labeled: np.ndarray = cv.drawLabel(filled, (1, 1, 5, 5), "cat", (0, 255, 0))
cv.drawLabel(filled, (1, 1, 5), "cat", (0, 255, 0)) # type: ignore[arg-type]
tinted: np.ndarray = cv.overlayMask(filled, filled > 0)
-cropped: np.ndarray = cv.cropEx(filled, (-5, -5, 20, 20), fill=0)
+cropped: np.ndarray = cv.cropRect(filled, (-5, -5, 20, 20), fill=0)
red_mask: np.ndarray = cv.inRangeEx(filled, (170, 100, 100), (10, 255, 255))
grid: np.ndarray = cv.montage([filled, cropped], cols=2, cellSize=(64, 64))
equalized: np.ndarray = cv.equalizeHistEx(filled, clahe=True)
sharpened: np.ndarray = cv.unsharpMask(filled, sigma=2.0)
label_map, palette_centers = cv.kmeansColors(filled, 4)
+clusters: cv.Clusters = cv.kmeansColors(filled, 4)
+cluster_maps: np.ndarray = clusters.maps
palette: list[tuple[tuple[int, ...], float]] = cv.dominantColors(filled, k=3)
posterized: np.ndarray = cv.colorQuantize(filled, 8)
auto_map, auto_centers = cv.meanShiftColors(filled)
@@ -63,7 +69,7 @@
contours: list[np.ndarray] = cv.findContoursEx(filled, minArea=10)
solid: np.ndarray = cv.fillHoles(filled, maxHoleArea=100)
clean: np.ndarray = cv.removeSmallObjects(filled, minArea=20)
-found: list[tuple[int, int, int, int, float]] = cv.findTemplate(filled, filled[:4, :4], threshold=0.9)
+found: np.ndarray = cv.findTemplate(filled, filled[:4, :4], threshold=0.9)
trimmed: np.ndarray = cv.cropToContent(filled, tolerance=8)
saved: bool = cv.imwriteEx("out/a.png", filled, makeDirs=True)
orange: tuple[int, ...] = cv.hexToBGR("#ff8800")
@@ -88,8 +94,9 @@
sticker: np.ndarray = cv.cutout(filled, filled[..., 0], feather=2)
thumbnail: np.ndarray | None = cv.readFrameAt("clip.mp4", seconds=1.5)
groups: np.ndarray = cv.clusterPoints([[0, 0], [1, 1]], eps=2.0)
-db_maps, db_labels = cv.DBSCAN(filled, 1.7, minSamples=2)
-cv.DBSCAN(filled, 1.7, min_samples=2) # type: ignore[call-arg]
+db_maps, db_centers = cv.dbscanColors(filled, 1.7, minSamples=2)
+cv.dbscanColors(filled, 1.7, min_samples=2) # type: ignore[call-arg]
+painted: np.ndarray = cv.drawClusters(filled, db_maps)
# Names that are not in the generated stub fall back to Any instead of an error.
cv.some_function_added_in_a_later_opencv_release()
diff --git a/tools/generate_cv2_exports.py b/tools/generate_cv2_exports.py
index 6e8f5e4..d215df1 100644
--- a/tools/generate_cv2_exports.py
+++ b/tools/generate_cv2_exports.py
@@ -26,6 +26,9 @@
OUTPUT = Path(__file__).resolve().parent.parent / "cv2u" / "_cv2_exports.pyi"
+# OpenCV submodules that cv2u replaces with its own subpackage (which passes the OpenCV names through).
+REPLACED = {"dnn"}
+
def _stub_path() -> Path:
spec = importlib.util.find_spec("cv2")
@@ -56,7 +59,7 @@ def visit(body: list[ast.stmt]) -> None:
visit(node.orelse)
visit(tree.body)
- return {n for n in names if not n.startswith("_")}
+ return {n for n in names if not n.startswith("_") and n not in REPLACED}
def render() -> str:
diff --git a/tools/regenerate_goldens.py b/tools/regenerate_goldens.py
index 015a85f..cf2e227 100644
--- a/tools/regenerate_goldens.py
+++ b/tools/regenerate_goldens.py
@@ -41,11 +41,11 @@ def main() -> None:
_write("rotateEx_45.png", cv.rotateEx(rot, 45))
_write("rotateEx_30_scale0.5.png", cv.rotateEx(rot, 30, scale=0.5))
_write("gammaCorrection_2.2.png", cv.gammaCorrection(rot, 2.2))
- _write("DHEdge.png", cv.DHEdge(gray))
+ _write("boldEdges.png", cv.boldEdges(gray))
dbs = cv2.imread(str(DATA / "dbscan_src.png"))
- maps, labels = cv.DBSCAN(dbs, 1.7, 2)
- _write("drawDBSCAN.png", cv.drawDBSCAN(dbs, maps, labels))
+ maps, _ = cv.dbscanColors(dbs, 1.7, 2)
+ _write("drawClusters.png", cv.drawClusters(dbs, maps))
if __name__ == "__main__":