moments2

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package moments2 provides image moments and shape descriptors for the github.com/malcolmston/opencv library.

The package operates on the library's existing image type, cv.Mat, and its geometry types cv.Point and cv.Point2f; it does not introduce a competing image representation. Functions accept single-channel Mats (grayscale or binary masks) and polygonal contours ([]cv.Point) as produced by the parent package's contour extraction.

The following families of descriptors are implemented, all in pure Go with no external dependencies:

  • Raw, central and normalized central moments of arbitrary order, computed from a raster image (ImageMoments, MaskMoments) or from a polygon via Green's theorem (ContourMoments).
  • Hu's seven rotation, scale and translation invariant moments (HuMoments) and OpenCV-compatible shape matching (MatchShapes).
  • Region shape descriptors: eccentricity, elongation, orientation, solidity, extent, circularity, aspect ratio and more.
  • Zernike and pseudo-Zernike moments on the unit disk.
  • Legendre moments on the unit square.
  • Flusser & Suk affine moment invariants.
  • Fourier descriptors of a closed contour with normalization and reconstruction.
  • Shape context histograms and their matching cost.
  • Convex hull indices, convexity defects and convexity tests.

All routines are deterministic and CPU-only.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AspectRatio

func AspectRatio(contour []cv.Point) float64

AspectRatio returns the ratio of the width to the height of a contour's upright bounding rectangle. It returns 0 for an empty contour.

func AxisLengths

func AxisLengths(m Moments) (major, minor float64)

AxisLengths returns the lengths of the major and minor axes of the ellipse that has the same second central moments as the region described by m. The values are full axis lengths (not semi-axes). It returns (0, 0) for a shape of zero mass.

func CentralMoment

func CentralMoment(src *cv.Mat, p, q int) float64

CentralMoment returns the central moment of order (p, q), taken about the image centroid, for any non-negative p and q. It panics if src is not single-channel.

func Circularity

func Circularity(area, perimeter float64) float64

Circularity returns the normalized circularity 4*pi*area/perimeter^2 of a region, a value in (0, 1] where 1 is a perfect circle. It returns 0 when the perimeter is zero.

func Compactness

func Compactness(area, perimeter float64) float64

Compactness returns the isoperimetric compactness perimeter^2/area of a region. The minimum value, achieved by a circle, is 4*pi. It returns 0 when area is zero.

func ConvexHullIndices

func ConvexHullIndices(contour []cv.Point) []int

ConvexHullIndices returns the indices into contour of its convex hull vertices in counter-clockwise order (in image coordinates, where y grows downward), computed with Andrew's monotone chain algorithm. Duplicate and collinear points are dropped. It returns nil for an empty contour.

func Convexity

func Convexity(contour []cv.Point) float64

Convexity returns the ratio of the convex-hull perimeter to the contour perimeter, a value in (0, 1] where 1 means the contour is convex. Boundary concavities lengthen the contour perimeter and lower the ratio. It returns 0 when the contour perimeter is zero.

func ConvexityRatio

func ConvexityRatio(contour []cv.Point) float64

ConvexityRatio returns a scalar convexity measure equal to one divided by one plus the total defect depth of a contour, normalized so that a convex shape scores 1 and deeper concavities score lower. It computes the hull internally.

func Eccentricity

func Eccentricity(m Moments) float64

Eccentricity returns the eccentricity of the equivalent ellipse of m, a value in [0, 1) where 0 is a perfect circle and values approaching 1 are highly elongated. It returns 0 for a shape of zero mass.

func Elongation

func Elongation(m Moments) float64

Elongation returns the ratio of the major to the minor axis length of the equivalent ellipse of m, always at least 1. A circle yields 1; an infinitely thin shape yields +Inf. It returns 0 for a shape of zero mass.

func EquivalentDiameter

func EquivalentDiameter(area float64) float64

EquivalentDiameter returns the diameter of the circle whose area equals the given region area, sqrt(4*area/pi).

func Extent

func Extent(contour []cv.Point) float64

Extent returns the ratio of a contour's area to the area of its upright bounding rectangle, a value in (0, 1]. It returns 0 for an empty contour.

func FlusserI1

func FlusserI1(m Moments) float64

FlusserI1 returns the first Flusser & Suk affine moment invariant, computed from the central moments of m and normalized by mu00^4:

