cv

package module
v0.1.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 and RGB↔HSV (ColorRGB2Gray, ColorGray2RGB, ColorRGB2BGR, ColorBGR2RGB, ColorBGR2Gray, ColorRGB2HSV, ColorHSV2RGB), plus InRange masking.
  • Filtering / convolution — generic Filter2D (Kernel / NewKernel) and the built-ins on top of it: Blur, BoxFilter, separable GaussianBlur (GaussianKernel1D), MedianBlur, Sobel, Scharr and Laplacian.
  • 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, and affine warping via WarpAffine with GetRotationMatrix2D.
  • 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 and EqualizeHist.

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.
  • Deferred. Heavyweight machine-vision machinery is intentionally out of scope: feature descriptors (SIFT/ORB), full contour hierarchies, camera calibration (calib3d), DNN inference, and video I/O.

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

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

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

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 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 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 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 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 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 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 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 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 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 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 (*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 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 Point

type Point struct {
	X int
	Y int
}

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

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

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

Jump to

Keyboard shortcuts

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