cv

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 10 Imported by: 0

README

opencv

Go Test Go Lint Go Vuln Go Reference Go Report Card Go Version Release

A standard-library-only Go port of OpenCV — image processing & computer vision with zero dependencies.

What it is

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. It is written entirely against the Go standard library — image, image/color, image/png, image/jpeg, math and friends — with no cgo and no third-party dependencies, so it builds and runs anywhere the Go toolchain does.

The central data structure is Mat, a dense row-major matrix of 8-bit unsigned samples backed by a flat []uint8. One-channel (grayscale) and three-channel (RGB) images are the common cases; convert to and from the standard library with FromImage / Mat.ToImage, and read or write PNG/JPEG with ImRead / ImWrite.

Installation

go get github.com/malcolmston/opencv
import cv "github.com/malcolmston/opencv"

The module path is github.com/malcolmston/opencv; the package name is cv.

Quick start

Load an image, convert it to grayscale, blur it, and run a Canny edge detector:

package main

import (
	"log"

	cv "github.com/malcolmston/opencv"
)

func main() {
	img, err := cv.ImRead("in.png")
	if err != nil {
		log.Fatal(err)
	}

	gray := cv.CvtColor(img, cv.ColorRGB2Gray)
	blur := cv.GaussianBlur(gray, 5, 1.4)
	edges := cv.Canny(blur, 50, 150)

	if err := cv.ImWrite("edges.png", edges); err != nil {
		log.Fatal(err)
	}
}

Features

  • Mat core — dense row-major []uint8 matrix (NewMat, Clone, Region, CopyTo, Split/Merge, SetTo, At/Set, AtPixel/SetPixel, Size, Total, Empty) and standard-library bridges FromImage / Mat.ToImage.
  • I/O (PNG + JPEG)ImRead / ImWrite for files and IMDecode / IMEncode for in-memory buffers, via the standard-library codecs.
  • Color conversionsCvtColor with RGB↔Gray, RGB↔BGR, RGB↔HSV, RGB↔Lab, RGB↔YCrCb and RGB↔HLS (ColorRGB2Gray, ColorGray2RGB, ColorRGB2BGR, ColorBGR2RGB, ColorBGR2Gray, ColorRGB2HSV, ColorHSV2RGB, ColorRGB2Lab, ColorLab2RGB, ColorRGB2YCrCb, ColorYCrCb2RGB, ColorRGB2HLS, ColorHLS2RGB), plus InRange masking.
  • Filtering / convolution — generic Filter2D (Kernel / NewKernel), separable Filter2DSep, and the built-ins: Blur, BoxFilter, GaussianBlur (GaussianKernel1D), MedianBlur, edge-preserving BilateralFilter, Sobel, Scharr and Laplacian.
  • Arithmetic & logic — element-wise Add, Subtract, AbsDiff, AddWeighted, Multiply, Divide, BitwiseAnd/Or/Xor/Not, Min, Max, Normalize and ConvertScaleAbs, all with saturation.
  • Thresholding — fixed and Otsu levels through Threshold, plus AdaptiveThreshold (mean and Gaussian).
  • MorphologyErode, Dilate and MorphologyEx (open, close, gradient, tophat, blackhat) over structuring elements from GetStructuringElement.
  • Geometric transformsResize (nearest / bilinear), Flip, Rotate, Transpose, affine warping via WarpAffine / GetRotationMatrix2D, projective warping via GetPerspectiveTransform / WarpPerspective, Remap, the PyrDown / PyrUp Gaussian pyramid and DistanceTransform.
  • Contours & shape — Suzuki-style FindContours (RETR_EXTERNAL/LIST/TREE, CHAIN_APPROX_NONE/SIMPLE with hierarchy), DrawContours, ContourArea, ArcLength, BoundingRect, MinAreaRect, ConvexHull, ApproxPolyDP and ImageMoments.
  • Connected componentsConnectedComponents and ConnectedComponentsWithStats (union-find, 4/8 connectivity).
  • Feature detectionCornerHarris, GoodFeaturesToTrack (Shi-Tomasi), HoughLines, HoughLinesP, HoughCircles and FASTCorners.
  • Edges & template matching — a full Canny pipeline and MatchTemplate with MinMaxLoc.
  • Drawing & textLine, Rectangle, Circle, Ellipse, Polylines, FillPoly, and PutText rendered with a built-in bitmap font.
  • HistogramsCalcHist, EqualizeHist, CalcBackProject, CompareHist and contrast-limited adaptive equalisation (CLAHE).

Modules

