如何在OpenCvSharp库中打印矩阵值

时间:2018-12-24 12:43:22

标签: c# opencv matrix iterator opencvsharp

我正在尝试使用Cv2.FindHomography方法找到两个源的单应性矩阵。到这里一切正常。问题是我无法获取/打印矩阵值。我真的是C#的初学者。我发现一种documentation属于它。但是,我不知道如何迭代这些值。

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

我的代码,

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 个答案:

答案 0 :(得分:2)

第一种方法是使用Data方法。

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

类型取决于矩阵的类型,如果是CV_8,则使用byte,如果是CV_32,则使用float等。


根据this-另一种方法是创建图像或矩阵(附加副本),然后访问每个元素

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

然后可以使用Image<,>.Data属性访问像素数据。

您还可以将Mat转换为Matrix <>对象。假设Mat包含8位数据

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

然后可以使用Matrix<>.Data属性访问像素数据。

答案 1 :(得分:1)

这里的方法不涉及复制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("");
}

只需确保尖括号(在这种情况下为double)内的类型正确。否则,您将获得无意义的值。