I1 = (mu20*mu02 - mu11^2) / mu00^4.

It is invariant to any affine transform of the shape. It returns 0 for a shape of zero mass.

func FlusserI2

func FlusserI2(m Moments) float64

FlusserI2 returns the second Flusser & Suk affine moment invariant, built from the third-order central moments and normalized by mu00^10. It is invariant to any affine transform. It returns 0 for a shape of zero mass.

func FlusserI3

func FlusserI3(m Moments) float64

FlusserI3 returns the third Flusser & Suk affine moment invariant, mixing second- and third-order central moments and normalized by mu00^7. It is invariant to any affine transform. It returns 0 for a shape of zero mass.

func FlusserI4

func FlusserI4(m Moments) float64

FlusserI4 returns the fourth Flusser & Suk affine moment invariant, the most complex of the classic set, normalized by mu00^11. It is invariant to any affine transform. It returns 0 for a shape of zero mass.

func FlusserInvariants

func FlusserInvariants(m Moments) [4]float64

FlusserInvariants returns the four classic Flusser & Suk affine moment invariants as an array [I1, I2, I3, I4].

func FormFactor

func FormFactor(area, perimeter float64) float64

FormFactor is an alias of Circularity: 4*pi*area/perimeter^2.

func FourierDescriptorDistance

func FourierDescriptorDistance(a, b []float64) float64

FourierDescriptorDistance returns the Euclidean distance between two normalized Fourier descriptor vectors, comparing only the overlapping leading coefficients when the lengths differ.

func FourierDescriptors

func FourierDescriptors(contour []cv.Point2f) []complex128

FourierDescriptors returns the discrete Fourier transform of a closed contour whose points are treated as complex numbers x+iy. The returned slice has the same length as the input and encodes the boundary shape; low-index coefficients capture coarse structure and high-index ones fine detail. It panics on an empty contour.

func FourierMagnitudeSpectrum

func FourierMagnitudeSpectrum(fd []complex128) []float64

FourierMagnitudeSpectrum returns the moduli of a sequence of Fourier descriptors, discarding phase.

func HuMoments

func HuMoments(m Moments) [7]float64

HuMoments returns Hu's seven invariant moments computed from the normalized central moments of m. The first six are invariant to translation, scale and rotation; the seventh additionally changes sign under reflection, allowing mirror images to be distinguished. The formulas match OpenCV's cv::HuMoments.

func IsContourConvex

func IsContourConvex(contour []cv.Point) bool

IsContourConvex reports whether a polygon is convex, that is whether every turn along its boundary has the same sign. Collinear vertices are permitted. It returns true for fewer than four vertices.

func LegendreMoment

func LegendreMoment(src *cv.Mat, p, q int) float64

LegendreMoment computes the Legendre moment L_pq of a single-channel image. Pixel centres are mapped onto the square [-1, 1] x [-1, 1] and the moment is the intensity-weighted projection onto the product P_p(x)*P_q(y) with the standard normalization (2p+1)(2q+1)/4. For a constant image of value c the moment L_00 equals c. It panics if src is not single-channel.

func LegendreMoments

func LegendreMoments(src *cv.Mat, maxOrder int) [][]float64

LegendreMoments returns all Legendre moments L_pq with p+q <= maxOrder as a dense (maxOrder+1) x (maxOrder+1) matrix; entries with p+q > maxOrder are left at zero. It panics if src is not single-channel or maxOrder is negative.

func LegendrePolynomial

func LegendrePolynomial(n int, x float64) float64

LegendrePolynomial evaluates the Legendre polynomial P_n(x) using the stable Bonnet recurrence. The argument x is normally taken in [-1, 1].

func LogHuMoments

func LogHuMoments(m Moments) [7]float64

LogHuMoments returns a sign-preserving log-magnitude transform of the seven Hu moments, -sign(h)*log10(|h|), which compresses their very wide dynamic range into a form suitable for direct comparison. A zero Hu value maps to zero.

func MatchShapes

func MatchShapes(a, b Moments, method MatchMethod) float64

MatchShapes returns a dissimilarity score between two shapes given by their moments, using their Hu invariants and the selected method. A score of zero means the shapes are identical up to translation, scale and rotation; larger values mean less similar. It panics on an unknown method.

func MaxDiameter

func MaxDiameter(contour []cv.Point) float64

