Table of Contents

Class Mat

Namespace
OpenCvSharp
Assembly
OpenCvSharp.dll

OpenCV C++ n-dimensional dense array class (cv::Mat)

public class Mat : DisposableCvObject, IDisposable, ICvPtrHolder
Inheritance
Mat
Implements
Derived
Mat<TElem>
Inherited Members

Constructors

Mat()

Creates empty Mat

public Mat()

Mat(Mat)

protected Mat(Mat m)

Parameters

m Mat

Mat(Mat, Range, Range?)

creates a matrix header for a part of the bigger matrix

public Mat(Mat m, Range rowRange, Range? colRange = null)

Parameters

m Mat

Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat::clone() .

rowRange Range

Range of the m rows to take. As usual, the range start is inclusive and the range end is exclusive. Use Range.All to take all the rows.

colRange Range?

Range of the m columns to take. Use Range.All to take all the columns.

Mat(Mat, params Range[])

creates a matrix header for a part of the bigger matrix

public Mat(Mat m, params Range[] ranges)

Parameters

m Mat

Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat.Clone() .

ranges Range[]

Array of selected ranges of m along each dimensionality.

Mat(Mat, Rect)

creates a matrix header for a part of the bigger matrix

public Mat(Mat m, Rect roi)

Parameters

m Mat

Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it. The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m . If you want to have an independent copy of the sub-array, use Mat.Clone() .

roi Rect

Region of interest.

Mat(Size, MatType)

constructs 2D matrix of the specified size and type

public Mat(Size size, MatType type)

Parameters

size Size

2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType.CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

Mat(Size, MatType, Scalar)

constructs 2D matrix and fills it with the specified Scalar value.

public Mat(Size size, MatType type, Scalar s)

Parameters

size Size

2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.

s Scalar

An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method .

Mat(IEnumerable<int>, MatType)

constructs n-dimensional matrix

public Mat(IEnumerable<int> sizes, MatType type)

Parameters

sizes IEnumerable<int>

Array of integers specifying an n-dimensional array shape.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

Mat(IEnumerable<int>, MatType, Scalar)

constructs n-dimensional matrix

public Mat(IEnumerable<int> sizes, MatType type, Scalar s)

Parameters

sizes IEnumerable<int>

Array of integers specifying an n-dimensional array shape.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

s Scalar

An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method .

Mat(IEnumerable<int>, MatType, Array, IEnumerable<long>?)

constructor for matrix headers pointing to user-allocated data

protected Mat(IEnumerable<int> sizes, MatType type, Array data, IEnumerable<long>? steps = null)

Parameters

sizes IEnumerable<int>

Array of integers specifying an n-dimensional array shape.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data Array

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

steps IEnumerable<long>

Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.

Mat(int, int, MatType)

constructs 2D matrix of the specified size and type

public Mat(int rows, int cols, MatType type)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

Mat(int, int, MatType, Scalar)

constructs 2D matrix and fills it with the specified Scalar value.

public Mat(int rows, int cols, MatType type, Scalar s)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

s Scalar

An optional value to initialize each matrix element with. To set all the matrix elements to the particular value after the construction, use SetTo(Scalar s) method .

Mat(int, int, MatType, Array, long)

constructor for matrix headers pointing to user-allocated data

protected Mat(int rows, int cols, MatType type, Array data, long step = 0)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data Array

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

step long

Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() .

Mat(int, int, MatType, nint, long)

constructor for matrix headers pointing to user-allocated data

[Obsolete("Use Mat.FromPixelData instead. This constructor has been deprecated because the introduction of 'nint' made overload resolution confusing.", true)]
public Mat(int rows, int cols, MatType type, nint data, long step = 0)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data nint

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

step long

Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() .

Mat(string, ImreadModes)

Loads an image from a file. (cv::imread)

public Mat(string fileName, ImreadModes flags = ImreadModes.Color)

Parameters

fileName string

Name of file to be loaded.

flags ImreadModes

Specifies color type of the loaded image

Fields

TypeMap

typeof(T) -> MatType

protected static readonly IReadOnlyDictionary<Type, MatType> TypeMap

Field Value

IReadOnlyDictionary<Type, MatType>

Properties

Cols

the number of columns or -1 when the array has more than 2 dimensions

public int Cols { get; }

Property Value

int

Data

pointer to the data

public nint Data { get; }

Property Value

nint

DataEnd

The pointer that is possible to compute a relative sub-array position in the main container array using locateROI()

public nint DataEnd { get; }

Property Value

nint

DataLimit

The pointer that is possible to compute a relative sub-array position in the main container array using locateROI()

public nint DataLimit { get; }

Property Value

nint

DataPointer

unsafe pointer to the data

public byte* DataPointer { get; }

Property Value

byte*

DataStart

The pointer that is possible to compute a relative sub-array position in the main container array using locateROI()

public nint DataStart { get; }

Property Value

nint

Dims

the array dimensionality, >= 2

public int Dims { get; }

Property Value

int

Flags

includes several bit-fields:

  • the magic signature
  • continuity flag
  • depth
  • number of channels
public int Flags { get; }

Property Value

int

Height

the number of rows or -1 when the array has more than 2 dimensions

public int Height { get; }

Property Value

int

this[Range, Range]

Extracts a rectangular submatrix.

public Mat this[Range rowRange, Range colRange] { get; set; }

Parameters

rowRange Range

Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range.All().

colRange Range

Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range.All().

Property Value

Mat

this[Range[]]

Extracts a rectangular submatrix.

[SuppressMessage("Microsoft.Design", "CA1043: Use integral or string argument for indexers")]
public Mat this[params Range[] ranges] { get; set; }

Parameters

ranges Range[]

Array of selected ranges along each array dimension.

Property Value

Mat

this[Rect]

Extracts a rectangular submatrix.

[SuppressMessage("Microsoft.Design", "CA1043: Use integral or string argument for indexers")]
public Mat this[Rect roi] { get; set; }

Parameters

roi Rect

Extracted submatrix specified as a rectangle.

Property Value

Mat

this[int, int, int, int]

Extracts a rectangular submatrix.

public Mat this[int rowStart, int rowEnd, int colStart, int colEnd] { get; set; }

Parameters

rowStart int

Start row of the extracted submatrix. The upper boundary is not included.

rowEnd int

End row of the extracted submatrix. The upper boundary is not included.

colStart int

Start column of the extracted submatrix. The upper boundary is not included.

colEnd int

End column of the extracted submatrix. The upper boundary is not included.

Property Value

Mat

this[Range, Range]

Extracts a rectangular submatrix.

public Mat this[Range rowRange, Range colRange] { get; set; }

Parameters

rowRange Range

Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range.All().

colRange Range

Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range.All().

Property Value

Mat

Rows

the number of rows or -1 when the array has more than 2 dimensions

public int Rows { get; }

Property Value

int

Width

the number of columns or -1 when the array has more than 2 dimensions

public int Width { get; }

Property Value

int

Methods

Abs()

Computes absolute value of each matrix element

public MatExpr Abs()

Returns

MatExpr

Accumulate(InputArray)

Adds an image to the accumulator.

public Mat Accumulate(InputArray mask)

Parameters

mask InputArray

Optional operation mask.

Returns

Mat

Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.

AccumulateSquare(InputArray)

Adds the square of a source image to the accumulator.

public Mat AccumulateSquare(InputArray mask)

Parameters

mask InputArray

Optional operation mask.

Returns

Mat

Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point.

AdaptiveThreshold(double, AdaptiveThresholdTypes, ThresholdTypes, int, double)

Applies an adaptive threshold to an array. Source matrix must be 8-bit single-channel image.

public Mat AdaptiveThreshold(double maxValue, AdaptiveThresholdTypes adaptiveMethod, ThresholdTypes thresholdType, int blockSize, double c)

Parameters

maxValue double

Non-zero value assigned to the pixels for which the condition is satisfied. See the details below.

adaptiveMethod AdaptiveThresholdTypes

Adaptive thresholding algorithm to use, ADAPTIVE_THRESH_MEAN_C or ADAPTIVE_THRESH_GAUSSIAN_C .

thresholdType ThresholdTypes

Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV .

blockSize int

Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.

c double

Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.

Returns

Mat

Destination image of the same size and the same type as src.

Add(Mat)

public MatExpr Add(Mat m)

Parameters

m Mat

Returns

MatExpr

Add(Scalar)

public MatExpr Add(Scalar s)

Parameters

s Scalar

Returns

MatExpr

AdjustROI(int, int, int, int)

Adjusts a submatrix size and position within the parent matrix.

public Mat AdjustROI(int dtop, int dbottom, int dleft, int dright)

Parameters

dtop int

Shift of the top submatrix boundary upwards.

dbottom int

Shift of the bottom submatrix boundary downwards.

dleft int

Shift of the left submatrix boundary to the left.

dright int

Shift of the right submatrix boundary to the right.

Returns

Mat

Alignment(int)

public Mat Alignment(int n = 4)

Parameters

n int

Returns

Mat

ApproxPolyDP(double, bool)

Approximates contour or a curve using Douglas-Peucker algorithm. The input is the polygon or curve to approximate and it must be 1 x N or N x 1 matrix of type CV_32SC2 or CV_32FC2.

public Mat ApproxPolyDP(double epsilon, bool closed)

Parameters

epsilon double

Specifies the approximation accuracy. This is the maximum distance between the original curve and its approximation.

closed bool

The result of the approximation; The type should match the type of the input curve

Returns

Mat

The result of the approximation; The type should match the type of the input curve

ArcLength(bool)

Calculates a contour perimeter or a curve length. The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix.

public double ArcLength(bool closed)

Parameters

closed bool

Indicates, whether the curve is closed or not

Returns

double

AsSpan<T>()

Creates a new span over the Mat.

public Span<T> AsSpan<T>() where T : unmanaged

Returns

Span<T>

Type Parameters

T

AssignTo(Mat, MatType?)

Provides a functional form of convertTo.

public void AssignTo(Mat m, MatType? type = null)

Parameters

m Mat

Destination array.

type MatType?

Desired destination array depth (or -1 if it should be the same as the source type).

At<T>(int)

Returns a value to the specified array element.

public ref T At<T>(int i0) where T : unmanaged

Parameters

i0 int

Index along the dimension 0

Returns

T

A value to the specified array element.

Type Parameters

T

At<T>(int, int)

Returns a value to the specified array element.

public ref T At<T>(int i0, int i1) where T : unmanaged

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

Returns

T

A value to the specified array element.

Type Parameters

T

At<T>(int, int, int)

Returns a value to the specified array element.

public ref T At<T>(int i0, int i1, int i2) where T : unmanaged

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

i2 int

Index along the dimension 2

Returns

T

A value to the specified array element.

Type Parameters

T

At<T>(params int[])

Returns a value to the specified array element.

public ref T At<T>(params int[] idx) where T : unmanaged

Parameters

idx int[]

Array of Mat::dims indices.

Returns

T

A value to the specified array element.

Type Parameters

T

BilateralFilter(int, double, double, BorderTypes)

Applies bilateral filter to the image The source image must be a 8-bit or floating-point, 1-channel or 3-channel image.

public Mat BilateralFilter(int d, double sigmaColor, double sigmaSpace, BorderTypes borderType = BorderTypes.Default)

Parameters

d int

The diameter of each pixel neighborhood, that is used during filtering. If it is non-positive, it's computed from sigmaSpace

sigmaColor double

Filter sigma in the color space. Larger value of the parameter means that farther colors within the pixel neighborhood will be mixed together, resulting in larger areas of semi-equal color

sigmaSpace double

Filter sigma in the coordinate space. Larger value of the parameter means that farther pixels will influence each other (as long as their colors are close enough; see sigmaColor). Then d>0 , it specifies the neighborhood size regardless of sigmaSpace, otherwise d is proportional to sigmaSpace

borderType BorderTypes

Returns

Mat

The destination image; will have the same size and the same type as src

BitwiseAnd(Mat)

public MatExpr BitwiseAnd(Mat m)

Parameters

m Mat

Returns

MatExpr

BitwiseAnd(double)

public MatExpr BitwiseAnd(double s)

Parameters

s double

Returns

MatExpr

BitwiseOr(Mat)

public MatExpr BitwiseOr(Mat m)

Parameters

m Mat

Returns

MatExpr

BitwiseOr(double)

public MatExpr BitwiseOr(double s)

Parameters

s double

Returns

MatExpr

Blur(Size, Point?, BorderTypes)

Smoothes image using normalized box filter

public Mat Blur(Size ksize, Point? anchor = null, BorderTypes borderType = BorderTypes.Default)

Parameters

ksize Size

The smoothing kernel size

anchor Point?

The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center

borderType BorderTypes

The border mode used to extrapolate pixels outside of the image

Returns

Mat

The destination image; will have the same size and the same type as src

BoundingRect()

Calculates the up-right bounding rectangle of a point set. The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix.

public Rect BoundingRect()

Returns

Rect

Minimal up-right bounding rectangle for the specified point set.

BoxFilter(MatType, Size, Point?, bool, BorderTypes)

Smoothes image using box filter

