Changelog¶
All notable changes to this project are documented in this file. The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[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).
Added¶
VideoReader,VideoWriterExandCameraStream: 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; photometricrandomBrightnessContrast,randomHSV,randomBlur. - Multi-image augmentations
mosaic(YOLO-style 4-image mosaic with boxes),mixupandcutMix(both return the mixing weightlamfor labels). maskToPolygons,polygonsToMask,boxesToPolygons,polygonsToBoxes,polygonArea,polygonIoU,maskIoU: polygon annotations and overlap measures (polygonIoUrasterizes 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.txtlabel files on any path, withmakeDirs.labelMapToColor,colorToLabelMap,instanceMasksToLabelMap,labelMapToMasks,drawSegmentation,drawPolygons: label maps, instance masks and their visualization with distinct class colors.flipBoxes,flipPoints,flipPolygons: flip annotations together withcv.flip(sameflipCodesemantics asFLIP_MODE_*).cv2u.dnnsubpackage (mirrorscv.dnn; everycv2.dnnname passes through):loadModel,readClassNames,preprocessImage,inferImage,postprocessDetections,postprocessClassification,softmax,sigmoid,drawDetections, and thePreprocessInfo/Detectionsnamed tuples for running detectors and classifiers end to end.heatmap,applyColorMapExandcolorBar: colorize float maps of any size, overlay them on an image and draw a legend strip.drawArrow(pixel-sized heads, both ends),drawRotatedRect/drawRotatedBoxes(fromcv.minAreaRect),drawPolygon(float points, translucent fill),drawSkeletonwithCOCO_SKELETON,drawTrajectory(fading tracks) anddrawCrosshair.- HUD helpers
drawTextBlock,drawFPS,drawProgressBaranddrawLegendwith translucent panels. compareImages(side, vertical, split, blend, diff),labeledMontage(titled grid) andblendImages(weighted average of N images).imageStats/ImageStats,isGrayscale,isBlank,isBlurry,brightnessScore,contrastScore,exposureScore,entropy,estimateNoise(Immerkær) andcolorfulness(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 throughcv.compareHist),dominantHueandmeanColor.- 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 behinddeskew),detectPageandscanDocument(detect +fourPointTransform+ enhance). cv2u.calib3dsubpackage:CameraCalibration,makeChessboard,objectPointsGrid,findChessboardEx,calibrateCameraEx,reprojectionErrors,undistortEx,saveCalibration,loadCalibrationfor chessboard camera calibration, undistortion and a JSON calibration file.stitchImages(cv.Stitcherwith exceptions and status names) andstitchPair(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 withIMREAD_REDUCED_*fast paths for 1/2, 1/4, 1/8 scales.imencodeEx,imdecodeEx,convertImageFormat: encode tobyteswith 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. ClustersandLetterboxnamed tuples (see Changed).CameraCalibration.usedViewslists the input viewscalibrateCameraExused (views without a board are skipped), andreprojectionErrorsaccepts the original corner list withNoneentries.
Changed¶
DBSCANis nowdbscanColors(src, eps, minSamples=4)and returnsClusters(maps, centers)like the other clusterers; labels are0 .. k-1with noise-1(was(maps, labels)with noise0and clusters from1).clusterPointsfollows the same convention (noise-1,int32labels).drawDBSCAN(src, maps, labels)is nowdrawClusters(src, maps): returns a new image, accepts gray or BGR input; noise pixels keep their original color.kmeansColors,meanShiftColors,peakColorsanddbscanColorsreturn aClusters(maps, centers)named tuple, andletterboxreturnsLetterbox(image, scale, offset); tuple unpacking keeps working.- Renamed:
DHEdge->boldEdges,cropEx->cropRect,centerCrop->cropCenter,detectBlobs->findBlobs,urlread->imreadUrl(now defaults toIMREAD_COLORlikecv.imread). - Renamed parameters:
matchFeatures(src, reference, ..., mask, referenceMask)(wasdst,dstMask);overlayImage(alpha=)(wasopacity);cropContour,applyMaskandflattenAlphatakefill=(wasbackground);expandBoxes(margin=)(waspixels). imcolor(size, color, channels=3)andmakeGradient(size, ...)takesize=(width, height)likecv.resizeinstead of a NumPy shape;channels=1gives a 2-D image.putTextEx(img, ...)anddrawContoursEx(img, contours, colors=None, labels=False, thickness=2, fontScale=0.5)draw in place and returnimglike every otherdraw*function (they returned a BGR copy); grayscale images stay grayscale.findTemplatereturns a float64(N, 5)array[x, y, w, h, score]instead of a list of tuples, so the result feedsnmsanddrawBoxesdirectly.cropRectraisesValueErrorwhen the box lies entirely outside the image instead of returning an empty array.cropRotatedRectdefaults toborderMode=cv.BORDER_CONSTANTlikerotateExandtranslate;rotateExhas explicit defaults (INTER_LINEAR,BORDER_CONSTANT,0).drawRoundedRectangle(img, rect, color, thickness=1, radius=8, lineType=...):radiuscomes beforelineType.drawPointsdefaultfontScaleis 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=). autoCannyaccepts 16-bit and float images (stretched to 8 bits) instead of raising;findLinesdoes the same.nmsrejectsiouThreshold > 1.minAreais afloateverywhere.- Validation is now uniform: every function rejects empty images, and every numeric parameter rejects NaN/infinity and out-of-range values, with a
ValueErrornaming the argument (about 50 functions gained checks). Every public function has completeArgs/Returns/Raisesdocstrings.
Removed¶
DBSCAN,drawDBSCAN,DHEdge,cropEx,centerCrop,detectBlobsandurlread(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.
Added¶
mapTiles(core): run a function over a large image tile by tile and merge the results (splitTiles, the function,mergeTiles), with an optional progress callback.imreadAllandimwriteAll(imgcodecs): read or write many files; an unreadable file raisesOSErrorwith its name, or givesNone/Falsewithstrict=False.toPillowaccepts every single-channel dtype Pillow has a mode for:uint16("I;16"),int32("I"),float32("F"),bool("1"), and 2-channel gray + alpha ("LA"); all round-trip throughfromPillow.- Benchmarks (
benchmarks/,pytest benchmarks): timings of the most used functions with pytest-benchmark, and regression guards that compare each wrapper with the plain OpenCV call it wraps (test_overhead.py). CI runs them on every pull request.
Changed¶
nmsuses OpenCV's C++ non-maximum suppression (cv.dnn.NMSBoxes) for the overlap test: about 20x faster on 1000 boxes. The result is unchanged (stable score order,scoreThresholdinclusive, empty array when nothing survives). The NumPy implementation remains as the fallback for builds without thednnmodule.overlayMaskblends withcv.addWeightedandcv.copyToinstead of NumPy fancy indexing: about 8x faster on a 1080p image with a large mask.mergeTilesplaces the tiles directly when they do not overlap and accumulates infloat32for 8- and 16-bit tiles (float64for wider dtypes): 2-4x faster.findContoursExno longer measures every contour whensort=FalseandminArea=0.
Fixed¶
fromPillowreturned 8-bit BGR for big-endian or native 16-bit grayscale ("I;16B","I;16L","I;16N"), silently losing precision; they now give nativeuint16. Premultiplied-alpha images ("RGBa","La") keep their alpha channel as BGRA instead of raising or dropping it.toPillowraised an OpenCV error on empty images; it now raisesValueError.
0.3.0 - 2026-11-06¶
32 new APIs (100 -> 132).
Added¶
- Boxes (
core):nms,xywhToXyxy,xyxyToXywh,clipBoxes,scaleBoxes(undo a resize or letterbox) andexpandBoxes: detector output to clean boxes on the original image. - Binarization and morphology (
imgproc):binarize(Otsu, adaptive, triangle or fixed, from any image) andmorphology(cv.morphologyExby operation name with the kernel built for you). - Detection (
imgproc):findLines,findCirclesanddetectBlobswith plain(N, 4)/(N, 3)array results. - Features (
imgproc):matchFeatures(detect, describe, match, ratio test) andalignImages(plus RANSAC and the warp) for ORB and SIFT. - Masks and crops:
maskBoundingRect,applyMask,centerCrop. - Drawing:
drawBoxes,drawPoints,drawGridanddistinctColors. - Contours (
imgproc), 11 new APIs: the steps aftercv.findContoursthat every project rewrites. contourStats: area, perimeter, rect, center, aspect ratio, extent, solidity, circularity, equivalent diameter and orientation as oneContourStatsnamed tuple.sortContours: reading order (left-to-right, top-to-bottom, ...) or by area / perimeter.filterContours: keep the contours whose measurements fall within the given ranges.contoursToMask: contours back to a filled or outlined mask (the inverse offindContoursEx).cropContour: crop one object with the outside blanked, kept, or transparent (BGRA).approxContour:cv.approxPolyDPwith the tolerance as a fraction of the perimeter.mergeContours: one convex hull around several pieces.drawContoursEx: each contour in its own color, optionally numbered or labeled at its centroid.boundingRects: everycv.boundingRectas an(N, 4)array, ready forboxIoU.-
asContour: any points to the(N, 1, 2)int32layout OpenCV wants. -
urlread(..., maxBytes=...): reject responses larger than a limit, from theContent-Lengthheader when present and otherwise while reading, so a large or hostile URL cannot fill memory.
Fixed¶
writeVideosilently dropped frames whose channel count differed from the first frame (the writer skipped them but the returned count still included them), and accepted BGRA first frames that produced an empty video. Every frame must now be grayscale or BGR and match the first one; anything else raisesValueError.rotateExwithscale0 or negative returned an unscaled image instead of failing; it now raisesValueError.fourPointTransformaccepted collinear or duplicate points (a singular transform and a garbage image) although its documentation promised aValueError; it now checks the area of the quadrilateral. Asizesmaller than 1x1 is rejected too.peakColorscrashed on an empty image orsigma=nanwith an unrelated error; both raiseValueError.- Consistent input validation across the extensions (see docs/principles.md): empty images,
NaN/ infinite parameters and colors outside the image's dtype range raiseValueErrornaming the argument, where they used to fail withIndexError,ZeroDivisionError,OverflowError,TypeErroror an OpenCV C++ assertion (adjustBrightnessContrast,adjustHSV,autoContrast,whiteBalance,cropToContent,fillHoles,removeSmallObjects,largestComponent,findContoursEx,skeletonize,cutout,letterbox,resizeEx,equalizeHistEx,unsharpMask,pixelate,ssim,diffMask,gammaCorrection,toGray,toBGR,toBGRA,hconcatEx,vconcatEx,montage,overlayImage,padToSize,padToMultiple).
0.2.1 - 2026-11-06¶
Added¶
- Tests that every extension in a submodule is exported from
cv2u, and that everycv.<name>in the README resolves. The public API can no longer drift from the documentation unnoticed.
0.2.0 - 2026-11-06¶
Changed¶
- OpenCV 4.10 and newer are supported again, alongside OpenCV 5. 4.10.0.84 is the first OpenCV build for NumPy 2.
- The OpenCV distribution is chosen with an extra:
[opencv](opencv-python),[headless](opencv-python-headless),[contrib]or[contrib-headless].opencv-pythonis no longer a hard dependency, so cv2u no longer installs a second, conflictingcv2next to a headless or contrib build. Without an extra, an already installed OpenCV is used;import cv2uexplains how to install one if there is none. Upgrade withpip install -U "python-opencv-utils[opencv]"to keep the 0.1.0 behavior.
Added¶
imgproctransformPoints: map points through a 2x3 affine or 3x3 perspective matrix, whatever their layout.cropRotatedRect: cut out a rotated box (cv.minAreaRect) as an upright image.deskew: straighten a tilted page; the angle is found from the text lines.flattenAlpha: composite a transparent image onto a background color or image.matchHistograms,colorTransfer: give an image the tones (histogram) or the color mood (Lab statistics) of another one.imageHash,hashDistance: perceptual hashes (dHash, aHash, pHash) for near-duplicate detection.pixelate: mosaic the whole image or one box.drawRoundedRectangle: rectangles with rounded corners, outlined or filled.coreboxIoU: intersection over union of every pair of boxes.imgcodecslistImages: the image files of a folder in natural order, optionally recursive.
0.1.0 - 2026-11-05¶
First official release.
Highlights¶
- Drop-in replacement for
cv2:import cv2u as cvgives you all of OpenCV plus the extensions below, following the official OpenCVimport cv2 as cvconvention. - Typed: type checkers and IDEs see OpenCV's own signatures through cv2u (
cv.imread,cv.cvtColor, ...), and every extension has type hints (py.typed, checked withmypy --strictand pyright). - Design principles that decide what belongs in cv2u, partly enforced by tests (no extension shadows an OpenCV name; OpenCV-style naming).
Requirements¶
- Python 3.11+ (tested on 3.11 through 3.15, and on the 3.16 pre-releases).
- OpenCV 5.0+ (
opencv-python), NumPy 2.0+, Pillow 10.1+.import cv2uraisesImportErrorif an oldercv2is installed. - Optional
clusterextra (pip install "python-opencv-utils[cluster]") for scikit-learn, needed bymeanShiftColors,DBSCANandclusterPoints.
Features¶
imgcodecsimreadEx,imwriteEx:cv.imread/cv.imwritethat also work with non-ASCII (e.g. Korean) paths on Windows;imwriteEx(..., makeDirs=True)creates missing folders.urlread: read an image from a URL, withtimeoutandheaders.toPillow,fromPillow: convert to/from Pillow with the right channel order (also palette, CMYK and transparent images).imencodeBase64,imdecodeBase64: images as base64 text or data URIs.imgproctoGray,toBGR,toBGRA: convert from any channel count, without errors for images already in that format.hexToBGR,bgrToHex: convert between hex colors and BGR tuples.adjustBrightnessContrast,adjustHSV,autoContrast,whiteBalance: photo-style color adjustments.sharpnessScore,ssim,diffMask: blur detection, structural similarity and change detection.translate: shift an image keeping its size.drawDashedLine,drawDashedRectangle,drawHistogram: dashed drawing and histogram plots.largestComponent,skeletonize,cutout: keep the main object, thin to lines, cut out with alpha.findContoursEx:cv.findContoursfor any image, sorted by area, with small contours dropped.fillHoles,removeSmallObjects: binary mask clean-up.findTemplate:cv.matchTemplateas a list of non-overlapping matches.resizeEx: resize keeping the aspect ratio, choosingINTER_AREA/INTER_LINEARautomatically.letterbox: fit into a fixed size keeping the aspect ratio and pad; returns the scale and offset.fourPointTransform: warp a quadrilateral (corners in any order) to an upright rectangle.autoCanny:cv.Cannywith thresholds chosen from the median brightness.equalizeHistEx:cv.equalizeHistfor color images too, optionally with CLAHE.unsharpMask: unsharp-mask sharpening.drawLabel: detector-style box with a label tag (Unicode labels with a TrueType font), drawn in place.overlayMask: tint masked pixels, e.g. to visualize a segmentation.putTextEx: draw Unicode text (e.g. Korean) with a TrueType font.videoioreadFrames: iterate over video frames (withstepandstart); the capture is released automatically.writeVideo: write frames with the size, color mode and codec detected automatically.videoInfo: size, frame rate, frame count and duration in one call.readFrameAt: read a single frame by number or time.highguiimshowInline: show images in Jupyter notebooks with their real colors.imshowEx:cv.imshowthat shrinks images larger than the screen.corerotateEx: rotate by any angle without cropping the corners.hconcatEx,vconcatEx: concatenate images of different sizes and channel counts, with optional gaps.overlayImage: alpha-blend a (transparent) image onto another, clipped at the borders.montage: arrange images in a grid.cropEx: crop safely when the box extends outside the image.cropToContent: trim a uniform border.padToMultiple,padToSize,splitTiles,mergeTiles: padding and tiling for large images and networks.inRangeEx:cv.inRangefor hue ranges that wrap around, such as red.imcolor,imcolorLike,makeGradient("horizontal","vertical"or"raster").centerPoint,isInside,cartesianToPolar,polarToCartesian(withangleInDegrees).gammaCorrection,DHEdge.dominantColors,colorQuantize,kmeansColors: color palettes, posterization and deterministic color k-means, built oncv.kmeans(no extra needed).peakColors: cv2u's own color clustering. It follows the peaks of the Lab color histogram, finds the number of colors by itself, uses every pixel, is deterministic and needs no extra.meanShiftColors: color clustering that finds the number of colors by itself.DBSCAN,drawDBSCAN: color clustering in the Lab color space.clusterPoints: group nearby points (keypoints, detections) with DBSCAN.flag: named constants for magic numbers that OpenCV takes without a constant of its ownFLIP_MODE_X,FLIP_MODE_Y,FLIP_MODE_XY(cv.flip),DDEPTH_SAME(ddepth=-1),ALL_CONTOURS(cv.drawContours),REDUCE_TO_ROW,REDUCE_TO_COL(cv.reduce),WAIT_FOREVERandKEY_ESC,KEY_ENTER,KEY_SPACE,KEY_TAB,KEY_BACKSPACE(cv.waitKey).- Invalid input raises
ValueErrorwith a clear message.
Project¶
- Documentation site built with Zensical: https://076923.github.io/cv2-utils/.
- Test suite with golden-image regression tests and coverage; CI on Linux, Windows and macOS.
- Releases are published from GitHub Actions with PyPI trusted publishing and digital attestations.
SECURITY.md,CODE_OF_CONDUCT.mdandCITATION.cff.