Beyond the root cv package, the library ships 40 module subpackages that mirror the layout of OpenCV's main and contrib modules. Each imports only the root cv package and the Go standard library — no cgo, no third-party dependencies — and each carries full godoc, deterministic tests and runnable examples. Import the ones you need:

import (
    cv "github.com/malcolmston/opencv"
    "github.com/malcolmston/opencv/features2d"
    "github.com/malcolmston/opencv/calib3d"
)
  • 2D featuresfeatures2d (ORB/BRIEF/BFMatcher), xfeatures2d (AGAST/BRISK/Star/blob), linedescriptor (LSD + LBD).
  • Geometry & 3Dcalib3d (homography+RANSAC, fundamental matrix, solvePnP, triangulate), stereo (BM/SGBM), rgbd (depth→3D, ICP), surface_matching (PPF+ICP), imgprocx (affine estimate, Gabor, log-polar).
  • Motion & trackingvideo (LK/Farnebäck/Kalman), optflow (Horn–Schunck/DIS), tracking (KCF/MedianFlow/CamShift), bgsegm (MOG2/KNN).
  • Detection & recognitionobjdetect (HOG/cascade/QR), aruco, face (Eigen/Fisher/LBPH), barcode (QR/EAN-13/Code128), datamatrix (ECC200), text (MSER), dnn (CNN inference), flann (ANN), saliency.
  • Photo & imagingphoto (denoise/inpaint/seamless clone), hdr (Debevec/Mertens + tonemap), xphoto (white balance/BM3D), intensity (gamma/BIMEF), fuzzy (F-transform), bioinspired (retina), dnn_superres.
  • Structured lightstructured_light (Gray-code/phase-shift), phase_unwrapping.
  • Segmentation & shapesegmentation (watershed/GrabCut), shape (fit line/ellipse, Hu moments), ximgproc (guided filter/SLIC), stitching.
  • Analysis & vizml (KNN/SVM/tree/k-means), quality (PSNR/SSIM), imghash, plot, videoio (GIF), mcc (ColorChecker + colour correction).

Scope & limits

  • CV_8U only. Samples are 8-bit unsigned; there is no floating-point or higher-bit-depth Mat. (Intermediate results such as MatchTemplate scores use a FloatMat.)
  • RGB, not BGR. By Go convention three-channel data is treated as RGB (matching the image package), not OpenCV's native BGR. Use CvtColor with ColorRGB2BGR when you need to interoperate with BGR-oriented code or data.
  • Approximations, not trained models. The module subpackages implement the classical algorithms directly; where OpenCV ships pre-trained weights or model files (deep SISR networks, learning-based white balance, DNN detectors, trained ER/BING classifiers) the Go ports use faithful weight-free approximations and say so in each package's doc.go. Every subpackage documents what it covers versus what it defers.

Documentation

License

MIT

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. The trade-off is scope: heavyweight machine-vision machinery such as dense feature descriptors (SIFT/ORB), camera calibration (calib3d), DNN inference and video I/O are intentionally out of scope. What remains is a faithful, genuinely useful image-processing and computer-vision toolkit.

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.

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

Examples

Constants

View Source
const Filled = -1

Filled is a sentinel thickness that fills a shape instead of outlining it.

Variables

This section is empty.

Functions

func ArcLength added in v0.2.0

func ArcLength(c []Point, closed bool) float64

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 CalcHist

func CalcHist(src *Mat, channel int) []int

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

func Circle(m *Mat, center Point, radius int, color Scalar, thickness int)

Circle draws a circle of the given radius centred at center. A positive thickness draws the outline; a negative thickness fills the disc.

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 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

func ContourArea(c Contour) float64

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 DrawContours added in v0.2.0

func DrawContours(m *Mat, contours []Contour, contourIdx int, color Scalar, thickness int)

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 Ellipse

func Ellipse(m *Mat, center Point, axesX, axesY int, angle float64, color Scalar, thickness int)

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 FillPoly

func FillPoly(m *Mat, polys [][]Point, color Scalar)

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 GaussianKernel1D

func GaussianKernel1D(ksize int, sigma float64) []float64

GaussianKernel1D returns a normalised 1-D Gaussian of length ksize. When sigma <= 0 it is derived from ksize (see GaussianBlur).

func IMEncode

func IMEncode(format string, m *Mat) ([]byte, error)

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

func ImWrite(path string, m *Mat) error

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 Line

func Line(m *Mat, pt1, pt2 Point, color Scalar, thickness int)

Line draws a straight line from pt1 to pt2 with the given colour and thickness (in pixels, minimum 1) using Bresenham's algorithm.

func MinMaxLoc

func MinMaxLoc(f *FloatMat) (minVal, maxVal float64, minX, minY, maxX, maxY int)