public Mat BoxFilter(MatType ddepth, Size ksize, Point? anchor = null, bool normalize = true, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType
ksize Size

The smoothing kernel size

anchor Point?

The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center

normalize bool

Indicates, whether the kernel is normalized by its area or not

borderType BorderTypes

The border mode used to extrapolate pixels outside of the image

Returns

Mat

The destination image; will have the same size and the same type as src

BuildPyramid(int, BorderTypes)

Upsamples an image and then blurs it.

public IEnumerable<Mat> BuildPyramid(int maxlevel, BorderTypes borderType = BorderTypes.Default)

Parameters

maxlevel int
borderType BorderTypes

Returns

IEnumerable<Mat>

Canny(double, double, int, bool)

Finds edges in an image using Canny algorithm.

public Mat Canny(double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false)

Parameters

threshold1 double

The first threshold for the hysteresis procedure

threshold2 double

The second threshold for the hysteresis procedure

apertureSize int

Aperture size for the Sobel operator [By default this is ApertureSize.Size3]

L2gradient bool

Indicates, whether the more accurate L2 norm should be used to compute the image gradient magnitude (true), or a faster default L1 norm is enough (false). [By default this is false]

Returns

Mat

The output edge map. It will have the same size and the same type as image

Cast<TMat>()

Creates type-specific Mat instance from this.

public TMat Cast<TMat>() where TMat : Mat

Returns

TMat

Type Parameters

TMat

Channels()

Returns the number of matrix channels.

public int Channels()

Returns

int

CheckRange(bool)

checks that each matrix element is within the specified range.

public bool CheckRange(bool quiet = true)

Parameters

quiet bool

The flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.

Returns

bool

CheckRange(bool, out Point, double, double)

checks that each matrix element is within the specified range.

public bool CheckRange(bool quiet, out Point pos, double minVal = -1.7976931348623157E+308, double maxVal = 1.7976931348623157E+308)

Parameters

quiet bool

The flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.

pos Point

The optional output parameter, where the position of the first outlier is stored.

minVal double

The inclusive lower boundary of valid values range

maxVal double

The exclusive upper boundary of valid values range

Returns

bool

CheckVector(int, int, bool)

public int CheckVector(int elemChannels, int depth = -1, bool requireContinuous = true)

Parameters

elemChannels int

Number of channels or number of columns the matrix should have. For a 2-D matrix, when the matrix has only 1 column, then it should have elemChannels channels; When the matrix has only 1 channel, then it should have elemChannels columns. For a 3-D matrix, it should have only one channel. Furthermore, if the number of planes is not one, then the number of rows within every plane has to be 1; if the number of rows within every plane is not 1, then the number of planes has to be 1.

depth int

The depth the matrix should have. Set it to -1 when any depth is fine.

requireContinuous bool

Set it to true to require the matrix to be continuous

Returns

int

-1 if the requirement is not satisfied. Otherwise, it returns the number of elements in the matrix. Note that an element may have multiple channels.

Circle(Point, int, Scalar, int, LineTypes, int)

Draws a circle

public void Circle(Point center, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

center Point

Center of the circle.

radius int

Radius of the circle.

color Scalar

Circle color.

thickness int

Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1]

lineType LineTypes

Type of the circle boundary. [By default this is LineType.Link8]

shift int

Number of fractional bits in the center coordinates and radius value. [By default this is 0]

Circle(int, int, int, Scalar, int, LineTypes, int)

Draws a circle

public void Circle(int centerX, int centerY, int radius, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

centerX int

X-coordinate of the center of the circle.

centerY int

Y-coordinate of the center of the circle.

radius int

Radius of the circle.

color Scalar

Circle color.

thickness int

Thickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1]

lineType LineTypes

Type of the circle boundary. [By default this is LineType.Link8]

shift int

Number of fractional bits in the center coordinates and radius value. [By default this is 0]

Clone()

Creates a full copy of the matrix.

public Mat Clone()

Returns

Mat

Clone(Rect)

Returns the partial Mat of the specified Mat

public Mat Clone(Rect roi)

Parameters

roi Rect

Returns

Mat

Col(int)

Creates a matrix header for the specified matrix column.

public Mat Col(int x)

Parameters

x int

A 0-based column index.

Returns

Mat

ColRange(Range)

Creates a matrix header for the specified column span.

public Mat ColRange(Range range)

Parameters

range Range

Returns

Mat

ColRange(int, int)

Creates a matrix header for the specified column span.

public Mat ColRange(int startCol, int endCol)

Parameters

startCol int

An inclusive 0-based start index of the column span.

endCol int

An exclusive 0-based ending index of the column span.

Returns

Mat

ColRange(Range)

Creates a matrix header for the specified column span.

public Mat ColRange(Range range)

Parameters

range Range

Returns

Mat

CompleteSymm(bool)

extends the symmetrical matrix from the lower half or from the upper half

public void CompleteSymm(bool lowerToUpper = false)

Parameters

lowerToUpper bool

If true, the lower half is copied to the upper half, otherwise the upper half is copied to the lower half

ConnectedComponents(OutputArray, PixelConnectivity)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public int ConnectedComponents(OutputArray labels, PixelConnectivity connectivity = PixelConnectivity.Connectivity8)

Parameters

labels OutputArray

destination labeled image

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

Returns

int

The number of labels

ConnectedComponents(OutputArray, PixelConnectivity, MatType)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public int ConnectedComponents(OutputArray labels, PixelConnectivity connectivity, MatType ltype)

Parameters

labels OutputArray

destination labeled image

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

ltype MatType

output image label type. Currently CV_32S and CV_16U are supported.

Returns

int

The number of labels

ConnectedComponents(out int[,], PixelConnectivity)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public int ConnectedComponents(out int[,] labels, PixelConnectivity connectivity)

Parameters

labels int[,]

destination labeled rectangular array

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

Returns

int

The number of labels

ConnectedComponentsEx(PixelConnectivity)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public ConnectedComponents ConnectedComponentsEx(PixelConnectivity connectivity = PixelConnectivity.Connectivity8)

Parameters

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

Returns

ConnectedComponents

ConnectedComponentsWithStats(OutputArray, OutputArray, OutputArray, PixelConnectivity)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public int ConnectedComponentsWithStats(OutputArray labels, OutputArray stats, OutputArray centroids, PixelConnectivity connectivity = PixelConnectivity.Connectivity8)

Parameters

labels OutputArray

destination labeled image

stats OutputArray

statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes

centroids OutputArray

floating point centroid (x,y) output for each label, including the background label

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

Returns

int

ConnectedComponentsWithStats(OutputArray, OutputArray, OutputArray, PixelConnectivity, MatType)

computes the connected components labeled image of boolean image. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image.

public int ConnectedComponentsWithStats(OutputArray labels, OutputArray stats, OutputArray centroids, PixelConnectivity connectivity, MatType ltype)

Parameters

labels OutputArray

destination labeled image

stats OutputArray

statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes

centroids OutputArray

floating point centroid (x,y) output for each label, including the background label

connectivity PixelConnectivity

8 or 4 for 8-way or 4-way connectivity respectively

ltype MatType

output image label type. Currently CV_32S and CV_16U are supported.

Returns

int

ContourArea(bool)

Calculates the contour area. The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix.

public double ContourArea(bool oriented = false)

Parameters

oriented bool

Returns

double

ConvertScaleAbs(double, double)

Scales, computes absolute values and converts the result to 8-bit.

public Mat ConvertScaleAbs(double alpha = 1, double beta = 0)

Parameters

alpha double

The optional scale factor. [By default this is 1]

beta double

The optional delta added to the scaled values. [By default this is 0]

Returns

Mat

ConvertTo(OutputArray, MatType, double, double)

Converts an array to another data type with optional scaling.

public void ConvertTo(OutputArray m, MatType rtype, double alpha = 1, double beta = 0)

Parameters

m OutputArray

output matrix; if it does not have a proper size or type before the operation, it is reallocated.

rtype MatType

desired output matrix type or, rather, the depth since the number of channels are the same as the input has; if rtype is negative, the output matrix will have the same type as the input.

alpha double

optional scale factor.

beta double

optional delta added to the scaled values.

ConvexHull(bool, bool)

Computes convex hull for a set of 2D points.

public Mat ConvexHull(bool clockwise = false, bool returnPoints = true)

Parameters

clockwise bool

If true, the output convex hull will be oriented clockwise, otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate system is assumed - the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.

returnPoints bool

Returns

Mat

The output convex hull. It is either a vector of points that form the hull (must have the same type as the input points), or a vector of 0-based point indices of the hull points in the original array (since the set of convex hull points is a subset of the original point set).

ConvexHullFloatPoints(bool)

Computes convex hull for a set of 2D points.

public Point2f[] ConvexHullFloatPoints(bool clockwise = false)

Parameters

clockwise bool

If true, the output convex hull will be oriented clockwise, otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate system is assumed - the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.

Returns

Point2f[]

The output convex hull. It is a vector of points that form the hull (must have the same type as the input points).

ConvexHullIndices(bool)

Computes convex hull for a set of 2D points.

public int[] ConvexHullIndices(bool clockwise = false)

Parameters

clockwise bool

If true, the output convex hull will be oriented clockwise, otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate system is assumed - the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.

Returns

int[]

The output convex hull. It is a vector of 0-based point indices of the hull points in the original array (since the set of convex hull points is a subset of the original point set).

ConvexHullPoints(bool)

Computes convex hull for a set of 2D points.

public Point[] ConvexHullPoints(bool clockwise = false)

Parameters

clockwise bool

If true, the output convex hull will be oriented clockwise, otherwise it will be oriented counter-clockwise. Here, the usual screen coordinate system is assumed - the origin is at the top-left corner, x axis is oriented to the right, and y axis is oriented downwards.

Returns

Point[]

The output convex hull. It is a vector of points that form the hull (must have the same type as the input points).

ConvexityDefects(InputArray)

Computes the contour convexity defects

public Mat ConvexityDefects(InputArray convexHull)

Parameters

convexHull InputArray

Convex hull obtained using convexHull() that should contain indices of the contour points that make the hull.

Returns

Mat

The output vector of convexity defects. Each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be fixpt_depth/256.0.

ConvexityDefectsAsVec(InputArray)

Computes the contour convexity defects

public Vec4i[] ConvexityDefectsAsVec(InputArray convexHull)

Parameters

convexHull InputArray

Convex hull obtained using convexHull() that should contain indices of the contour points that make the hull.

Returns

Vec4i[]

The output vector of convexity defects. Each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be fixpt_depth/256.0.

CopyMakeBorder(int, int, int, int, BorderTypes, Scalar?)

Forms a border around the image

public Mat CopyMakeBorder(int top, int bottom, int left, int right, BorderTypes borderType, Scalar? value = null)

Parameters

top int

Specify how much pixels in each direction from the source image rectangle one needs to extrapolate

bottom int

Specify how much pixels in each direction from the source image rectangle one needs to extrapolate

left int

Specify how much pixels in each direction from the source image rectangle one needs to extrapolate

right int

Specify how much pixels in each direction from the source image rectangle one needs to extrapolate

borderType BorderTypes

The border type

value Scalar?

The border value if borderType == Constant

Returns

Mat

CopyTo(Mat, InputArray?)

Copies the matrix to another one.

public void CopyTo(Mat m, InputArray? mask = null)

Parameters

m Mat

Destination matrix. If it does not have a proper size or type before the operation, it is reallocated.

mask InputArray

Operation mask. Its non-zero elements indicate which matrix elements need to be copied.

CopyTo(OutputArray, InputArray?)

Copies the matrix to another one.

public void CopyTo(OutputArray m, InputArray? mask = null)

Parameters

m OutputArray

Destination matrix. If it does not have a proper size or type before the operation, it is reallocated.

mask InputArray

Operation mask. Its non-zero elements indicate which matrix elements need to be copied.

CornerEigenValsAndVecs(int, int, BorderTypes)

computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix at each pixel. The output is stored as 6-channel matrix.

public Mat CornerEigenValsAndVecs(int blockSize, int ksize, BorderTypes borderType = BorderTypes.Default)

Parameters

blockSize int
ksize int
borderType BorderTypes

Returns

Mat

CornerSubPix(IEnumerable<Point2f>, Size, Size, TermCriteria)

adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria

public Point2f[] CornerSubPix(IEnumerable<Point2f> inputCorners, Size winSize, Size zeroZone, TermCriteria criteria)

Parameters

inputCorners IEnumerable<Point2f>

Initial coordinates of the input corners and refined coordinates provided for output.

winSize Size

Half of the side length of the search window.

zeroZone Size

Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such a size.

criteria TermCriteria

Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after criteria.maxCount iterations or when the corner position moves by less than criteria.epsilon on some iteration.

Returns

Point2f[]

CountNonZero()

computes the number of nonzero array elements

public int CountNonZero()

Returns

int

number of non-zero elements in mtx

Create(MatType, params int[])

Allocates new array data if needed.

public void Create(MatType type, params int[] sizes)

Parameters

type MatType

New matrix type.

sizes int[]

Array of integers specifying a new array shape.

Create(Size, MatType)

Allocates new array data if needed.

public void Create(Size size, MatType type)

Parameters

size Size

Alternative new matrix size specification: Size(cols, rows)

type MatType

New matrix type.

Create(int, int, MatType)

Allocates new array data if needed.

public void Create(int rows, int cols, MatType type)

Parameters

rows int

New number of rows.

cols int

New number of columns.

type MatType

New matrix type.

CreateHanningWindow(Size, MatType)

Computes a Hanning window coefficients in two dimensions.

public void CreateHanningWindow(Size winSize, MatType type)

Parameters

winSize Size

The window size specifications

type MatType

Created array type

Cross(InputArray)

Computes a cross-product of two 3-element vectors.

public Mat Cross(InputArray m)

Parameters

m InputArray

Another cross-product operand.

Returns

Mat

CvtColor(ColorConversionCodes, int)

Converts image from one color space to another

public Mat CvtColor(ColorConversionCodes code, int dstCn = 0)

Parameters

code ColorConversionCodes

The color space conversion code

dstCn int

The number of channels in the destination image; if the parameter is 0, the number of the channels will be derived automatically from src and the code

Returns

Mat

The destination image; will have the same size and the same depth as src

Dct(DctFlags)

performs forward or inverse 1D or 2D Discrete Cosine Transformation

public Mat Dct(DctFlags flags = DctFlags.None)

Parameters

flags DctFlags

Transformation flags, a combination of DctFlag2 values

Returns

Mat

The destination array; will have the same size and same type as src

Depth()

Returns the depth of a matrix element.

public int Depth()

Returns

int

Determinant()

computes determinant of a square matrix. The input matrix must have CV_32FC1 or CV_64FC1 type and square size.

public double Determinant()

Returns

double

determinant of the specified matrix.

Dft(DftFlags, int)

Performs a forward Discrete Fourier transform of 1D or 2D floating-point array.

public Mat Dft(DftFlags flags = DftFlags.None, int nonzeroRows = 0)

Parameters

flags DftFlags

Transformation flags, a combination of the DftFlag2 values

nonzeroRows int

When the parameter != 0, the function assumes that only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, thus the function can handle the rest of the rows more efficiently and thus save some time. This technique is very useful for computing array cross-correlation or convolution using DFT

Returns

Mat

The destination array, which size and type depends on the flags

Diag(Mat)

Extracts a diagonal from a matrix, or creates a diagonal matrix.

public static Mat Diag(Mat d)

Parameters

d Mat

One-dimensional matrix that represents the main diagonal.

Returns

Mat

Diag(MatDiagType)

Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values:

public Mat Diag(MatDiagType d = MatDiagType.Main)

Parameters

d MatDiagType

Single-column matrix that forms a diagonal matrix or index of the diagonal, with the following values:

Returns

Mat

Dilate(InputArray?, Point?, int, BorderTypes, Scalar?)

Dilates an image by using a specific structuring element.

public Mat Dilate(InputArray? element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

element InputArray

The structuring element used for dilation. If element=new Mat() , a 3x3 rectangular structuring element is used

anchor Point?

Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center

iterations int

The number of times dilation is applied. [By default this is 1]

borderType BorderTypes

The pixel extrapolation method. [By default this is BorderTypes.Constant]

borderValue Scalar?

The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()]

Returns

Mat

The destination image. It will have the same size and the same type as src

DisposeManaged()

Releases managed resources

protected override void DisposeManaged()

DisposeUnmanaged()

releases unmanaged resources

protected override void DisposeUnmanaged()

DistanceTransform(DistanceTypes, DistanceTransformMasks)

Computes the distance transform map

public Mat<float> DistanceTransform(DistanceTypes distanceType, DistanceTransformMasks maskSize)

Parameters

distanceType DistanceTypes
maskSize DistanceTransformMasks

Returns

Mat<float>

Divide(Mat)

public MatExpr Divide(Mat m)

Parameters

m Mat

Returns

MatExpr

Divide(double)

public MatExpr Divide(double s)

Parameters

s double

Returns

MatExpr

Dot(InputArray)

Computes a dot-product of two vectors.

public double Dot(InputArray m)

Parameters

m InputArray

another dot-product operand.

Returns

double

DrawContours(IEnumerable<Mat>, int, Scalar, int, LineTypes, Mat?, int, Point?)

Draws contours in the image

public void DrawContours(IEnumerable<Mat> contours, int contourIdx, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, Mat? hierarchy = null, int maxLevel = 2147483647, Point? offset = null)

Parameters

contours IEnumerable<Mat>

All the input contours. Each contour is stored as a point vector.

contourIdx int

Parameter indicating a contour to draw. If it is negative, all the contours are drawn.

color Scalar

Color of the contours.

thickness int

Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn.

lineType LineTypes

Line connectivity.

hierarchy Mat

Optional information about hierarchy. It is only needed if you want to draw only some of the contours

maxLevel int

Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available.

offset Point?

Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy)

DrawContours(IEnumerable<IEnumerable<Point>>, int, Scalar, int, LineTypes, IEnumerable<HierarchyIndex>?, int, Point?)

Draws contours in the image

public void DrawContours(IEnumerable<IEnumerable<Point>> contours, int contourIdx, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, IEnumerable<HierarchyIndex>? hierarchy = null, int maxLevel = 2147483647, Point? offset = null)

Parameters

contours IEnumerable<IEnumerable<Point>>

All the input contours. Each contour is stored as a point vector.

contourIdx int

Parameter indicating a contour to draw. If it is negative, all the contours are drawn.

color Scalar

Color of the contours.

thickness int

Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn.

lineType LineTypes

Line connectivity.

hierarchy IEnumerable<HierarchyIndex>

Optional information about hierarchy. It is only needed if you want to draw only some of the contours

maxLevel int

Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available.

offset Point?

Optional contour shift parameter. Shift all the drawn contours by the specified offset = (dx, dy)

DrawMarker(Point, Scalar, MarkerTypes, int, int, LineTypes)

Draws a marker on a predefined position in an image.

The function cv::drawMarker draws a marker on a given position in the image.For the moment several marker types are supported, see #MarkerTypes for more information.

public void DrawMarker(Point position, Scalar color, MarkerTypes markerType = MarkerTypes.Cross, int markerSize = 20, int thickness = 1, LineTypes lineType = LineTypes.Link8)

Parameters

position Point

The point where the crosshair is positioned.

color Scalar

Line color.

markerType MarkerTypes

The specific type of marker you want to use.

markerSize int

The length of the marker axis [default = 20 pixels]

thickness int

Line thickness.

lineType LineTypes

Type of the line.

Dump(FormatType)

Returns a string that represents each element value of Mat. This method corresponds to std::ostream << Mat

public string Dump(FormatType format = FormatType.Default)

Parameters

format FormatType

Returns

string

ElemSize()

Returns the matrix element size in bytes.

public int ElemSize()

Returns

int

ElemSize1()

Returns the size of each matrix element channel in bytes.

public int ElemSize1()

Returns

int

Ellipse(Point, Size, double, double, double, Scalar, int, LineTypes, int)

Draws simple or thick elliptic arc or fills ellipse sector

