Documentation
¶
Overview ¶
Package cv is a from-scratch, standard-library-only port of a useful subset of Python's OpenCV (cv2), focused on classic image processing and computer vision primitives.
The package is written entirely against the Go standard library — image, image/color, image/png, image/jpeg, math and friends. It uses no cgo and no third-party dependencies, so it builds and runs anywhere the Go toolchain does. This root package holds the core imgproc toolkit; the heavier machine-vision machinery — dense feature descriptors (SIFT/ORB/AKAZE), camera calibration and stereo (calib3d, stereo), DNN inference, optical flow and video — lives in importable subpackages under this module (see Subpackages below), each also standard-library-only. The remaining unavoidable gaps are capabilities that genuinely need a GPU or trained model files, which a zero-dependency, cgo-free port cannot provide.
The Mat type ¶
The central data structure is Mat, a dense row-major matrix of 8-bit unsigned samples backed by a flat []uint8. A Mat has Rows, Cols and Channels; one-channel (grayscale) and three-channel (RGB) images are the common cases, but any positive channel count is supported. Pixels are stored interleaved: the sample for row y, column x, channel c lives at index (y*Cols+x)*Channels + c. Convert to and from the standard library with FromImage and Mat.ToImage, and read or write PNG/JPEG files with ImRead and ImWrite.
Unless documented otherwise, this package treats three-channel data as RGB (matching Go's image package), not OpenCV's native BGR. Use CvtColor with ColorRGB2BGR when you need to interoperate with BGR-oriented code or data.
Conventions ¶
Coordinates follow the image convention: x is the column (horizontal) and y is the row (vertical), with the origin at the top-left. Functions that take a point-like pair take it as (x, y). Border handling for neighbourhood operations replicates the edge sample (OpenCV's BORDER_REPLICATE), which avoids the dark halos that zero-padding produces.
Filtering and analysis ¶
The package provides a generic Filter2D convolution plus the common specialisations built on it: Blur/BoxFilter, separable GaussianBlur, MedianBlur, Sobel, Scharr and Laplacian. Thresholding covers fixed and [Otsu] levels via Threshold as well as AdaptiveThreshold. Morphology offers Erode, Dilate and MorphologyEx over structuring elements from GetStructuringElement. Geometric transforms include Resize, Flip, Rotate, Transpose and affine warping through WarpAffine and GetRotationMatrix2D. Edge and template tooling provides a full Canny pipeline and MatchTemplate with MinMaxLoc. Drawing primitives (Line, Rectangle, Circle, Ellipse, PutText, Polylines, FillPoly) render directly onto a Mat, and CalcHist/EqualizeHist cover histograms.
Colour, arithmetic and shape analysis ¶
CvtColor additionally converts between RGB and CIE L*a*b* (ColorRGB2Lab), Y'CrCb (ColorRGB2YCrCb) and HLS (ColorRGB2HLS). Element-wise Mat arithmetic with saturation is available through Add, Subtract, AbsDiff, AddWeighted, Multiply, Divide, the bitwise ops (BitwiseAnd, BitwiseOr, BitwiseXor, BitwiseNot), Min, Max, Normalize and ConvertScaleAbs. BilateralFilter adds edge-preserving smoothing and Filter2DSep exposes separable convolution.
Structural analysis covers Suzuki-style FindContours with retrieval modes and a hierarchy, DrawContours, ContourArea, ArcLength, BoundingRect, MinAreaRect, ConvexHull, ApproxPolyDP and ImageMoments, plus ConnectedComponents and ConnectedComponentsWithStats. Feature detection provides CornerHarris, GoodFeaturesToTrack, HoughLines, HoughLinesP, HoughCircles and FASTCorners. Projective geometry adds GetPerspectiveTransform with WarpPerspective, Remap, the PyrDown / PyrUp Gaussian pyramid and DistanceTransform. Histogram tooling gains CalcBackProject, CompareHist and CLAHE.
Linear algebra, signal and geometry ¶
Beyond image processing the root package carries the numerical core OpenCV exposes in cv2: dense linear algebra over FloatMat — Invert, Solve, Determinant, Trace, Eigen, SVDecomp, Gemm, PCACompute / PCAProject / PCABackProject, Mahalanobis and CalcCovarMatrix; array utilities Reduce, Repeat, Sort, SortIdx, MinMaxIdx, FindNonZero, Transform and the channel helpers ExtractChannel, InsertChannel and MixChannels; element-wise math Exp, Log, Pow, Sqrt, Magnitude, Phase, CartToPolar and PolarToCart; and the frequency-domain routines DFT, IDFT, DCT, IDCT, MulSpectrums, CreateHanningWindow and PhaseCorrelate. Contour and shape predicates (PointPolygonTest, IsContourConvex, MinEnclosingCircle, FitLine, MatchShapes, HuMoments) and extended drawing (DrawMarker, ArrowedLine, GetTextSize, FillConvexPoly, BoxPoints) round out the core surface.
Subpackages ¶
This root package is the core; the wider computer-vision surface lives in 58 importable subpackages under the same module, each standard-library-only and depending only on this package. They mirror OpenCV's main and contrib modules:
- Features & matching: features2d, xfeatures2d, flann, linedescriptor
- Geometry & 3D: calib3d, stereo, rgbd, surface_matching, structured_light, phase_unwrapping, ccalib, rapid
- Detection & recognition: objdetect, face, aruco, barcode, datamatrix, text, dnn, saliency, xobjdetect
- Motion & tracking: video, optflow, tracking, bgsegm, videostab
- Photo & imaging: photo, xphoto, hdr, intensity, fuzzy, bioinspired, dnn_superres
- Segmentation, shape & stitching: segmentation, shape, ximgproc, stitching, hfs
- Analysis & viz: ml, quality, imghash, plot, videoio, mcc, gapi, imgprocx
A family of cuda* packages (cudaarithm, cudaimgproc, cudafilters, cudawarping, cudafeatures2d, cudabgsegm, cudaobjdetect, cudaoptflow, cudastereo, cudacodec, cudacore, cudalegacy) mirrors the API shape of OpenCV's GPU modules. They are CPU-backed and cgo-free: a GpuMat wraps an ordinary host Mat and Stream is a no-op, so code ports naturally from OpenCV's cuda modules but runs on the CPU — API parity, not acceleration.
Errors and panics ¶
Constructors and I/O functions that can fail return an error. Pixel-level helpers such as Mat.At and Mat.Set favour speed and panic on out-of-range access, mirroring a Go slice index. Processing functions validate their arguments and panic with a descriptive message on programmer error (for example a mismatched channel count) rather than returning an error for every call.
Index ¶
- Constants
- func Accumulate(src *Mat, dst *FloatMat)
- func AccumulateSquare(src *Mat, dst *FloatMat)
- func AccumulateWeighted(src *Mat, dst *FloatMat, alpha float64)
- func ArcLength(c []Point, closed bool) float64
- func ArrowedLine(m *Mat, pt1, pt2 Point, color Scalar, thickness int, tipLength float64)
- func BorderInterpolate(p, length int, borderType BorderType) int
- func CalcHist(src *Mat, channel int) []int
- func Circle(m *Mat, center Point, radius int, color Scalar, thickness int)
- func ClipLine(rect Rect, pt1, pt2 Point) (Point, Point, bool)
- func CompareHist(h1, h2 []int, method HistCompMethod) float64
- func CompleteSymm(m *FloatMat, lowerToUpper bool)
- func ConnectedComponents(src *Mat, conn Connectivity) (labels []int, count int)
- func ContourArea(c Contour) float64
- func CountNonZero(src *Mat) int
- func Determinant(m *FloatMat) float64
- func DrawContours(m *Mat, contours []Contour, contourIdx int, color Scalar, thickness int)
- func DrawMarker(m *Mat, position Point, color Scalar, markerType MarkerType, ...)
- func Ellipse(m *Mat, center Point, axesX, axesY int, angle float64, color Scalar, ...)
- func Entropy(src *Mat) float64
- func FillConvexPoly(m *Mat, pts []Point, color Scalar)
- func FillPoly(m *Mat, polys [][]Point, color Scalar)
- func FindContours(src *Mat, mode RetrievalMode, approx ContourApproxMode) ([]Contour, []HierarchyNode)
- func FitLine(pts []Point) (vx, vy, x0, y0 float64)
- func GaussianKernel1D(ksize int, sigma float64) []float64
- func GaussianKernel2D(ksize int, sigma float64) [][]float64
- func GetDerivKernels(dx, dy, ksize int) (kx, ky []float64)
- func GetGaussianKernel(ksize int, sigma float64) []float64
- func HuMoments(m Moments) [7]float64
- func IMEncode(format string, m *Mat) ([]byte, error)
- func ImWrite(path string, m *Mat) error
- func InsertChannel(src, dst *Mat, coi int)
- func IsContourConvex(contour []Point) bool
- func Line(m *Mat, pt1, pt2 Point, color Scalar, thickness int)
- func MSE(a, b *Mat) float64
- func Mahalanobis(v1, v2, icovar *FloatMat) float64
- func MatchShapes(a, b Moments) float64
- func Median(src *Mat) float64
- func MinMaxIdx(src *FloatMat) (minVal, maxVal float64, minIdx, maxIdx int)
- func MinMaxLoc(f *FloatMat) (minVal, maxVal float64, minX, minY, maxX, maxY int)
- func MinMaxLocMat(src *Mat) (minVal, maxVal float64, minX, minY, maxX, maxY int)
- func MixChannels(srcs, dsts []*Mat, fromTo [][2]int)
- func NormInfMat(m *Mat) float64
- func NormL1Mat(m *Mat) float64
- func NormL2Mat(m *Mat) float64
- func PSNR(a, b *Mat) float64
- func PhaseCorrelate(a, b *FloatMat) (shiftX, shiftY, response float64)
- func PointPolygonTest(contour []Point, pt Point, measureDist bool) float64
- func Polylines(m *Mat, polys [][]Point, closed bool, color Scalar, thickness int)
- func PutText(m *Mat, text string, org Point, scale int, color Scalar)
- func Rectangle(m *Mat, pt1, pt2 Point, color Scalar, thickness int)
- func SetIdentity(m *FloatMat, value float64)
- func SobelFloat(src *Mat, dx, dy, ksize int) [][]float64
- func SortIdx(src *FloatMat, byRow, descending bool) [][]int
- func StdDevMat(src *Mat) float64
- func Trace(m *FloatMat) float64
- func VarianceMat(src *Mat) float64
- type AdaptiveMethod
- type AffineMatrix
- type BayerPattern
- type BorderType
- type ColorConversionCode
- type ColormapType
- type ComponentStats
- type Connectivity
- type Contour
- type ContourApproxMode
- type FlipCode
- type FloatMat
- func CalcCovarMatrix(data *FloatMat, normalize bool) (covar, mean *FloatMat)
- func CartToPolar(x, y *FloatMat, angleInDegrees bool) (magnitude, angle *FloatMat)
- func CornerHarris(src *Mat, blockSize, ksize int, k float64) *FloatMat
- func CornerMinEigenVal(src *Mat, blockSize, ksize int) *FloatMat
- func CreateHanningWindow(rows, cols int) *FloatMat
- func DCT(src *FloatMat) *FloatMat
- func DFT(re, im *FloatMat) (outRe, outIm *FloatMat)
- func DistanceTransform(src *Mat) *FloatMat
- func Eigen(src *FloatMat) (eigenvalues []float64, eigenvectors *FloatMat)
- func Exp(src *FloatMat) *FloatMat
- func Gemm(a, b *FloatMat, alpha float64, c *FloatMat, beta float64, transA, transB bool) *FloatMat
- func GetGaborKernel(ksize int, sigma, theta, lambda, gamma, psi float64) *FloatMat
- func IDCT(src *FloatMat) *FloatMat
- func IDFT(re, im *FloatMat, scale bool) (outRe, outIm *FloatMat)
- func Integral(src *Mat) *FloatMat
- func IntegralSquared(src *Mat) *FloatMat
- func Invert(m *FloatMat) (*FloatMat, bool)
- func Log(src *FloatMat) *FloatMat
- func Magnitude(x, y *FloatMat) *FloatMat
- func MatchTemplate(src, templ *Mat, mode TemplateMatchMode) *FloatMat
- func MulSpectrums(aRe, aIm, bRe, bIm *FloatMat, conjB bool) (re, im *FloatMat)
- func NewFloatMat(rows, cols int) *FloatMat
- func PCABackProject(coeffs, mean, eigenvectors *FloatMat) *FloatMat
- func PCACompute(data *FloatMat, maxComponents int) (mean, eigenvectors *FloatMat, eigenvalues []float64)
- func PCAProject(data, mean, eigenvectors *FloatMat) *FloatMat
- func Phase(x, y *FloatMat, angleInDegrees bool) *FloatMat
- func PolarToCart(magnitude, angle *FloatMat, angleInDegrees bool) (x, y *FloatMat)
- func Pow(src *FloatMat, power float64) *FloatMat
- func PreCornerDetect(src *Mat) *FloatMat
- func Reduce(src *FloatMat, toRow bool, op ReduceOp) *FloatMat
- func Repeat(src *FloatMat, ny, nx int) *FloatMat
- func SVDecomp(src *FloatMat) (w []float64, u, vt *FloatMat)
- func ScaleAdd(a *FloatMat, alpha float64, b *FloatMat) *FloatMat
- func Solve(a, b *FloatMat) (*FloatMat, bool)
- func Sort(src *FloatMat, byRow, descending bool) *FloatMat
- func SpatialGradient(src *Mat) (dx, dy *FloatMat)
- func SqrBoxFilter(src *Mat, ksize int, normalize bool) *FloatMat
- func Sqrt(src *FloatMat) *FloatMat
- type HierarchyNode
- type HistCompMethod
- type HoughCircle
- type InterpolationFlag
- type Kernel
- type LineIterator
- type LineSegment
- type MarkerType
- type Mat
- func AbsDiff(a, b *Mat) *Mat
- func AdaptiveThreshold(src *Mat, maxval float64, method AdaptiveMethod, typ ThresholdType, ...) *Mat
- func Add(a, b *Mat) *Mat
- func AddWeighted(a *Mat, alpha float64, b *Mat, beta, gamma float64) *Mat
- func ApplyColorMap(src *Mat, colormap ColormapType) *Mat
- func BilateralFilter(src *Mat, d int, sigmaColor, sigmaSpace float64) *Mat
- func BitwiseAnd(a, b *Mat) *Mat
- func BitwiseNot(src *Mat) *Mat
- func BitwiseOr(a, b *Mat) *Mat
- func BitwiseXor(a, b *Mat) *Mat
- func Blur(src *Mat, ksize int) *Mat
- func BoxFilter(src *Mat, ksize int, normalize bool) *Mat
- func CLAHE(src *Mat, clipLimit float64, tileGridSize int) *Mat
- func CMYKToRGB(src *Mat) *Mat
- func CalcBackProject(src *Mat, channel int, hist []int) *Mat
- func Canny(src *Mat, lowThresh, highThresh float64) *Mat
- func ConvertScaleAbs(src *Mat, alpha, beta float64) *Mat
- func CopyMakeBorder(src *Mat, top, bottom, left, right int, borderType BorderType, value Scalar) *Mat
- func CvtColor(src *Mat, code ColorConversionCode) *Mat
- func Demosaic(src *Mat, pattern BayerPattern) *Mat
- func Dilate(src, kernel *Mat, iterations int) *Mat
- func Divide(a, b *Mat, scale float64) *Mat
- func EqualizeHist(src *Mat) *Mat
- func Erode(src, kernel *Mat, iterations int) *Mat
- func ExtractChannel(src *Mat, coi int) *Mat
- func Filter2D(src *Mat, kernel Kernel, delta float64) *Mat
- func Filter2DSep(src *Mat, kx, ky []float64, delta float64) *Mat
- func Flip(src *Mat, code FlipCode) *Mat
- func FloodFill(src *Mat, seedX, seedY int, newVal float64, loDiff, upDiff float64) (*Mat, int)
- func FromImage(img image.Image) *Mat
- func GammaCorrect(src *Mat, gamma float64) *Mat
- func GaussianBlur(src *Mat, ksize int, sigma float64) *Mat
- func GetRectSubPix(src *Mat, width, height int, centerX, centerY float64) *Mat
- func GetStructuringElement(shape MorphShape, rows, cols int) *Mat
- func HSVFullToRGB(src *Mat) *Mat
- func IMDecode(data []byte) (*Mat, error)
- func ImRead(path string) (*Mat, error)
- func InRange(src *Mat, lo, hi []uint8) *Mat
- func LUT(src *Mat, table []uint8) *Mat
- func LUTChannels(src *Mat, tables [][]uint8) *Mat
- func Laplacian(src *Mat, ksize int, scale, delta float64) *Mat
- func LinearPolar(src *Mat, width, height int, centerX, centerY, maxRadius float64) *Mat
- func LogPolar(src *Mat, width, height int, centerX, centerY, maxRadius float64) *Mat
- func Max(a, b *Mat) *Mat
- func MedianBlur(src *Mat, ksize int) *Mat
- func Merge(planes []*Mat) *Mat
- func Min(a, b *Mat) *Mat
- func MorphologyEx(src, kernel *Mat, op MorphType, iterations int) *Mat
- func Multiply(a, b *Mat, scale float64) *Mat
- func NewMat(rows, cols, channels int) *Mat
- func Normalize(src *Mat, alpha, beta float64) *Mat
- func PyrDown(src *Mat) *Mat
- func PyrUp(src *Mat) *Mat
- func RGBToCMYK(src *Mat) *Mat
- func RGBToGray601(src *Mat) *Mat
- func RGBToGray709(src *Mat) *Mat
- func RGBToHSVFull(src *Mat) *Mat
- func RGBToXYZ(src *Mat) *Mat
- func RGBToYUV(src *Mat) *Mat
- func Remap(src *Mat, mapX, mapY *FloatMat, interp InterpolationFlag) *Mat
- func Resize(src *Mat, width, height int, interp InterpolationFlag) *Mat
- func Rotate(src *Mat, code RotateCode) *Mat
- func Scharr(src *Mat, dx, dy int, scale, delta float64) *Mat
- func Sobel(src *Mat, dx, dy, ksize int, scale, delta float64) *Mat
- func StackBlur(src *Mat, ksize int) *Mat
- func Subtract(a, b *Mat) *Mat
- func Threshold(src *Mat, thresh, maxval float64, typ ThresholdType) (*Mat, float64)
- func Transform(src *Mat, m *FloatMat) *Mat
- func Transpose(src *Mat) *Mat
- func TriangleThreshold(src *Mat) (*Mat, float64)
- func WarpAffine(src *Mat, m AffineMatrix, width, height int, interp InterpolationFlag) *Mat
- func WarpPerspective(src *Mat, m PerspectiveMatrix, width, height int, interp InterpolationFlag) *Mat
- func WarpPolar(src *Mat, width, height int, centerX, centerY, maxRadius float64, ...) *Mat
- func XYZToRGB(src *Mat) *Mat
- func YUVToRGB(src *Mat) *Mat
- func (m *Mat) At(y, x, c int) uint8
- func (m *Mat) AtPixel(y, x int) []uint8
- func (m *Mat) Clone() *Mat
- func (m *Mat) CopyTo(dst *Mat, y, x int)
- func (m *Mat) Empty() bool
- func (m *Mat) Region(y, x, height, width int) *Mat
- func (m *Mat) Set(y, x, c int, value uint8)
- func (m *Mat) SetPixel(y, x int, values []uint8)
- func (m *Mat) SetTo(value uint8)
- func (m *Mat) Size() (rows, cols int)
- func (m *Mat) Split() []*Mat
- func (m *Mat) ToImage() image.Image
- func (m *Mat) Total() int
- type Moments
- type MorphShape
- type MorphType
- type PerspectiveMatrix
- type Point
- func ApproxPolyDP(curve []Point, epsilon float64, closed bool) []Point
- func ConvexHull(pts []Point) []Point
- func Ellipse2Poly(center Point, axesX, axesY int, angle, arcStart, arcEnd float64, delta int) []Point
- func FASTCorners(src *Mat, threshold int, nonmaxSuppression bool) []Point
- func FindNonZero(src *Mat) []Point
- func GetTextSize(text string, scale int) (size Point, baseline int)
- func GoodFeaturesToTrack(src *Mat, maxCorners int, qualityLevel, minDistance float64, blockSize int) []Point
- type Point2f
- type PolarLine
- type Rect
- type ReduceOp
- type RetrievalMode
- type RotateCode
- type RotatedRect
- type Scalar
- type TemplateMatchMode
- type ThresholdType
- type WarpPolarMode
Examples ¶
Constants ¶
const Filled = -1
Filled is a sentinel thickness that fills a shape instead of outlining it.
Variables ¶
This section is empty.
Functions ¶
func Accumulate ¶ added in v0.5.0
Accumulate adds a single-channel image to an accumulator FloatMat in place (dst += src). It panics on a size mismatch or a multi-channel source. This is OpenCV's cv::accumulate.
func AccumulateSquare ¶ added in v0.5.0
AccumulateSquare adds the squared samples of a single-channel image to an accumulator FloatMat in place (dst += src²). It panics on a size mismatch or a multi-channel source. This is OpenCV's cv::accumulateSquare.
func AccumulateWeighted ¶ added in v0.5.0
AccumulateWeighted updates a running average accumulator in place: dst = (1-alpha)*dst + alpha*src. Larger alpha weights recent frames more, making this a simple exponential background model. It panics on a size mismatch or a multi-channel source. This is OpenCV's cv::accumulateWeighted.
func ArcLength ¶ added in v0.2.0
ArcLength returns the perimeter (closed) or length (open) of a curve as the sum of Euclidean distances between consecutive points. When closed is true the segment from the last point back to the first is included.
func ArrowedLine ¶ added in v0.5.0
ArrowedLine draws a line segment from pt1 to pt2 with an arrow head at pt2. tipLength is the length of the arrow head as a fraction of the segment length (OpenCV's default is 0.1). It mirrors cv::arrowedLine.
func BorderInterpolate ¶ added in v0.6.0
func BorderInterpolate(p, length int, borderType BorderType) int
BorderInterpolate maps an out-of-range coordinate p in [ -inf, +inf ) to a valid index in [0, length) according to borderType, mirroring cv2.borderInterpolate. BorderConstant is reported as -1 (the caller supplies the constant). It panics if length is not positive.
func CalcHist ¶
CalcHist computes a 256-bin intensity histogram of the given channel of src. The returned slice has length 256 where entry i counts samples equal to i. It panics if channel is out of range.
func Circle ¶
Circle draws a circle of the given radius centred at center. A positive thickness draws the outline; a negative thickness fills the disc.
func ClipLine ¶ added in v0.5.0
ClipLine clips the segment pt1-pt2 against the rectangle rect using the Liang-Barsky algorithm. It returns the clipped endpoints and reports whether any part of the segment lies inside the rectangle. It mirrors cv::clipLine.
func CompareHist ¶ added in v0.2.0
func CompareHist(h1, h2 []int, method HistCompMethod) float64
CompareHist measures the similarity of two equal-length histograms under the chosen method, matching OpenCV's compareHist. It panics if the histograms differ in length.
func CompleteSymm ¶ added in v0.5.0
CompleteSymm makes a square matrix symmetric by copying one triangle onto the other. When lowerToUpper is true the lower triangle is mirrored into the upper triangle; otherwise the upper triangle is mirrored into the lower one. It panics if the matrix is not square.
func ConnectedComponents ¶ added in v0.2.0
func ConnectedComponents(src *Mat, conn Connectivity) (labels []int, count int)
ConnectedComponents labels the connected foreground regions of a binary single-channel image with a two-pass union-find algorithm. Any non-zero sample is foreground. It returns a label slice in row-major order (0 marks the background, 1..count-1 the components) together with the total number of labels including the background. conn selects 4- or 8-connectivity. It panics if src is not single-channel or conn is invalid.
func ContourArea ¶ added in v0.2.0
ContourArea returns the area enclosed by a contour using the shoelace formula. The result is the polygon area through the contour's points and is always non-negative; a contour of fewer than three points has zero area.
Because border points sit on pixel centres, the area of a solid W×H block is (W-1)*(H-1) rather than W*H.
func CountNonZero ¶ added in v0.5.0
CountNonZero returns the number of non-zero samples across all channels of src, matching OpenCV's cv::countNonZero (which requires a single channel but is generalised here to any channel count).
func Determinant ¶ added in v0.5.0
Determinant returns the determinant of a square matrix, computed by Gaussian elimination with partial pivoting. It panics if the matrix is not square.
func DrawContours ¶ added in v0.2.0
DrawContours renders contours onto m. When contourIdx is negative every contour is drawn; otherwise only that index. A positive thickness draws the closed outline; a negative thickness (or Filled) fills each contour.
func DrawMarker ¶ added in v0.5.0
func DrawMarker(m *Mat, position Point, color Scalar, markerType MarkerType, markerSize, thickness int)
DrawMarker draws a marker of the given type centred at position, with a bounding size of markerSize pixels and the given line thickness. It mirrors OpenCV's cv::drawMarker.
func Ellipse ¶
Ellipse draws an axis-aligned or rotated ellipse centred at center with the given semi-axes (axesX, axesY). angle rotates the ellipse in degrees. A positive thickness draws the outline; a negative thickness fills it. The ellipse is rendered as a closed polygon sampled around its perimeter.
func Entropy ¶ added in v0.6.0
Entropy returns the Shannon entropy in bits of the sample distribution of a single-channel image, a value in [0, 8] for 8-bit data. It requires a single-channel image.
func FillConvexPoly ¶ added in v0.5.0
FillConvexPoly fills a convex polygon with a solid colour using a scanline fill that is faster and cleaner than the general FillPoly for convex shapes. The vertices may be given in either winding order. It mirrors cv::fillConvexPoly.
func FillPoly ¶
FillPoly fills one or more polygons with a solid colour using an even-odd scanline algorithm, so overlapping regions of a single call cancel.
func FindContours ¶ added in v0.2.0
func FindContours(src *Mat, mode RetrievalMode, approx ContourApproxMode) ([]Contour, []HierarchyNode)
FindContours extracts contours from a binary single-channel image using the Suzuki–Abe border-following algorithm. Any non-zero sample is treated as foreground. mode selects the retrieval strategy (RetrExternal, RetrList or RetrTree) and approx selects point storage (ChainApproxNone or ChainApproxSimple).
It returns the contours together with a parallel hierarchy slice (one HierarchyNode per contour, same indexing). For RetrExternal and RetrList every hierarchy entry's Parent and FirstChild are -1. The source is not modified. It panics if src is not single-channel.
Example ¶
// A 20x20 filled square yields one external contour of area (20-1)^2.
m := NewMat(40, 40, 1)
for y := 10; y < 30; y++ {
for x := 10; x < 30; x++ {
m.Set(y, x, 0, 255)
}
}
contours, _ := FindContours(m, RetrExternal, ChainApproxSimple)
fmt.Printf("%d contours, area %.0f, corners %d\n",
len(contours), ContourArea(contours[0]), len(contours[0]))
Output: 1 contours, area 361, corners 4
func FitLine ¶ added in v0.5.0
FitLine fits a line to a set of points by total least squares (minimising the orthogonal distance) and returns it as a unit direction (vx, vy) and a point (x0, y0) on the line, matching the parameterisation of OpenCV's cv::fitLine with DIST_L2. It panics on fewer than two points.
func GaussianKernel1D ¶
GaussianKernel1D returns a normalised 1-D Gaussian of length ksize. When sigma <= 0 it is derived from ksize (see GaussianBlur).
func GaussianKernel2D ¶ added in v0.6.0
GaussianKernel2D returns the ksize x ksize separable Gaussian kernel formed by the outer product of two GetGaussianKernel vectors. It panics on a non-positive even ksize.
func GetDerivKernels ¶ added in v0.6.0
GetDerivKernels returns the row (kx) and column (ky) kernels used to compute image derivatives of order dx and dy with an aperture of ksize, mirroring cv2.getDerivKernels. kx is the horizontal kernel and ky the vertical one; a Sobel filter convolves rows with kx and columns with ky. It panics on an even or non-positive ksize.
func GetGaussianKernel ¶ added in v0.6.0
GetGaussianKernel returns a normalised 1D Gaussian kernel of length ksize, mirroring cv2.getGaussianKernel. When sigma is not positive it is derived from ksize with OpenCV's rule sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8. It panics if ksize is not a positive odd number.
func HuMoments ¶ added in v0.5.0
HuMoments returns the seven Hu invariant moments computed from a set of normalised central moments, matching OpenCV's cv::HuMoments. They are invariant to translation, scale and rotation.
func IMEncode ¶
IMEncode encodes the Mat into a byte slice using the named format. Valid formats are "png", "jpg" and "jpeg" (case-insensitive, a leading dot is ignored).
func ImWrite ¶
ImWrite encodes the Mat and writes it to path. The format is chosen from the file extension: ".png" uses PNG, ".jpg"/".jpeg" uses JPEG at quality 95.
func InsertChannel ¶ added in v0.5.0
InsertChannel writes the single-channel src into channel coi of dst in place. The two matrices must share dimensions and src must be single-channel. It panics on a mismatch or an out-of-range coi.
func IsContourConvex ¶ added in v0.5.0
IsContourConvex reports whether a polygon is convex, i.e. every turn between consecutive edges has the same orientation and there are no self-intersections implied by a sign change. Fewer than three vertices are treated as non-convex. This mirrors OpenCV's cv::isContourConvex.
func Line ¶
Line draws a straight line from pt1 to pt2 with the given colour and thickness (in pixels, minimum 1) using Bresenham's algorithm.
func MSE ¶ added in v0.6.0
MSE returns the mean squared error between two equally shaped 8-bit matrices, averaged over all samples.
func Mahalanobis ¶ added in v0.5.0
Mahalanobis returns the Mahalanobis distance between two vectors v1 and v2 given the inverse covariance matrix icovar. The vectors may be laid out as rows or columns; their total element count must match the dimension of icovar. It panics on a dimension mismatch.
func MatchShapes ¶ added in v0.5.0
MatchShapes compares two shapes given by their moments using the log-scaled Hu-moment metric I1 (OpenCV's CONTOURS_MATCH_I1). A smaller value means a closer match; identical shapes score 0.
func MinMaxIdx ¶ added in v0.5.0
MinMaxIdx scans a FloatMat and returns the minimum and maximum values along with their flat indices (row-major). This mirrors OpenCV's cv::minMaxIdx for a 2-D array. It panics on an empty matrix.
func MinMaxLoc ¶
MinMaxLoc scans a FloatMat and returns the minimum and maximum values with their (x, y) locations. It panics on an empty matrix.
func MinMaxLocMat ¶ added in v0.6.0
MinMaxLocMat returns the minimum and maximum sample values of a single-channel Mat and their (x, y) locations, mirroring cv2.minMaxLoc. It requires a single-channel image.
func MixChannels ¶ added in v0.5.0
MixChannels copies specified channels from a set of source Mats into a set of destination Mats. Each entry of fromTo is a pair (srcIndex, dstIndex) into the flattened channel lists of srcs and dsts respectively. All matrices must share the same width and height. This mirrors OpenCV's cv::mixChannels. It panics on a dimension mismatch or an out-of-range index.
func NormInfMat ¶ added in v0.6.0
NormInfMat returns the infinity norm (largest absolute sample value) of m, matching cv2.norm with NORM_INF.
func NormL1Mat ¶ added in v0.6.0
NormL1Mat returns the L1 norm (sum of absolute sample values) of m, matching cv2.norm with NORM_L1.
func NormL2Mat ¶ added in v0.6.0
NormL2Mat returns the L2 norm (square root of the sum of squared samples) of m, matching cv2.norm with NORM_L2.
func PSNR ¶ added in v0.6.0
PSNR returns the peak signal-to-noise ratio in decibels between two equally sized 8-bit matrices, mirroring cv2.PSNR. Identical inputs return +Inf.
func PhaseCorrelate ¶ added in v0.5.0
PhaseCorrelate estimates the translational shift between two real images a and b using the phase-correlation method: it multiplies the cross-power spectrum, normalises it and locates the peak of the inverse transform. It returns the sub-pixel shift (shiftX, shiftY) that maps a onto b and the peak response in [0,1]. Shifts larger than half a dimension are reported as negative. It panics on a size mismatch.
func PointPolygonTest ¶ added in v0.5.0
PointPolygonTest reports the relationship between a point and a polygon given by its vertices. When measureDist is false it returns +1 if the point is inside, -1 if outside and 0 if on an edge. When measureDist is true it returns the signed distance to the nearest edge (positive inside, negative outside). This mirrors OpenCV's cv::pointPolygonTest.
Example ¶
ExamplePointPolygonTest classifies points against a square.
sq := []Point{{0, 0}, {10, 0}, {10, 10}, {0, 10}}
fmt.Println(PointPolygonTest(sq, Point{5, 5}, false))
fmt.Println(PointPolygonTest(sq, Point{20, 5}, false))
fmt.Println(PointPolygonTest(sq, Point{0, 5}, false))
Output: 1 -1 0
func Polylines ¶
Polylines draws one or more polylines. When closed is true each polyline's last point is joined back to its first. thickness is the line width.
func PutText ¶
PutText renders text at org (the bottom-left of the first glyph) using a built-in 5×7 bitmap font. scale integer-magnifies each glyph pixel and color/thickness control the appearance. Only ASCII 32–126 are drawn; unknown runes render as blanks.
func Rectangle ¶
Rectangle draws an axis-aligned rectangle spanning corners pt1 and pt2. A positive thickness draws the outline; a negative thickness (or Filled) fills the interior.
func SetIdentity ¶ added in v0.5.0
SetIdentity sets a matrix to a scaled identity: the main diagonal is filled with value and every other element is set to zero. It works on rectangular matrices, matching OpenCV's cv::setIdentity.
func SobelFloat ¶
SobelFloat computes the Sobel derivative and returns unclamped per-channel float results, preserving sign and magnitude. See Sobel for the parameter meaning.
func SortIdx ¶ added in v0.5.0
SortIdx returns, for each row (byRow true) or column (byRow false), the indices that would sort the elements in ascending order unless descending is set. The result has the same shape as src, matching OpenCV's cv::sortIdx.
func StdDevMat ¶ added in v0.6.0
StdDevMat returns the population standard deviation of all samples in src.
func Trace ¶ added in v0.5.0
Trace returns the sum of the diagonal elements of a matrix. For a non-square matrix the shorter of the two dimensions bounds the diagonal, matching OpenCV's cv::trace (which reports the first component of the scalar).
func VarianceMat ¶ added in v0.6.0
VarianceMat returns the population variance of all samples in src.
Types ¶
type AdaptiveMethod ¶
type AdaptiveMethod int
AdaptiveMethod selects how AdaptiveThreshold computes the local threshold.
const ( // AdaptiveThreshMeanC uses the mean of the blockSize×blockSize // neighbourhood, minus C, as the local threshold. AdaptiveThreshMeanC AdaptiveMethod = iota // AdaptiveThreshGaussianC uses a Gaussian-weighted neighbourhood mean, // minus C, as the local threshold. AdaptiveThreshGaussianC )
type AffineMatrix ¶
type AffineMatrix [6]float64
AffineMatrix is a 2×3 affine transform stored row-major:
[ m0 m1 m2 ] [ m3 m4 m5 ]
It maps a source point (x, y) to (m0*x + m1*y + m2, m3*x + m4*y + m5).
func GetAffineTransform ¶ added in v0.6.0
func GetAffineTransform(src, dst [3]Point2f) AffineMatrix
GetAffineTransform computes the 2x3 affine transform that maps the three source points to the three destination points, mirroring cv2.getAffineTransform. It panics when the source points are collinear.
func GetRotationMatrix2D ¶
func GetRotationMatrix2D(cx, cy, angle, scale float64) AffineMatrix
GetRotationMatrix2D builds the 2×3 affine matrix that rotates around the point (cx, cy) by angle degrees (counter-clockwise, matching OpenCV) and uniformly scales by scale.
func InvertAffineTransform ¶ added in v0.6.0
func InvertAffineTransform(m AffineMatrix) AffineMatrix
InvertAffineTransform returns the inverse of a 2x3 affine transform, mirroring cv2.invertAffineTransform. It panics when the linear part is singular.
type BayerPattern ¶ added in v0.6.0
type BayerPattern int
BayerPattern names the 2x2 colour-filter arrangement of a raw Bayer mosaic for Demosaic. The two letters give the colours of the top-left and its horizontal neighbour on the first row.
const ( // BayerRG has R,G on the first row and G,B on the second. BayerRG BayerPattern = iota // BayerGR has G,R on the first row and B,G on the second. BayerGR // BayerBG has B,G on the first row and G,R on the second. BayerBG // BayerGB has G,B on the first row and R,G on the second. BayerGB )
type BorderType ¶ added in v0.6.0
type BorderType int
BorderType selects how out-of-bounds samples are synthesised by neighbourhood operations and CopyMakeBorder, mirroring OpenCV's cv::BorderTypes.
const ( // BorderConstant pads with a fixed value: iiiiii|abcdefgh|iiiiiii. BorderConstant BorderType = iota // BorderReplicate repeats the edge sample: aaaaaa|abcdefgh|hhhhhhh. BorderReplicate // BorderReflect mirrors including the edge: fedcba|abcdefgh|hgfedcb. BorderReflect // BorderWrap tiles the image: cdefgh|abcdefgh|abcdefg. BorderWrap // BorderReflect101 mirrors excluding the edge: gfedcb|abcdefgh|gfedcba. BorderReflect101 )
type ColorConversionCode ¶
type ColorConversionCode int
ColorConversionCode selects a colour-space conversion for CvtColor. The constants mirror the equivalent cv2.COLOR_* codes.
const ( // ColorRGB2Gray converts three-channel RGB to single-channel grayscale // using the ITU-R BT.601 luma weights (0.299R + 0.587G + 0.114B). ColorRGB2Gray ColorConversionCode = iota // ColorGray2RGB replicates the single gray channel into three RGB channels. ColorGray2RGB // ColorRGB2BGR swaps the red and blue channels (and vice versa). ColorRGB2BGR // ColorBGR2RGB is identical to ColorRGB2BGR; swapping is its own inverse. ColorBGR2RGB // ColorBGR2Gray converts three-channel BGR to grayscale. ColorBGR2Gray // ColorRGB2HSV converts RGB to HSV. Hue is in [0,179] (degrees/2, matching // OpenCV's 8-bit convention), saturation and value are in [0,255]. ColorRGB2HSV // ColorHSV2RGB converts HSV (see ColorRGB2HSV for ranges) back to RGB. ColorHSV2RGB // ColorRGB2Lab converts RGB to CIE L*a*b* (D65 white point). In 8-bit form // L is scaled to [0,255] and a,b are stored with a +128 offset, matching // OpenCV's convention. ColorRGB2Lab // ColorLab2RGB converts CIE L*a*b* (see ColorRGB2Lab for ranges) back to RGB. ColorLab2RGB // ColorRGB2YCrCb converts RGB to Y'CrCb. Y is luma; Cr and Cb are the // red/blue chroma differences stored with a +128 offset. ColorRGB2YCrCb // ColorYCrCb2RGB converts Y'CrCb (see ColorRGB2YCrCb) back to RGB. ColorYCrCb2RGB // ColorRGB2HLS converts RGB to HLS. Hue is in [0,179] (degrees/2), while // lightness and saturation are in [0,255]. ColorRGB2HLS // ColorHLS2RGB converts HLS (see ColorRGB2HLS for ranges) back to RGB. ColorHLS2RGB )
type ColormapType ¶ added in v0.5.0
type ColormapType int
ColormapType selects a false-colour palette for ApplyColorMap.
const ( // ColormapGray maps intensity to a neutral grayscale ramp. ColormapGray ColormapType = iota // ColormapJet maps intensity through the classic blue-cyan-yellow-red ramp. ColormapJet // ColormapHot maps intensity through a black-red-yellow-white ramp. ColormapHot // ColormapBone maps intensity through a blue-tinted grayscale ramp. ColormapBone )
type ComponentStats ¶ added in v0.2.0
type ComponentStats struct {
// Label is the component's index (0 is the background).
Label int
// Rect is the axis-aligned bounding box of the component.
Rect Rect
// Area is the number of pixels in the component.
Area int
// CentroidX and CentroidY are the mean pixel coordinates of the component.
CentroidX float64
CentroidY float64
}
ComponentStats summarises one connected component: its bounding box, pixel area and centroid, mirroring the per-label rows of OpenCV's connectedComponentsWithStats.
func ConnectedComponentsWithStats ¶ added in v0.2.0
func ConnectedComponentsWithStats(src *Mat, conn Connectivity) (labels []int, count int, stats []ComponentStats)
ConnectedComponentsWithStats labels a binary single-channel image like ConnectedComponents and additionally returns per-label statistics (bounding box, area and centroid). The returned stats slice has one entry per label, index 0 describing the background. conn selects 4- or 8-connectivity.
type Connectivity ¶ added in v0.2.0
type Connectivity int
Connectivity selects the neighbourhood used by connected-component labelling.
const ( // Connectivity4 considers the 4 edge-adjacent neighbours (N, S, E, W). Connectivity4 Connectivity = 4 // Connectivity8 also considers the 4 diagonal neighbours. Connectivity8 Connectivity = 8 )
type Contour ¶ added in v0.2.0
type Contour []Point
Contour is an ordered list of boundary points describing a connected shape, as produced by FindContours. Points are in traversal order around the border.
type ContourApproxMode ¶ added in v0.2.0
type ContourApproxMode int
ContourApproxMode selects how FindContours stores each border's points.
const ( // ChainApproxNone stores every point along the border. ChainApproxNone ContourApproxMode = iota // ChainApproxSimple collapses straight horizontal, vertical and diagonal // runs to their end points, so a rectangle keeps only its four corners. ChainApproxSimple )
type FloatMat ¶
FloatMat is a single-channel matrix of float64 values, used for results such as MatchTemplate scores whose range is not confined to [0,255].
func CalcCovarMatrix ¶ added in v0.5.0
CalcCovarMatrix computes the covariance matrix and mean of a set of samples. Each row of data is one observation and each column one variable. The returned covariance is a variables×variables matrix and mean is a 1×variables row vector. When normalize is true the covariance is divided by the number of samples, otherwise it is a scatter matrix (OpenCV's default is unnormalised). It panics on empty input.
func CartToPolar ¶ added in v0.5.0
CartToPolar converts Cartesian coordinates (x, y) to polar magnitude and angle. The angle range and unit follow Phase. It panics on a size mismatch.
func CornerHarris ¶ added in v0.2.0
CornerHarris computes the Harris corner response of a single-channel image. For each pixel it forms the structure tensor M summed over a blockSize window of Sobel gradients (aperture ksize) and returns R = det(M) - k*trace(M)^2 as a FloatMat. Large positive responses indicate corners. It panics if src is not single-channel.
func CornerMinEigenVal ¶ added in v0.6.0
CornerMinEigenVal returns, for each pixel, the smaller eigenvalue of the blockSize x blockSize structure tensor built from Sobel derivatives of the given aperture, mirroring cv2.cornerMinEigenVal. Larger values mark stronger corners. It requires a single-channel input and a Sobel aperture of 1 or 3.
func CreateHanningWindow ¶ added in v0.5.0
CreateHanningWindow builds a rows×cols Hann (raised-cosine) window, the 2-D separable product of 1-D Hann windows. It is typically multiplied into an image before PhaseCorrelate to suppress edge effects. It panics unless both dimensions are positive.
func DCT ¶ added in v0.5.0
DCT computes the 2-D discrete cosine transform (type-II, orthonormal) of a real matrix. Use IDCT to invert it.
Example ¶
ExampleDCT shows that IDCT inverts DCT.
m := NewFloatMat(1, 4)
copy(m.Data, []float64{1, 2, 3, 4})
back := IDCT(DCT(m))
fmt.Printf("%.0f %.0f %.0f %.0f\n", back.Data[0], back.Data[1], back.Data[2], back.Data[3])
Output: 1 2 3 4
func DFT ¶ added in v0.5.0
DFT computes the forward 2-D discrete Fourier transform of a complex image given as separate real and imaginary planes, returning the complex spectrum as (real, imaginary) planes. For a real input pass a zero-filled imaginary plane. It panics on a size mismatch.
func DistanceTransform ¶ added in v0.2.0
DistanceTransform computes, for each non-zero (foreground) pixel of a binary single-channel image, the approximate Euclidean distance to the nearest zero (background) pixel, returning the distances as a FloatMat. It uses a two-pass 3×3 chamfer with weights 1 (orthogonal) and √2 (diagonal). Background pixels have distance 0. It panics if src is not single-channel.
func Eigen ¶ added in v0.5.0
Eigen computes the eigenvalues and eigenvectors of a real symmetric matrix using the cyclic Jacobi method. The eigenvalues are returned in descending order and the returned matrix holds the corresponding unit eigenvectors as its rows, matching OpenCV's cv::eigen layout. It panics if the matrix is not square.
func Gemm ¶ added in v0.5.0
Gemm computes the generalised matrix product alpha*op(a)*op(b) + beta*c, where op(x) is x transposed when the corresponding flag is set. If c is nil the beta term is omitted. This mirrors OpenCV's cv::gemm. It panics on a dimension mismatch.
func GetGaborKernel ¶ added in v0.5.0
GetGaborKernel builds a Gabor filter kernel of size ksize×ksize. sigma is the standard deviation of the Gaussian envelope, theta the orientation of the normal to the parallel stripes in radians, lambda the wavelength of the sinusoidal factor, gamma the spatial aspect ratio and psi the phase offset. It mirrors OpenCV's cv::getGaborKernel. It panics unless ksize is positive.
func IDCT ¶ added in v0.5.0
IDCT computes the inverse 2-D discrete cosine transform (type-III, orthonormal), so that IDCT(DCT(x)) recovers x.
func IDFT ¶ added in v0.5.0
IDFT computes the inverse 2-D discrete Fourier transform of a complex spectrum given as (real, imaginary) planes. When scale is true the result is divided by the number of elements, so that IDFT(DFT(x)) recovers x. It panics on a size mismatch.
func Integral ¶ added in v0.5.0
Integral computes the summed-area table (integral image) of a single-channel Mat. The result has one extra row and column of leading zeros, so element (y+1, x+1) equals the sum of every source sample in the rectangle [0,y]×[0,x]; the sum over any axis-aligned rectangle can then be found in constant time. It panics if src is not single-channel. This mirrors OpenCV's cv::integral.
func IntegralSquared ¶ added in v0.5.0
IntegralSquared computes the summed-area table of the squared sample values of a single-channel Mat, laid out like Integral with a leading zero row and column. Together with Integral it enables constant-time variance queries. It panics if src is not single-channel.
func Invert ¶ added in v0.5.0
Invert computes the inverse of a square matrix using Gauss-Jordan elimination with partial pivoting. The boolean result reports whether the matrix was non-singular; when false the returned matrix is all zeros. It panics if the matrix is not square.
Example ¶
ExampleInvert inverts a 2×2 matrix and confirms M·M⁻¹ is the identity.
m := NewFloatMat(2, 2)
copy(m.Data, []float64{4, 7, 2, 6})
inv, ok := Invert(m)
prod := Gemm(m, inv, 1, nil, 0, false, false)
fmt.Println(ok)
fmt.Printf("%.0f %.0f %.0f %.0f\n", prod.Data[0], prod.Data[1], prod.Data[2], prod.Data[3])
Output: true 1 0 0 1
func Log ¶ added in v0.5.0
Log returns the element-wise natural logarithm of src. Non-positive inputs map to negative infinity, following math.Log.
func Magnitude ¶ added in v0.5.0
Magnitude returns the element-wise Euclidean magnitude sqrt(x²+y²) of two matrices of matching size. It panics on a size mismatch.
func MatchTemplate ¶
func MatchTemplate(src, templ *Mat, mode TemplateMatchMode) *FloatMat
MatchTemplate slides templ over src and returns a single-channel float result map of shape (src.Rows-templ.Rows+1) × (src.Cols-templ.Cols+1). Each entry holds the similarity of templ against the patch of src at that top-left position under the chosen mode. Both inputs must have the same channel count and templ must fit inside src.
The result is returned as a FloatMat because match scores are not bounded to [0,255]; use MinMaxLoc to locate the best match.
Example ¶
src := NewMat(6, 6, 1)
for i := range src.Data {
src.Data[i] = uint8(i)
}
templ := src.Region(2, 3, 2, 2)
res := MatchTemplate(src, templ, TmSqdiff)
_, _, minX, minY, _, _ := MinMaxLoc(res)
fmt.Printf("%d,%d\n", minX, minY)
Output: 3,2
func MulSpectrums ¶ added in v0.5.0
MulSpectrums multiplies two complex spectra element-wise, optionally conjugating the second operand (as needed for correlation). Each spectrum is a pair of (real, imaginary) planes of matching size. It panics on a size mismatch.
func NewFloatMat ¶
NewFloatMat allocates a zero-filled FloatMat.
func PCABackProject ¶ added in v0.5.0
PCABackProject reconstructs observations from their principal-component coefficients (one observation per row) using mean and eigenvectors (one axis per row), returning approximate observations with one row each and one column per original variable. It is the inverse of PCAProject. It panics on a dimension mismatch.
func PCACompute ¶ added in v0.5.0
func PCACompute(data *FloatMat, maxComponents int) (mean, eigenvectors *FloatMat, eigenvalues []float64)
PCACompute performs principal component analysis on a set of samples (one observation per row) and returns the sample mean (1×variables), the first maxComponents principal axes as the rows of eigenvectors, and the associated eigenvalues (variances) in descending order. Passing maxComponents <= 0 or greater than the number of variables keeps all components. It panics on empty input.
func PCAProject ¶ added in v0.5.0
PCAProject projects data (one observation per row) onto the principal subspace defined by mean and eigenvectors (one axis per row), returning the coefficients with one row per observation and one column per component. It panics on a dimension mismatch.
func Phase ¶ added in v0.5.0
Phase returns the element-wise orientation atan2(y, x) of two matrices of matching size. When angleInDegrees is true the result is in degrees in [0, 360); otherwise it is in radians in [0, 2π), matching OpenCV. It panics on a size mismatch.
func PolarToCart ¶ added in v0.5.0
PolarToCart converts polar magnitude and angle back to Cartesian x and y components. When angleInDegrees is true the angle is interpreted in degrees. It panics on a size mismatch.
func Pow ¶ added in v0.5.0
Pow raises every element of src to the given power. Fractional powers of negative numbers follow OpenCV by using the absolute value of the base.
func PreCornerDetect ¶ added in v0.5.0
PreCornerDetect computes the corner-detection function Dx²·Dyy + Dy²·Dxx − 2·Dx·Dy·Dxy from the first and second derivatives of a single-channel image, matching OpenCV's cv::preCornerDetect. Peaks of the result indicate corners. It panics if src is not single-channel.
func Reduce ¶ added in v0.5.0
Reduce collapses a FloatMat to a single row or single column by combining elements with op. When toRow is true every column is reduced across its rows, producing a 1×Cols result; otherwise every row is reduced across its columns, producing a Rows×1 result. It panics on an empty matrix.
Example ¶
ExampleReduce sums each column of a matrix into a single row.
m := NewFloatMat(2, 3)
copy(m.Data, []float64{1, 2, 3, 4, 5, 6})
row := Reduce(m, true, ReduceSum)
fmt.Printf("%.0f %.0f %.0f\n", row.Data[0], row.Data[1], row.Data[2])
Output: 5 7 9
func Repeat ¶ added in v0.5.0
Repeat tiles src ny times vertically and nx times horizontally, returning a FloatMat of size (Rows*ny)×(Cols*nx). It panics unless ny and nx are positive.
func SVDecomp ¶ added in v0.5.0
SVDecomp computes the singular value decomposition of a matrix A so that A = u * diag(w) * vt. It uses the one-sided Jacobi method and returns the singular values w in descending order, the left singular vectors as the columns of u (rows×n), and the transposed right singular vectors vt (n×n), where n is the number of columns of the input.
func ScaleAdd ¶ added in v0.5.0
ScaleAdd computes the element-wise alpha*a + b for two matrices of matching size (OpenCV's scaleAdd / axpy). It panics on a size mismatch.
func Solve ¶ added in v0.5.0
Solve solves the linear system a*x = b for x, where a is an N×N matrix and b is an N×M right-hand side (M may be 1). It uses Gauss-Jordan elimination with partial pivoting. The boolean reports whether a was non-singular. It panics if the shapes are incompatible.
func Sort ¶ added in v0.5.0
Sort sorts a FloatMat either row-by-row (byRow true) or column-by-column (byRow false), in ascending order unless descending is set. It returns a new matrix, matching OpenCV's cv::sort with SORT_EVERY_ROW / SORT_EVERY_COLUMN.
func SpatialGradient ¶ added in v0.5.0
SpatialGradient computes the first-order x and y derivatives of a single-channel image with the 3×3 Sobel operator, returning them as FloatMats (unclamped, so they carry sign). It mirrors OpenCV's cv::spatialGradient. It panics if src is not single-channel.
func SqrBoxFilter ¶ added in v0.6.0
SqrBoxFilter returns, for each pixel, the sum (or mean when normalize is true) of the squared samples in a ksize x ksize neighbourhood with replicated borders, as a FloatMat. It mirrors cv2.sqrBoxFilter and requires a single-channel input and a positive odd ksize.
type HierarchyNode ¶ added in v0.2.0
HierarchyNode mirrors OpenCV's 4-element hierarchy entry. Each field is an index into the slice of contours returned by FindContours, or -1 when absent. Next and Prev link siblings at the same nesting level; FirstChild is the first contour nested one level deeper; Parent is the enclosing contour.
type HistCompMethod ¶ added in v0.2.0
type HistCompMethod int
HistCompMethod selects the similarity measure used by CompareHist.
const ( // HistCmpCorrel is the Pearson correlation; higher (up to 1) means more // similar. HistCmpCorrel HistCompMethod = iota // HistCmpChiSqr is the chi-square distance; lower (0) means more similar. HistCmpChiSqr // HistCmpIntersect is histogram intersection; higher means more similar. HistCmpIntersect // HistCmpBhattacharyya is the Bhattacharyya distance; lower (0) means more // similar. HistCmpBhattacharyya )
type HoughCircle ¶ added in v0.2.0
HoughCircle is a detected circle with an integer centre and radius, as returned by HoughCircles.
func HoughCircles ¶ added in v0.2.0
func HoughCircles(src *Mat, minDist, param1, param2 float64, minRadius, maxRadius int) []HoughCircle
HoughCircles detects circles in a single-channel (typically grayscale) image using the Hough gradient method. Edges are found with Canny at high threshold param1 (low threshold param1/2); every edge pixel then votes for centre candidates along its gradient direction across the radius range [minRadius, maxRadius]. Accumulator peaks of at least param2 votes become circles, and detections closer than minDist are merged. It panics if src is not single-channel or the radius range is invalid.
type InterpolationFlag ¶
type InterpolationFlag int
InterpolationFlag selects the resampling method used by Resize and WarpAffine.
const ( // InterNearest picks the nearest source sample (fast, blocky). InterNearest InterpolationFlag = iota // InterLinear uses bilinear interpolation of the four nearest samples. InterLinear )
type Kernel ¶
Kernel is a 2-D convolution kernel stored row-major with Rows*Cols float weights. Build one with NewKernel or the specialised helpers.
type LineIterator ¶ added in v0.6.0
type LineIterator struct {
// contains filtered or unexported fields
}
LineIterator walks the integer pixels along the segment from one point to another using Bresenham's algorithm, mirroring OpenCV's cv::LineIterator. It yields every pixel from the start point through the end point inclusive.
func NewLineIterator ¶ added in v0.6.0
func NewLineIterator(x0, y0, x1, y1 int) *LineIterator
NewLineIterator creates an 8-connected iterator over the segment (x0, y0) to (x1, y1). The iterator starts positioned on the first pixel; call Pos to read it and Next to advance.
func (*LineIterator) Count ¶ added in v0.6.0
func (it *LineIterator) Count() int
Count returns the total number of pixels the iterator will visit.
func (*LineIterator) Next ¶ added in v0.6.0
func (it *LineIterator) Next() bool
Next advances to the following pixel and reports whether the iterator is still valid afterwards.
func (*LineIterator) Points ¶ added in v0.6.0
func (it *LineIterator) Points() []Point
Points returns every pixel along the segment as a slice, from start to end inclusive. It does not consume the receiver's current position.
func (*LineIterator) Pos ¶ added in v0.6.0
func (it *LineIterator) Pos() Point
Pos returns the pixel the iterator currently points at.
func (*LineIterator) Valid ¶ added in v0.6.0
func (it *LineIterator) Valid() bool
Valid reports whether the iterator still points at a pixel of the segment.
type LineSegment ¶ added in v0.2.0
LineSegment is a finite line segment between two end points, as returned by HoughLinesP.
func HoughLinesP ¶ added in v0.2.0
func HoughLinesP(src *Mat, rhoStep, thetaStep float64, threshold, minLineLength, maxLineGap int) []LineSegment
HoughLinesP detects line segments in a binary edge image. It runs the standard Hough transform to find candidate line directions, then, for each accumulator peak (at least threshold votes), gathers the edge pixels lying on that line, orders them, and splits them into segments, bridging gaps up to maxLineGap and emitting segments at least minLineLength long. The traversal is deterministic (raster order), unlike OpenCV's randomised implementation. It panics if src is not single-channel.
type MarkerType ¶ added in v0.5.0
type MarkerType int
MarkerType selects the glyph drawn by DrawMarker.
const ( // MarkerCross draws a upright plus sign (+). MarkerCross MarkerType = iota // MarkerTiltedCross draws a diagonal cross (×). MarkerTiltedCross // MarkerStar draws an eight-pointed star (combined + and ×). MarkerStar // MarkerDiamond draws a diamond outline. MarkerDiamond // MarkerSquare draws an axis-aligned square outline. MarkerSquare // MarkerTriangleUp draws an upward-pointing triangle outline. MarkerTriangleUp // MarkerTriangleDown draws a downward-pointing triangle outline. MarkerTriangleDown )
type Mat ¶
type Mat struct {
// Rows is the image height (number of rows).
Rows int
// Cols is the image width (number of columns).
Cols int
// Channels is the number of samples per pixel.
Channels int
// Data holds the samples, length Rows*Cols*Channels, in row-major,
// channel-interleaved order.
Data []uint8
}
Mat is a dense, row-major matrix of 8-bit unsigned samples and the central type of the package, analogous to OpenCV's cv::Mat for the CV_8U depth.
Samples are stored interleaved by channel in the flat Data slice: the value for row y, column x and channel c is at index (y*Cols+x)*Channels + c. A grayscale image uses Channels == 1; an RGB image uses Channels == 3. The zero value of Mat is not usable — construct instances with NewMat, FromImage, Mat.Clone and the transform functions in this package.
func AbsDiff ¶ added in v0.2.0
AbsDiff returns the per-sample absolute difference |a-b|. The inputs must have identical dimensions and channel counts.
func AdaptiveThreshold ¶
func AdaptiveThreshold(src *Mat, maxval float64, method AdaptiveMethod, typ ThresholdType, blockSize int, c float64) *Mat
AdaptiveThreshold thresholds a single-channel Mat using a threshold computed per pixel from its neighbourhood. blockSize is the odd neighbourhood size and C is a constant subtracted from the local mean. typ must be ThreshBinary or ThreshBinaryInv. It panics on invalid arguments.
func Add ¶ added in v0.2.0
Add returns the per-sample sum of a and b, saturating at 255. The inputs must have identical dimensions and channel counts.
func AddWeighted ¶ added in v0.2.0
AddWeighted computes the per-sample weighted sum alpha*a + beta*b + gamma, rounding and saturating to [0,255]. It is the classic image-blending operation. The inputs must have identical dimensions and channel counts.
Example ¶
a := NewMat(1, 1, 1) a.Set(0, 0, 0, 100) b := NewMat(1, 1, 1) b.Set(0, 0, 0, 200) out := AddWeighted(a, 0.5, b, 0.5, 0) fmt.Println(out.At(0, 0, 0))
Output: 150
func ApplyColorMap ¶ added in v0.5.0
func ApplyColorMap(src *Mat, colormap ColormapType) *Mat
ApplyColorMap converts a single-channel intensity image to a three-channel RGB image using the given colormap, mirroring OpenCV's cv::applyColorMap (though colours are emitted in RGB order to match this package's convention). It panics if src is not single-channel.
Example ¶
ExampleApplyColorMap maps a grayscale ramp to RGB and reports the channel count of the result.
src := NewMat(1, 3, 1)
src.Data = []uint8{0, 128, 255}
out := ApplyColorMap(src, ColormapJet)
fmt.Println(out.Channels)
Output: 3
func BilateralFilter ¶ added in v0.2.0
BilateralFilter smooths src while preserving edges: each output sample is a weighted average of its neighbours where the weight combines a spatial Gaussian (standard deviation sigmaSpace) with a range Gaussian on the intensity difference (standard deviation sigmaColor). d is the diameter of the neighbourhood in pixels; when d <= 0 it is derived as 2*round(1.5*sigmaSpace)+1. Larger sigmaColor mixes across bigger intensity gaps. Borders are replicated.
func BitwiseAnd ¶ added in v0.2.0
BitwiseAnd returns the per-sample bitwise AND of a and b. The inputs must have identical dimensions and channel counts.
func BitwiseNot ¶ added in v0.2.0
BitwiseNot returns the per-sample bitwise complement (255-value) of src.
func BitwiseOr ¶ added in v0.2.0
BitwiseOr returns the per-sample bitwise OR of a and b. The inputs must have identical dimensions and channel counts.
func BitwiseXor ¶ added in v0.2.0
BitwiseXor returns the per-sample bitwise XOR of a and b. The inputs must have identical dimensions and channel counts.
func Blur ¶
Blur smooths src with a normalised ksize×ksize box (mean) filter. It is a convenience wrapper over BoxFilter with normalize set to true.
Example ¶
// The mean of the 3x3 neighbourhood at the centre of a ramp is 50.
m := NewMat(3, 3, 1)
copy(m.Data, []uint8{10, 20, 30, 40, 50, 60, 70, 80, 90})
out := Blur(m, 3)
fmt.Println(out.At(1, 1, 0))
Output: 50
func BoxFilter ¶
BoxFilter smooths src with a normalised or unnormalised ksize×ksize averaging kernel. When normalize is true the kernel sums to one (a mean filter); otherwise it is a plain sum. ksize must be a positive odd integer.
func CLAHE ¶ added in v0.2.0
CLAHE applies Contrast-Limited Adaptive Histogram Equalisation to a single-channel image. The image is divided into a tileGridSize×tileGridSize grid; a clipped, equalised mapping is built per tile (bins are capped at clipLimit times the average bin count and the excess is redistributed) and the mappings are bilinearly interpolated between tile centres to avoid block artefacts. clipLimit <= 0 disables clipping (plain adaptive equalisation). It panics if src is not single-channel or tileGridSize < 1.
func CMYKToRGB ¶ added in v0.6.0
CMYKToRGB is the inverse of RGBToCMYK, converting a 4-channel CMYK image to 8-bit RGB. It panics unless src has four channels.
func CalcBackProject ¶ added in v0.2.0
CalcBackProject projects a 256-bin histogram back onto an image: each output pixel is set to the histogram value of the corresponding channel intensity in src, rescaled so the largest bin maps to 255. The result is a single-channel "probability" map highlighting regions whose colour matches the histogram — the core of histogram-based tracking. It panics if channel is out of range or hist is not 256 bins.
func Canny ¶
Canny runs the full Canny edge-detection pipeline on a single-channel image and returns a binary edge map (edges are 255, background 0).
The stages are: a small Gaussian smoothing, 3×3 Sobel gradients, non-maximum suppression along the gradient direction, and double-threshold hysteresis that keeps weak edges only when connected to a strong one. lowThresh and highThresh are gradient-magnitude thresholds with lowThresh < highThresh. It panics if src is not single-channel.
func ConvertScaleAbs ¶ added in v0.2.0
ConvertScaleAbs computes |src*alpha + beta| per sample, rounds, and saturates to [0,255]. It is OpenCV's convertScaleAbs and is handy for turning a signed gradient into a displayable magnitude.
func CopyMakeBorder ¶ added in v0.6.0
func CopyMakeBorder(src *Mat, top, bottom, left, right int, borderType BorderType, value Scalar) *Mat
CopyMakeBorder returns a copy of src enlarged by the given border widths on each side, filling the new pixels according to borderType. For BorderConstant the supplied value is used for each channel. This mirrors cv2.copyMakeBorder. It panics on negative border widths.
func CvtColor ¶
func CvtColor(src *Mat, code ColorConversionCode) *Mat
CvtColor converts src between colour spaces according to code and returns a new Mat. It panics if the source channel count does not match what the code expects.
Example ¶
// A single white RGB pixel converts to full-intensity gray.
m := NewMat(1, 1, 3)
m.SetPixel(0, 0, []uint8{255, 255, 255})
gray := CvtColor(m, ColorRGB2Gray)
fmt.Println(gray.At(0, 0, 0))
Output: 255
func Demosaic ¶ added in v0.6.0
func Demosaic(src *Mat, pattern BayerPattern) *Mat
Demosaic reconstructs a 3-channel RGB image from a single-channel Bayer mosaic by averaging, for each missing colour, the same-colour samples in the 3x3 neighbourhood (replicated borders). This mirrors cv2.cvtColor with the COLOR_Bayer*2RGB codes. It requires a single-channel input.
func Dilate ¶
Dilate grows bright regions by replacing each sample with the maximum over the structuring element's footprint. iterations repeats the operation.
func Divide ¶ added in v0.2.0
Divide returns the per-sample quotient scale*a/b, rounding and saturating to [0,255]. Division by zero yields 0 (matching OpenCV). The inputs must have identical dimensions and channel counts.
func EqualizeHist ¶
EqualizeHist performs global histogram equalisation on a single-channel image to spread its intensities across the full range and improve contrast. It panics if src is not single-channel.
func Erode ¶
Erode shrinks bright regions by replacing each sample with the minimum over the structuring element's footprint. iterations repeats the operation (a value < 1 is treated as 1).
func ExtractChannel ¶ added in v0.5.0
ExtractChannel returns a single-channel Mat holding channel coi of src. It panics if coi is out of range.
func Filter2D ¶
Filter2D convolves each channel of src with kernel and returns a new Mat of the same shape. Borders are handled by edge replication. The delta is added to every filtered sample before rounding and clamping to [0,255].
Following OpenCV, this performs correlation with the kernel anchored at its centre; for symmetric kernels correlation and true convolution coincide.
func Filter2DSep ¶ added in v0.2.0
Filter2DSep applies a separable linear filter: src is convolved with the horizontal 1-D kernel kx and the vertical 1-D kernel ky in two passes. This is mathematically equivalent to convolving with the outer product ky·kxᵀ but far cheaper. delta is added before rounding and clamping to [0,255]. Borders are replicated.
func FloodFill ¶ added in v0.6.0
FloodFill fills the 4-connected region of a single-channel image around the seed (seedX, seedY) whose samples stay within loDiff below and upDiff above each already-filled neighbour, painting them with newVal. It returns the filled copy and the number of pixels changed, mirroring cv2.floodFill with the default (floating-range) comparison. It requires a single-channel image.
func FromImage ¶
FromImage converts any image.Image into a Mat. If the source is grayscale (color.Gray or color.Gray16) the result is single-channel; otherwise it is three-channel RGB with the alpha channel dropped. Samples are scaled to the 8-bit range.
func GammaCorrect ¶ added in v0.6.0
GammaCorrect applies the power-law mapping out = 255*(in/255)^gamma to every sample of src via a lookup table and returns the result. Gamma below 1 brightens, above 1 darkens. It panics on a non-positive gamma.
func GaussianBlur ¶
GaussianBlur convolves src with a separable Gaussian kernel of size ksize×ksize. sigma is the standard deviation; when sigma <= 0 it is derived from the kernel size as OpenCV does: 0.3*((ksize-1)*0.5 - 1) + 0.8. ksize must be a positive odd integer.
func GetRectSubPix ¶ added in v0.6.0
GetRectSubPix extracts a width x height patch centred on the fractional point (centerX, centerY) using bilinear interpolation with replicated borders, mirroring cv2.getRectSubPix. It panics on non-positive dimensions.
func GetStructuringElement ¶
func GetStructuringElement(shape MorphShape, rows, cols int) *Mat
GetStructuringElement returns a structuring element (kernel) of the given shape and size as a single-channel Mat whose set elements are 1 and unset elements are 0. rows and cols must be positive and odd for a well-defined centre anchor.
func HSVFullToRGB ¶ added in v0.6.0
HSVFullToRGB is the inverse of RGBToHSVFull, converting a full-range HSV image back to 8-bit RGB. It mirrors cv2.cvtColor with COLOR_HSV2RGB_FULL.
func ImRead ¶
ImRead loads an image file from path and returns it as a Mat. PNG and JPEG are supported through the standard library decoders. The channel count of the result follows FromImage: grayscale files yield a single-channel Mat, everything else yields three-channel RGB.
func InRange ¶
InRange produces a single-channel mask that is 255 where every channel of src lies within the inclusive [lo, hi] band and 0 elsewhere. lo and hi must have one entry per channel. It is handy for colour segmentation, e.g. on an HSV image. It panics if the bounds do not match the channel count.
func LUT ¶ added in v0.6.0
LUT applies a 256-entry lookup table to every sample of src and returns the result, mirroring cv2.LUT. The same table is applied to all channels; it panics if table does not have exactly 256 entries.
func LUTChannels ¶ added in v0.6.0
LUTChannels applies a separate 256-entry table to each channel of src and returns the result. It panics unless len(tables) equals src.Channels and each table has 256 entries.
func Laplacian ¶
Laplacian computes the Laplacian (sum of second spatial derivatives) of src. ksize 1 uses the classic 4-neighbour stencil; ksize 3 uses the Sobel-based second-derivative sum. Results are scaled, offset by delta and clamped.
func LinearPolar ¶ added in v0.6.0
LinearPolar remaps src to linear polar coordinates, a convenience wrapper for WarpPolar with WarpPolarLinear, mirroring cv2.linearPolar.
func LogPolar ¶ added in v0.6.0
LogPolar remaps src to log-polar coordinates, a convenience wrapper for WarpPolar with WarpPolarLog, mirroring cv2.logPolar.
func Max ¶ added in v0.2.0
Max returns the per-sample maximum of a and b. The inputs must have identical dimensions and channel counts.
func MedianBlur ¶
MedianBlur replaces each sample with the median of its ksize×ksize neighbourhood, an effective remedy for salt-and-pepper noise. ksize must be a positive odd integer. Borders are replicated.
func Merge ¶
Merge combines single-channel Mats into one interleaved multi-channel Mat. Every input must be single-channel and share the same dimensions. It panics otherwise or if no planes are given.
func Min ¶ added in v0.2.0
Min returns the per-sample minimum of a and b. The inputs must have identical dimensions and channel counts.
func MorphologyEx ¶
MorphologyEx performs a compound morphological operation selected by op over the given structuring element. Subtractive operations saturate at zero.
func Multiply ¶ added in v0.2.0
Multiply returns the per-sample product a*b*scale, rounding and saturating to [0,255]. The inputs must have identical dimensions and channel counts.
func NewMat ¶
NewMat allocates a zero-filled Mat with the given dimensions. It panics if any dimension is not positive.
func Normalize ¶ added in v0.2.0
Normalize linearly rescales src so that its minimum sample maps to alpha and its maximum to beta, writing the rounded, clamped result to a new Mat. This is OpenCV's NORM_MINMAX normalisation. A constant image maps every sample to alpha.
func PyrDown ¶ added in v0.2.0
PyrDown blurs src with the 5-tap binomial pyramid kernel and drops every other row and column, halving each dimension (rounding up). It is one level of a Gaussian pyramid.
func PyrUp ¶ added in v0.2.0
PyrUp doubles each dimension of src by inserting zero rows and columns and smoothing with a 5-tap Gaussian scaled by 4 (so average brightness is preserved). It is the up-sampling step of a Gaussian pyramid.
func RGBToCMYK ¶ added in v0.6.0
RGBToCMYK converts an 8-bit RGB image to CMYK and returns a 4-channel image whose channels are C, M, Y and K, each scaled to [0,255].
func RGBToGray601 ¶ added in v0.6.0
RGBToGray601 converts an 8-bit RGB image to single-channel grayscale using the ITU-R BT.601 luma weights (0.299, 0.587, 0.114), matching OpenCV's default COLOR_RGB2GRAY.
func RGBToGray709 ¶ added in v0.6.0
RGBToGray709 converts an 8-bit RGB image to single-channel grayscale using the ITU-R BT.709 luma weights (0.2126, 0.7152, 0.0722).
func RGBToHSVFull ¶ added in v0.6.0
RGBToHSVFull converts an 8-bit RGB image to HSV with the hue scaled to the full 0..255 range (rather than 0..179), mirroring cv2.cvtColor with COLOR_RGB2HSV_FULL. Saturation and value also occupy 0..255.
func RGBToXYZ ¶ added in v0.6.0
RGBToXYZ converts an 8-bit RGB image to CIE 1931 XYZ using OpenCV's linear transform matrix, returning a 3-channel image whose channels are X, Y and Z clamped to [0,255]. This mirrors cv2.cvtColor with COLOR_RGB2XYZ.
func RGBToYUV ¶ added in v0.6.0
RGBToYUV converts an 8-bit RGB image to analogue BT.601 Y'UV, with U and V offset by 128 so they fit in [0,255]. This mirrors cv2.cvtColor with COLOR_RGB2YUV.
func Remap ¶ added in v0.2.0
func Remap(src *Mat, mapX, mapY *FloatMat, interp InterpolationFlag) *Mat
Remap resamples src at the per-pixel source coordinates given by mapX and mapY (each a FloatMat of the output size): the destination pixel (x, y) is taken from src at (mapX[y,x], mapY[y,x]) using the chosen interpolation. Out-of-range coordinates yield zero. mapX and mapY must have identical dimensions. It panics otherwise.
func Resize ¶
func Resize(src *Mat, width, height int, interp InterpolationFlag) *Mat
Resize scales src to the given width and height using the chosen interpolation. Both dimensions must be positive.
func Rotate ¶
func Rotate(src *Mat, code RotateCode) *Mat
Rotate performs a lossless 90/180/270-degree rotation and returns a new Mat. For arbitrary angles use GetRotationMatrix2D with WarpAffine.
func Scharr ¶
Scharr computes an image derivative with the 3×3 Scharr operator, which has better rotational symmetry than a 3×3 Sobel. Exactly one of dx, dy must be 1 and the other 0. Results are scaled, offset by delta and clamped to [0,255].
func Sobel ¶
Sobel computes an image derivative using the Sobel operator. dx and dy are the derivative orders (0, 1 or 2, not both zero) and ksize is the aperture (1 or 3). The gradient can be signed; results are scaled by scale, offset by delta and then clamped to [0,255], so callers wanting the true magnitude should combine the x and y results themselves. Use SobelFloat for unclamped output.
func StackBlur ¶ added in v0.6.0
StackBlur blurs src with a fast separable triangular window of the given odd radius-defining size, the same effective kernel as Mario Klingemann's stack blur. Larger ksize yields stronger smoothing. It mirrors cv2.stackBlur and panics on a non-positive odd ksize.
func Subtract ¶ added in v0.2.0
Subtract returns the per-sample difference a-b, saturating at 0. The inputs must have identical dimensions and channel counts.
func Threshold ¶
func Threshold(src *Mat, thresh, maxval float64, typ ThresholdType) (*Mat, float64)
Threshold applies a fixed-level threshold to a single-channel Mat and returns the result together with the threshold that was used. When the ThreshOtsu flag is OR-ed into typ the level argument is ignored and Otsu's optimal value is returned. It panics if src is not single-channel.
Example ¶
m := grayLine(10, 100, 200)
out, used := Threshold(m, 120, 255, ThreshBinary)
fmt.Printf("%v %d\n", out.Data, int(used))
Output: [0 0 255] 120
func Transform ¶ added in v0.5.0
Transform applies a linear transform to the channel vector of every pixel of src. The transform matrix m has one row per output channel and either Channels or Channels+1 columns; the extra column, when present, is a constant (bias) term. The result is a Mat with m.Rows channels, with values rounded and saturated to [0,255]. It panics on a dimension mismatch.
func TriangleThreshold ¶ added in v0.6.0
TriangleThreshold binarises a single-channel image using the triangle algorithm to pick the threshold automatically, mirroring cv2.threshold with THRESH_TRIANGLE. It returns the thresholded image and the chosen level.
func WarpAffine ¶
func WarpAffine(src *Mat, m AffineMatrix, width, height int, interp InterpolationFlag) *Mat
WarpAffine applies the inverse-mapped affine transform m to src, producing an output of the given width and height. Each destination pixel is sampled from src with the chosen interpolation; coordinates outside the source are filled with zero. width and height must be positive.
func WarpPerspective ¶ added in v0.2.0
func WarpPerspective(src *Mat, m PerspectiveMatrix, width, height int, interp InterpolationFlag) *Mat
WarpPerspective applies the projective transform m to src, producing an output of the given width and height. Each destination pixel is inverse-mapped into src and sampled with the chosen interpolation; coordinates outside src are left zero. width and height must be positive and m must be invertible.
func WarpPolar ¶ added in v0.6.0
func WarpPolar(src *Mat, width, height int, centerX, centerY, maxRadius float64, mode WarpPolarMode) *Mat
WarpPolar remaps src into polar coordinates about (centerX, centerY): the output has the given width (angle, 0..2π) and height (radius, 0..maxRadius), sampled bilinearly. It mirrors cv2.warpPolar. It panics on non-positive dimensions or maxRadius.
func XYZToRGB ¶ added in v0.6.0
XYZToRGB is the inverse of RGBToXYZ, converting a 3-channel XYZ image back to 8-bit RGB. It mirrors cv2.cvtColor with COLOR_XYZ2RGB.
func YUVToRGB ¶ added in v0.6.0
YUVToRGB is the inverse of RGBToYUV, converting a 3-channel Y'UV image back to 8-bit RGB. It mirrors cv2.cvtColor with COLOR_YUV2RGB.
func (*Mat) At ¶
At returns the sample at row y, column x and channel c. It panics if the coordinates are out of range, mirroring a Go slice index.
func (*Mat) CopyTo ¶
CopyTo writes this Mat into dst so that its top-left sample lands at column x, row y of dst. Samples that fall outside dst are clipped. It panics if the channel counts differ.
func (*Mat) Region ¶
Region returns a deep-copied sub-matrix (region of interest) covering the half-open rectangle [x, x+width) × [y, y+height). Unlike OpenCV's ROI, which shares memory with the parent, the returned Mat is independent. It panics if the rectangle is empty or extends outside the source.
func (*Mat) Set ¶
Set stores value at row y, column x and channel c. It panics if the coordinates are out of range.
func (*Mat) SetPixel ¶
SetPixel stores every channel sample of pixel (x, y). It panics if values does not have exactly Channels elements or the coordinates are out of range.
func (*Mat) Split ¶
Split separates a multi-channel Mat into a slice of single-channel Mats, one per channel, in channel order.
type Moments ¶ added in v0.2.0
type Moments struct {
M00, M10, M01, M20, M11, M02, M30, M21, M12, M03 float64
Mu20, Mu11, Mu02, Mu30, Mu21, Mu12, Mu03 float64
Nu20, Nu11, Nu02, Nu30, Nu21, Nu12, Nu03 float64
}
Moments holds the spatial, central and normalised central moments of an image up to third order, mirroring OpenCV's cv::Moments. Spatial moments are Mpq, central moments (translation invariant) are Mupq and normalised central moments (scale invariant) are Nupq.
func ImageMoments ¶ added in v0.2.0
ImageMoments computes the moments of a single-channel image, weighting each pixel (x, y) by its sample value. For a binary mask this yields geometric moments of the white region. It panics if src is not single-channel.
type MorphShape ¶
type MorphShape int
MorphShape selects the shape of a structuring element built by GetStructuringElement.
const ( // MorphRect is a filled rectangle: every element is set. MorphRect MorphShape = iota // MorphCross is a plus/cross: only the centre row and column are set. MorphCross // MorphEllipse is a filled ellipse inscribed in the element rectangle. MorphEllipse )
type MorphType ¶
type MorphType int
MorphType selects the compound operation performed by MorphologyEx.
const ( // MorphErode is a plain erosion. MorphErode MorphType = iota // MorphDilate is a plain dilation. MorphDilate // MorphOpen is erosion followed by dilation; it removes small bright specks. MorphOpen // MorphClose is dilation followed by erosion; it fills small dark holes. MorphClose // MorphGradient is dilation minus erosion; it highlights edges. MorphGradient // MorphTophat is source minus its opening; it isolates small bright details. MorphTophat // MorphBlackhat is the closing minus the source; it isolates small dark // details. MorphBlackhat )
type PerspectiveMatrix ¶ added in v0.2.0
type PerspectiveMatrix [9]float64
PerspectiveMatrix is a 3×3 projective transform stored row-major (h0..h8). It maps a source point (x, y) to (x', y') where
w = h6*x + h7*y + h8 x' = (h0*x + h1*y + h2) / w y' = (h3*x + h4*y + h5) / w
func GetPerspectiveTransform ¶ added in v0.2.0
func GetPerspectiveTransform(src, dst [4]Point) PerspectiveMatrix
GetPerspectiveTransform computes the 3×3 homography that maps the four source points src to the four destination points dst, solving the resulting 8×8 linear system (with h8 fixed to 1). The four points in each set should be in corresponding order and no three collinear. It panics if the system is singular.
Example ¶
// Map a quad onto a 100x100 axis-aligned square and check a corner lands.
src := [4]Point{{20, 20}, {80, 30}, {75, 85}, {25, 75}}
dst := [4]Point{{0, 0}, {100, 0}, {100, 100}, {0, 100}}
m := GetPerspectiveTransform(src, dst)
w := m[6]*80 + m[7]*30 + m[8]
fmt.Printf("%.0f,%.0f\n", (m[0]*80+m[1]*30+m[2])/w, (m[3]*80+m[4]*30+m[5])/w)
Output: 100,0
type Point ¶
Point is an integer image coordinate (x is the column, y is the row).
func ApproxPolyDP ¶ added in v0.2.0
ApproxPolyDP simplifies a curve with the Douglas–Peucker algorithm, dropping points that lie within epsilon of the retained polyline. Larger epsilon yields a coarser approximation. When closed is true the curve is treated as a closed polygon.
func ConvexHull ¶ added in v0.2.0
ConvexHull computes the convex hull of a set of points with Andrew's monotone chain algorithm and returns its vertices in counter-clockwise order (in image coordinates, where y grows downward). Duplicate and collinear interior points are removed. Fewer than three input points are returned as-is (deduplicated).
func Ellipse2Poly ¶ added in v0.5.0
func Ellipse2Poly(center Point, axesX, axesY int, angle, arcStart, arcEnd float64, delta int) []Point
Ellipse2Poly approximates an elliptical arc with a polyline. The ellipse is centred at center with semi-axes axesX and axesY, rotated by angle degrees; the arc spans from arcStart to arcEnd degrees and is sampled every delta degrees. It mirrors cv::ellipse2Poly.
func FASTCorners ¶ added in v0.2.0
FASTCorners detects corners with the FAST-9 algorithm on a single-channel image: a pixel is a corner when at least 9 contiguous pixels on the radius-3 Bresenham circle are all brighter than the centre plus threshold or all darker than the centre minus threshold. When nonmaxSuppression is true, corners that are not the strongest (by summed absolute contrast) within their 3×3 neighbourhood are discarded. It panics if src is not single-channel.
func FindNonZero ¶ added in v0.5.0
FindNonZero returns the coordinates of every non-zero sample in a single-channel Mat, in row-major order. It panics if src is not single-channel.
func GetTextSize ¶ added in v0.5.0
GetTextSize returns the bounding box (width, height) of text rendered with PutText at the given integer scale, together with the baseline offset below the box. The width and height are exact for the built-in 5×7 bitmap font. It mirrors cv::getTextSize.
func GoodFeaturesToTrack ¶ added in v0.2.0
func GoodFeaturesToTrack(src *Mat, maxCorners int, qualityLevel, minDistance float64, blockSize int) []Point
GoodFeaturesToTrack finds strong corners with the Shi–Tomasi measure (the smaller eigenvalue of the windowed structure tensor). Corners weaker than qualityLevel times the strongest are discarded, the survivors are taken in descending strength, and each accepted corner suppresses others within minDistance. At most maxCorners points are returned (all of them when maxCorners <= 0). blockSize is the tensor window size. It panics if src is not single-channel.
type Point2f ¶ added in v0.5.0
Point2f is a floating-point image coordinate (x is the column, y is the row), the analogue of OpenCV's cv::Point2f.
func BoxPoints ¶ added in v0.5.0
func BoxPoints(r RotatedRect) [4]Point2f
BoxPoints returns the four corner points of a rotated rectangle as floating-point coordinates, in the order bottom-left, top-left, top-right, bottom-right (matching OpenCV's cv::boxPoints convention where y grows downward).
func MinEnclosingCircle ¶ added in v0.5.0
MinEnclosingCircle returns the centre and radius of the smallest circle that encloses every input point, computed with Welzl's randomised algorithm (run deterministically over the given order). It panics on an empty point set.
func PerspectiveTransform ¶ added in v0.5.0
func PerspectiveTransform(pts []Point2f, m PerspectiveMatrix) []Point2f
PerspectiveTransform applies a 3×3 projective transform to a slice of floating-point points, dividing by the homogeneous coordinate, matching OpenCV's cv::perspectiveTransform for 2-D points.
type PolarLine ¶ added in v0.2.0
PolarLine is a line in Hesse normal form: the set of points (x, y) with x*cos(Theta) + y*sin(Theta) = Rho. Rho is in pixels and Theta in radians, matching the output of HoughLines.
func HoughLines ¶ added in v0.2.0
HoughLines detects lines in a binary edge image with the standard Hough transform. It accumulates votes over a (rho, theta) grid quantised by rhoStep (pixels) and thetaStep (radians), then returns every accumulator peak — a local maximum whose vote count is at least threshold — as a PolarLine, sorted by descending votes. It panics if src is not single-channel.
type Rect ¶ added in v0.2.0
Rect is an axis-aligned rectangle with an integer top-left corner (X, Y) and a Width and Height in pixels, matching OpenCV's cv::Rect.
func BoundingRect ¶ added in v0.2.0
BoundingRect returns the smallest upright rectangle that contains every point. Width and Height count pixels inclusively, so a single point yields a 1×1 rectangle. It panics on an empty point set.
type ReduceOp ¶ added in v0.5.0
type ReduceOp int
ReduceOp selects the accumulation performed by Reduce.
type RetrievalMode ¶ added in v0.2.0
type RetrievalMode int
RetrievalMode selects which contours FindContours returns and how their hierarchy is built, mirroring OpenCV's RETR_* modes.
const ( // RetrExternal returns only the outermost contours, discarding any holes // nested inside them. Every returned entry has no parent. RetrExternal RetrievalMode = iota // RetrList returns every contour (outer borders and holes) as a flat list // with no parent/child relationships recorded. RetrList // RetrTree returns every contour and reconstructs the full nesting tree in // the hierarchy (parent, child and sibling links). RetrTree )
type RotateCode ¶
type RotateCode int
RotateCode selects one of the three lossless right-angle rotations for Rotate.
const ( // Rotate90CW rotates 90° clockwise. Rotate90CW RotateCode = iota // Rotate180 rotates 180°. Rotate180 // Rotate90CCW rotates 90° counter-clockwise (270° clockwise). Rotate90CCW )
type RotatedRect ¶ added in v0.2.0
type RotatedRect struct {
CenterX float64
CenterY float64
Width float64
Height float64
Angle float64
}
RotatedRect is a rectangle that may be rotated about its centre, matching OpenCV's cv::RotatedRect. The centre is in fractional pixel coordinates, Width and Height are the side lengths, and Angle is the rotation in degrees.
func MinAreaRect ¶ added in v0.2.0
func MinAreaRect(pts []Point) RotatedRect
MinAreaRect returns the minimum-area rotated rectangle enclosing the points, found by rotating calipers over the convex hull: for each hull edge the axis-aligned bounding box in that edge's frame is measured and the smallest is kept. It panics on an empty point set.
func (RotatedRect) Points ¶ added in v0.2.0
func (r RotatedRect) Points() [4]Point
Points returns the four corner points of the rotated rectangle in order, rounded to the nearest pixel.
type Scalar ¶
type Scalar [4]float64
Scalar is a colour with up to four components, matching cv2's Scalar. When drawing on a Mat only the first Channels components are used; RGB images interpret the components as (R, G, B).
func Mean ¶ added in v0.6.0
Mean returns the per-channel average of all samples in m as a Scalar (unused channels are zero), mirroring cv2.mean. It panics on an empty matrix.
func MeanStdDev ¶ added in v0.6.0
MeanStdDev returns the per-channel mean and (population) standard deviation of m, mirroring cv2.meanStdDev. It panics on an empty matrix.
type TemplateMatchMode ¶
type TemplateMatchMode int
TemplateMatchMode selects the similarity measure used by MatchTemplate.
const ( // TmSqdiff is the sum of squared differences; the best match is the // minimum (0 is a perfect match). TmSqdiff TemplateMatchMode = iota // TmSqdiffNormed is the normalised sum of squared differences in [0,1]; // the best match is the minimum. TmSqdiffNormed // TmCcoeff is the correlation coefficient (covariance of mean-subtracted // patches); the best match is the maximum. TmCcoeff // TmCcoeffNormed is the normalised correlation coefficient in [-1,1]; the // best match is the maximum. TmCcoeffNormed )
type ThresholdType ¶
type ThresholdType int
ThresholdType selects the behaviour of Threshold. It may be combined with ThreshOtsu using a bitwise OR to have the threshold chosen automatically.
const ( // ThreshBinary sets samples above the threshold to maxval, others to 0. ThreshBinary ThresholdType = iota // ThreshBinaryInv sets samples above the threshold to 0, others to maxval. ThreshBinaryInv // ThreshTrunc clamps samples above the threshold to the threshold value. ThreshTrunc // ThreshToZero zeroes samples at or below the threshold, keeps the rest. ThreshToZero // ThreshToZeroInv zeroes samples above the threshold, keeps the rest. ThreshToZeroInv )
const ThreshOtsu ThresholdType = 8
ThreshOtsu is an OR-able flag that makes Threshold ignore the supplied level and compute an optimal global threshold with Otsu's method. It is only meaningful for single-channel input.
type WarpPolarMode ¶ added in v0.6.0
type WarpPolarMode int
WarpPolarMode selects linear or semi-log radial mapping for WarpPolar.
const ( // WarpPolarLinear maps radius linearly to the output rows. WarpPolarLinear WarpPolarMode = iota // WarpPolarLog maps radius logarithmically (log-polar). WarpPolarLog )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package aruco provides square fiducial marker generation and detection on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package aruco provides square fiducial marker generation and detection on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package barcode provides 1D and 2D barcode generation and detection on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package barcode provides 1D and 2D barcode generation and detection on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package bgsegm is a from-scratch, standard-library-only port of a useful subset of OpenCV's background-segmentation module (bgsegm plus the two subtractors that live in the core video module).
|
Package bgsegm is a from-scratch, standard-library-only port of a useful subset of OpenCV's background-segmentation module (bgsegm plus the two subtractors that live in the core video module). |
|
Package bioinspired is a from-scratch, standard-library-only port of a useful subset of OpenCV's bioinspired contrib module: biologically-inspired (retina) vision models.
|
Package bioinspired is a from-scratch, standard-library-only port of a useful subset of OpenCV's bioinspired contrib module: biologically-inspired (retina) vision models. |
|
Package calib2 is a pure standard-library implementation of camera calibration and multi-view 3D geometry, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package calib2 is a pure standard-library implementation of camera calibration and multi-view 3D geometry, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package calib3d is a standard-library-only implementation of the classic camera-geometry and multi-view routines from OpenCV's calib3d module, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package calib3d is a standard-library-only implementation of the classic camera-geometry and multi-view routines from OpenCV's calib3d module, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package ccalib is a standard-library-only port of OpenCV's ccalib module — custom calibration patterns and the omnidirectional (fisheye / catadioptric) camera model — built on top of the root cv package (github.com/malcolmston/opencv).
|
Package ccalib is a standard-library-only port of OpenCV's ccalib module — custom calibration patterns and the omnidirectional (fisheye / catadioptric) camera model — built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package colorspaces2 provides extended colour-science utilities that build on the root cv package's cv.Mat image type.
|
Package colorspaces2 provides extended colour-science utilities that build on the root cv package's cv.Mat image type. |
|
Package connected provides connected-component analysis for binary images, built entirely on the parent module's github.com/malcolmston/opencv.Mat type and the Go standard library.
|
Package connected provides connected-component analysis for binary images, built entirely on the parent module's github.com/malcolmston/opencv.Mat type and the Go standard library. |
|
Package contours2 provides contour extraction and shape analysis for the github.com/malcolmston/opencv library.
|
Package contours2 provides contour extraction and shape analysis for the github.com/malcolmston/opencv library. |
|
Package core provides the small fixed-size value types from OpenCV's core module — the concrete point, vector, matrix, size, rectangle and helper types that cv2 exposes as templated typedefs (cv::Point_, cv::Point3_, cv::Size_, cv::Rect_, cv::Vec, cv::Matx, cv::Scalar, cv::Complex, cv::Range, cv::RotatedRect, cv::KeyPoint, cv::DMatch and cv::TermCriteria).
|
Package core provides the small fixed-size value types from OpenCV's core module — the concrete point, vector, matrix, size, rectangle and helper types that cv2 exposes as templated typedefs (cv::Point_, cv::Point3_, cv::Size_, cv::Rect_, cv::Vec, cv::Matx, cv::Scalar, cv::Complex, cv::Range, cv::RotatedRect, cv::KeyPoint, cv::DMatch and cv::TermCriteria). |
|
Package cudaarithm is a CPU-backed, API-compatible mirror of OpenCV's cudaarithm module.
|
Package cudaarithm is a CPU-backed, API-compatible mirror of OpenCV's cudaarithm module. |
|
Package cudabgsegm is a CPU-backed, API-compatible mirror of OpenCV's cudabgsegm module — the GPU background-segmentation subtractors that in upstream OpenCV live under the cv::cuda namespace (createBackgroundSubtractorMOG, createBackgroundSubtractorMOG2, createBackgroundSubtractorGMG and createBackgroundSubtractorFGD).
|
Package cudabgsegm is a CPU-backed, API-compatible mirror of OpenCV's cudabgsegm module — the GPU background-segmentation subtractors that in upstream OpenCV live under the cv::cuda namespace (createBackgroundSubtractorMOG, createBackgroundSubtractorMOG2, createBackgroundSubtractorGMG and createBackgroundSubtractorFGD). |
|
Package cudacodec is a CPU-backed, API-compatible mirror of OpenCV's cudacodec module for the cv image toolkit (github.com/malcolmston/opencv).
|
Package cudacodec is a CPU-backed, API-compatible mirror of OpenCV's cudacodec module for the cv image toolkit (github.com/malcolmston/opencv). |
|
Package cudacore is a CPU-backed, API-compatible mirror of the core cuda submodule of OpenCV (the cv::cuda names declared in core/cuda.hpp): device management and the GpuMat device-matrix container.
|
Package cudacore is a CPU-backed, API-compatible mirror of the core cuda submodule of OpenCV (the cv::cuda names declared in core/cuda.hpp): device management and the GpuMat device-matrix container. |
|
Package cudafeatures2d is a CPU-backed, API-compatible mirror of OpenCV's cudafeatures2d module for the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package cudafeatures2d is a CPU-backed, API-compatible mirror of OpenCV's cudafeatures2d module for the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package cudafilters is a pure-Go, CPU-backed, API-compatible mirror of OpenCV's cudafilters module.
|
Package cudafilters is a pure-Go, CPU-backed, API-compatible mirror of OpenCV's cudafilters module. |
|
Package cudaimgproc is a pure-Go, standard-library-only mirror of OpenCV's cudaimgproc module.
|
Package cudaimgproc is a pure-Go, standard-library-only mirror of OpenCV's cudaimgproc module. |
|
Package cudalegacy is a CPU-backed, API-compatible mirror of OpenCV's cudalegacy module — the grab-bag of "device functions" and legacy NPP/NCV helpers that historically lived under the cv::cuda and NCV namespaces (background subtraction, image pyramids, connected-component labelling on the device, block-matching optical flow, motion-compensated frame interpolation, needle-map visualisation, graph-cut segmentation and planar pose estimation).
|
Package cudalegacy is a CPU-backed, API-compatible mirror of OpenCV's cudalegacy module — the grab-bag of "device functions" and legacy NPP/NCV helpers that historically lived under the cv::cuda and NCV namespaces (background subtraction, image pyramids, connected-component labelling on the device, block-matching optical flow, motion-compensated frame interpolation, needle-map visualisation, graph-cut segmentation and planar pose estimation). |
|
Package cudaobjdetect is a CPU-backed, API-compatible mirror of OpenCV's cv::cuda objdetect module (opencv_contrib's cudaobjdetect).
|
Package cudaobjdetect is a CPU-backed, API-compatible mirror of OpenCV's cv::cuda objdetect module (opencv_contrib's cudaobjdetect). |
|
Package cudaoptflow is a CPU-backed, API-compatible mirror of OpenCV's cudaoptflow module (cv::cuda dense and sparse optical flow).
|
Package cudaoptflow is a CPU-backed, API-compatible mirror of OpenCV's cudaoptflow module (cv::cuda dense and sparse optical flow). |
|
Package cudastereo is a standard-library-only, CPU-backed mirror of OpenCV's cudastereo module (cv::cuda stereo correspondence).
|
Package cudastereo is a standard-library-only, CPU-backed mirror of OpenCV's cudastereo module (cv::cuda stereo correspondence). |
|
Package cudawarping is a CPU-backed, API-compatible mirror of OpenCV's cudawarping module (the cv::cuda geometric image transformations) built on the standard-library-only OpenCV port github.com/malcolmston/opencv, imported here as cv.
|
Package cudawarping is a CPU-backed, API-compatible mirror of OpenCV's cudawarping module (the cv::cuda geometric image transformations) built on the standard-library-only OpenCV port github.com/malcolmston/opencv, imported here as cv. |
|
Package datamatrix is a self-contained, dependency-free ECC200 Data Matrix codec for the stdlib-only OpenCV port.
|
Package datamatrix is a self-contained, dependency-free ECC200 Data Matrix codec for the stdlib-only OpenCV port. |
|
Package dnn is a small, standard-library-only feed-forward neural-network inference engine, a from-scratch port of a useful subset of OpenCV's dnn module.
|
Package dnn is a small, standard-library-only feed-forward neural-network inference engine, a from-scratch port of a useful subset of OpenCV's dnn module. |
|
Package dnn_superres is a pure-Go, standard-library-only single-image super-resolution toolkit built on top of the OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package dnn_superres is a pure-Go, standard-library-only single-image super-resolution toolkit built on top of the OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
docs
|
|
|
gen
command
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser).
|
Command gendocs generates a static HTML documentation site for a Go module using only the standard library (go/doc, go/parser). |
|
Package draw2 provides a self-contained 2-D drawing and rendering toolkit for the parent computer-vision library's Mat image type.
|
Package draw2 provides a self-contained 2-D drawing and rendering toolkit for the parent computer-vision library's Mat image type. |
|
Package edges2 is a standard-library-only toolkit of edge, line and circle detection built on top of the parent package's github.com/malcolmston/opencv.Mat image type.
|
Package edges2 is a standard-library-only toolkit of edge, line and circle detection built on top of the parent package's github.com/malcolmston/opencv.Mat image type. |
|
Command examples demonstrates the cv package end-to-end: it synthesises a small colour image, converts it to grayscale, blurs it, runs Canny edge detection, annotates a copy with a rectangle and label, and writes each intermediate result to a PNG file in the working directory.
|
Command examples demonstrates the cv package end-to-end: it synthesises a small colour image, converts it to grayscale, blurs it, runs Canny edge detection, annotates a copy with a rectangle and label, and writes each intermediate result to a PNG file in the working directory. |
|
Package face is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib face module: classic (non-neural) face recognition.
|
Package face is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib face module: classic (non-neural) face recognition. |
|
Package features2d provides 2D feature detection, description and matching on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package features2d provides 2D feature detection, description and matching on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package features3 provides classic feature detection and description primitives on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package features3 provides classic feature detection and description primitives on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package filters2 is a standard-library-only collection of advanced image filtering, denoising and multi-scale analysis routines built on top of the parent package's github.com/malcolmston/opencv.Mat image type.
|
Package filters2 is a standard-library-only collection of advanced image filtering, denoising and multi-scale analysis routines built on top of the parent package's github.com/malcolmston/opencv.Mat image type. |
|
Package flann is a from-scratch, standard-library-only port of a useful subset of OpenCV's flann module: FLANN, "Fast Library for Approximate Nearest Neighbors".
|
Package flann is a from-scratch, standard-library-only port of a useful subset of OpenCV's flann module: FLANN, "Fast Library for Approximate Nearest Neighbors". |
|
Package freqdomain provides frequency-domain image processing on top of the parent cv package's image types.
|
Package freqdomain provides frequency-domain image processing on top of the parent cv package's image types. |
|
Package fuzzy is a standard-library-only implementation of fuzzy (F-)transform image processing built on the root cv package (github.com/malcolmston/opencv).
|
Package fuzzy is a standard-library-only implementation of fuzzy (F-)transform image processing built on the root cv package (github.com/malcolmston/opencv). |
|
Package gapi is a pure-Go port of OpenCV's G-API (graph API) module built on the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package gapi is a pure-Go port of OpenCV's G-API (graph API) module built on the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package geom_cv provides computational-geometry primitives that are useful for computer vision, built entirely on the Go standard library and on the core types of the parent github.com/malcolmston/opencv package.
|
Package geom_cv provides computational-geometry primitives that are useful for computer vision, built entirely on the Go standard library and on the core types of the parent github.com/malcolmston/opencv package. |
|
Package hdr is a standard-library-only implementation of the high-dynamic-range imaging pipeline from OpenCV's photo module, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package hdr is a standard-library-only implementation of the high-dynamic-range imaging pipeline from OpenCV's photo module, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package hfs is a pure-Go port of OpenCV's hfs module (Hierarchical Feature Selection for efficient image segmentation) built on the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package hfs is a pure-Go port of OpenCV's hfs module (Hierarchical Feature Selection for efficient image segmentation) built on the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package histogram2 provides a pure-Go, standard-library-only toolkit of classic histogram-based computer-vision routines built on top of the parent package's cv.Mat image type.
|
Package histogram2 provides a pure-Go, standard-library-only toolkit of classic histogram-based computer-vision routines built on top of the parent package's cv.Mat image type. |
|
Package imghash is a from-scratch, standard-library-only port of a useful subset of OpenCV's img_hash contrib module: perceptual image hashing.
|
Package imghash is a from-scratch, standard-library-only port of a useful subset of OpenCV's img_hash contrib module: perceptual image hashing. |
|
Package imghash2 implements perceptual image hashing on top of the parent module's cv.Mat image type, using only the Go standard library.
|
Package imghash2 implements perceptual image hashing on top of the parent module's cv.Mat image type, using only the Go standard library. |
|
Package imgprocx provides extended geometric and frequency-domain image processing on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package imgprocx provides extended geometric and frequency-domain image processing on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package inpaint is a standard-library-only image inpainting, restoration and gradient-domain editing toolkit built on top of the root cv package (github.com/malcolmston/opencv).
|
Package inpaint is a standard-library-only image inpainting, restoration and gradient-domain editing toolkit built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package intensity is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib intensity_transform module, together with a small set of classic point operations and a low-light tone-mapping pipeline.
|
Package intensity is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib intensity_transform module, together with a small set of classic point operations and a low-light tone-mapping pipeline. |
|
Package linedescriptor is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib module line_descriptor.
|
Package linedescriptor is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib module line_descriptor. |
|
Package matching2 implements descriptor matching and multiple-view geometry on top of the parent cv module, using only the Go standard library.
|
Package matching2 implements descriptor matching and multiple-view geometry on top of the parent cv module, using only the Go standard library. |
|
Package mcc provides Macbeth/ColorChecker chart detection and color correction on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package mcc provides Macbeth/ColorChecker chart detection and color correction on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package ml is a from-scratch, standard-library-only port of a useful subset of OpenCV's ml module: classic (non-neural) machine-learning models for statistical classification, regression and clustering.
|
Package ml is a from-scratch, standard-library-only port of a useful subset of OpenCV's ml module: classic (non-neural) machine-learning models for statistical classification, regression and clustering. |
|
Package ml2 is a from-scratch, standard-library-only toolkit of classic (non-neural) machine-learning models aimed at computer-vision workflows: classification, regression, clustering and dimensionality reduction over feature vectors extracted from images.
|
Package ml2 is a from-scratch, standard-library-only toolkit of classic (non-neural) machine-learning models aimed at computer-vision workflows: classification, regression, clustering and dimensionality reduction over feature vectors extracted from images. |
|
Package moments2 provides image moments and shape descriptors for the github.com/malcolmston/opencv library.
|
Package moments2 provides image moments and shape descriptors for the github.com/malcolmston/opencv library. |
|
Package morph2 is a standard-library-only toolkit of advanced mathematical morphology built on top of the parent package's github.com/malcolmston/opencv.Mat image type.
|
Package morph2 is a standard-library-only toolkit of advanced mathematical morphology built on top of the parent package's github.com/malcolmston/opencv.Mat image type. |
|
Package objdetect provides classic, learning-free object-detection tooling for the parent github.com/malcolmston/opencv package: a Histogram of Oriented Gradients (HOG) descriptor with a linear-SVM sliding-window detector, a Viola–Jones Haar cascade classifier that reads OpenCV's XML cascade files, and a QR-code finder-pattern locator.
|
Package objdetect provides classic, learning-free object-detection tooling for the parent github.com/malcolmston/opencv package: a Histogram of Oriented Gradients (HOG) descriptor with a linear-SVM sliding-window detector, a Viola–Jones Haar cascade classifier that reads OpenCV's XML cascade files, and a QR-code finder-pattern locator. |
|
Package optflow implements extended and dense optical-flow algorithms on top of the root cv package, mirroring a useful subset of OpenCV's contrib optflow module.
|
Package optflow implements extended and dense optical-flow algorithms on top of the root cv package, mirroring a useful subset of OpenCV's contrib optflow module. |
|
Package phase_unwrapping implements two-dimensional phase unwrapping on top of the root cv package, mirroring a useful subset of OpenCV's phase_unwrapping contrib module (whose principal class is HistogramPhaseUnwrapping).
|
Package phase_unwrapping implements two-dimensional phase unwrapping on top of the root cv package, mirroring a useful subset of OpenCV's phase_unwrapping contrib module (whose principal class is HistogramPhaseUnwrapping). |
|
Package photo is a standard-library-only computational-photography toolkit built on top of the root cv package (github.com/malcolmston/opencv).
|
Package photo is a standard-library-only computational-photography toolkit built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package photo2 is a standard-library-only computational-photography toolkit built on the root cv package (github.com/malcolmston/opencv).
|
Package photo2 is a standard-library-only computational-photography toolkit built on the root cv package (github.com/malcolmston/opencv). |
|
Package plot provides 2-D data plotting and intensity colormaps for the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package plot provides 2-D data plotting and intensity colormaps for the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package pyramids implements image pyramids and scale-space machinery on top of the parent cv module's image types.
|
Package pyramids implements image pyramids and scale-space machinery on top of the parent cv module's image types. |
|
Package quality is a from-scratch, standard-library-only port of a useful subset of OpenCV's quality module: objective image-quality assessment (IQA) metrics.
|
Package quality is a from-scratch, standard-library-only port of a useful subset of OpenCV's quality module: objective image-quality assessment (IQA) metrics. |
|
Package rapid is a standard-library-only port of OpenCV's rapid module for real-time silhouette-based 3D pose tracking, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package rapid is a standard-library-only port of OpenCV's rapid module for real-time silhouette-based 3D pose tracking, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package rgbd is a standard-library-only implementation of the depth-map and point-cloud routines from OpenCV's contrib rgbd module, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package rgbd is a standard-library-only implementation of the depth-map and point-cloud routines from OpenCV's contrib rgbd module, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package saliency is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib saliency module: algorithms that highlight the regions of an image (or video) most likely to draw human visual attention.
|
Package saliency is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib saliency module: algorithms that highlight the regions of an image (or video) most likely to draw human visual attention. |
|
Package saliency2 is a standard-library-only toolkit of visual saliency and attention algorithms built on top of the parent cv package's cv.Mat image type.
|
Package saliency2 is a standard-library-only toolkit of visual saliency and attention algorithms built on top of the parent cv package's cv.Mat image type. |
|
Package segment2 provides image-segmentation algorithms built on the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package segment2 provides image-segmentation algorithms built on the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package segmentation provides region-based image segmentation built on the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package segmentation provides region-based image segmentation built on the stdlib-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package shape provides shape descriptors, fitting and matching built on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package shape provides shape descriptors, fitting and matching built on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package shapefit provides geometric primitive fitting and Hough-transform shape detection for point sets and binary edge images.
|
Package shapefit provides geometric primitive fitting and Hough-transform shape detection for point sets and binary edge images. |
|
Package stereo is a standard-library-only implementation of the classic stereo-correspondence and disparity routines from OpenCV's calib3d and contrib stereo modules, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package stereo is a standard-library-only implementation of the classic stereo-correspondence and disparity routines from OpenCV's calib3d and contrib stereo modules, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package stereo2 is a self-contained, standard-library-only toolkit for binocular stereo vision and depth reconstruction, built on top of the core github.com/malcolmston/opencv package.
|
Package stereo2 is a self-contained, standard-library-only toolkit for binocular stereo vision and depth reconstruction, built on top of the core github.com/malcolmston/opencv package. |
|
Package stitch implements image stitching and panorama construction on top of the core github.com/malcolmston/opencv image types, using only the Go standard library.
|
Package stitch implements image stitching and panorama construction on top of the core github.com/malcolmston/opencv image types, using only the Go standard library. |
|
Package stitching assembles overlapping images into a single panorama on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package stitching assembles overlapping images into a single panorama on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package structured_light is a standard-library-only implementation of the structured-light pattern generation and decoding routines from OpenCV's contrib "structured_light" module, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package structured_light is a standard-library-only implementation of the structured-light pattern generation and decoding routines from OpenCV's contrib "structured_light" module, built on top of the root cv package (github.com/malcolmston/opencv). |
|
Package superres is a pure-Go, standard-library-only toolkit for image super-resolution, high-quality interpolation and the supporting building blocks those techniques need.
|
Package superres is a pure-Go, standard-library-only toolkit for image super-resolution, high-quality interpolation and the supporting building blocks those techniques need. |
|
Package surface_matching is a standard-library-only implementation of 3-D surface matching by Point-Pair Features (PPF), mirroring the algorithm of OpenCV's contrib surface_matching module (Drost, Ulrich, Navab & Ilic, "Model Globally, Match Locally: Efficient and Robust 3D Object Recognition", CVPR 2010).
|
Package surface_matching is a standard-library-only implementation of 3-D surface matching by Point-Pair Features (PPF), mirroring the algorithm of OpenCV's contrib surface_matching module (Drost, Ulrich, Navab & Ilic, "Model Globally, Match Locally: Efficient and Robust 3D Object Recognition", CVPR 2010). |
|
Package template2 implements classic template matching on top of the parent package's cv.Mat image type.
|
Package template2 implements classic template matching on top of the parent package's cv.Mat image type. |
|
Package text is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib text module: classical scene-text detection on top of the grayscale-and-contours machinery in github.com/malcolmston/opencv (imported here as cv).
|
Package text is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib text module: classical scene-text detection on top of the grayscale-and-contours machinery in github.com/malcolmston/opencv (imported here as cv). |
|
Package textdet implements classical (non-neural) text-detection and document-analysis primitives on top of the parent module's cv.Mat image type.
|
Package textdet implements classical (non-neural) text-detection and document-analysis primitives on top of the parent module's cv.Mat image type. |
|
Package texture implements classic image-texture analysis on top of the root package's cv.Mat image type, using only the Go standard library.
|
Package texture implements classic image-texture analysis on top of the root package's cv.Mat image type, using only the Go standard library. |
|
Package threshold2 implements image thresholding and binarization algorithms on top of the parent package's cv.Mat image type.
|
Package threshold2 implements image thresholding and binarization algorithms on top of the parent package's cv.Mat image type. |
|
Package tracking implements classical, CPU-only computer-vision tracking and motion-estimation algorithms on top of the root cv package (github.com/malcolmston/opencv, imported as cv).
|
Package tracking implements classical, CPU-only computer-vision tracking and motion-estimation algorithms on top of the root cv package (github.com/malcolmston/opencv, imported as cv). |
|
Package transforms2 implements pure-Go geometric image transformations for the parent cv package, operating on its cv.Mat (8-bit, channel-interleaved) and cv.FloatMat types.
|
Package transforms2 implements pure-Go geometric image transformations for the parent cv package, operating on its cv.Mat (8-bit, channel-interleaved) and cv.FloatMat types. |
|
Package video implements motion-analysis and tracking primitives on top of the root cv package, mirroring a useful subset of OpenCV's video module.
|
Package video implements motion-analysis and tracking primitives on top of the root cv package, mirroring a useful subset of OpenCV's video module. |
|
Package videoio provides a small, standard-library-only "video" layer for the cv image-processing toolkit (github.com/malcolmston/opencv).
|
Package videoio provides a small, standard-library-only "video" layer for the cv image-processing toolkit (github.com/malcolmston/opencv). |
|
Package videoproc implements temporal (video) computer-vision primitives on top of the root cv package (github.com/malcolmston/opencv), mirroring a useful subset of OpenCV's video, bgsegm and optflow modules.
|
Package videoproc implements temporal (video) computer-vision primitives on top of the root cv package (github.com/malcolmston/opencv), mirroring a useful subset of OpenCV's video, bgsegm and optflow modules. |
|
Package videostab is a pure-Go port of a working subset of OpenCV's videostab module: global-motion estimation, camera-trajectory smoothing and the one-pass / two-pass video stabilization pipelines, together with the supporting border-inpainting and deblurring stages.
|
Package videostab is a pure-Go port of a working subset of OpenCV's videostab module: global-motion estimation, camera-trajectory smoothing and the one-pass / two-pass video stabilization pipelines, together with the supporting border-inpainting and deblurring stages. |
|
Package xfeatures2d provides additional ("contrib") 2D feature detectors and descriptors on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
|
Package xfeatures2d provides additional ("contrib") 2D feature detectors and descriptors on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv). |
|
Package ximgproc is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib module ximgproc ("extended image processing").
|
Package ximgproc is a from-scratch, standard-library-only port of a useful subset of OpenCV's contrib module ximgproc ("extended image processing"). |
|
Package xobjdetect is a pure-Go port of OpenCV's xobjdetect module: a WaldBoost object detector built on integral-channel (ACF-style) features.
|
Package xobjdetect is a pure-Go port of OpenCV's xobjdetect module: a WaldBoost object detector built on integral-channel (ACF-style) features. |
|
Package xphoto is a standard-library-only port of a useful subset of OpenCV's xphoto contrib module, built on top of the root cv package (github.com/malcolmston/opencv).
|
Package xphoto is a standard-library-only port of a useful subset of OpenCV's xphoto contrib module, built on top of the root cv package (github.com/malcolmston/opencv). |