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 feature descriptors (SIFT/ORB), full contour hierarchies, camera calibration, DNN inference and video I/O are intentionally out of scope. What remains is a faithful, genuinely useful image-processing 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.
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 CalcHist(src *Mat, channel int) []int
- func Circle(m *Mat, center Point, radius int, color Scalar, thickness int)
- func Ellipse(m *Mat, center Point, axesX, axesY int, angle float64, color Scalar, ...)
- func FillPoly(m *Mat, polys [][]Point, color Scalar)
- func GaussianKernel1D(ksize int, sigma float64) []float64
- func IMEncode(format string, m *Mat) ([]byte, error)
- func ImWrite(path string, m *Mat) error
- func Line(m *Mat, pt1, pt2 Point, color Scalar, thickness int)
- func MinMaxLoc(f *FloatMat) (minVal, maxVal float64, minX, minY, maxX, maxY int)
- 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 SobelFloat(src *Mat, dx, dy, ksize int) [][]float64
- type AdaptiveMethod
- type AffineMatrix
- type ColorConversionCode
- type FlipCode
- type FloatMat
- type InterpolationFlag
- type Kernel
- type Mat
- func AdaptiveThreshold(src *Mat, maxval float64, method AdaptiveMethod, typ ThresholdType, ...) *Mat
- func Blur(src *Mat, ksize int) *Mat
- func BoxFilter(src *Mat, ksize int, normalize bool) *Mat
- func Canny(src *Mat, lowThresh, highThresh float64) *Mat
- func CvtColor(src *Mat, code ColorConversionCode) *Mat
- func Dilate(src, kernel *Mat, iterations int) *Mat
- func EqualizeHist(src *Mat) *Mat
- func Erode(src, kernel *Mat, iterations int) *Mat
- func Filter2D(src *Mat, kernel Kernel, delta float64) *Mat
- func Flip(src *Mat, code FlipCode) *Mat
- func FromImage(img image.Image) *Mat
- func GaussianBlur(src *Mat, ksize int, sigma float64) *Mat
- func GetStructuringElement(shape MorphShape, rows, cols int) *Mat
- func IMDecode(data []byte) (*Mat, error)
- func ImRead(path string) (*Mat, error)
- func InRange(src *Mat, lo, hi []uint8) *Mat
- func Laplacian(src *Mat, ksize int, scale, delta float64) *Mat
- func MedianBlur(src *Mat, ksize int) *Mat
- func Merge(planes []*Mat) *Mat
- func MorphologyEx(src, kernel *Mat, op MorphType, iterations int) *Mat
- func NewMat(rows, cols, channels int) *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 Threshold(src *Mat, thresh, maxval float64, typ ThresholdType) (*Mat, float64)
- func Transpose(src *Mat) *Mat
- func WarpAffine(src *Mat, m AffineMatrix, width, height int, interp InterpolationFlag) *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 MorphShape
- type MorphType
- type Point
- type RotateCode
- type Scalar
- type TemplateMatchMode
- type ThresholdType
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 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 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 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 GaussianKernel1D ¶
GaussianKernel1D returns a normalised 1-D Gaussian of length ksize. When sigma <= 0 it is derived from ksize (see GaussianBlur).
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 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 MinMaxLoc ¶
MinMaxLoc scans a FloatMat and returns the minimum and maximum values with their (x, y) locations. It panics on an empty matrix.
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.
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 )
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 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 ¶
NewFloatMat allocates a zero-filled FloatMat.
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 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 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 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 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 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 ¶
Dilate grows bright regions by replacing each sample with the maximum over the structuring element's footprint. iterations repeats the operation.
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 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 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 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 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 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 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 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 MorphologyEx ¶
MorphologyEx performs a compound morphological operation selected by op over the given structuring element. Subtractive operations saturate at zero.
func NewMat ¶
NewMat allocates a zero-filled Mat with the given dimensions. It panics if any dimension is not positive.
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 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.Println(out.Data, int(used))
Output: [0 0 255] 120
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 (*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 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 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 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).
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
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. |