MaxDiameter returns the greatest distance between any two vertices of a contour (its Feret diameter). It returns 0 for fewer than two points.

func NormalizedCentralMoment

func NormalizedCentralMoment(src *cv.Mat, p, q int) float64

NormalizedCentralMoment returns the normalized central moment of order (p, q), equal to mu_pq / M00^(1+(p+q)/2), which is invariant to uniform scaling. It panics if src is not single-channel.

func NormalizedFourierDescriptors

func NormalizedFourierDescriptors(fd []complex128) []float64

NormalizedFourierDescriptors returns a translation-, scale-, rotation- and start-point-invariant descriptor derived from fd. Translation invariance comes from dropping the zero-frequency term; scale invariance from dividing by the magnitude of the first non-zero descriptor; and rotation and start-point invariance from taking magnitudes. The result has length len(fd)-1 with the leading element equal to 1. It returns nil for fewer than two descriptors.

func Orientation

func Orientation(m Moments) float64

Orientation returns the angle, in radians in the range (-pi/2, pi/2], of the major axis of the equivalent ellipse of m relative to the positive x axis. It returns 0 for a shape of zero mass or a rotationally symmetric one.

func PolygonArea

func PolygonArea(pts []cv.Point) float64

PolygonArea returns the absolute area enclosed by a polygon using the shoelace formula. Vertices are given in order and the polygon is treated as closed.

func PolygonCentroid

func PolygonCentroid(pts []cv.Point) cv.Point2f

PolygonCentroid returns the area centroid of a polygon computed from its first moments. It returns the origin for a degenerate polygon of zero area.

func PolygonPerimeter

func PolygonPerimeter(pts []cv.Point) float64

PolygonPerimeter returns the closed perimeter length of a polygon, the sum of the Euclidean edge lengths including the closing edge.

func PseudoZernikeMoment

func PseudoZernikeMoment(src *cv.Mat, n, m int) complex128

PseudoZernikeMoment computes the complex pseudo-Zernike moment A_nm of a single-channel image over the inscribed unit disk. Pseudo-Zernike moments provide more low-order descriptors than ordinary Zernike moments and are more robust to noise. It returns 0 when |m| > n. It panics if src is not single-channel.

func PseudoZernikeRadial

func PseudoZernikeRadial(n, m int, rho float64) float64

PseudoZernikeRadial evaluates the pseudo-Zernike radial polynomial R_n^m(rho) for a radius rho in [0, 1]. Unlike the Zernike polynomials these are defined for every m with |m| <= n regardless of the parity of (n-m). It returns 0 when |m| > n.

func RadialPolynomial

func RadialPolynomial(n, m int, rho float64) float64

RadialPolynomial evaluates the Zernike radial polynomial R_n^m(rho) for a radius rho in [0, 1]. It returns 0 when (n-|m|) is odd or |m| > n, the cases in which the polynomial is undefined or identically zero.

func RawMoment

func RawMoment(src *cv.Mat, p, q int) float64

RawMoment returns the spatial moment of order (p, q), sum of value*x^p*y^q over all pixels, for any non-negative p and q. It panics if src is not single-channel.

func ReconstructContour

func ReconstructContour(fd []complex128, numPoints, numDescriptors int) []cv.Point2f

ReconstructContour approximates a contour from its Fourier descriptors, keeping only the numDescriptors lowest-frequency coefficients (paired from the low and high ends of the spectrum) and evaluating the inverse transform at numPoints equally spaced parameter values. It is the inverse companion of FourierDescriptors and is useful for visualising how many harmonics a shape requires. It panics if numPoints is less than one.

func Rectangularity

func Rectangularity(contour []cv.Point) float64

Rectangularity returns the ratio of a contour's area to the area of its minimum-area rotated bounding rectangle, a value in (0, 1] measuring how well the shape fills its tightest rectangle. It returns 0 when that rectangle has zero area.

func ResampleContour

func ResampleContour(contour []cv.Point, n int) []cv.Point2f

ResampleContour resamples a closed contour to exactly n points spaced equally along its arc length, returning the new points as cv.Point2f. It panics if n is less than one or the contour has fewer than two points.

func Roundness

func Roundness(area, maxDiameter float64) float64

