如何在 EmguCV 中将图像转换为矩阵,然后将矩阵转换为位图?

How can I convert Image to Matrix and then Matrix to Bitmap in EmguCV?

我正在尝试执行以下操作:

public partial class Form1 : Form
{
const string path = @"lena.png";

public Form1()
{
    InitializeComponent();

    Image<Bgr, byte> color = new Image<Bgr, byte>(path);

    Matrix<byte> matrix = new Matrix<byte>(color.Rows, color.Cols);

    matrix.Data = color.ToMatrix();// just an analogy

    pictureBox1.Image = col.Bitmap;
    pictureBox2.Image = gray.Bitmap;
}
}

如何在 EmguCV 中将 Image 转换为 Matrix

如何将 Matrix 转换为 Bitmap

正在将 Image 转换为 Matrix

这里要注意的重要一点是 Image and Matrix inherit from CvArray. That means it is possible to use the (inherited) method CopyTo 将数据从 Image 实例复制到具有相同深度和维度的 Matrix 实例。

注意: 相关性有 3 个维度 -- 宽度、高度和通道数。

Image<Bgr, byte> color = ... ; // Initialized in some manner

Matrix<byte> matrix = new Matrix<byte>(color.Rows, color.Cols, color.NumberOfChannels);

color.CopyTo(matrix);

注意:由于需要复制整个数据数组,因此这种方法会产生成本。

正在将 Matrix 转换为 Bitmap

这个其实很简单。 Matrix 继承数组数据的 属性 Mat, which returns a Mat header(意思是现有数据数组的薄包装)。因为这只是创建了一个 header,所以速度非常快(不涉及副本)。

注意: 由于是 header,我假设基于我对 C++ API 的经验(尽管这似乎没有记录) 只要基础 Matrix object 保持在范围内,Mat object 就有效。

Mat 提供了一个 Bitmap property, which behaves identically to Image.Bitmap.

Bitmap b = matrix.Mat.Bitmap;

另一种选择是使用与以前相同的方法将数据复制回 Image 实例。

matrix.CopyTo(color);

然后你可以使用 Bitmap 属性(速度快,但只要你使用 Bitmap 就需要 Image 实例)。

Bitmap b = color.Bitmap;

另一种选择是使用 ToBitmap 方法,该方法复制数据,因此不依赖于源 Image 实例。

Bitmap b = color.ToBitmap();

用于测试的来源:

using System;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.Structure;
// ============================================================================
namespace CS1 {
// ============================================================================
class Test
{
    static void Main()
    {
        Image<Bgr, byte> color = new Image<Bgr, byte>(2, 2);
        for (int r = 0; r < color.Rows; r++) {
            for (int c = 0; c < color.Cols; c++) {
                int n = (c + r * color.Cols) * 3;
                color[r, c] = new Bgr(n, n+1, n+2);
            }
        }

        Matrix<byte> matrix = new Matrix<byte>(color.Rows, color.Cols, color.NumberOfChannels);

        color.CopyTo(matrix);

        Bitmap b = matrix.Mat.Bitmap;

        matrix.CopyTo(color);

        b = color.Bitmap;

        b = color.ToBitmap();
    }
}
// ============================================================================
} // namespace CS1
// ============================================================================

我用来生成编译解决方案的CMake文件:

cmake_minimum_required(VERSION 3.11)
project(CS1 VERSION 0.1.0 LANGUAGES CSharp)

add_executable(cs1
    src/test.cs
)

set_property(TARGET cs1
    PROPERTY VS_DOTNET_TARGET_FRAMEWORK_VERSION "v4.6.1"
)

set_property(TARGET cs1 
    PROPERTY VS_DOTNET_REFERENCES
    "System"
    "System.Drawing"
)

set_target_properties(cs1 PROPERTIES 
    VS_DOTNET_REFERENCE_emgu_cv_world "deps/Emgu.CV.World.dll"
)