public void Ellipse(Point center, Size axes, double angle, double startAngle, double endAngle, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

center Point

Center of the ellipse.

axes Size

Length of the ellipse axes.

angle double

Rotation angle.

startAngle double

Starting angle of the elliptic arc.

endAngle double

Ending angle of the elliptic arc.

color Scalar

Ellipse color.

thickness int

Thickness of the ellipse arc. [By default this is 1]

lineType LineTypes

Type of the ellipse boundary. [By default this is LineType.Link8]

shift int

Number of fractional bits in the center coordinates and axes' values. [By default this is 0]

Ellipse(RotatedRect, Scalar, int, LineTypes)

Draws simple or thick elliptic arc or fills ellipse sector

public void Ellipse(RotatedRect box, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8)

Parameters

box RotatedRect

The enclosing box of the ellipse drawn

color Scalar

Ellipse color.

thickness int

Thickness of the ellipse boundary. [By default this is 1]

lineType LineTypes

Type of the ellipse boundary. [By default this is LineType.Link8]

Empty()

Returns true if the array has no elements.

public bool Empty()

Returns

bool

EmptyClone()

Makes a Mat that have the same size, depth and channels as this image

public Mat EmptyClone()

Returns

Mat

EqualizeHist()

Normalizes the grayscale image brightness and contrast by normalizing its histogram. The source matrix is 8-bit single channel image.

public Mat EqualizeHist()

Returns

Mat

The destination image; will have the same size and the same type as src

Equals(Mat)

operator ==

public MatExpr Equals(Mat m)

Parameters

m Mat

Returns

MatExpr

Equals(double)

operator ==

public MatExpr Equals(double d)

Parameters

d double

Returns

MatExpr

Erode(InputArray?, Point?, int, BorderTypes, Scalar?)

Erodes an image by using a specific structuring element.

public Mat Erode(InputArray? element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

element InputArray

The structuring element used for dilation. If element=new Mat(), a 3x3 rectangular structuring element is used

anchor Point?

Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center

iterations int

The number of times erosion is applied

borderType BorderTypes

The pixel extrapolation method

borderValue Scalar?

The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()]

Returns

Mat

The destination image. It will have the same size and the same type as src

Exp()

computes exponent of each matrix element (dst = e**src)

public Mat Exp()

Returns

Mat

The destination array; will have the same size and same type as src

ExtractChannel(int)

extracts a single channel from src (coi is 0-based index)

public Mat ExtractChannel(int coi)

Parameters

coi int

Returns

Mat

Eye(Size, MatType)

Returns an identity matrix of the specified size and type.

public static MatExpr Eye(Size size, MatType type)

Parameters

size Size

Alternative to the matrix size specification Size(cols, rows) .

type MatType

Created matrix type.

Returns

MatExpr

Eye(int, int, MatType)

Returns an identity matrix of the specified size and type.

public static MatExpr Eye(int rows, int cols, MatType type)

Parameters

rows int

Number of rows.

cols int

Number of columns.

type MatType

Created matrix type.

Returns

MatExpr

FillConvexPoly(IEnumerable<Point>, Scalar, LineTypes, int)

Fills a convex polygon.

public void FillConvexPoly(IEnumerable<Point> pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

pts IEnumerable<Point>

The polygon vertices

color Scalar

Polygon color

lineType LineTypes

Type of the polygon boundaries

shift int

The number of fractional bits in the vertex coordinates

FillPoly(IEnumerable<IEnumerable<Point>>, Scalar, LineTypes, int, Point?)

Fills the area bounded by one or more polygons

public void FillPoly(IEnumerable<IEnumerable<Point>> pts, Scalar color, LineTypes lineType = LineTypes.Link8, int shift = 0, Point? offset = null)

Parameters

pts IEnumerable<IEnumerable<Point>>

Array of polygons, each represented as an array of points

color Scalar

Polygon color

lineType LineTypes

Type of the polygon boundaries

shift int

The number of fractional bits in the vertex coordinates

offset Point?

Filter2D(MatType, InputArray, Point?, double, BorderTypes)

Convolves an image with the kernel

public Mat Filter2D(MatType ddepth, InputArray kernel, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType

The desired depth of the destination image. If it is negative, it will be the same as src.depth()

kernel InputArray

Convolution kernel (or rather a correlation kernel), a single-channel floating point matrix. If you want to apply different kernels to different channels, split the image into separate color planes using split() and process them individually

anchor Point?

The anchor of the kernel that indicates the relative position of a filtered point within the kernel. The anchor should lie within the kernel. The special default value (-1,-1) means that the anchor is at the kernel center

delta double

The optional value added to the filtered pixels before storing them in dst

borderType BorderTypes

The pixel extrapolation method

Returns

Mat

The destination image. It will have the same size and the same number of channels as src

FindContours(out Mat[], OutputArray, RetrievalModes, ContourApproximationModes, Point?)

Finds contours in a binary image. The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours.

public void FindContours(out Mat[] contours, OutputArray hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null)

Parameters

contours Mat[]

Detected contours. Each contour is stored as a vector of points.

hierarchy OutputArray

Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the members of the elements hierarchy[i] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.

mode RetrievalModes

Contour retrieval mode

method ContourApproximationModes

Contour approximation method

offset Point?

Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.

FindContours(out Point[][], out HierarchyIndex[], RetrievalModes, ContourApproximationModes, Point?)

Finds contours in a binary image. The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours.

public void FindContours(out Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes mode, ContourApproximationModes method, Point? offset = null)

Parameters

contours Point[][]

Detected contours. Each contour is stored as a vector of points.

hierarchy HierarchyIndex[]

Optional output vector, containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the members of the elements hierarchy[i] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.

mode RetrievalModes

Contour retrieval mode

method ContourApproximationModes

Contour approximation method

offset Point?

Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.

FindContoursAsArray(RetrievalModes, ContourApproximationModes, Point?)

Finds contours in a binary image. The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours.

public Point[][] FindContoursAsArray(RetrievalModes mode, ContourApproximationModes method, Point? offset = null)

Parameters

mode RetrievalModes

Contour retrieval mode

method ContourApproximationModes

Contour approximation method

offset Point?

Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.

Returns

Point[][]

Detected contours. Each contour is stored as a vector of points.

FindContoursAsMat(RetrievalModes, ContourApproximationModes, Point?)

Finds contours in a binary image. The source is an 8-bit single-channel image. Non-zero pixels are treated as 1’s. Zero pixels remain 0’s, so the image is treated as binary. The function modifies this image while extracting the contours.

public Mat<Point>[] FindContoursAsMat(RetrievalModes mode, ContourApproximationModes method, Point? offset = null)

Parameters

mode RetrievalModes

Contour retrieval mode

method ContourApproximationModes

Contour approximation method

offset Point?

Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.

Returns

Mat<Point>[]

Detected contours. Each contour is stored as a vector of points.

FindNonZero()

returns the list of locations of non-zero pixels

public Mat FindNonZero()

Returns

Mat

FitEllipse()

Fits ellipse to the set of 2D points.

public RotatedRect FitEllipse()

Returns

RotatedRect

FitLine2D(DistanceTypes, double, double, double)

Fits line to the set of 2D points using M-estimator algorithm. The input is vector of 2D points.

public Line2D FitLine2D(DistanceTypes distType, double param, double reps, double aeps)

Parameters

distType DistanceTypes

Distance used by the M-estimator

param double

Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen.

reps double

Sufficient accuracy for the radius (distance between the coordinate origin and the line).

aeps double

Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps.

Returns

Line2D

Output line parameters.

FitLine3D(DistanceTypes, double, double, double)

Fits line to the set of 3D points using M-estimator algorithm. The input is vector of 3D points.

public Line3D FitLine3D(DistanceTypes distType, double param, double reps, double aeps)

Parameters

distType DistanceTypes

Distance used by the M-estimator

param double

Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen.

reps double

Sufficient accuracy for the radius (distance between the coordinate origin and the line).

aeps double

Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps.

Returns

Line3D

Output line parameters.

Flip(FlipMode)

reverses the order of the rows, columns or both in a matrix

public Mat Flip(FlipMode flipCode)

Parameters

flipCode FlipMode

Specifies how to flip the array: 0 means flipping around the x-axis, positive (e.g., 1) means flipping around y-axis, and negative (e.g., -1) means flipping around both axes. See also the discussion below for the formulas.

Returns

Mat

The destination array; will have the same size and same type as src

FloodFill(InputOutputArray, Point, Scalar)

Fills a connected component with the given color. Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below.

public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal)

Parameters

mask InputOutputArray

(For the second function only) Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller. The function uses and updates the mask, so you take responsibility of initializing the mask content. Flood-filling cannot go across non-zero pixels in the mask. For example, an edge detector output can be used as a mask to stop filling at edges. It is possible to use the same mask in multiple calls to the function to make sure the filled area does not overlap.

seedPoint Point

Starting point.

newVal Scalar

New value of the repainted domain pixels.

Returns

int

FloodFill(InputOutputArray, Point, Scalar, out Rect, Scalar?, Scalar?, FloodFillFlags)

Fills a connected component with the given color. Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below.

public int FloodFill(InputOutputArray mask, Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4)

Parameters

mask InputOutputArray

(For the second function only) Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller. The function uses and updates the mask, so you take responsibility of initializing the mask content. Flood-filling cannot go across non-zero pixels in the mask. For example, an edge detector output can be used as a mask to stop filling at edges. It is possible to use the same mask in multiple calls to the function to make sure the filled area does not overlap.

seedPoint Point

Starting point.

newVal Scalar

New value of the repainted domain pixels.

rect Rect

Optional output parameter set by the function to the minimum bounding rectangle of the repainted domain.

loDiff Scalar?

Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.

upDiff Scalar?

Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.

flags FloodFillFlags

Operation flags. Lower bits contain a connectivity value, 4 (default) or 8, used within the function. Connectivity determines which neighbors of a pixel are considered.

Returns

int

FloodFill(Point, Scalar)

Fills a connected component with the given color. Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below.

public int FloodFill(Point seedPoint, Scalar newVal)

Parameters

seedPoint Point

Starting point.

newVal Scalar

New value of the repainted domain pixels.

Returns

int

FloodFill(Point, Scalar, out Rect, Scalar?, Scalar?, FloodFillFlags)

Fills a connected component with the given color. Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below.

public int FloodFill(Point seedPoint, Scalar newVal, out Rect rect, Scalar? loDiff = null, Scalar? upDiff = null, FloodFillFlags flags = FloodFillFlags.Link4)

Parameters

seedPoint Point

Starting point.

newVal Scalar

New value of the repainted domain pixels.

rect Rect

Optional output parameter set by the function to the minimum bounding rectangle of the repainted domain.

loDiff Scalar?

Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.

upDiff Scalar?

Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component.

flags FloodFillFlags

Operation flags. Lower bits contain a connectivity value, 4 (default) or 8, used within the function. Connectivity determines which neighbors of a pixel are considered.

Returns

int

ForEachAsByte(MatForeachFunctionByte)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsByte(MatForeachFunctionByte operation)

Parameters

operation MatForeachFunctionByte

ForEachAsDouble(MatForeachFunctionDouble)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsDouble(MatForeachFunctionDouble operation)

Parameters

operation MatForeachFunctionDouble

ForEachAsFloat(MatForeachFunctionFloat)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsFloat(MatForeachFunctionFloat operation)

Parameters

operation MatForeachFunctionFloat

ForEachAsInt16(MatForeachFunctionInt16)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsInt16(MatForeachFunctionInt16 operation)

Parameters

operation MatForeachFunctionInt16

ForEachAsInt32(MatForeachFunctionInt32)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsInt32(MatForeachFunctionInt32 operation)

Parameters

operation MatForeachFunctionInt32

ForEachAsVec2b(MatForeachFunctionVec2b)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec2b(MatForeachFunctionVec2b operation)

Parameters

operation MatForeachFunctionVec2b

ForEachAsVec2d(MatForeachFunctionVec2d)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec2d(MatForeachFunctionVec2d operation)

Parameters

operation MatForeachFunctionVec2d

ForEachAsVec2f(MatForeachFunctionVec2f)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec2f(MatForeachFunctionVec2f operation)

Parameters

operation MatForeachFunctionVec2f

ForEachAsVec2i(MatForeachFunctionVec2i)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec2i(MatForeachFunctionVec2i operation)

Parameters

operation MatForeachFunctionVec2i

ForEachAsVec2s(MatForeachFunctionVec2s)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec2s(MatForeachFunctionVec2s operation)

Parameters

operation MatForeachFunctionVec2s

ForEachAsVec3b(MatForeachFunctionVec3b)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec3b(MatForeachFunctionVec3b operation)

Parameters

operation MatForeachFunctionVec3b

ForEachAsVec3d(MatForeachFunctionVec3d)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec3d(MatForeachFunctionVec3d operation)

Parameters

operation MatForeachFunctionVec3d

ForEachAsVec3f(MatForeachFunctionVec3f)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec3f(MatForeachFunctionVec3f operation)

Parameters

operation MatForeachFunctionVec3f

ForEachAsVec3i(MatForeachFunctionVec3i)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec3i(MatForeachFunctionVec3i operation)

Parameters

operation MatForeachFunctionVec3i

ForEachAsVec3s(MatForeachFunctionVec3s)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec3s(MatForeachFunctionVec3s operation)

Parameters

operation MatForeachFunctionVec3s

ForEachAsVec4b(MatForeachFunctionVec4b)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec4b(MatForeachFunctionVec4b operation)

Parameters

operation MatForeachFunctionVec4b

ForEachAsVec4d(MatForeachFunctionVec4d)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec4d(MatForeachFunctionVec4d operation)

Parameters

operation MatForeachFunctionVec4d

ForEachAsVec4f(MatForeachFunctionVec4f)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec4f(MatForeachFunctionVec4f operation)

Parameters

operation MatForeachFunctionVec4f

ForEachAsVec4i(MatForeachFunctionVec4i)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec4i(MatForeachFunctionVec4i operation)

Parameters

operation MatForeachFunctionVec4i

ForEachAsVec4s(MatForeachFunctionVec4s)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec4s(MatForeachFunctionVec4s operation)

Parameters

operation MatForeachFunctionVec4s

ForEachAsVec6b(MatForeachFunctionVec6b)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec6b(MatForeachFunctionVec6b operation)

Parameters

operation MatForeachFunctionVec6b

ForEachAsVec6d(MatForeachFunctionVec6d)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec6d(MatForeachFunctionVec6d operation)

Parameters

operation MatForeachFunctionVec6d

ForEachAsVec6f(MatForeachFunctionVec6f)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec6f(MatForeachFunctionVec6f operation)

Parameters

operation MatForeachFunctionVec6f

ForEachAsVec6i(MatForeachFunctionVec6i)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec6i(MatForeachFunctionVec6i operation)

Parameters

operation MatForeachFunctionVec6i

ForEachAsVec6s(MatForeachFunctionVec6s)

Runs the given functor over all matrix elements in parallel.

public void ForEachAsVec6s(MatForeachFunctionVec6s operation)

Parameters

operation MatForeachFunctionVec6s

FromArray<TElem>(IEnumerable<TElem>)

Initializes as N x 1 matrix and copies array data to this

public static Mat<TElem> FromArray<TElem>(IEnumerable<TElem> enumerable) where TElem : unmanaged

Parameters

enumerable IEnumerable<TElem>

Source array data to be copied to this

Returns

Mat<TElem>

Type Parameters

TElem

FromArray<TElem>(TElem[,])

Initializes as M x N matrix and copies array data to this

public static Mat<TElem> FromArray<TElem>(TElem[,] arr) where TElem : unmanaged

Parameters

arr TElem[,]

Source array data to be copied to this

Returns

Mat<TElem>

Type Parameters

TElem

FromArray<TElem>(params TElem[])

Initializes as N x 1 matrix and copies array data to this

public static Mat<TElem> FromArray<TElem>(params TElem[] arr) where TElem : unmanaged

Parameters

arr TElem[]

Source array data to be copied to this

Returns

Mat<TElem>

Type Parameters

TElem

FromImageData(byte[], ImreadModes)

Creates the Mat instance from image data (using cv::decode)

public static Mat FromImageData(byte[] imageBytes, ImreadModes mode = ImreadModes.Color)

Parameters

imageBytes byte[]
mode ImreadModes

Returns

Mat

FromImageData(ReadOnlySpan<byte>, ImreadModes)

Reads image from the specified buffer in memory.

public static Mat FromImageData(ReadOnlySpan<byte> span, ImreadModes mode = ImreadModes.Color)

Parameters

span ReadOnlySpan<byte>

The input slice of bytes.

mode ImreadModes

The same flags as in imread

Returns

Mat

FromNativePointer(nint)

Creates from native cv::Mat* pointer

public static Mat FromNativePointer(nint ptr)

Parameters

ptr nint

Returns

Mat

FromPixelData(IEnumerable<int>, MatType, Array, IEnumerable<long>?)

constructor for matrix headers pointing to user-allocated data

public static Mat FromPixelData(IEnumerable<int> sizes, MatType type, Array data, IEnumerable<long>? steps = null)

Parameters

sizes IEnumerable<int>

Array of integers specifying an n-dimensional array shape.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data Array

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

steps IEnumerable<long>

Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.

Returns

Mat

FromPixelData(IEnumerable<int>, MatType, nint, IEnumerable<long>?)

constructor for matrix headers pointing to user-allocated data

public static Mat FromPixelData(IEnumerable<int> sizes, MatType type, nint data, IEnumerable<long>? steps = null)

Parameters

sizes IEnumerable<int>

Array of integers specifying an n-dimensional array shape.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data nint

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

steps IEnumerable<long>

Array of ndims-1 steps in case of a multi-dimensional array (the last step is always set to the element size). If not specified, the matrix is assumed to be continuous.

Returns

Mat

FromPixelData(int, int, MatType, Array, long)

constructor for matrix headers pointing to user-allocated data

public static Mat FromPixelData(int rows, int cols, MatType type, Array data, long step = 0)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data Array

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

step long

Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() .

Returns

Mat

FromPixelData(int, int, MatType, nint, long)

constructor for matrix headers pointing to user-allocated data

public static Mat FromPixelData(int rows, int cols, MatType type, nint data, long step = 0)

Parameters

rows int

Number of rows in a 2D array.

cols int

Number of columns in a 2D array.

type MatType

Array type. Use MatType.CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or MatType. CV_8UC(n), ..., CV_64FC(n) to create multi-channel matrices.

data nint

Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically de-allocated, so you should take care of it.

step long

Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize() .

Returns

Mat

FromStream(Stream, ImreadModes)

Creates the Mat instance from System.IO.Stream

public static Mat FromStream(Stream stream, ImreadModes mode)

Parameters

stream Stream
mode ImreadModes

Returns

Mat

GaussianBlur(Size, double, double, BorderTypes)

Blurs an image using a Gaussian filter. The input image can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.

public Mat GaussianBlur(Size ksize, double sigmaX, double sigmaY = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ksize Size

Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero’s and then they are computed from sigma* .

sigmaX double

Gaussian kernel standard deviation in X direction.

sigmaY double

Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see getGaussianKernel() for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY.

borderType BorderTypes

pixel extrapolation method

Returns

Mat

GetArray<T>(out T[])

Get the data of this matrix as array

[Pure]
public bool GetArray<T>(out T[] data) where T : unmanaged

Parameters

data T[]

Primitive or Vec array to be copied

Returns

bool

Length of copied bytes

Type Parameters

T

Examples

using var m1 = new Mat(1, 1, MatType.CV_8UC1); m1.GetArray(out byte[] array);

using var m2 = new Mat(1, 1, MatType.CV_32SC1); m2.GetArray(out int[] array);

using var m3 = new Mat(1, 1, MatType.CV_8UC(6)); m3.GetArray(out Vec6b[] array);

using var m4 = new Mat(1, 1, MatType.CV_64FC4); m4.GetArray(out Vec4d[] array);

GetDefaultNewCameraMatrix(Size?, bool)

returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true)

public Mat GetDefaultNewCameraMatrix(Size? imgSize = null, bool centerPrincipalPoint = false)

Parameters

imgSize Size?

Camera view image size in pixels.

centerPrincipalPoint bool

Location of the principal point in the new camera matrix. The parameter indicates whether this location should be at the image center or not.

Returns

Mat

the camera matrix that is either an exact copy of the input cameraMatrix (when centerPrinicipalPoint=false), or the modified one (when centerPrincipalPoint=true).

GetGenericIndexer<T>()

Gets a type-specific indexer. The indexer has getters/setters to access each matrix element.

public Mat.Indexer<T> GetGenericIndexer<T>() where T : struct

Returns

Mat.Indexer<T>

Type Parameters

T

GetRectSubPix(Size, Point2f, int)

Retrieves a pixel rectangle from an image with sub-pixel accuracy.

public Mat GetRectSubPix(Size patchSize, Point2f center, int patchType = -1)

Parameters

patchSize Size

Size of the extracted patch.

center Point2f

Floating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image.

patchType int

Depth of the extracted pixels. By default, they have the same depth as src.

Returns

Mat

Extracted patch that has the size patchSize and the same number of channels as src .

GetRectangularArray<T>(out T[,])

Get the data of this matrix as array

[Pure]
public bool GetRectangularArray<T>(out T[,] data) where T : unmanaged

Parameters

data T[,]

Primitive or Vec array to be copied

Returns

bool

Length of copied bytes

Type Parameters

T

Examples

using var m1 = new Mat(1, 1, MatType.CV_8UC1); m1.GetRectangularArray(out byte[,] array);

using var m2 = new Mat(1, 1, MatType.CV_32SC1); m2.GetRectangularArray(out int[,] array);

using var m3 = new Mat(1, 1, MatType.CV_8UC(6)); m3.GetRectangularArray(out Vec6b[,] array);

using var m4 = new Mat(1, 1, MatType.CV_64FC4); m4.GetRectangularArray(out Vec4d[,] array);

GetUMat(AccessFlag, UMatUsageFlags)

Retrieve UMat from Mat

public UMat GetUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags)

Parameters

accessFlags AccessFlag
usageFlags UMatUsageFlags

Returns

UMat

GetUnsafeGenericIndexer<T>()

Gets a type-specific unsafe indexer. The indexer has getters/setters to access each matrix element.

public Mat.UnsafeIndexer<T> GetUnsafeGenericIndexer<T>() where T : unmanaged

Returns

Mat.UnsafeIndexer<T>

Type Parameters

T

Get<T>(int)

Returns a value to the specified array element.

public T Get<T>(int i0) where T : struct

Parameters

i0 int

Index along the dimension 0

Returns

T

A value to the specified array element.

Type Parameters

T

Get<T>(int, int)

Returns a value to the specified array element.

public T Get<T>(int i0, int i1) where T : struct

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

Returns

T

A value to the specified array element.

Type Parameters

T

Get<T>(int, int, int)

Returns a value to the specified array element.

public T Get<T>(int i0, int i1, int i2) where T : struct

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

i2 int

Index along the dimension 2

Returns

T

A value to the specified array element.

Type Parameters

T

Get<T>(params int[])

Returns a value to the specified array element.

public T Get<T>(params int[] idx) where T : struct

Parameters

idx int[]

Array of Mat::dims indices.

Returns

T

A value to the specified array element.

Type Parameters

T

GoodFeaturesToTrack(int, double, double, InputArray, int, bool, double)

Finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima. Input matrix must be 8-bit or floating-point 32-bit, single-channel image.

public Point2f[] GoodFeaturesToTrack(int maxCorners, double qualityLevel, double minDistance, InputArray mask, int blockSize, bool useHarrisDetector, double k)

Parameters

maxCorners int

Maximum number of corners to return. If there are more corners than are found, the strongest of them is returned.

qualityLevel double

Parameter characterizing the minimal accepted quality of image corners. The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue or the Harris function response (see cornerHarris() ). The corners with the quality measure less than the product are rejected. For example, if the best corner has the quality measure = 1500, and the qualityLevel=0.01, then all the corners with the quality measure less than 15 are rejected.

minDistance double

Minimum possible Euclidean distance between the returned corners.

mask InputArray

Optional region of interest. If the image is not empty (it needs to have the type CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected.

blockSize int

Size of an average block for computing a derivative covariation matrix over each pixel neighborhood.

useHarrisDetector bool

Parameter indicating whether to use a Harris detector

k double

Free parameter of the Harris detector.

Returns

Point2f[]

Output vector of detected corners.

GrabCut(InputOutputArray, Rect, InputOutputArray, InputOutputArray, int, GrabCutModes)

Segments the image using GrabCut algorithm. The input is 8-bit 3-channel image.

public void GrabCut(InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, GrabCutModes mode)

Parameters

mask InputOutputArray

Input/output 8-bit single-channel mask. The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. Its elements may have Cv2.GC_BGD / Cv2.GC_FGD / Cv2.GC_PR_BGD / Cv2.GC_PR_FGD

rect Rect

ROI containing a segmented object. The pixels outside of the ROI are marked as "obvious background". The parameter is only used when mode==GC_INIT_WITH_RECT.

bgdModel InputOutputArray

Temporary array for the background model. Do not modify it while you are processing the same image.

fgdModel InputOutputArray

Temporary arrays for the foreground model. Do not modify it while you are processing the same image.

iterCount int

Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL .

mode GrabCutModes

Operation mode that could be one of GrabCutFlag value.

GreaterThan(Mat)

operator >

public MatExpr GreaterThan(Mat m)

Parameters

m Mat

Returns

MatExpr

GreaterThan(double)

operator >

public MatExpr GreaterThan(double d)

Parameters

d double

Returns

MatExpr

GreaterThanOrEqual(Mat)

operator >=

public MatExpr GreaterThanOrEqual(Mat m)

Parameters

m Mat

Returns

MatExpr

GreaterThanOrEqual(double)

operator >=

public MatExpr GreaterThanOrEqual(double d)

Parameters

d double

Returns

MatExpr

HoughCircles(HoughModes, double, double, double, double, int, int)

Finds circles in a grayscale image using a Hough transform. The input matrix must be 8-bit, single-channel and grayscale.

public CircleSegment[] HoughCircles(HoughModes method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0)

Parameters

method HoughModes

The available methods are HoughMethods.Gradient and HoughMethods.GradientAlt

dp double

The inverse ratio of the accumulator resolution to the image resolution.

minDist double

Minimum distance between the centers of the detected circles.

param1 double

The first method-specific parameter. [By default this is 100]

param2 double

The second method-specific parameter. [By default this is 100]

minRadius int

Minimum circle radius. [By default this is 0]

maxRadius int

Maximum circle radius. [By default this is 0]

Returns

CircleSegment[]

The output vector found circles. Each vector is encoded as 3-element floating-point vector (x, y, radius)

HoughLines(double, double, int, double, double)

Finds lines in a binary image using standard Hough transform. The input matrix must be 8-bit, single-channel, binary source image. This image may be modified by the function.

public LineSegmentPolar[] HoughLines(double rho, double theta, int threshold, double srn = 0, double stn = 0)

Parameters

rho double

Distance resolution of the accumulator in pixels

theta double

Angle resolution of the accumulator in radians

threshold int

The accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold )

srn double

For the multi-scale Hough transform it is the divisor for the distance resolution rho. [By default this is 0]

stn double

For the multi-scale Hough transform it is the divisor for the distance resolution theta. [By default this is 0]

Returns

LineSegmentPolar[]

The output vector of lines. Each line is represented by a two-element vector (rho, theta) . rho is the distance from the coordinate origin (0,0) (top-left corner of the image) and theta is the line rotation angle in radians

HoughLinesP(double, double, int, double, double)

Finds lines segments in a binary image using probabilistic Hough transform.

public LineSegmentPoint[] HoughLinesP(double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0)

Parameters

rho double

Distance resolution of the accumulator in pixels

theta double

Angle resolution of the accumulator in radians

threshold int

The accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold )

minLineLength double

The minimum line length. Line segments shorter than that will be rejected. [By default this is 0]

maxLineGap double

The maximum allowed gap between points on the same line to link them. [By default this is 0]

Returns

LineSegmentPoint[]

The output lines. Each line is represented by a 4-element vector (x1, y1, x2, y2)

Idct(DctFlags)

performs inverse 1D or 2D Discrete Cosine Transformation

public Mat Idct(DctFlags flags = DctFlags.None)

Parameters

flags DctFlags

Transformation flags, a combination of DctFlag2 values

Returns

Mat

The destination array; will have the same size and same type as src

Idft(DftFlags, int)

Performs an inverse Discrete Fourier transform of 1D or 2D floating-point array.

public Mat Idft(DftFlags flags = DftFlags.None, int nonzeroRows = 0)

Parameters

flags DftFlags

Transformation flags, a combination of the DftFlag2 values

nonzeroRows int

When the parameter != 0, the function assumes that only the first nonzeroRows rows of the input array ( DFT_INVERSE is not set) or only the first nonzeroRows of the output array ( DFT_INVERSE is set) contain non-zeros, thus the function can handle the rest of the rows more efficiently and thus save some time. This technique is very useful for computing array cross-correlation or convolution using DFT

Returns

Mat

The destination array, which size and type depends on the flags

ImDecode(byte[], ImreadModes)

Creates the Mat instance from image data (using cv::decode)

public static Mat ImDecode(byte[] imageBytes, ImreadModes mode = ImreadModes.Color)

Parameters

imageBytes byte[]
mode ImreadModes

Returns

Mat

ImDecode(ReadOnlySpan<byte>, ImreadModes)

Reads image from the specified buffer in memory.

public static Mat ImDecode(ReadOnlySpan<byte> span, ImreadModes mode = ImreadModes.Color)

Parameters

span ReadOnlySpan<byte>

The input slice of bytes.

mode ImreadModes

The same flags as in imread

Returns

Mat

ImEncode(string, params ImageEncodingParam[])

Encodes an image into a memory buffer.

public byte[] ImEncode(string ext = ".png", params ImageEncodingParam[] prms)

Parameters

ext string

Encodes an image into a memory buffer.

prms ImageEncodingParam[]

Format-specific parameters.

Returns

byte[]

ImEncode(string, int[]?)

Encodes an image into a memory buffer.

public byte[] ImEncode(string ext = ".png", int[]? prms = null)

Parameters

ext string

Encodes an image into a memory buffer.

prms int[]

Format-specific parameters.

Returns

byte[]

ImWrite(string, params ImageEncodingParam[])

Saves an image to a specified file.

public bool ImWrite(string fileName, params ImageEncodingParam[] prms)

Parameters

fileName string
prms ImageEncodingParam[]

Returns

bool

ImWrite(string, int[]?)

Saves an image to a specified file.

public bool ImWrite(string fileName, int[]? prms = null)

Parameters

fileName string
prms int[]

Returns

bool

InRange(InputArray, InputArray)

Checks if array elements lie between the elements of two other arrays.

public Mat InRange(InputArray lowerb, InputArray upperb)

Parameters

lowerb InputArray

inclusive lower boundary array or a scalar.

upperb InputArray

inclusive upper boundary array or a scalar.

Returns

Mat

The destination array, will have the same size as src and CV_8U type

InRange(Scalar, Scalar)

Checks if array elements lie between the elements of two other arrays.

public Mat InRange(Scalar lowerb, Scalar upperb)

Parameters

lowerb Scalar

inclusive lower boundary array or a scalar.

upperb Scalar

inclusive upper boundary array or a scalar.

Returns

Mat

The destination array, will have the same size as src and CV_8U type

InsertChannel(InputOutputArray, int)

inserts a single channel to dst (coi is 0-based index)

public void InsertChannel(InputOutputArray dst, int coi)

Parameters

dst InputOutputArray
coi int

Inv(DecompTypes)

Inverses a matrix.

public MatExpr Inv(DecompTypes method = DecompTypes.LU)

Parameters

method DecompTypes

Matrix inversion method

Returns

MatExpr

InvertAffineTransform()

Inverts an affine transformation.

public Mat InvertAffineTransform()

Returns

Mat

Output reverse affine transformation.

IsContinuous()

Reports whether the matrix is continuous or not.

public bool IsContinuous()

Returns

bool

IsContourConvex()

Returns true if the contour is convex. Does not support contours with self-intersection

public bool IsContourConvex()

Returns

bool

IsSubmatrix()

Returns whether this matrix is a part of other matrix or not.

public bool IsSubmatrix()

Returns

bool

LUT(InputArray)

transforms array of numbers using a lookup table: dst(i)=lut(src(i))

public Mat LUT(InputArray lut)

Parameters

lut InputArray

Look-up table of 256 elements. In the case of multi-channel source array, the table should either have a single channel (in this case the same table is used for all channels) or the same number of channels as in the source array

Returns

Mat

LUT(byte[])

transforms array of numbers using a lookup table: dst(i)=lut(src(i))

public Mat LUT(byte[] lut)

Parameters

lut byte[]

Look-up table of 256 elements. In the case of multi-channel source array, the table should either have a single channel (in this case the same table is used for all channels) or the same number of channels as in the source array

Returns

Mat

Laplacian(MatType, int, double, double, BorderTypes)

Calculates the Laplacian of an image

public Mat Laplacian(MatType ddepth, int ksize = 1, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType

The desired depth of the destination image

ksize int

The aperture size used to compute the second-derivative filters

scale double

The optional scale factor for the computed Laplacian values (by default, no scaling is applied

delta double

The optional delta value, added to the results prior to storing them in dst

borderType BorderTypes

The pixel extrapolation method

Returns

Mat

Destination image; will have the same size and the same number of channels as src

LessThan(Mat)

operator <

public MatExpr LessThan(Mat m)

Parameters

m Mat

Returns

MatExpr

LessThan(double)

operator <

public MatExpr LessThan(double d)

Parameters

d double

Returns

MatExpr

LessThanOrEqual(Mat)

operator <=

public MatExpr LessThanOrEqual(Mat m)

Parameters

m Mat

Returns

MatExpr

LessThanOrEqual(double)

operator <=

public MatExpr LessThanOrEqual(double d)

Parameters

d double

Returns

MatExpr

Line(Point, Point, Scalar, int, LineTypes, int)

Draws a line segment connecting two points

public void Line(Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

pt1 Point

First point of the line segment.

pt2 Point

Second point of the line segment.

color Scalar

Line color.

thickness int

Line thickness. [By default this is 1]

lineType LineTypes

Type of the line. [By default this is LineType.Link8]

shift int

Number of fractional bits in the point coordinates. [By default this is 0]

Line(int, int, int, int, Scalar, int, LineTypes, int)

Draws a line segment connecting two points

public void Line(int pt1X, int pt1Y, int pt2X, int pt2Y, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

pt1X int

First point's x-coordinate of the line segment.

pt1Y int

First point's y-coordinate of the line segment.

pt2X int

Second point's x-coordinate of the line segment.

pt2Y int

Second point's y-coordinate of the line segment.

color Scalar

Line color.

thickness int

Line thickness. [By default this is 1]

lineType LineTypes

Type of the line. [By default this is LineType.Link8]

shift int

Number of fractional bits in the point coordinates. [By default this is 0]

LocateROI(out Size, out Point)

Locates the matrix header within a parent matrix.

public void LocateROI(out Size wholeSize, out Point ofs)

Parameters

wholeSize Size

Output parameter that contains the size of the whole matrix containing *this as a part.

ofs Point

Output parameter that contains an offset of *this inside the whole matrix.

Log()

computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))

public Mat Log()

Returns

Mat

The destination array; will have the same size and same type as src

MatchTemplate(InputArray, TemplateMatchModes, InputArray?)

Computes the proximity map for the raster template and the image where the template is searched for The input is Image where the search is running; should be 8-bit or 32-bit floating-point.

public Mat MatchTemplate(InputArray templ, TemplateMatchModes method, InputArray? mask = null)

Parameters

templ InputArray

Searched template; must be not greater than the source image and have the same data type

method TemplateMatchModes

Specifies the comparison method

mask InputArray

Mask of searched template. It must have the same datatype and size with templ. It is not set by default.

Returns

Mat

A map of comparison results; will be single-channel 32-bit floating-point. If image is WxH and templ is wxh then result will be (W-w+1) x (H-h+1).

Mean(InputArray?)

computes mean value of selected array elements

public Scalar Mean(InputArray? mask = null)

Parameters

mask InputArray

The optional operation mask

Returns

Scalar

MeanStdDev(OutputArray, OutputArray, InputArray?)

computes mean value and standard deviation of all or selected array elements

public void MeanStdDev(OutputArray mean, OutputArray stddev, InputArray? mask = null)

Parameters

mean OutputArray

The output parameter: computed mean value

stddev OutputArray

The output parameter: computed standard deviation

mask InputArray

The optional operation mask

MedianBlur(int)

Smoothes image using median filter. The source image must have 1-, 3- or 4-channel and its depth should be CV_8U , CV_16U or CV_32F.

public Mat MedianBlur(int ksize)

Parameters

ksize int

The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ...

Returns

Mat

The destination array; will have the same size and the same type as src.

MinAreaRect()

Finds the minimum area rotated rectangle enclosing a 2D point set. The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix.

public RotatedRect MinAreaRect()

Returns

RotatedRect

MinEnclosingCircle(out Point2f, out float)

Finds the minimum area circle enclosing a 2D point set. The input is 2D point set, represented by CV_32SC2 or CV_32FC2 matrix.

public void MinEnclosingCircle(out Point2f center, out float radius)

Parameters

center Point2f

The output center of the circle

radius float

The output radius of the circle

MinMaxIdx(out double, out double)

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxIdx(out double minVal, out double maxVal)

Parameters

minVal double

Pointer to returned minimum value

maxVal double

Pointer to returned maximum value

MinMaxIdx(out double, out double, int[], int[], InputArray?)

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxIdx(out double minVal, out double maxVal, int[] minIdx, int[] maxIdx, InputArray? mask = null)

Parameters

minVal double

Pointer to returned minimum value

maxVal double

Pointer to returned maximum value

minIdx int[]
maxIdx int[]
mask InputArray

MinMaxIdx(int[], int[])

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxIdx(int[] minIdx, int[] maxIdx)

Parameters

minIdx int[]
maxIdx int[]

MinMaxLoc(out Point, out Point)

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxLoc(out Point minLoc, out Point maxLoc)

Parameters

minLoc Point

Pointer to returned minimum location

maxLoc Point

Pointer to returned maximum location

MinMaxLoc(out double, out double)

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxLoc(out double minVal, out double maxVal)

Parameters

minVal double

Pointer to returned minimum value

maxVal double

Pointer to returned maximum value

MinMaxLoc(out double, out double, out Point, out Point, InputArray?)

finds global minimum and maximum array elements and returns their values and their locations

public void MinMaxLoc(out double minVal, out double maxVal, out Point minLoc, out Point maxLoc, InputArray? mask = null)

Parameters

minVal double

Pointer to returned minimum value

maxVal double

Pointer to returned maximum value

minLoc Point

Pointer to returned minimum location

maxLoc Point

Pointer to returned maximum location

mask InputArray

The optional mask used to select a sub-array

Moments(bool)

Calculates all of the moments up to the third order of a polygon or rasterized shape. The input is a raster image (single-channel, 8-bit or floating-point 2D array).

public Moments Moments(bool binaryImage = false)

Parameters

binaryImage bool

If it is true, then all the non-zero image pixels are treated as 1’s

Returns

Moments

MorphologyEx(MorphTypes, InputArray?, Point?, int, BorderTypes, Scalar?)

Performs advanced morphological transformations

public Mat MorphologyEx(MorphTypes op, InputArray? element, Point? anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

op MorphTypes

Type of morphological operation

element InputArray

Structuring element

anchor Point?

Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center

iterations int

Number of times erosion and dilation are applied. [By default this is 1]

borderType BorderTypes

The pixel extrapolation method. [By default this is BorderTypes.Constant]

borderValue Scalar?

The border value in case of a constant border. The default value has a special meaning. [By default this is CvCpp.MorphologyDefaultBorderValue()]

Returns

Mat

Destination image. It will have the same size and the same type as src

Mul(InputArray, double)

Performs an element-wise multiplication or division of the two matrices.

public MatExpr Mul(InputArray m, double scale = 1)

Parameters

m InputArray
scale double

Returns

MatExpr

MulTransposed(bool, InputArray?, double, int)

multiplies matrix by its transposition from the left or from the right

public Mat MulTransposed(bool aTa, InputArray? delta = null, double scale = 1, int dtype = -1)

Parameters

aTa bool

Specifies the multiplication ordering; see the description below

delta InputArray

The optional delta matrix, subtracted from src before the multiplication. When the matrix is empty ( delta=Mat() ), it’s assumed to be zero, i.e. nothing is subtracted, otherwise if it has the same size as src, then it’s simply subtracted, otherwise it is "repeated" to cover the full src and then subtracted. Type of the delta matrix, when it's not empty, must be the same as the type of created destination matrix, see the rtype description

scale double

The optional scale factor for the matrix product

dtype int

When it’s negative, the destination matrix will have the same type as src . Otherwise, it will have type=CV_MAT_DEPTH(rtype), which should be either CV_32F or CV_64F

Returns

Mat

Multiply(Mat)

public MatExpr Multiply(Mat m)

Parameters

m Mat

Returns

MatExpr

Multiply(double)

public MatExpr Multiply(double s)

Parameters

s double

Returns

MatExpr

Negate()

public MatExpr Negate()

Returns

MatExpr

Norm(NormTypes, InputArray?)

computes norm of the selected array part

public double Norm(NormTypes normType = NormTypes.L2, InputArray? mask = null)

Parameters

normType NormTypes

Type of the norm

mask InputArray

The optional operation mask

Returns

double

Normalize(double, double, NormTypes, int, InputArray?)

scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values

public Mat Normalize(double alpha = 1, double beta = 0, NormTypes normType = NormTypes.L2, int dtype = -1, InputArray? mask = null)

Parameters

alpha double

The norm value to normalize to or the lower range boundary in the case of range normalization

beta double

The upper range boundary in the case of range normalization; not used for norm normalization

normType NormTypes

The normalization type

dtype int

When the parameter is negative, the destination array will have the same type as src, otherwise it will have the same number of channels as src and the depth =CV_MAT_DEPTH(rtype)

mask InputArray

The optional operation mask

Returns

Mat

NotEquals(Mat)

operator !=

public MatExpr NotEquals(Mat m)

Parameters

m Mat

Returns

MatExpr

NotEquals(double)

operator !=

public MatExpr NotEquals(double d)

Parameters

d double

Returns

MatExpr

Ones(MatType, params int[])

Returns an array of all 1’s of the specified size and type.

public static MatExpr Ones(MatType type, params int[] sizes)

Parameters

type MatType

Created matrix type.

sizes int[]

Array of integers specifying the array shape.

Returns

MatExpr

Ones(Size, MatType)

Returns an array of all 1’s of the specified size and type.

public static MatExpr Ones(Size size, MatType type)

Parameters

size Size

Alternative to the matrix size specification Size(cols, rows) .

type MatType

Created matrix type.

Returns

MatExpr

Ones(int, int, MatType)

Returns an array of all 1’s of the specified size and type.

public static MatExpr Ones(int rows, int cols, MatType type)

Parameters

rows int

Number of rows.

cols int

Number of columns.

type MatType

Created matrix type.

Returns

MatExpr

OnesComplement()

public MatExpr OnesComplement()

Returns

MatExpr

PatchNaNs(double)

converts NaN's to the given number

public void PatchNaNs(double val = 0)

Parameters

val double

PerspectiveTransform(InputArray)

performs perspective transformation of each element of multi-channel input matrix

public Mat PerspectiveTransform(InputArray m)

Parameters

m InputArray

3x3 or 4x4 transformation matrix

Returns

Mat

The destination array; it will have the same size and same type as src

Plus()

public MatExpr Plus()

Returns

MatExpr

PointPolygonTest(Point2f, bool)

Checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary.

public double PointPolygonTest(Point2f pt, bool measureDist)

Parameters

pt Point2f

Point tested against the contour.

measureDist bool

If true, the function estimates the signed distance from the point to the nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not.

Returns

double

Positive (inside), negative (outside), or zero (on an edge) value.

Polylines(IEnumerable<IEnumerable<Point>>, bool, Scalar, int, LineTypes, int)

draws one or more polygonal curves

public void Polylines(IEnumerable<IEnumerable<Point>> pts, bool isClosed, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

pts IEnumerable<IEnumerable<Point>>
isClosed bool
color Scalar
thickness int
lineType LineTypes
shift int

PopBack(int)

removes several hyper-planes from bottom of the matrix (Mat.pop_back)

public void PopBack(int nElems = 1)

Parameters

nElems int

Pow(double)

raises the input matrix elements to the specified power (b = a**power)

public Mat Pow(double power)

Parameters

power double

The exponent of power

Returns

Mat

The destination array; will have the same size and the same type as src

PreCornerDetect(int, BorderTypes)

computes another complex cornerness criteria at each pixel

public Mat PreCornerDetect(int ksize, BorderTypes borderType = BorderTypes.Default)

Parameters

ksize int
borderType BorderTypes

Returns

Mat

Ptr(int)

Returns a pointer to the specified matrix row.

public nint Ptr(int i0)

Parameters

i0 int

Index along the dimension 0

Returns

nint

Ptr(int, int)

Returns a pointer to the specified matrix element.

public nint Ptr(int i0, int i1)

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

Returns

nint

Ptr(int, int, int)

Returns a pointer to the specified matrix element.

public nint Ptr(int i0, int i1, int i2)

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

i2 int

Index along the dimension 2

Returns

nint

Ptr(params int[])

Returns a pointer to the specified matrix element.

public nint Ptr(params int[] idx)

Parameters

idx int[]

Array of Mat::dims indices.

Returns

nint

PushBack(Mat)

Adds elements to the bottom of the matrix. (Mat.push_back)

public void PushBack(Mat m)

Parameters

m Mat

Added line(s)

PushBack(Point)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point value)

Parameters

value Point

Added element

PushBack(Point2d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point2d value)

Parameters

value Point2d

Added element

PushBack(Point2f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point2f value)

Parameters

value Point2f

Added element

PushBack(Point3d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point3d value)

Parameters

value Point3d

Added element

PushBack(Point3f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point3f value)

Parameters

value Point3f

Added element

PushBack(Point3i)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Point3i value)

Parameters

value Point3i

Added element

PushBack(Rect)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Rect value)

Parameters

value Rect

Added element

PushBack(Rect2d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Rect2d value)

Parameters

value Rect2d

Added element

PushBack(Rect2f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Rect2f value)

Parameters

value Rect2f

Added element

PushBack(Size)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Size value)

Parameters

value Size

Added element

PushBack(Size2d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Size2d value)

Parameters

value Size2d

Added element

PushBack(Size2f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Size2f value)

Parameters

value Size2f

Added element

PushBack(Vec2b)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2b value)

Parameters

value Vec2b

Added element

PushBack(Vec2d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2d value)

Parameters

value Vec2d

Added element

PushBack(Vec2f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2f value)

Parameters

value Vec2f

Added element

PushBack(Vec2i)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2i value)

Parameters

value Vec2i

Added element

PushBack(Vec2s)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2s value)

Parameters

value Vec2s

Added element

PushBack(Vec2w)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec2w value)

Parameters

value Vec2w

Added element

PushBack(Vec3b)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3b value)

Parameters

value Vec3b

Added element

PushBack(Vec3d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3d value)

Parameters

value Vec3d

Added element

PushBack(Vec3f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3f value)

Parameters

value Vec3f

Added element

PushBack(Vec3i)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3i value)

Parameters

value Vec3i

Added element

PushBack(Vec3s)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3s value)

Parameters

value Vec3s

Added element

PushBack(Vec3w)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec3w value)

Parameters

value Vec3w

Added element

PushBack(Vec4b)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4b value)

Parameters

value Vec4b

Added element

PushBack(Vec4d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4d value)

Parameters

value Vec4d

Added element

PushBack(Vec4f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4f value)

Parameters

value Vec4f

Added element

PushBack(Vec4i)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4i value)

Parameters

value Vec4i

Added element

PushBack(Vec4s)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4s value)

Parameters

value Vec4s

Added element

PushBack(Vec4w)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec4w value)

Parameters

value Vec4w

Added element

PushBack(Vec6b)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6b value)

Parameters

value Vec6b

Added element

PushBack(Vec6d)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6d value)

Parameters

value Vec6d

Added element

PushBack(Vec6f)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6f value)

Parameters

value Vec6f

Added element

PushBack(Vec6i)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6i value)

Parameters

value Vec6i

Added element

PushBack(Vec6s)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6s value)

Parameters

value Vec6s

Added element

PushBack(Vec6w)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(Vec6w value)

Parameters

value Vec6w

Added element

PushBack(byte)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(byte value)

Parameters

value byte

Added element

PushBack(double)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(double value)

Parameters

value double

Added element

PushBack(short)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(short value)

Parameters

value short

Added element

PushBack(int)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(int value)

Parameters

value int

Added element

PushBack(sbyte)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(sbyte value)

Parameters

value sbyte

Added element

PushBack(float)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(float value)

Parameters

value float

Added element

PushBack(ushort)

Adds elements to the bottom of the matrix. (Mat::push_back)

public void PushBack(ushort value)

Parameters

value ushort

Added element

PutText(string, Point, HersheyFonts, double, Scalar, int, LineTypes, bool)

renders text string in the image

public void PutText(string text, Point org, HersheyFonts fontFace, double fontScale, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, bool bottomLeftOrigin = false)

Parameters

text string
org Point
fontFace HersheyFonts
fontScale double
color Scalar
thickness int
lineType LineTypes
bottomLeftOrigin bool

PyrDown(Size?, BorderTypes)

Blurs an image and downsamples it.

public Mat PyrDown(Size? dstSize = null, BorderTypes borderType = BorderTypes.Default)

Parameters

dstSize Size?

size of the output image; by default, it is computed as Size((src.cols+1)/2

borderType BorderTypes

Returns

Mat

PyrMeanShiftFiltering(double, double, int, TermCriteria?)

Performs initial step of meanshift segmentation of an image. The source matrix is 8-bit, 3-channel image.

public Mat PyrMeanShiftFiltering(double sp, double sr, int maxLevel = 1, TermCriteria? termcrit = null)

Parameters

sp double

The spatial window radius.

sr double

The color window radius.

maxLevel int

Maximum level of the pyramid for the segmentation.

termcrit TermCriteria?

Termination criteria: when to stop meanshift iterations.

Returns

Mat

The destination image of the same format and the same size as the source.

PyrUp(Size?, BorderTypes)

Upsamples an image and then blurs it.

public Mat PyrUp(Size? dstSize = null, BorderTypes borderType = BorderTypes.Default)

Parameters

dstSize Size?

size of the output image; by default, it is computed as Size(src.cols2, (src.rows2)

borderType BorderTypes

Returns

Mat

RandShuffle(double)

shuffles the input array elements

public void RandShuffle(double iterFactor)

Parameters

iterFactor double

The scale factor that determines the number of random swap operations.

RandShuffle(double, ref RNG)

shuffles the input array elements

public void RandShuffle(double iterFactor, ref RNG rng)

Parameters

iterFactor double

The scale factor that determines the number of random swap operations.

rng RNG

The optional random number generator used for shuffling. If it is null, theRng() is used instead.

Randn(InputArray, InputArray)

fills array with normally-distributed random numbers with the specified mean and the standard deviation

public void Randn(InputArray mean, InputArray stddev)

Parameters

mean InputArray

The mean value (expectation) of the generated random numbers

stddev InputArray

The standard deviation of the generated random numbers

Randn(Scalar, Scalar)

fills array with normally-distributed random numbers with the specified mean and the standard deviation

public void Randn(Scalar mean, Scalar stddev)

Parameters

mean Scalar

The mean value (expectation) of the generated random numbers

stddev Scalar

The standard deviation of the generated random numbers

Randu(InputArray, InputArray)

fills array with uniformly-distributed random numbers from the range [low, high)

public void Randu(InputArray low, InputArray high)

Parameters

low InputArray

The inclusive lower boundary of the generated random numbers

high InputArray

The exclusive upper boundary of the generated random numbers

Randu(Scalar, Scalar)

fills array with uniformly-distributed random numbers from the range [low, high)

public void Randu(Scalar low, Scalar high)

Parameters

low Scalar

The inclusive lower boundary of the generated random numbers

high Scalar

The exclusive upper boundary of the generated random numbers

Rectangle(Point, Point, Scalar, int, LineTypes, int)

Draws simple, thick or filled rectangle

public void Rectangle(Point pt1, Point pt2, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

pt1 Point

One of the rectangle vertices.

pt2 Point

Opposite rectangle vertex.

color Scalar

Line color (RGB) or brightness (grayscale image).

thickness int

Thickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1]

lineType LineTypes

Type of the line, see cvLine description. [By default this is LineType.Link8]

shift int

Number of fractional bits in the point coordinates. [By default this is 0]

Rectangle(Rect, Scalar, int, LineTypes, int)

Draws simple, thick or filled rectangle

public void Rectangle(Rect rect, Scalar color, int thickness = 1, LineTypes lineType = LineTypes.Link8, int shift = 0)

Parameters

rect Rect

Rectangle.

color Scalar

Line color (RGB) or brightness (grayscale image).

thickness int

Thickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1]

lineType LineTypes

Type of the line, see cvLine description. [By default this is LineType.Link8]

shift int

Number of fractional bits in the point coordinates. [By default this is 0]

Reduce(ReduceDimension, ReduceTypes, int)

transforms 2D matrix to 1D row or column vector by taking sum, minimum, maximum or mean value over all the rows

public Mat Reduce(ReduceDimension dim, ReduceTypes rtype, int dtype)

Parameters

dim ReduceDimension

The dimension index along which the matrix is reduced. 0 means that the matrix is reduced to a single row and 1 means that the matrix is reduced to a single column

rtype ReduceTypes
dtype int

When it is negative, the destination vector will have the same type as the source matrix, otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), mtx.channels())

Returns

Mat

Release()

Releases the resources

public void Release()

Remap(InputArray, InputArray, InterpolationFlags, BorderTypes, Scalar?)

Applies a generic geometrical transformation to an image.

public Mat Remap(InputArray map1, InputArray map2, InterpolationFlags interpolation = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

map1 InputArray

The first map of either (x,y) points or just x values having the type CV_16SC2, CV_32FC1, or CV_32FC2.

map2 InputArray

The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if map1 is (x,y) points), respectively.

interpolation InterpolationFlags

Interpolation method. The method INTER_AREA is not supported by this function.

borderMode BorderTypes

Pixel extrapolation method. When borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function.

borderValue Scalar?

Value used in case of a constant border. By default, it is 0.

Returns

Mat

Destination image. It has the same size as map1 and the same type as src

Repeat(int, int)

replicates the input matrix the specified number of times in the horizontal and/or vertical direction

public Mat Repeat(int ny, int nx)

Parameters

ny int

How many times the src is repeated along the vertical axis

nx int

How many times the src is repeated along the horizontal axis

Returns

Mat

Reserve(int)

Reserves space for the certain number of rows.

The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class.

public void Reserve(int sz)

Parameters

sz int

Number of rows.

ReserveBuffer(int)

Reserves space for the certain number of bytes.

The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, nothing happens. If matrix has to be reallocated its previous content could be lost.

public void ReserveBuffer(int sz)

Parameters

sz int

Number of bytes.

Reshape(int, int)

Changes the shape and/or the number of channels of a 2D matrix without copying the data.

public Mat Reshape(int cn, int rows = 0)

Parameters

cn int

New number of channels. If the parameter is 0, the number of channels remains the same.

rows int

New number of rows. If the parameter is 0, the number of rows remains the same.

Returns

Mat

Reshape(int, params int[])

Changes the shape and/or the number of channels of a 2D matrix without copying the data.

public Mat Reshape(int cn, params int[] newDims)

Parameters

cn int

New number of channels. If the parameter is 0, the number of channels remains the same.

newDims int[]

New number of rows. If the parameter is 0, the number of rows remains the same.

Returns

Mat

Resize(Size, double, double, InterpolationFlags)

Resizes an image.

public Mat Resize(Size dsize, double fx = 0, double fy = 0, InterpolationFlags interpolation = InterpolationFlags.Linear)

Parameters

dsize Size

output image size; if it equals zero, it is computed as: dsize = Size(round(fxsrc.cols), round(fysrc.rows)) Either dsize or both fx and fy must be non-zero.

fx double

scale factor along the horizontal axis; when it equals 0, it is computed as: (double)dsize.width/src.cols

fy double

scale factor along the vertical axis; when it equals 0, it is computed as: (double)dsize.height/src.rows

interpolation InterpolationFlags

interpolation method

Returns

Mat

output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is the same as of src.

Resize(int)

Changes the number of matrix rows.

public void Resize(int sz)

Parameters

sz int

New number of rows.

Resize(int, Scalar)

Changes the number of matrix rows.

public void Resize(int sz, Scalar s)

Parameters

sz int

New number of rows.

s Scalar

Value assigned to the newly added elements.

Row(int)

Creates a matrix header for the specified matrix row.

public Mat Row(int y)

Parameters

y int

A 0-based row index.

Returns

Mat

RowRange(Range)

Creates a matrix header for the specified row span.

public Mat RowRange(Range range)

Parameters

range Range

Returns

Mat

RowRange(int, int)

Creates a matrix header for the specified row span.

public Mat RowRange(int startRow, int endRow)

Parameters

startRow int
endRow int

Returns

Mat

RowRange(Range)

Creates a matrix header for the specified row span.

public Mat RowRange(Range range)

Parameters

range Range

Returns

Mat

SaveImage(string, params ImageEncodingParam[])

Saves an image to a specified file.

public bool SaveImage(string fileName, params ImageEncodingParam[] prms)

Parameters

fileName string
prms ImageEncodingParam[]

Returns

bool

SaveImage(string, int[]?)

Saves an image to a specified file.

public bool SaveImage(string fileName, int[]? prms = null)

Parameters

fileName string
prms int[]

Returns

bool

Scharr(MatType, int, int, double, double, BorderTypes)

Calculates the first x- or y- image derivative using Scharr operator

public Mat Scharr(MatType ddepth, int xorder, int yorder, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType

The destination image depth

xorder int

Order of the derivative x

yorder int

Order of the derivative y

scale double

The optional scale factor for the computed derivative values (by default, no scaling is applie

delta double

The optional delta value, added to the results prior to storing them in dst

borderType BorderTypes

The pixel extrapolation method

Returns

Mat

The destination image; will have the same size and the same number of channels as src

SepFilter2D(MatType, InputArray, InputArray, Point?, double, BorderTypes)

Applies separable linear filter to an image

public Mat SepFilter2D(MatType ddepth, InputArray kernelX, InputArray kernelY, Point? anchor = null, double delta = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType

The destination image depth

kernelX InputArray

The coefficients for filtering each row

kernelY InputArray

The coefficients for filtering each column

anchor Point?

The anchor position within the kernel; The default value (-1, 1) means that the anchor is at the kernel center

delta double

The value added to the filtered results before storing them

borderType BorderTypes

The pixel extrapolation method

Returns

Mat

The destination image; will have the same size and the same number of channels as src

SetArray<T>(params T[])

Set the specified array data to this matrix

public bool SetArray<T>(params T[] data) where T : unmanaged

Parameters

data T[]

Primitive or Vec array to be copied

Returns

bool

Length of copied bytes

Type Parameters

T

SetIdentity(Scalar?)

initializes scaled identity matrix (not necessarily square).

public void SetIdentity(Scalar? s = null)

Parameters

s Scalar?

The value to assign to the diagonal elements

SetRectangularArray<T>(T[,])

Set the specified array data to this matrix

public bool SetRectangularArray<T>(T[,] data) where T : unmanaged

Parameters

data T[,]

Primitive or Vec array to be copied

Returns

bool

Length of copied bytes

Type Parameters

T

SetTo(InputArray, Mat?)

Sets all or some of the array elements to the specified value.

public Mat SetTo(InputArray value, Mat? mask = null)

Parameters

value InputArray
mask Mat

Returns

Mat

SetTo(Scalar, Mat?)

Sets all or some of the array elements to the specified value.

public Mat SetTo(Scalar value, Mat? mask = null)

Parameters

value Scalar
mask Mat

Returns

Mat

Set<T>(int, int, int, T)

Set a value to the specified array element.

public void Set<T>(int i0, int i1, int i2, T value) where T : struct

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

i2 int

Index along the dimension 2

value T

Type Parameters

T

Set<T>(int, int, T)

Set a value to the specified array element.

public void Set<T>(int i0, int i1, T value) where T : struct

Parameters

i0 int

Index along the dimension 0

i1 int

Index along the dimension 1

value T

Type Parameters

T

Set<T>(int, T)

Set a value to the specified array element.

public void Set<T>(int i0, T value) where T : struct

Parameters

i0 int

Index along the dimension 0

value T

Type Parameters

T

Set<T>(int[], T)

Set a value to the specified array element.

public void Set<T>(int[] idx, T value) where T : struct

Parameters

idx int[]

Array of Mat::dims indices.

value T

Type Parameters

T

Size()

Returns a matrix size.

public Size Size()

Returns

Size

Size(int)

Returns a matrix size.

public int Size(int dim)

Parameters

dim int

Returns

int

Sobel(MatType, int, int, int, double, double, BorderTypes)

Calculates the first, second, third or mixed image derivatives using an extended Sobel operator

public Mat Sobel(MatType ddepth, int xorder, int yorder, int ksize = 3, double scale = 1, double delta = 0, BorderTypes borderType = BorderTypes.Default)

Parameters

ddepth MatType

The destination image depth

xorder int

Order of the derivative x

yorder int

Order of the derivative y

ksize int

Size of the extended Sobel kernel, must be 1, 3, 5 or 7

scale double

The optional scale factor for the computed derivative values (by default, no scaling is applied

delta double

The optional delta value, added to the results prior to storing them in dst

borderType BorderTypes

The pixel extrapolation method

Returns

Mat

The destination image; will have the same size and the same number of channels as src

Sort(SortFlags)

sorts independently each matrix row or each matrix column

public Mat Sort(SortFlags flags)

Parameters

flags SortFlags

The operation flags, a combination of the SortFlag values

Returns

Mat

The destination array of the same size and the same type as src

SortIdx(SortFlags)

sorts independently each matrix row or each matrix column

public Mat SortIdx(SortFlags flags)

Parameters

flags SortFlags

The operation flags, a combination of SortFlag values

Returns

Mat

The destination integer array of the same size as src

Split()

Copies each plane of a multi-channel array to a dedicated array

public Mat[] Split()

Returns

Mat[]

The number of arrays must match mtx.channels() . The arrays themselves will be reallocated if needed

Sqrt()

computes square root of each matrix element (dst = src**0.5)

public Mat Sqrt()

Returns

Mat

The destination array; will have the same size and the same type as src

Step()

Returns number of bytes each matrix row occupies.

public long Step()

Returns

long

Step(int)

Returns number of bytes each matrix row occupies.

public long Step(int i)

Parameters

i int

Returns

long

Step1(int)

Returns a normalized step.

public long Step1(int i = 0)

Parameters

i int

Returns

long

SubMat(Range, Range)

Extracts a rectangular submatrix.

public Mat SubMat(Range rowRange, Range colRange)

Parameters

rowRange Range

Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all().

colRange Range

Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all().

Returns

Mat

SubMat(params Range[])

Extracts a rectangular submatrix.

public Mat SubMat(params Range[] ranges)

Parameters

ranges Range[]

Array of selected ranges along each array dimension.

Returns

Mat

SubMat(Rect)

Extracts a rectangular submatrix.

public Mat SubMat(Rect roi)

Parameters

roi Rect

Extracted submatrix specified as a rectangle.

Returns

Mat

SubMat(int, int, int, int)

Extracts a rectangular submatrix.

public Mat SubMat(int rowStart, int rowEnd, int colStart, int colEnd)

Parameters

rowStart int
rowEnd int
colStart int
colEnd int

Returns

Mat

SubMat(Range, Range)

Extracts a rectangular submatrix.

public Mat SubMat(Range rowRange, Range colRange)

Parameters

rowRange Range

Start and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all().

colRange Range

Start and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all().

Returns

Mat

Subtract(Mat)

public MatExpr Subtract(Mat m)

Parameters

m Mat

Returns

MatExpr

Subtract(Scalar)

public MatExpr Subtract(Scalar s)

Parameters

s Scalar

Returns

MatExpr

Sum()

computes sum of array elements

public Scalar Sum()

Returns

Scalar

T()

Transposes a matrix.

public MatExpr T()

Returns

MatExpr

Threshold(double, double, ThresholdTypes)

Applies a fixed-level threshold to each array element. The input matrix must be single-channel, 8-bit or 32-bit floating point.

public Mat Threshold(double thresh, double maxval, ThresholdTypes type)

Parameters

thresh double

threshold value.

maxval double

maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.

type ThresholdTypes

thresholding type (see the details below).

Returns

Mat

output array of the same size and type as src.

ToBytes(string, params ImageEncodingParam[])

Encodes an image into a memory buffer.

public byte[] ToBytes(string ext = ".png", params ImageEncodingParam[] prms)

Parameters

ext string

Encodes an image into a memory buffer.

prms ImageEncodingParam[]

Format-specific parameters.

Returns

byte[]

ToBytes(string, int[]?)

Encodes an image into a memory buffer.

public byte[] ToBytes(string ext = ".png", int[]? prms = null)

Parameters

ext string

Encodes an image into a memory buffer.

prms int[]

Format-specific parameters.

Returns

byte[]

ToMemoryStream(string, params ImageEncodingParam[])

Converts Mat to System.IO.MemoryStream

public MemoryStream ToMemoryStream(string ext = ".png", params ImageEncodingParam[] prms)

Parameters

ext string
prms ImageEncodingParam[]

Returns

MemoryStream

ToString()

Returns a string that represents this Mat.

public override string ToString()

Returns

string

Total()

Returns the total number of array elements.

public long Total()

Returns

long

Total(int, int)

Returns the total number of array elements. The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim

public long Total(int startDim, int endDim = 2147483647)

Parameters

startDim int
endDim int

Returns

long

Trace()

computes trace of a matrix

public Scalar Trace()

Returns

Scalar

Transform(InputArray)

performs affine transformation of each element of multi-channel input matrix

public Mat Transform(InputArray m)

Parameters

m InputArray

The transformation matrix

Returns

Mat

The destination array; will have the same size and depth as src and as many channels as mtx.rows

Transpose()

transposes the matrix

public Mat Transpose()

Returns

Mat

The destination array of the same type as src

Type()

Returns the type of a matrix element.

public MatType Type()

Returns

MatType

Undistort(InputArray, InputArray, InputArray?)

corrects lens distortion for the given camera matrix and distortion coefficients

public Mat Undistort(InputArray cameraMatrix, InputArray distCoeffs, InputArray? newCameraMatrix = null)

Parameters

cameraMatrix InputArray

Input camera matrix

distCoeffs InputArray

Input vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]]) of 4, 5, or 8 elements. If the vector is null, the zero distortion coefficients are assumed.

newCameraMatrix InputArray

Camera matrix of the distorted image. By default, it is the same as cameraMatrix but you may additionally scale and shift the result by using a different matrix.

Returns

Mat

Output (corrected) image that has the same size and type as src .

UndistortPoints(InputArray, InputArray, InputArray?, InputArray?)

Computes the ideal point coordinates from the observed point coordinates. Input matrix is an observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2).

public Mat UndistortPoints(InputArray cameraMatrix, InputArray distCoeffs, InputArray? r = null, InputArray? p = null)

Parameters

cameraMatrix InputArray

Camera matrix

distCoeffs InputArray

Input vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]]) of 4, 5, or 8 elements. If the vector is null, the zero distortion coefficients are assumed.

r InputArray

Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by stereoRectify() can be passed here. If the matrix is empty, the identity transformation is used.

p InputArray

New camera matrix (3x3) or new projection matrix (3x4). P1 or P2 computed by stereoRectify() can be passed here. If the matrix is empty, the identity new camera matrix is used.

Returns

Mat

Output ideal point coordinates after undistortion and reverse perspective transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.

WarpAffine(InputArray, Size, InterpolationFlags, BorderTypes, Scalar?)

Applies an affine transformation to an image.

public Mat WarpAffine(InputArray m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

m InputArray

2x3 transformation matrix.

dsize Size

size of the output image.

flags InterpolationFlags

combination of interpolation methods and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation (dst -> src) .

borderMode BorderTypes

pixel extrapolation method; when borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to the "outliers" in the source image are not modified by the function.

borderValue Scalar?

value used in case of a constant border; by default, it is 0.

Returns

Mat

output image that has the size dsize and the same type as src.

WarpPerspective(Mat, Size, InterpolationFlags, BorderTypes, Scalar?)

Applies a perspective transformation to an image.

public Mat WarpPerspective(Mat m, Size dsize, InterpolationFlags flags = InterpolationFlags.Linear, BorderTypes borderMode = BorderTypes.Constant, Scalar? borderValue = null)

Parameters

m Mat

3x3 transformation matrix.

dsize Size

size of the output image.

flags InterpolationFlags

combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation (dst -> src).

borderMode BorderTypes

pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE).

borderValue Scalar?

value used in case of a constant border; by default, it equals 0.

Returns

Mat

output image that has the size dsize and the same type as src.

Watershed(InputOutputArray)

Performs a marker-based image segmentation using the watershed algorithm. Input matrix is 8-bit 3-channel image.

public void Watershed(InputOutputArray markers)

Parameters

markers InputOutputArray

Input/output 32-bit single-channel image (map) of markers. It should have the same size as image.

WriteToStream(Stream, string, params ImageEncodingParam[])

Writes image data encoded from this Mat to System.IO.Stream

public void WriteToStream(Stream stream, string ext = ".png", params ImageEncodingParam[] prms)

Parameters

stream Stream
ext string
prms ImageEncodingParam[]

Xor(Mat)

public MatExpr Xor(Mat m)

Parameters

m Mat

Returns

MatExpr

Xor(double)

public MatExpr Xor(double s)

Parameters

s double

Returns

MatExpr

Zeros(MatType, params int[])

Returns a zero array of the specified size and type.

public static MatExpr Zeros(MatType type, params int[] sizes)

Parameters

type MatType

Created matrix type.

sizes int[]

Returns

MatExpr

Zeros(Size, MatType)

Returns a zero array of the specified size and type.

public static MatExpr Zeros(Size size, MatType type)

Parameters

size Size

Alternative to the matrix size specification Size(cols, rows) .

type MatType

Created matrix type.

Returns

MatExpr

Zeros(int, int, MatType)

Returns a zero array of the specified size and type.

public static MatExpr Zeros(int rows, int cols, MatType type)

Parameters

rows int

Number of rows.

cols int

Number of columns.

type MatType

Created matrix type.

Returns

MatExpr

Operators

operator +(Mat, Mat)

public static MatExpr operator +(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator +(Mat, Scalar)

public static MatExpr operator +(Mat a, Scalar s)

Parameters

a Mat
s Scalar

Returns

MatExpr

operator +(Scalar, Mat)

public static MatExpr operator +(Scalar s, Mat a)

Parameters

s Scalar
a Mat

Returns

MatExpr

operator &(Mat, Mat)

public static MatExpr operator &(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator &(Mat, double)

public static MatExpr operator &(Mat a, double s)

Parameters

a Mat
s double

Returns

MatExpr

operator &(double, Mat)

public static MatExpr operator &(double s, Mat a)

Parameters

s double
a Mat

Returns

MatExpr

operator |(Mat, Mat)

public static MatExpr operator |(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator |(Mat, double)

public static MatExpr operator |(Mat a, double s)

Parameters

a Mat
s double

Returns

MatExpr

operator |(double, Mat)

public static MatExpr operator |(double s, Mat a)

Parameters

s double
a Mat

Returns

MatExpr

operator /(Mat, Mat)

public static MatExpr operator /(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator /(Mat, double)

public static MatExpr operator /(Mat a, double s)

Parameters

a Mat
s double

Returns

MatExpr

operator /(double, Mat)

public static MatExpr operator /(double s, Mat a)

Parameters

s double
a Mat

Returns

MatExpr

operator ^(Mat, Mat)

public static MatExpr operator ^(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator ^(Mat, double)

public static MatExpr operator ^(Mat a, double s)

Parameters

a Mat
s double

Returns

MatExpr

operator ^(double, Mat)

public static MatExpr operator ^(double s, Mat a)

Parameters

s double
a Mat

Returns

MatExpr

operator *(Mat, Mat)

public static MatExpr operator *(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator *(Mat, double)

public static MatExpr operator *(Mat a, double s)

Parameters

a Mat
s double

Returns

MatExpr

operator *(double, Mat)

public static MatExpr operator *(double s, Mat a)

Parameters

s double
a Mat

Returns

MatExpr

operator ~(Mat)

public static MatExpr operator ~(Mat m)

Parameters

m Mat

Returns

MatExpr

operator -(Mat, Mat)

public static MatExpr operator -(Mat a, Mat b)

Parameters

a Mat
b Mat

Returns

MatExpr

operator -(Mat, Scalar)

public static MatExpr operator -(Mat a, Scalar s)

Parameters

a Mat
s Scalar

Returns

MatExpr

operator -(Scalar, Mat)

public static MatExpr operator -(Scalar s, Mat a)

Parameters

s Scalar
a Mat

Returns

MatExpr

operator -(Mat)

public static MatExpr operator -(Mat mat)

Parameters

mat Mat

Returns

MatExpr

operator +(Mat)

public static Mat operator +(Mat mat)

Parameters

mat Mat

Returns

Mat