[英]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
和Matrix
都從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.