MinMaxLoc scans a FloatMat and returns the minimum and maximum values with their (x, y) locations. It panics on an empty matrix.

func Polylines

func Polylines(m *Mat, polys [][]Point, closed bool, color Scalar, thickness int)

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

func PutText(m *Mat, text string, org Point, scale int, color Scalar)

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

func Rectangle(m *Mat, pt1, pt2 Point, color Scalar, thickness int)

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 SobelFloat

func SobelFloat(src *Mat, dx, dy, ksize int) [][]float64

SobelFloat computes the Sobel derivative and returns unclamped per-channel float results, preserving sign and magnitude. See Sobel for the parameter meaning.

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 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.

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 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 FlipCode

type FlipCode int

FlipCode selects the axis for Flip.

const (
	// FlipVertical mirrors around the horizontal axis (top-bottom).
	FlipVertical FlipCode = iota
	// FlipHorizontal mirrors around the vertical axis (left-right).
	FlipHorizontal
	// FlipBoth mirrors around both axes (equivalent to a 180° rotation).
	FlipBoth
)

type FloatMat

type FloatMat struct {
	Rows int
	Cols int
	Data []float64
}

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 CornerHarris added in v0.2.0

func CornerHarris(src *Mat, blockSize, ksize int, k float64) *FloatMat

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 DistanceTransform added in v0.2.0

func DistanceTransform(src *Mat) *FloatMat

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 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 NewFloatMat

func NewFloatMat(rows, cols int) *FloatMat

NewFloatMat allocates a zero-filled FloatMat.

func (*FloatMat) At

func (f *FloatMat) At(y, x int) float64

At returns the value at row y, column x.

type HierarchyNode added in v0.2.0

type HierarchyNode struct {
	Next       int
	Prev       int
	FirstChild int
	Parent     int
}

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

type HoughCircle struct {
	X      int
	Y      int
	Radius int
}

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

type Kernel struct {
	Rows int
	Cols int
	Data []float64
}

Kernel is a 2-D convolution kernel stored row-major with Rows*Cols float weights. Build one with NewKernel or the specialised helpers.

func NewKernel

func NewKernel(rows, cols int, data []float64) Kernel

NewKernel builds a Kernel from row-major data. It panics if len(data) does not equal rows*cols or a dimension is not positive.

type LineSegment added in v0.2.0

type LineSegment struct {
	Pt1 Point
	Pt2 Point
}

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 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

func AbsDiff(a, b *Mat) *Mat

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

func Add(a, b *Mat) *Mat

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

func AddWeighted(a *Mat, alpha float64, b *Mat, beta, gamma float64) *Mat

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 BilateralFilter added in v0.2.0

func BilateralFilter(src *Mat, d int, sigmaColor, sigmaSpace float64) *Mat

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

func BitwiseAnd(a, b *Mat) *Mat

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

func BitwiseNot(src *Mat) *Mat

BitwiseNot returns the per-sample bitwise complement (255-value) of src.

func BitwiseOr added in v0.2.0

func BitwiseOr(a, b *Mat) *Mat

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

func BitwiseXor(a, b *Mat) *Mat

BitwiseXor returns the per-sample bitwise XOR of a and b. The inputs must have identical dimensions and channel counts.

func Blur

func Blur(src *Mat, ksize int) *Mat

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

func BoxFilter(src *Mat, ksize int, normalize bool) *Mat

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

func CLAHE(src *Mat, clipLimit float64, tileGridSize int) *Mat

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 CalcBackProject added in v0.2.0

func CalcBackProject(src *Mat, channel int, hist []int) *Mat

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

func Canny(src *Mat, lowThresh, highThresh float64) *Mat

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

func ConvertScaleAbs(src *Mat, alpha, beta float64) *Mat

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 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 Dilate

func Dilate(src, kernel *Mat, iterations int) *Mat

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

func Divide(a, b *Mat, scale float64) *Mat

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

func EqualizeHist(src *Mat) *Mat

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

func Erode(src, kernel *Mat, iterations int) *Mat

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 Filter2D

func Filter2D(src *Mat, kernel Kernel, delta float64) *Mat

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

func Filter2DSep(src *Mat, kx, ky []float64, delta float64) *Mat

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 Flip

func Flip(src *Mat, code FlipCode) *Mat

Flip mirrors src along the axis chosen by code and returns a new Mat.

func FromImage

func FromImage(img image.Image) *Mat

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 GaussianBlur

func GaussianBlur(src *Mat, ksize int, sigma float64) *Mat

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 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 IMDecode

func IMDecode(data []byte) (*Mat, error)

IMDecode decodes an in-memory image (PNG or JPEG) into a Mat.

func ImRead

func ImRead(path string) (*Mat, error)

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

func InRange(src *Mat, lo, hi []uint8) *Mat

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 Laplacian

func Laplacian(src *Mat, ksize int, scale, delta float64) *Mat

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 Max added in v0.2.0

func Max(a, b *Mat) *Mat

Max returns the per-sample maximum of a and b. The inputs must have identical dimensions and channel counts.

func MedianBlur

func MedianBlur(src *Mat, ksize int) *Mat

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

func Merge(planes []*Mat) *Mat

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

func Min(a, b *Mat) *Mat

Min returns the per-sample minimum of a and b. The inputs must have identical dimensions and channel counts.

func MorphologyEx

func MorphologyEx(src, kernel *Mat, op MorphType, iterations int) *Mat

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

func Multiply(a, b *Mat, scale float64) *Mat

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

func NewMat(rows, cols, channels int) *Mat

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

func Normalize(src *Mat, alpha, beta float64) *Mat

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

func PyrDown(src *Mat) *Mat

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

func PyrUp(src *Mat) *Mat

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 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

func Scharr(src *Mat, dx, dy int, scale, delta float64) *Mat

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

func Sobel(src *Mat, dx, dy, ksize int, scale, delta float64) *Mat

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 Subtract added in v0.2.0

func Subtract(a, b *Mat) *Mat

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 Transpose

func Transpose(src *Mat) *Mat

Transpose swaps rows and columns, returning a new Mat of shape Cols×Rows.

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 (*Mat) At

func (m *Mat) At(y, x, c int) uint8

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) AtPixel

func (m *Mat) AtPixel(y, x int) []uint8

AtPixel returns all channel samples of pixel (x, y) as a fresh slice.

func (*Mat) Clone

func (m *Mat) Clone() *Mat

Clone returns a deep copy of the Mat with its own backing storage.

func (*Mat) CopyTo

func (m *Mat) CopyTo(dst *Mat, y, x int)

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) Empty

func (m *Mat) Empty() bool

Empty reports whether the Mat has no samples.

func (*Mat) Region

func (m *Mat) Region(y, x, height, width int) *Mat

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

func (m *Mat) Set(y, x, c int, value uint8)

Set stores value at row y, column x and channel c. It panics if the coordinates are out of range.

func (*Mat) SetPixel

func (m *Mat) SetPixel(y, x int, values []uint8)

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) SetTo

func (m *Mat) SetTo(value uint8)

SetTo fills every sample of every channel with value.

func (*Mat) Size

func (m *Mat) Size() (rows, cols int)

Size returns the matrix dimensions as (rows, cols).

func (*Mat) Split

func (m *Mat) Split() []*Mat

Split separates a multi-channel Mat into a slice of single-channel Mats, one per channel, in channel order.

func (*Mat) ToImage

func (m *Mat) ToImage() image.Image

ToImage converts the Mat into an image from the standard library. A single-channel Mat becomes *image.Gray; a three-channel Mat becomes *image.RGBA with full opacity. Other channel counts are rendered by using the first channel as gray. The Mat is treated as RGB, not BGR.

func (*Mat) Total

func (m *Mat) Total() int

Total returns the number of pixels (Rows*Cols), ignoring channels.

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

func ImageMoments(src *Mat) Moments

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.

func (Moments) Centroid added in v0.2.0

func (m Moments) Centroid() (x, y float64)

Centroid returns the intensity-weighted centre of mass (M10/M00, M01/M00). It returns (0, 0) for an image of zero total mass.

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

type Point struct {
	X int
	Y int
}

Point is an integer image coordinate (x is the column, y is the row).

func ApproxPolyDP added in v0.2.0

func ApproxPolyDP(curve []Point, epsilon float64, closed bool) []Point

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

func ConvexHull(pts []Point) []Point

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 FASTCorners added in v0.2.0

func FASTCorners(src *Mat, threshold int, nonmaxSuppression bool) []Point

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 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 PolarLine added in v0.2.0

type PolarLine struct {
	Rho   float64
	Theta float64
}

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

func HoughLines(src *Mat, rhoStep, thetaStep float64, threshold int) []PolarLine

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

type Rect struct {
	X      int
	Y      int
	Width  int
	Height int
}

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

func BoundingRect(pts []Point) Rect

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 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 NewScalar

func NewScalar(v ...float64) Scalar

NewScalar builds a Scalar from the given components (missing entries are zero, extra entries are ignored).

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.

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 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 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).
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 tracking implements single-object (short-term) visual trackers on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
Package tracking implements single-object (short-term) visual trackers on top of the standard-library-only OpenCV port github.com/malcolmston/opencv (imported here as cv).
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 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 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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL