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
mMat
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
mMatArray 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() .
rowRangeRangeRange 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.
colRangeRange?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
mMatArray 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() .
rangesRange[]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
mMatArray 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() .
roiRectRegion of interest.
Mat(Size, MatType)
constructs 2D matrix of the specified size and type
public Mat(Size size, MatType type)
Parameters
sizeSize2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.
typeMatTypeArray 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
sizeSize2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the number of columns go in the reverse order.
typeMatTypeArray 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.
sScalarAn 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
sizesIEnumerable<int>Array of integers specifying an n-dimensional array shape.
typeMatTypeArray 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
sizesIEnumerable<int>Array of integers specifying an n-dimensional array shape.
typeMatTypeArray 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.
sScalarAn 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
sizesIEnumerable<int>Array of integers specifying an n-dimensional array shape.
typeMatTypeArray 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.
dataArrayPointer 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.
stepsIEnumerable<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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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.
sScalarAn 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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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.
dataArrayPointer 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.
steplongNumber 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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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.
datanintPointer 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.
steplongNumber 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
fileNamestringName of file to be loaded.
flagsImreadModesSpecifies color type of the loaded image
Fields
TypeMap
typeof(T) -> MatType
protected static readonly IReadOnlyDictionary<Type, MatType> TypeMap
Field Value
Properties
Cols
the number of columns or -1 when the array has more than 2 dimensions
public int Cols { get; }
Property Value
Data
pointer to the data
public nint Data { get; }
Property Value
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
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
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
Dims
the array dimensionality, >= 2
public int Dims { get; }
Property Value
Flags
includes several bit-fields:
- the magic signature
- continuity flag
- depth
- number of channels
public int Flags { get; }
Property Value
Height
the number of rows or -1 when the array has more than 2 dimensions
public int Height { get; }
Property Value
this[Range, Range]
Extracts a rectangular submatrix.
public Mat this[Range rowRange, Range colRange] { get; set; }
Parameters
rowRangeRangeStart and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range.All().
colRangeRangeStart and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range.All().
Property Value
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
rangesRange[]Array of selected ranges along each array dimension.
Property Value
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
roiRectExtracted submatrix specified as a rectangle.
Property Value
this[int, int, int, int]
Extracts a rectangular submatrix.
public Mat this[int rowStart, int rowEnd, int colStart, int colEnd] { get; set; }
Parameters
rowStartintStart row of the extracted submatrix. The upper boundary is not included.
rowEndintEnd row of the extracted submatrix. The upper boundary is not included.
colStartintStart column of the extracted submatrix. The upper boundary is not included.
colEndintEnd column of the extracted submatrix. The upper boundary is not included.
Property Value
this[Range, Range]
Extracts a rectangular submatrix.
public Mat this[Range rowRange, Range colRange] { get; set; }
Parameters
rowRangeRangeStart and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range.All().
colRangeRangeStart and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range.All().
Property Value
Rows
the number of rows or -1 when the array has more than 2 dimensions
public int Rows { get; }
Property Value
Width
the number of columns or -1 when the array has more than 2 dimensions
public int Width { get; }
Property Value
Methods
Abs()
Computes absolute value of each matrix element
public MatExpr Abs()
Returns
Accumulate(InputArray)
Adds an image to the accumulator.
public Mat Accumulate(InputArray mask)
Parameters
maskInputArrayOptional 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
maskInputArrayOptional 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
maxValuedoubleNon-zero value assigned to the pixels for which the condition is satisfied. See the details below.
adaptiveMethodAdaptiveThresholdTypesAdaptive thresholding algorithm to use, ADAPTIVE_THRESH_MEAN_C or ADAPTIVE_THRESH_GAUSSIAN_C .
thresholdTypeThresholdTypesThresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV .
blockSizeintSize of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
cdoubleConstant 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
mMat
Returns
Add(Scalar)
public MatExpr Add(Scalar s)
Parameters
sScalar
Returns
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
dtopintShift of the top submatrix boundary upwards.
dbottomintShift of the bottom submatrix boundary downwards.
dleftintShift of the left submatrix boundary to the left.
drightintShift of the right submatrix boundary to the right.
Returns
Alignment(int)
public Mat Alignment(int n = 4)
Parameters
nint
Returns
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
epsilondoubleSpecifies the approximation accuracy. This is the maximum distance between the original curve and its approximation.
closedboolThe 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
closedboolIndicates, whether the curve is closed or not
Returns
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
mMatDestination array.
typeMatType?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
i0intIndex 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
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
i0intIndex along the dimension 0
i1intIndex along the dimension 1
i2intIndex 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
idxint[]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
dintThe diameter of each pixel neighborhood, that is used during filtering. If it is non-positive, it's computed from sigmaSpace
sigmaColordoubleFilter 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
sigmaSpacedoubleFilter 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
borderTypeBorderTypes
Returns
- Mat
The destination image; will have the same size and the same type as src
BitwiseAnd(Mat)
public MatExpr BitwiseAnd(Mat m)
Parameters
mMat
Returns
BitwiseAnd(double)
public MatExpr BitwiseAnd(double s)
Parameters
sdouble
Returns
BitwiseOr(Mat)
public MatExpr BitwiseOr(Mat m)
Parameters
mMat
Returns
BitwiseOr(double)
public MatExpr BitwiseOr(double s)
Parameters
sdouble
Returns
Blur(Size, Point?, BorderTypes)
Smoothes image using normalized box filter
public Mat Blur(Size ksize, Point? anchor = null, BorderTypes borderType = BorderTypes.Default)
Parameters
ksizeSizeThe smoothing kernel size
anchorPoint?The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center
borderTypeBorderTypesThe 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
ddepthMatTypeksizeSizeThe smoothing kernel size
anchorPoint?The anchor point. The default value Point(-1,-1) means that the anchor is at the kernel center
normalizeboolIndicates, whether the kernel is normalized by its area or not
borderTypeBorderTypesThe 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
maxlevelintborderTypeBorderTypes
Returns
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
threshold1doubleThe first threshold for the hysteresis procedure
threshold2doubleThe second threshold for the hysteresis procedure
apertureSizeintAperture size for the Sobel operator [By default this is ApertureSize.Size3]
L2gradientboolIndicates, 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
CheckRange(bool)
checks that each matrix element is within the specified range.
public bool CheckRange(bool quiet = true)
Parameters
quietboolThe flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.
Returns
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
quietboolThe flag indicating whether the functions quietly return false when the array elements are out of range, or they throw an exception.
posPointThe optional output parameter, where the position of the first outlier is stored.
minValdoubleThe inclusive lower boundary of valid values range
maxValdoubleThe exclusive upper boundary of valid values range
Returns
CheckVector(int, int, bool)
public int CheckVector(int elemChannels, int depth = -1, bool requireContinuous = true)
Parameters
elemChannelsintNumber 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.
depthintThe depth the matrix should have. Set it to -1 when any depth is fine.
requireContinuousboolSet 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
centerPointCenter of the circle.
radiusintRadius of the circle.
colorScalarCircle color.
thicknessintThickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1]
lineTypeLineTypesType of the circle boundary. [By default this is LineType.Link8]
shiftintNumber 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
centerXintX-coordinate of the center of the circle.
centerYintY-coordinate of the center of the circle.
radiusintRadius of the circle.
colorScalarCircle color.
thicknessintThickness of the circle outline if positive, otherwise indicates that a filled circle has to be drawn. [By default this is 1]
lineTypeLineTypesType of the circle boundary. [By default this is LineType.Link8]
shiftintNumber 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
Clone(Rect)
Returns the partial Mat of the specified Mat
public Mat Clone(Rect roi)
Parameters
roiRect
Returns
Col(int)
Creates a matrix header for the specified matrix column.
public Mat Col(int x)
Parameters
xintA 0-based column index.
Returns
ColRange(Range)
Creates a matrix header for the specified column span.
public Mat ColRange(Range range)
Parameters
rangeRange
Returns
ColRange(int, int)
Creates a matrix header for the specified column span.
public Mat ColRange(int startCol, int endCol)
Parameters
startColintAn inclusive 0-based start index of the column span.
endColintAn exclusive 0-based ending index of the column span.
Returns
ColRange(Range)
Creates a matrix header for the specified column span.
public Mat ColRange(Range range)
Parameters
rangeRange
Returns
CompleteSymm(bool)
extends the symmetrical matrix from the lower half or from the upper half
public void CompleteSymm(bool lowerToUpper = false)
Parameters
lowerToUpperboolIf 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
labelsOutputArraydestination labeled image
connectivityPixelConnectivity8 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
labelsOutputArraydestination labeled image
connectivityPixelConnectivity8 or 4 for 8-way or 4-way connectivity respectively
ltypeMatTypeoutput 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
labelsint[,]destination labeled rectangular array
connectivityPixelConnectivity8 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
connectivityPixelConnectivity8 or 4 for 8-way or 4-way connectivity respectively
Returns
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
labelsOutputArraydestination labeled image
statsOutputArraystatistics 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
centroidsOutputArrayfloating point centroid (x,y) output for each label, including the background label
connectivityPixelConnectivity8 or 4 for 8-way or 4-way connectivity respectively
Returns
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
labelsOutputArraydestination labeled image
statsOutputArraystatistics 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
centroidsOutputArrayfloating point centroid (x,y) output for each label, including the background label
connectivityPixelConnectivity8 or 4 for 8-way or 4-way connectivity respectively
ltypeMatTypeoutput image label type. Currently CV_32S and CV_16U are supported.
Returns
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
orientedbool
Returns
ConvertScaleAbs(double, double)
Scales, computes absolute values and converts the result to 8-bit.
public Mat ConvertScaleAbs(double alpha = 1, double beta = 0)
Parameters
alphadoubleThe optional scale factor. [By default this is 1]
betadoubleThe optional delta added to the scaled values. [By default this is 0]
Returns
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
mOutputArrayoutput matrix; if it does not have a proper size or type before the operation, it is reallocated.
rtypeMatTypedesired 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.
alphadoubleoptional scale factor.
betadoubleoptional 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
clockwiseboolIf 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.
returnPointsbool
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
clockwiseboolIf 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
clockwiseboolIf 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
clockwiseboolIf 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
convexHullInputArrayConvex 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
convexHullInputArrayConvex 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
topintSpecify how much pixels in each direction from the source image rectangle one needs to extrapolate
bottomintSpecify how much pixels in each direction from the source image rectangle one needs to extrapolate
leftintSpecify how much pixels in each direction from the source image rectangle one needs to extrapolate
rightintSpecify how much pixels in each direction from the source image rectangle one needs to extrapolate
borderTypeBorderTypesThe border type
valueScalar?The border value if borderType == Constant
Returns
CopyTo(Mat, InputArray?)
Copies the matrix to another one.
public void CopyTo(Mat m, InputArray? mask = null)
Parameters
mMatDestination matrix. If it does not have a proper size or type before the operation, it is reallocated.
maskInputArrayOperation 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
mOutputArrayDestination matrix. If it does not have a proper size or type before the operation, it is reallocated.
maskInputArrayOperation 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
blockSizeintksizeintborderTypeBorderTypes
Returns
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
inputCornersIEnumerable<Point2f>Initial coordinates of the input corners and refined coordinates provided for output.
winSizeSizeHalf of the side length of the search window.
zeroZoneSizeHalf 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.
criteriaTermCriteriaCriteria 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
Create(Size, MatType)
Allocates new array data if needed.
public void Create(Size size, MatType type)
Parameters
Create(int, int, MatType)
Allocates new array data if needed.
public void Create(int rows, int cols, MatType type)
Parameters
CreateHanningWindow(Size, MatType)
Computes a Hanning window coefficients in two dimensions.
public void CreateHanningWindow(Size winSize, MatType type)
Parameters
Cross(InputArray)
Computes a cross-product of two 3-element vectors.
public Mat Cross(InputArray m)
Parameters
mInputArrayAnother cross-product operand.
Returns
CvtColor(ColorConversionCodes, int)
Converts image from one color space to another
public Mat CvtColor(ColorConversionCodes code, int dstCn = 0)
Parameters
codeColorConversionCodesThe color space conversion code
dstCnintThe 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
flagsDctFlagsTransformation 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
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
flagsDftFlagsTransformation flags, a combination of the DftFlag2 values
nonzeroRowsintWhen 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
dMatOne-dimensional matrix that represents the main diagonal.
Returns
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
dMatDiagTypeSingle-column matrix that forms a diagonal matrix or index of the diagonal, with the following values:
Returns
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
elementInputArrayThe structuring element used for dilation. If element=new Mat() , a 3x3 rectangular structuring element is used
anchorPoint?Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center
iterationsintThe number of times dilation is applied. [By default this is 1]
borderTypeBorderTypesThe pixel extrapolation method. [By default this is BorderTypes.Constant]
borderValueScalar?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
distanceTypeDistanceTypesmaskSizeDistanceTransformMasks
Returns
Divide(Mat)
public MatExpr Divide(Mat m)
Parameters
mMat
Returns
Divide(double)
public MatExpr Divide(double s)
Parameters
sdouble
Returns
Dot(InputArray)
Computes a dot-product of two vectors.
public double Dot(InputArray m)
Parameters
mInputArrayanother dot-product operand.
Returns
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
contoursIEnumerable<Mat>All the input contours. Each contour is stored as a point vector.
contourIdxintParameter indicating a contour to draw. If it is negative, all the contours are drawn.
colorScalarColor of the contours.
thicknessintThickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn.
lineTypeLineTypesLine connectivity.
hierarchyMatOptional information about hierarchy. It is only needed if you want to draw only some of the contours
maxLevelintMaximal 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.
offsetPoint?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
contoursIEnumerable<IEnumerable<Point>>All the input contours. Each contour is stored as a point vector.
contourIdxintParameter indicating a contour to draw. If it is negative, all the contours are drawn.
colorScalarColor of the contours.
thicknessintThickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn.
lineTypeLineTypesLine connectivity.
hierarchyIEnumerable<HierarchyIndex>Optional information about hierarchy. It is only needed if you want to draw only some of the contours
maxLevelintMaximal 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.
offsetPoint?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
positionPointThe point where the crosshair is positioned.
colorScalarLine color.
markerTypeMarkerTypesThe specific type of marker you want to use.
markerSizeintThe length of the marker axis [default = 20 pixels]
thicknessintLine thickness.
lineTypeLineTypesType 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
formatFormatType
Returns
ElemSize()
Returns the matrix element size in bytes.
public int ElemSize()
Returns
ElemSize1()
Returns the size of each matrix element channel in bytes.
public int ElemSize1()
Returns
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
centerPointCenter of the ellipse.
axesSizeLength of the ellipse axes.
angledoubleRotation angle.
startAngledoubleStarting angle of the elliptic arc.
endAngledoubleEnding angle of the elliptic arc.
colorScalarEllipse color.
thicknessintThickness of the ellipse arc. [By default this is 1]
lineTypeLineTypesType of the ellipse boundary. [By default this is LineType.Link8]
shiftintNumber 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
boxRotatedRectThe enclosing box of the ellipse drawn
colorScalarEllipse color.
thicknessintThickness of the ellipse boundary. [By default this is 1]
lineTypeLineTypesType of the ellipse boundary. [By default this is LineType.Link8]
Empty()
Returns true if the array has no elements.
public bool Empty()
Returns
EmptyClone()
Makes a Mat that have the same size, depth and channels as this image
public Mat EmptyClone()
Returns
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
mMat
Returns
Equals(double)
operator ==
public MatExpr Equals(double d)
Parameters
ddouble
Returns
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
elementInputArrayThe structuring element used for dilation. If element=new Mat(), a 3x3 rectangular structuring element is used
anchorPoint?Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center
iterationsintThe number of times erosion is applied
borderTypeBorderTypesThe pixel extrapolation method
borderValueScalar?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
coiint
Returns
Eye(Size, MatType)
Returns an identity matrix of the specified size and type.
public static MatExpr Eye(Size size, MatType type)
Parameters
sizeSizeAlternative to the matrix size specification Size(cols, rows) .
typeMatTypeCreated matrix type.
Returns
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
Returns
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
ptsIEnumerable<Point>The polygon vertices
colorScalarPolygon color
lineTypeLineTypesType of the polygon boundaries
shiftintThe 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
ptsIEnumerable<IEnumerable<Point>>Array of polygons, each represented as an array of points
colorScalarPolygon color
lineTypeLineTypesType of the polygon boundaries
shiftintThe number of fractional bits in the vertex coordinates
offsetPoint?
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
ddepthMatTypeThe desired depth of the destination image. If it is negative, it will be the same as src.depth()
kernelInputArrayConvolution 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
anchorPoint?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
deltadoubleThe optional value added to the filtered pixels before storing them in dst
borderTypeBorderTypesThe 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
contoursMat[]Detected contours. Each contour is stored as a vector of points.
hierarchyOutputArrayOptional 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.
modeRetrievalModesContour retrieval mode
methodContourApproximationModesContour approximation method
offsetPoint?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
contoursPoint[][]Detected contours. Each contour is stored as a vector of points.
hierarchyHierarchyIndex[]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.
modeRetrievalModesContour retrieval mode
methodContourApproximationModesContour approximation method
offsetPoint?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
modeRetrievalModesContour retrieval mode
methodContourApproximationModesContour approximation method
offsetPoint?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
modeRetrievalModesContour retrieval mode
methodContourApproximationModesContour approximation method
offsetPoint?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
FindNonZero()
returns the list of locations of non-zero pixels
public Mat FindNonZero()
Returns
FitEllipse()
Fits ellipse to the set of 2D points.
public RotatedRect FitEllipse()
Returns
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
distTypeDistanceTypesDistance used by the M-estimator
paramdoubleNumerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen.
repsdoubleSufficient accuracy for the radius (distance between the coordinate origin and the line).
aepsdoubleSufficient 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
distTypeDistanceTypesDistance used by the M-estimator
paramdoubleNumerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen.
repsdoubleSufficient accuracy for the radius (distance between the coordinate origin and the line).
aepsdoubleSufficient 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
flipCodeFlipModeSpecifies 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
maskInputOutputArray(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.
seedPointPointStarting point.
newValScalarNew value of the repainted domain pixels.
Returns
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
maskInputOutputArray(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.
seedPointPointStarting point.
newValScalarNew value of the repainted domain pixels.
rectRectOptional output parameter set by the function to the minimum bounding rectangle of the repainted domain.
loDiffScalar?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.
upDiffScalar?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.
flagsFloodFillFlagsOperation 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
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
Returns
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
seedPointPointStarting point.
newValScalarNew value of the repainted domain pixels.
rectRectOptional output parameter set by the function to the minimum bounding rectangle of the repainted domain.
loDiffScalar?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.
upDiffScalar?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.
flagsFloodFillFlagsOperation 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
ForEachAsByte(MatForeachFunctionByte)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsByte(MatForeachFunctionByte operation)
Parameters
operationMatForeachFunctionByte
ForEachAsDouble(MatForeachFunctionDouble)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsDouble(MatForeachFunctionDouble operation)
Parameters
operationMatForeachFunctionDouble
ForEachAsFloat(MatForeachFunctionFloat)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsFloat(MatForeachFunctionFloat operation)
Parameters
operationMatForeachFunctionFloat
ForEachAsInt16(MatForeachFunctionInt16)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsInt16(MatForeachFunctionInt16 operation)
Parameters
operationMatForeachFunctionInt16
ForEachAsInt32(MatForeachFunctionInt32)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsInt32(MatForeachFunctionInt32 operation)
Parameters
operationMatForeachFunctionInt32
ForEachAsVec2b(MatForeachFunctionVec2b)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec2b(MatForeachFunctionVec2b operation)
Parameters
operationMatForeachFunctionVec2b
ForEachAsVec2d(MatForeachFunctionVec2d)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec2d(MatForeachFunctionVec2d operation)
Parameters
operationMatForeachFunctionVec2d
ForEachAsVec2f(MatForeachFunctionVec2f)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec2f(MatForeachFunctionVec2f operation)
Parameters
operationMatForeachFunctionVec2f
ForEachAsVec2i(MatForeachFunctionVec2i)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec2i(MatForeachFunctionVec2i operation)
Parameters
operationMatForeachFunctionVec2i
ForEachAsVec2s(MatForeachFunctionVec2s)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec2s(MatForeachFunctionVec2s operation)
Parameters
operationMatForeachFunctionVec2s
ForEachAsVec3b(MatForeachFunctionVec3b)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec3b(MatForeachFunctionVec3b operation)
Parameters
operationMatForeachFunctionVec3b
ForEachAsVec3d(MatForeachFunctionVec3d)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec3d(MatForeachFunctionVec3d operation)
Parameters
operationMatForeachFunctionVec3d
ForEachAsVec3f(MatForeachFunctionVec3f)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec3f(MatForeachFunctionVec3f operation)
Parameters
operationMatForeachFunctionVec3f
ForEachAsVec3i(MatForeachFunctionVec3i)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec3i(MatForeachFunctionVec3i operation)
Parameters
operationMatForeachFunctionVec3i
ForEachAsVec3s(MatForeachFunctionVec3s)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec3s(MatForeachFunctionVec3s operation)
Parameters
operationMatForeachFunctionVec3s
ForEachAsVec4b(MatForeachFunctionVec4b)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec4b(MatForeachFunctionVec4b operation)
Parameters
operationMatForeachFunctionVec4b
ForEachAsVec4d(MatForeachFunctionVec4d)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec4d(MatForeachFunctionVec4d operation)
Parameters
operationMatForeachFunctionVec4d
ForEachAsVec4f(MatForeachFunctionVec4f)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec4f(MatForeachFunctionVec4f operation)
Parameters
operationMatForeachFunctionVec4f
ForEachAsVec4i(MatForeachFunctionVec4i)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec4i(MatForeachFunctionVec4i operation)
Parameters
operationMatForeachFunctionVec4i
ForEachAsVec4s(MatForeachFunctionVec4s)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec4s(MatForeachFunctionVec4s operation)
Parameters
operationMatForeachFunctionVec4s
ForEachAsVec6b(MatForeachFunctionVec6b)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec6b(MatForeachFunctionVec6b operation)
Parameters
operationMatForeachFunctionVec6b
ForEachAsVec6d(MatForeachFunctionVec6d)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec6d(MatForeachFunctionVec6d operation)
Parameters
operationMatForeachFunctionVec6d
ForEachAsVec6f(MatForeachFunctionVec6f)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec6f(MatForeachFunctionVec6f operation)
Parameters
operationMatForeachFunctionVec6f
ForEachAsVec6i(MatForeachFunctionVec6i)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec6i(MatForeachFunctionVec6i operation)
Parameters
operationMatForeachFunctionVec6i
ForEachAsVec6s(MatForeachFunctionVec6s)
Runs the given functor over all matrix elements in parallel.
public void ForEachAsVec6s(MatForeachFunctionVec6s operation)
Parameters
operationMatForeachFunctionVec6s
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
enumerableIEnumerable<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
arrTElem[,]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
arrTElem[]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
imageBytesbyte[]modeImreadModes
Returns
FromImageData(ReadOnlySpan<byte>, ImreadModes)
Reads image from the specified buffer in memory.
public static Mat FromImageData(ReadOnlySpan<byte> span, ImreadModes mode = ImreadModes.Color)
Parameters
spanReadOnlySpan<byte>The input slice of bytes.
modeImreadModesThe same flags as in imread
Returns
FromNativePointer(nint)
Creates from native cv::Mat* pointer
public static Mat FromNativePointer(nint ptr)
Parameters
ptrnint
Returns
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
sizesIEnumerable<int>Array of integers specifying an n-dimensional array shape.
typeMatTypeArray 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.
dataArrayPointer 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.
stepsIEnumerable<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
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
sizesIEnumerable<int>Array of integers specifying an n-dimensional array shape.
typeMatTypeArray 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.
datanintPointer 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.
stepsIEnumerable<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
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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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.
dataArrayPointer 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.
steplongNumber 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
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
rowsintNumber of rows in a 2D array.
colsintNumber of columns in a 2D array.
typeMatTypeArray 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.
datanintPointer 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.
steplongNumber 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
FromStream(Stream, ImreadModes)
Creates the Mat instance from System.IO.Stream
public static Mat FromStream(Stream stream, ImreadModes mode)
Parameters
streamStreammodeImreadModes
Returns
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
ksizeSizeGaussian 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* .
sigmaXdoubleGaussian kernel standard deviation in X direction.
sigmaYdoubleGaussian 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.
borderTypeBorderTypespixel extrapolation method
Returns
GetArray<T>(out T[])
Get the data of this matrix as array
[Pure]
public bool GetArray<T>(out T[] data) where T : unmanaged
Parameters
dataT[]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
imgSizeSize?Camera view image size in pixels.
centerPrincipalPointboolLocation 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
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
patchSizeSizeSize of the extracted patch.
centerPoint2fFloating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image.
patchTypeintDepth 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
dataT[,]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
accessFlagsAccessFlagusageFlagsUMatUsageFlags
Returns
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
i0intIndex 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
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
i0intIndex along the dimension 0
i1intIndex along the dimension 1
i2intIndex 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
idxint[]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
maxCornersintMaximum number of corners to return. If there are more corners than are found, the strongest of them is returned.
qualityLeveldoubleParameter 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.
minDistancedoubleMinimum possible Euclidean distance between the returned corners.
maskInputArrayOptional 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.
blockSizeintSize of an average block for computing a derivative covariation matrix over each pixel neighborhood.
useHarrisDetectorboolParameter indicating whether to use a Harris detector
kdoubleFree 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
maskInputOutputArrayInput/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
rectRectROI 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.
bgdModelInputOutputArrayTemporary array for the background model. Do not modify it while you are processing the same image.
fgdModelInputOutputArrayTemporary arrays for the foreground model. Do not modify it while you are processing the same image.
iterCountintNumber 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 .
modeGrabCutModesOperation mode that could be one of GrabCutFlag value.
GreaterThan(Mat)
operator >
public MatExpr GreaterThan(Mat m)
Parameters
mMat
Returns
GreaterThan(double)
operator >
public MatExpr GreaterThan(double d)
Parameters
ddouble
Returns
GreaterThanOrEqual(Mat)
operator >=
public MatExpr GreaterThanOrEqual(Mat m)
Parameters
mMat
Returns
GreaterThanOrEqual(double)
operator >=
public MatExpr GreaterThanOrEqual(double d)
Parameters
ddouble
Returns
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
methodHoughModesThe available methods are HoughMethods.Gradient and HoughMethods.GradientAlt
dpdoubleThe inverse ratio of the accumulator resolution to the image resolution.
minDistdoubleMinimum distance between the centers of the detected circles.
param1doubleThe first method-specific parameter. [By default this is 100]
param2doubleThe second method-specific parameter. [By default this is 100]
minRadiusintMinimum circle radius. [By default this is 0]
maxRadiusintMaximum 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
rhodoubleDistance resolution of the accumulator in pixels
thetadoubleAngle resolution of the accumulator in radians
thresholdintThe accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold )
srndoubleFor the multi-scale Hough transform it is the divisor for the distance resolution rho. [By default this is 0]
stndoubleFor 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
rhodoubleDistance resolution of the accumulator in pixels
thetadoubleAngle resolution of the accumulator in radians
thresholdintThe accumulator threshold parameter. Only those lines are returned that get enough votes ( > threshold )
minLineLengthdoubleThe minimum line length. Line segments shorter than that will be rejected. [By default this is 0]
maxLineGapdoubleThe 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
flagsDctFlagsTransformation 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
flagsDftFlagsTransformation flags, a combination of the DftFlag2 values
nonzeroRowsintWhen 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
imageBytesbyte[]modeImreadModes
Returns
ImDecode(ReadOnlySpan<byte>, ImreadModes)
Reads image from the specified buffer in memory.
public static Mat ImDecode(ReadOnlySpan<byte> span, ImreadModes mode = ImreadModes.Color)
Parameters
spanReadOnlySpan<byte>The input slice of bytes.
modeImreadModesThe same flags as in imread
Returns
ImEncode(string, params ImageEncodingParam[])
Encodes an image into a memory buffer.
public byte[] ImEncode(string ext = ".png", params ImageEncodingParam[] prms)
Parameters
extstringEncodes an image into a memory buffer.
prmsImageEncodingParam[]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
Returns
- byte[]
ImWrite(string, params ImageEncodingParam[])
Saves an image to a specified file.
public bool ImWrite(string fileName, params ImageEncodingParam[] prms)
Parameters
fileNamestringprmsImageEncodingParam[]
Returns
ImWrite(string, int[]?)
Saves an image to a specified file.
public bool ImWrite(string fileName, int[]? prms = null)
Parameters
Returns
InRange(InputArray, InputArray)
Checks if array elements lie between the elements of two other arrays.
public Mat InRange(InputArray lowerb, InputArray upperb)
Parameters
lowerbInputArrayinclusive lower boundary array or a scalar.
upperbInputArrayinclusive 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
lowerbScalarinclusive lower boundary array or a scalar.
upperbScalarinclusive 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
dstInputOutputArraycoiint
Inv(DecompTypes)
Inverses a matrix.
public MatExpr Inv(DecompTypes method = DecompTypes.LU)
Parameters
methodDecompTypesMatrix inversion method
Returns
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
IsContourConvex()
Returns true if the contour is convex. Does not support contours with self-intersection
public bool IsContourConvex()
Returns
IsSubmatrix()
Returns whether this matrix is a part of other matrix or not.
public bool IsSubmatrix()
Returns
LUT(InputArray)
transforms array of numbers using a lookup table: dst(i)=lut(src(i))
public Mat LUT(InputArray lut)
Parameters
lutInputArrayLook-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
LUT(byte[])
transforms array of numbers using a lookup table: dst(i)=lut(src(i))
public Mat LUT(byte[] lut)
Parameters
lutbyte[]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
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
ddepthMatTypeThe desired depth of the destination image
ksizeintThe aperture size used to compute the second-derivative filters
scaledoubleThe optional scale factor for the computed Laplacian values (by default, no scaling is applied
deltadoubleThe optional delta value, added to the results prior to storing them in dst
borderTypeBorderTypesThe 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
mMat
Returns
LessThan(double)
operator <
public MatExpr LessThan(double d)
Parameters
ddouble
Returns
LessThanOrEqual(Mat)
operator <=
public MatExpr LessThanOrEqual(Mat m)
Parameters
mMat
Returns
LessThanOrEqual(double)
operator <=
public MatExpr LessThanOrEqual(double d)
Parameters
ddouble
Returns
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
pt1PointFirst point of the line segment.
pt2PointSecond point of the line segment.
colorScalarLine color.
thicknessintLine thickness. [By default this is 1]
lineTypeLineTypesType of the line. [By default this is LineType.Link8]
shiftintNumber 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
pt1XintFirst point's x-coordinate of the line segment.
pt1YintFirst point's y-coordinate of the line segment.
pt2XintSecond point's x-coordinate of the line segment.
pt2YintSecond point's y-coordinate of the line segment.
colorScalarLine color.
thicknessintLine thickness. [By default this is 1]
lineTypeLineTypesType of the line. [By default this is LineType.Link8]
shiftintNumber 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
wholeSizeSizeOutput parameter that contains the size of the whole matrix containing *this as a part.
ofsPointOutput 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
templInputArraySearched template; must be not greater than the source image and have the same data type
methodTemplateMatchModesSpecifies the comparison method
maskInputArrayMask 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
maskInputArrayThe optional operation mask
Returns
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
meanOutputArrayThe output parameter: computed mean value
stddevOutputArrayThe output parameter: computed standard deviation
maskInputArrayThe 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
ksizeintThe 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
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
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
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
minValdoublePointer to returned minimum value
maxValdoublePointer to returned maximum value
minIdxint[]maxIdxint[]maskInputArray
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
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
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
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
minValdoublePointer to returned minimum value
maxValdoublePointer to returned maximum value
minLocPointPointer to returned minimum location
maxLocPointPointer to returned maximum location
maskInputArrayThe 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
binaryImageboolIf it is true, then all the non-zero image pixels are treated as 1’s
Returns
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
opMorphTypesType of morphological operation
elementInputArrayStructuring element
anchorPoint?Position of the anchor within the element. The default value (-1, -1) means that the anchor is at the element center
iterationsintNumber of times erosion and dilation are applied. [By default this is 1]
borderTypeBorderTypesThe pixel extrapolation method. [By default this is BorderTypes.Constant]
borderValueScalar?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
mInputArrayscaledouble
Returns
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
aTaboolSpecifies the multiplication ordering; see the description below
deltaInputArrayThe 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
scaledoubleThe optional scale factor for the matrix product
dtypeintWhen 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
Multiply(Mat)
public MatExpr Multiply(Mat m)
Parameters
mMat
Returns
Multiply(double)
public MatExpr Multiply(double s)
Parameters
sdouble
Returns
Negate()
public MatExpr Negate()
Returns
Norm(NormTypes, InputArray?)
computes norm of the selected array part
public double Norm(NormTypes normType = NormTypes.L2, InputArray? mask = null)
Parameters
normTypeNormTypesType of the norm
maskInputArrayThe optional operation mask
Returns
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
alphadoubleThe norm value to normalize to or the lower range boundary in the case of range normalization
betadoubleThe upper range boundary in the case of range normalization; not used for norm normalization
normTypeNormTypesThe normalization type
dtypeintWhen 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)
maskInputArrayThe optional operation mask
Returns
NotEquals(Mat)
operator !=
public MatExpr NotEquals(Mat m)
Parameters
mMat
Returns
NotEquals(double)
operator !=
public MatExpr NotEquals(double d)
Parameters
ddouble
Returns
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
Returns
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
sizeSizeAlternative to the matrix size specification Size(cols, rows) .
typeMatTypeCreated matrix type.
Returns
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
Returns
OnesComplement()
public MatExpr OnesComplement()
Returns
PatchNaNs(double)
converts NaN's to the given number
public void PatchNaNs(double val = 0)
Parameters
valdouble
PerspectiveTransform(InputArray)
performs perspective transformation of each element of multi-channel input matrix
public Mat PerspectiveTransform(InputArray m)
Parameters
mInputArray3x3 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
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
ptPoint2fPoint tested against the contour.
measureDistboolIf 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
ptsIEnumerable<IEnumerable<Point>>isClosedboolcolorScalarthicknessintlineTypeLineTypesshiftint
PopBack(int)
removes several hyper-planes from bottom of the matrix (Mat.pop_back)
public void PopBack(int nElems = 1)
Parameters
nElemsint
Pow(double)
raises the input matrix elements to the specified power (b = a**power)
public Mat Pow(double power)
Parameters
powerdoubleThe 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
ksizeintborderTypeBorderTypes
Returns
Ptr(int)
Returns a pointer to the specified matrix row.
public nint Ptr(int i0)
Parameters
i0intIndex along the dimension 0
Returns
Ptr(int, int)
Returns a pointer to the specified matrix element.
public nint Ptr(int i0, int i1)
Parameters
Returns
Ptr(int, int, int)
Returns a pointer to the specified matrix element.
public nint Ptr(int i0, int i1, int i2)
Parameters
i0intIndex along the dimension 0
i1intIndex along the dimension 1
i2intIndex along the dimension 2
Returns
Ptr(params int[])
Returns a pointer to the specified matrix element.
public nint Ptr(params int[] idx)
Parameters
idxint[]Array of Mat::dims indices.
Returns
PushBack(Mat)
Adds elements to the bottom of the matrix. (Mat.push_back)
public void PushBack(Mat m)
Parameters
mMatAdded line(s)
PushBack(Point)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point value)
Parameters
valuePointAdded element
PushBack(Point2d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point2d value)
Parameters
valuePoint2dAdded element
PushBack(Point2f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point2f value)
Parameters
valuePoint2fAdded element
PushBack(Point3d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point3d value)
Parameters
valuePoint3dAdded element
PushBack(Point3f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point3f value)
Parameters
valuePoint3fAdded element
PushBack(Point3i)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Point3i value)
Parameters
valuePoint3iAdded element
PushBack(Rect)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Rect value)
Parameters
valueRectAdded element
PushBack(Rect2d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Rect2d value)
Parameters
valueRect2dAdded element
PushBack(Rect2f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Rect2f value)
Parameters
valueRect2fAdded element
PushBack(Size)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Size value)
Parameters
valueSizeAdded element
PushBack(Size2d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Size2d value)
Parameters
valueSize2dAdded element
PushBack(Size2f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Size2f value)
Parameters
valueSize2fAdded element
PushBack(Vec2b)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2b value)
Parameters
valueVec2bAdded element
PushBack(Vec2d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2d value)
Parameters
valueVec2dAdded element
PushBack(Vec2f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2f value)
Parameters
valueVec2fAdded element
PushBack(Vec2i)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2i value)
Parameters
valueVec2iAdded element
PushBack(Vec2s)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2s value)
Parameters
valueVec2sAdded element
PushBack(Vec2w)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec2w value)
Parameters
valueVec2wAdded element
PushBack(Vec3b)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3b value)
Parameters
valueVec3bAdded element
PushBack(Vec3d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3d value)
Parameters
valueVec3dAdded element
PushBack(Vec3f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3f value)
Parameters
valueVec3fAdded element
PushBack(Vec3i)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3i value)
Parameters
valueVec3iAdded element
PushBack(Vec3s)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3s value)
Parameters
valueVec3sAdded element
PushBack(Vec3w)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec3w value)
Parameters
valueVec3wAdded element
PushBack(Vec4b)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4b value)
Parameters
valueVec4bAdded element
PushBack(Vec4d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4d value)
Parameters
valueVec4dAdded element
PushBack(Vec4f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4f value)
Parameters
valueVec4fAdded element
PushBack(Vec4i)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4i value)
Parameters
valueVec4iAdded element
PushBack(Vec4s)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4s value)
Parameters
valueVec4sAdded element
PushBack(Vec4w)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec4w value)
Parameters
valueVec4wAdded element
PushBack(Vec6b)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6b value)
Parameters
valueVec6bAdded element
PushBack(Vec6d)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6d value)
Parameters
valueVec6dAdded element
PushBack(Vec6f)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6f value)
Parameters
valueVec6fAdded element
PushBack(Vec6i)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6i value)
Parameters
valueVec6iAdded element
PushBack(Vec6s)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6s value)
Parameters
valueVec6sAdded element
PushBack(Vec6w)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(Vec6w value)
Parameters
valueVec6wAdded element
PushBack(byte)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(byte value)
Parameters
valuebyteAdded element
PushBack(double)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(double value)
Parameters
valuedoubleAdded element
PushBack(short)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(short value)
Parameters
valueshortAdded element
PushBack(int)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(int value)
Parameters
valueintAdded element
PushBack(sbyte)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(sbyte value)
Parameters
valuesbyteAdded element
PushBack(float)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(float value)
Parameters
valuefloatAdded element
PushBack(ushort)
Adds elements to the bottom of the matrix. (Mat::push_back)
public void PushBack(ushort value)
Parameters
valueushortAdded 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
textstringorgPointfontFaceHersheyFontsfontScaledoublecolorScalarthicknessintlineTypeLineTypesbottomLeftOriginbool
PyrDown(Size?, BorderTypes)
Blurs an image and downsamples it.
public Mat PyrDown(Size? dstSize = null, BorderTypes borderType = BorderTypes.Default)
Parameters
dstSizeSize?size of the output image; by default, it is computed as Size((src.cols+1)/2
borderTypeBorderTypes
Returns
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
spdoubleThe spatial window radius.
srdoubleThe color window radius.
maxLevelintMaximum level of the pyramid for the segmentation.
termcritTermCriteria?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
dstSizeSize?size of the output image; by default, it is computed as Size(src.cols2, (src.rows2)
borderTypeBorderTypes
Returns
RandShuffle(double)
shuffles the input array elements
public void RandShuffle(double iterFactor)
Parameters
iterFactordoubleThe 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
iterFactordoubleThe scale factor that determines the number of random swap operations.
rngRNGThe 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
meanInputArrayThe mean value (expectation) of the generated random numbers
stddevInputArrayThe 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
meanScalarThe mean value (expectation) of the generated random numbers
stddevScalarThe 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
lowInputArrayThe inclusive lower boundary of the generated random numbers
highInputArrayThe 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
lowScalarThe inclusive lower boundary of the generated random numbers
highScalarThe 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
pt1PointOne of the rectangle vertices.
pt2PointOpposite rectangle vertex.
colorScalarLine color (RGB) or brightness (grayscale image).
thicknessintThickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1]
lineTypeLineTypesType of the line, see cvLine description. [By default this is LineType.Link8]
shiftintNumber 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
rectRectRectangle.
colorScalarLine color (RGB) or brightness (grayscale image).
thicknessintThickness of lines that make up the rectangle. Negative values make the function to draw a filled rectangle. [By default this is 1]
lineTypeLineTypesType of the line, see cvLine description. [By default this is LineType.Link8]
shiftintNumber 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
dimReduceDimensionThe 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
rtypeReduceTypesdtypeintWhen 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
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
map1InputArrayThe first map of either (x,y) points or just x values having the type CV_16SC2, CV_32FC1, or CV_32FC2.
map2InputArrayThe second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if map1 is (x,y) points), respectively.
interpolationInterpolationFlagsInterpolation method. The method INTER_AREA is not supported by this function.
borderModeBorderTypesPixel 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.
borderValueScalar?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
nyintHow many times the src is repeated along the vertical axis
nxintHow many times the src is repeated along the horizontal axis
Returns
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
szintNumber 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
szintNumber 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
cnintNew number of channels. If the parameter is 0, the number of channels remains the same.
rowsintNew number of rows. If the parameter is 0, the number of rows remains the same.
Returns
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
cnintNew number of channels. If the parameter is 0, the number of channels remains the same.
newDimsint[]New number of rows. If the parameter is 0, the number of rows remains the same.
Returns
Resize(Size, double, double, InterpolationFlags)
Resizes an image.
public Mat Resize(Size dsize, double fx = 0, double fy = 0, InterpolationFlags interpolation = InterpolationFlags.Linear)
Parameters
dsizeSizeoutput 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.
fxdoublescale factor along the horizontal axis; when it equals 0, it is computed as: (double)dsize.width/src.cols
fydoublescale factor along the vertical axis; when it equals 0, it is computed as: (double)dsize.height/src.rows
interpolationInterpolationFlagsinterpolation 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
szintNew number of rows.
Resize(int, Scalar)
Changes the number of matrix rows.
public void Resize(int sz, Scalar s)
Parameters
Row(int)
Creates a matrix header for the specified matrix row.
public Mat Row(int y)
Parameters
yintA 0-based row index.
Returns
RowRange(Range)
Creates a matrix header for the specified row span.
public Mat RowRange(Range range)
Parameters
rangeRange
Returns
RowRange(int, int)
Creates a matrix header for the specified row span.
public Mat RowRange(int startRow, int endRow)
Parameters
Returns
RowRange(Range)
Creates a matrix header for the specified row span.
public Mat RowRange(Range range)
Parameters
rangeRange
Returns
SaveImage(string, params ImageEncodingParam[])
Saves an image to a specified file.
public bool SaveImage(string fileName, params ImageEncodingParam[] prms)
Parameters
fileNamestringprmsImageEncodingParam[]
Returns
SaveImage(string, int[]?)
Saves an image to a specified file.
public bool SaveImage(string fileName, int[]? prms = null)
Parameters
Returns
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
ddepthMatTypeThe destination image depth
xorderintOrder of the derivative x
yorderintOrder of the derivative y
scaledoubleThe optional scale factor for the computed derivative values (by default, no scaling is applie
deltadoubleThe optional delta value, added to the results prior to storing them in dst
borderTypeBorderTypesThe 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
ddepthMatTypeThe destination image depth
kernelXInputArrayThe coefficients for filtering each row
kernelYInputArrayThe coefficients for filtering each column
anchorPoint?The anchor position within the kernel; The default value (-1, 1) means that the anchor is at the kernel center
deltadoubleThe value added to the filtered results before storing them
borderTypeBorderTypesThe 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
dataT[]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
sScalar?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
dataT[,]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
valueInputArraymaskMat
Returns
SetTo(Scalar, Mat?)
Sets all or some of the array elements to the specified value.
public Mat SetTo(Scalar value, Mat? mask = null)
Parameters
Returns
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
i0intIndex along the dimension 0
i1intIndex along the dimension 1
i2intIndex along the dimension 2
valueT
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
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
i0intIndex along the dimension 0
valueT
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
idxint[]Array of Mat::dims indices.
valueT
Type Parameters
T
Size()
Returns a matrix size.
public Size Size()
Returns
Size(int)
Returns a matrix size.
public int Size(int dim)
Parameters
dimint
Returns
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
ddepthMatTypeThe destination image depth
xorderintOrder of the derivative x
yorderintOrder of the derivative y
ksizeintSize of the extended Sobel kernel, must be 1, 3, 5 or 7
scaledoubleThe optional scale factor for the computed derivative values (by default, no scaling is applied
deltadoubleThe optional delta value, added to the results prior to storing them in dst
borderTypeBorderTypesThe 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
flagsSortFlagsThe 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
flagsSortFlagsThe 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
Step(int)
Returns number of bytes each matrix row occupies.
public long Step(int i)
Parameters
iint
Returns
Step1(int)
Returns a normalized step.
public long Step1(int i = 0)
Parameters
iint
Returns
SubMat(Range, Range)
Extracts a rectangular submatrix.
public Mat SubMat(Range rowRange, Range colRange)
Parameters
rowRangeRangeStart and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all().
colRangeRangeStart and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all().
Returns
SubMat(params Range[])
Extracts a rectangular submatrix.
public Mat SubMat(params Range[] ranges)
Parameters
rangesRange[]Array of selected ranges along each array dimension.
Returns
SubMat(Rect)
Extracts a rectangular submatrix.
public Mat SubMat(Rect roi)
Parameters
roiRectExtracted submatrix specified as a rectangle.
Returns
SubMat(int, int, int, int)
Extracts a rectangular submatrix.
public Mat SubMat(int rowStart, int rowEnd, int colStart, int colEnd)
Parameters
Returns
SubMat(Range, Range)
Extracts a rectangular submatrix.
public Mat SubMat(Range rowRange, Range colRange)
Parameters
rowRangeRangeStart and end row of the extracted submatrix. The upper boundary is not included. To select all the rows, use Range::all().
colRangeRangeStart and end column of the extracted submatrix. The upper boundary is not included. To select all the columns, use Range::all().
Returns
Subtract(Mat)
public MatExpr Subtract(Mat m)
Parameters
mMat
Returns
Subtract(Scalar)
public MatExpr Subtract(Scalar s)
Parameters
sScalar
Returns
Sum()
computes sum of array elements
public Scalar Sum()
Returns
T()
Transposes a matrix.
public MatExpr T()
Returns
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
threshdoublethreshold value.
maxvaldoublemaximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
typeThresholdTypesthresholding 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
extstringEncodes an image into a memory buffer.
prmsImageEncodingParam[]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
Returns
- byte[]
ToMemoryStream(string, params ImageEncodingParam[])
Converts Mat to System.IO.MemoryStream
public MemoryStream ToMemoryStream(string ext = ".png", params ImageEncodingParam[] prms)
Parameters
extstringprmsImageEncodingParam[]
Returns
ToString()
Returns a string that represents this Mat.
public override string ToString()
Returns
Total()
Returns the total number of array elements.
public long Total()
Returns
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
Returns
Trace()
computes trace of a matrix
public Scalar Trace()
Returns
Transform(InputArray)
performs affine transformation of each element of multi-channel input matrix
public Mat Transform(InputArray m)
Parameters
mInputArrayThe 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
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
cameraMatrixInputArrayInput camera matrix
distCoeffsInputArrayInput 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.
newCameraMatrixInputArrayCamera 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
cameraMatrixInputArrayCamera matrix
distCoeffsInputArrayInput 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.
rInputArrayRectification 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.
pInputArrayNew 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
mInputArray2x3 transformation matrix.
dsizeSizesize of the output image.
flagsInterpolationFlagscombination of interpolation methods and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation (dst -> src) .
borderModeBorderTypespixel 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.
borderValueScalar?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
mMat3x3 transformation matrix.
dsizeSizesize of the output image.
flagsInterpolationFlagscombination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation (dst -> src).
borderModeBorderTypespixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE).
borderValueScalar?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
markersInputOutputArrayInput/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
streamStreamextstringprmsImageEncodingParam[]
Xor(Mat)
public MatExpr Xor(Mat m)
Parameters
mMat
Returns
Xor(double)
public MatExpr Xor(double s)
Parameters
sdouble
Returns
Zeros(MatType, params int[])
Returns a zero array of the specified size and type.
public static MatExpr Zeros(MatType type, params int[] sizes)
Parameters
Returns
Zeros(Size, MatType)
Returns a zero array of the specified size and type.
public static MatExpr Zeros(Size size, MatType type)
Parameters
sizeSizeAlternative to the matrix size specification Size(cols, rows) .
typeMatTypeCreated matrix type.
Returns
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
Returns
Operators
operator +(Mat, Mat)
public static MatExpr operator +(Mat a, Mat b)
Parameters
Returns
operator +(Mat, Scalar)
public static MatExpr operator +(Mat a, Scalar s)
Parameters
Returns
operator +(Scalar, Mat)
public static MatExpr operator +(Scalar s, Mat a)
Parameters
Returns
operator &(Mat, Mat)
public static MatExpr operator &(Mat a, Mat b)
Parameters
Returns
operator &(Mat, double)
public static MatExpr operator &(Mat a, double s)
Parameters
Returns
operator &(double, Mat)
public static MatExpr operator &(double s, Mat a)
Parameters
Returns
operator |(Mat, Mat)
public static MatExpr operator |(Mat a, Mat b)
Parameters
Returns
operator |(Mat, double)
public static MatExpr operator |(Mat a, double s)
Parameters
Returns
operator |(double, Mat)
public static MatExpr operator |(double s, Mat a)
Parameters
Returns
operator /(Mat, Mat)
public static MatExpr operator /(Mat a, Mat b)
Parameters
Returns
operator /(Mat, double)
public static MatExpr operator /(Mat a, double s)
Parameters
Returns
operator /(double, Mat)
public static MatExpr operator /(double s, Mat a)
Parameters
Returns
operator ^(Mat, Mat)
public static MatExpr operator ^(Mat a, Mat b)
Parameters
Returns
operator ^(Mat, double)
public static MatExpr operator ^(Mat a, double s)
Parameters
Returns
operator ^(double, Mat)
public static MatExpr operator ^(double s, Mat a)
Parameters
Returns
operator *(Mat, Mat)
public static MatExpr operator *(Mat a, Mat b)
Parameters
Returns
operator *(Mat, double)
public static MatExpr operator *(Mat a, double s)
Parameters
Returns
operator *(double, Mat)
public static MatExpr operator *(double s, Mat a)
Parameters
Returns
operator ~(Mat)
public static MatExpr operator ~(Mat m)
Parameters
mMat
Returns
operator -(Mat, Mat)
public static MatExpr operator -(Mat a, Mat b)
Parameters
Returns
operator -(Mat, Scalar)
public static MatExpr operator -(Mat a, Scalar s)
Parameters
Returns
operator -(Scalar, Mat)
public static MatExpr operator -(Scalar s, Mat a)
Parameters
Returns
operator -(Mat)
public static MatExpr operator -(Mat mat)
Parameters
matMat
Returns
operator +(Mat)
public static Mat operator +(Mat mat)
Parameters
matMat