[英]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.