How to print matrix values in OpenCvSharp library

Viewed 1919

I'm trying to find homography matrix of two sources using Cv2.FindHomography method. Everything works fine up to here. The problem is that I cannot get/print matrix values. I'm really beginner-level for C#. I've found a sort of documentation belonging to it. However, I don't understand how to iterate over the values.

this[int startCol, int endCol]
override MatExpr OpenCvSharp.Mat.ColExprIndexer.this[int startCol, int endCol]
getset
Creates a matrix header for the specified column span.

Parameters
startCol    An inclusive 0-based start index of the column span.
endCol  An exclusive 0-based ending index of the column span.
Returns

My code,

Point2d[] points1 = new Point2d[]
{
  new Point2d(141, 131), new Point2d(480, 159)
};
Point2d[] points2 = new Point2d[]
{
  new Point2d(318, 256),
  new Point2d(5, 1)
};

Mat hCv = Cv2.FindHomography(points1, points2);
// I want to print the the resultant matrix
2 Answers

First method is using Data method.

byte[] data = new byte[hCv.Width * hCv.Height];
Marshal.Copy(hCv.DataPointer, data, 0, hCv.Width * hCv.Height);

for(int i = 0; i < data.Length; i++)
{
    // Print data[i]
}

Type depends on type of matrix, if its CV_8, then use byte, in case of CV_32, use float etc.


According to this - another method is to create image or matrix (additional copy) and then access each elements

Image<Bgr, Byte> img = hCv.ToImage<Bgr, Byte>();

The pixel data can then be accessed using the Image<,>.Data property.

You can also convert the Mat to an Matrix<> object. Assuming the Mat contains 8-bit data

Matrix<Byte> matrix = new Matrix<Byte>(hCv.Rows, hCv.Cols, mat.NumberOfChannels);
hCv.CopyTo(matrix);

The pixel data can then be accessed using the Matrix<>.Data property.

Here's an approach that doesn't involve making a copy of the Mat:

for (var rowIndex = 0; rowIndex < hCv.Rows; rowIndex++)
{
    for (var colIndex = 0; colIndex < hCv.Cols; colIndex++)
    {
        Debug.Write($"{hCv.At<double>(rowIndex, colIndex)} ");
    }
    Debug.WriteLine("");
}

Just make sure the type inside the angle brackets (double in this case) is correct. Otherwise you'll get nonsense values.

Related