Roundness returns 4*area/(pi*maxDiameter^2), a compactness measure that, unlike circularity, is insensitive to boundary roughness because it uses the longest diameter rather than the perimeter. It returns 0 when maxDiameter is zero.

func ShapeContextCost

func ShapeContextCost(a, b ShapeContextHistogram) float64

ShapeContextCost returns the chi-square dissimilarity between two shape context histograms, the standard local matching cost, in the range [0, 1]. Both histograms are normalized to sum to one before comparison so that points with different numbers of neighbours remain comparable. It panics if the histograms have different dimensions.

func ShapeContextMatchCost

func ShapeContextMatchCost(a, b []ShapeContextHistogram) float64

ShapeContextMatchCost returns the mean over all reference points of the best per-point ShapeContextCost between two shape context descriptors, a global dissimilarity between two shapes. For each histogram in a it takes the minimum cost against any histogram in b. It returns 0 if either descriptor is empty.

func Solidity

func Solidity(contour []cv.Point) float64

Solidity returns the ratio of a contour's area to the area of its convex hull, a value in (0, 1] where 1 means the shape is convex. It returns 0 when the hull area is zero.

func ZernikeMagnitude

func ZernikeMagnitude(src *cv.Mat, n, m int) float64

ZernikeMagnitude returns the modulus of the Zernike moment A_nm, a rotation invariant shape feature. It panics if src is not single-channel.

func ZernikeMoment

func ZernikeMoment(src *cv.Mat, n, m int) complex128

ZernikeMoment computes the complex Zernike moment A_nm of a single-channel image over the unit disk inscribed in the image. Pixel intensities are the mass; coordinates are mapped so the largest image dimension spans the disk diameter and pixels outside the disk are ignored. It returns 0 when (n-|m|) is odd or |m| > n. It panics if src is not single-channel.

Types

type ConvexityDefect

type ConvexityDefect struct {
	// StartIndex is the index into the contour of the defect's start hull point.
	StartIndex int
	// EndIndex is the index into the contour of the defect's end hull point.
	EndIndex int
	// FarIndex is the index into the contour of the deepest interior point.
	FarIndex int
	// Start is the hull point where the defect begins.
	Start cv.Point
	// End is the hull point where the defect ends.
	End cv.Point
	// Far is the contour point of maximum depth inside the defect.
	Far cv.Point
	// Depth is the perpendicular distance from Far to the segment Start-End.
	Depth float64
}

ConvexityDefect describes a concavity of a contour relative to its convex hull: the segment of the hull it lies under (from Start to End) and the contour point Far that departs furthest from that segment, at distance Depth.

func ConvexityDefects

func ConvexityDefects(contour []cv.Point, hull []int, minDepth float64) []ConvexityDefect

ConvexityDefects finds the concavities of a contour with respect to its convex hull. The hull is given as indices into contour in traversal order, as returned by ConvexHullIndices. For each pair of consecutive hull vertices it scans the contour points between them and, if any lies farther than minDepth from the connecting chord, records the deepest one as a defect. Defects are returned in hull order. It returns nil when the contour or hull is too small.

type EllipseParams

type EllipseParams struct {
	// Center is the ellipse centre in image coordinates.
	Center cv.Point2f
	// Major is the full length of the major axis.
	Major float64
	// Minor is the full length of the minor axis.
	Minor float64
	// Angle is the orientation of the major axis in radians.
	Angle float64
}

EllipseParams describes an ellipse by its centre, full axis lengths and the orientation of its major axis in radians.

func FitEllipse

func FitEllipse(m Moments) EllipseParams

FitEllipse returns the ellipse that has the same centroid and second central moments as the region described by m. This is the classic moment-based ellipse fit; it does not perform an algebraic least-squares fit to boundary points. It returns the zero EllipseParams for a shape of zero mass.

type MatchMethod

type MatchMethod int

MatchMethod selects the dissimilarity formula used by MatchShapes.

const (
	// MatchI1 sums the absolute differences of the reciprocals of the
	// log-transformed Hu moments (OpenCV CONTOURS_MATCH_I1).
	MatchI1 MatchMethod = 1
	// MatchI2 sums the absolute differences of the log-transformed Hu moments
	// (OpenCV CONTOURS_MATCH_I2).
	MatchI2 MatchMethod = 2
	// MatchI3 takes the maximum relative difference of the log-transformed Hu
	// moments (OpenCV CONTOURS_MATCH_I3).
	MatchI3 MatchMethod = 3
)

type Moments

type Moments struct {
	// Spatial (raw) moments.
	M00, M10, M01, M20, M11, M02, M30, M21, M12, M03 float64
	// Central moments about the centroid.
	Mu20, Mu11, Mu02, Mu30, Mu21, Mu12, Mu03 float64
	// Normalized central moments.
	Nu20, Nu11, Nu02, Nu30, Nu21, Nu12, Nu03 float64
}

Moments holds the spatial (raw), central and normalized central moments of an image or contour up to the third order, mirroring OpenCV's cv::Moments.

Spatial moments Mpq weight each unit of mass by x^p*y^q. Central moments Mupq are the same sums taken about the centroid and are therefore invariant to translation. Normalized central moments Nupq additionally divide by a power of M00 and are invariant to uniform scale.

func ContourMoments

func ContourMoments(pts []cv.Point) Moments

ContourMoments computes the moments of the region enclosed by a polygon using Green's theorem, matching OpenCV's contour-based cv::moments. The polygon is given by its vertices in order; it is treated as closed. Fewer than three vertices yield a zero Moments value.

func ImageMoments

func ImageMoments(src *cv.Mat) Moments

ImageMoments computes the full set of moments of a single-channel image, weighting each pixel (x, y) by its sample value. For a binary mask this yields the geometric moments of the foreground region. It panics if src is not single-channel.

func MaskMoments

func MaskMoments(src *cv.Mat) Moments

MaskMoments computes moments treating every non-zero pixel as a unit of mass, ignoring the actual sample value. This is the correct choice for a binary segmentation where foreground pixels may not all equal 255. It panics if src is not single-channel.

func (Moments) Area

func (m Moments) Area() float64

Area returns the zeroth spatial moment M00, which for a binary mask equals the number of foreground pixels and for a contour equals the enclosed area.

func (Moments) Centroid

func (m Moments) Centroid() cv.Point2f

Centroid returns the mass-weighted centre (M10/M00, M01/M00) as a cv.Point2f. It returns the origin for a shape of zero total mass.

type ShapeContextHistogram

type ShapeContextHistogram struct {
	// RadialBins is the number of log-distance bins.
	RadialBins int
	// AngularBins is the number of angular bins spanning the full circle.
	AngularBins int
	// Counts holds the per-bin counts in row-major order.
	Counts []float64
}

ShapeContextHistogram is the log-polar histogram computed at one reference point of a shape. It is stored row-major with RadialBins rows and AngularBins columns; the value at radial bin r and angular bin a is at index r*AngularBins + a. Its entries sum to the number of other points that fell inside the histogram's radial range.

func ComputeShapeContext

func ComputeShapeContext(points []cv.Point2f, radialBins, angularBins int, innerRadius, outerRadius float64) []ShapeContextHistogram

ComputeShapeContext computes the shape context descriptor of a point set: for each reference point it builds a log-polar histogram of the relative positions of all the other points. Distances are normalized by their mean and binned logarithmically between innerRadius and outerRadius (as fractions of that mean distance); angles are binned uniformly over the full circle. The returned slice is parallel to points. It panics if there are fewer than two points or the bin counts are not positive.

type ZernikeCoefficient

type ZernikeCoefficient struct {
	// N is the radial order of the moment.
	N int
	// M is the azimuthal repetition of the moment.
	M int
	// Value is the complex moment A_nm.
	Value complex128
}

ZernikeCoefficient is a single complex Zernike moment A_nm together with its order n and repetition m.

func ZernikeMoments

func ZernikeMoments(src *cv.Mat, maxOrder int) []ZernikeCoefficient

ZernikeMoments computes every valid Zernike moment up to and including radial order maxOrder, returning them ordered by n then by m from 0 to n. Only the non-negative repetitions are returned because A_n,-m is the complex conjugate of A_nm. It panics if src is not single-channel or maxOrder is negative.

func (ZernikeCoefficient) Magnitude

func (z ZernikeCoefficient) Magnitude() float64

Magnitude returns the modulus of the coefficient, which is invariant to rotation of the underlying image.

func (ZernikeCoefficient) Phase

func (z ZernikeCoefficient) Phase() float64

Phase returns the argument of the coefficient in radians.

Jump to

Keyboard shortcuts

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