簡體   English   中英

如何在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

這里要注意的重要一點是ImageMatrix都從CvArray繼承。 這意味着可以使用(繼承的) 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 ,該屬性為該數組數據返回一個Mat頭(意味着在現有數據數組周圍的薄包裝)。 由於這只是創建標題,因此非常快(不涉及副本)。

注意:由於是標頭,因此根據我對C ++ API的經驗(即使似乎沒有記錄),我假設只要基礎Matrix對象保持作用域, Mat對象就有效。

Mat提供了一個Bitmap屬性,其行為與Image.Bitmap相同。

Bitmap b = matrix.Mat.Bitmap;

另一個選擇是使用與以前相同的方法將數據復制回Image實例。

matrix.CopyTo(color);

然后你可以使用Bitmap屬性(快,但要求Image的實例,只要您使用活Bitmap )。

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"
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM