我如何获得一个.NET位图和OpenCV的图像指向相同的内存块? [英] How do I get a .NET Bitmap and an OpenCV image to point to the same chunk of memory?

查看:200
本文介绍了我如何获得一个.NET位图和OpenCV的图像指向相同的内存块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得一个.NET位图和OpenCV的图像指向相同的内存块?我知道,我可以从一个复制到其他,但我会preFER,他们只是指向同一个像素。

How do I get a .NET Bitmap and an OpenCV image to point to the same chunk of memory? I know that I can copy from one to the other, but I would prefer that they just point to the same pixels.

奖励积分使用Emgu的解决方案。

Bonus points for a solution using Emgu.

推荐答案

下面只是一个理论,可能无法正常工作,我不是很有经验的OpenCV的/ emgucv

Following is just a theory and might not work, I'm not very experienced with opencv/emgucv

两个 System.Drawing.Bitmap Emgu.CV.Image 已构造以 SCAN0 作为参数。您可以为图像的分配内存和这个指针传递给构造函数。 内存可以通过 VAR PTR = Marshal.AllocHGlobal分配(步幅*高)(不要忘记释放OFC)或通过分配sufficent大小的管理的阵列和aquiring其地址。地址可以是获得性方式如下:

Both System.Drawing.Bitmap and Emgu.CV.Image have constructors taking scan0 as an argument. You can allocate memory for image and pass this pointer to that constructors. memory can be allocated by var ptr = Marshal.AllocHGlobal(stride*height) (dont forget to free ofc) or by allocating a managed array of sufficent size and aquiring its address. Address can be aquired following way:

var array = new byte[stride*height];
var gch = GCHandle.Alloc(array, GCHandleType.Pinned);
var ptr = gch.AddrOfPinnedObject();

此也销阵列,因此它不能被垃圾收集器和地址移到不会改变。

This also "pins" array, so it cannot be moved by garbage collector and address won't change.

我们将使用这些构造函数:

We are going to use these constructors:

Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0);
Image<Bgr, Byte>(int width, int height, int stride, IntPtr scan0);

宽度高度参数是不言自明的。 格式为位图 PixelFormat.Format24bppRgb 步幅是图像的单行字节的数量,还必须对齐(是4的倍数)。你可以这样说:

width and height arguments are self-explanatory. format for bitmap is PixelFormat.Format24bppRgb. stride is amount of bytes for single line of image, it also must be aligned (be a multiple of 4). You can get it this way:

var stride = (width * 3);
var align = stride % 4;
if(align != 0) stride += 4 - align;

SCAN0 是一个指向我们的内存块。

And scan0 is a pointer to our memory block.

所以我建议在创建后 System.Drawing.Bitmap Emgu.CV.Image 使用这些构造会使用相同的内存块。如果不是,则意味着OpenCV的或位图或两者所提供的内存块和可能的解决方案(如果存在的话)副本definetly不值得努力。

So I suggest that after creating System.Drawing.Bitmap and Emgu.CV.Image using these constructors will use the same memory block. If not, it means that opencv or Bitmap or both copy provided memory block and possible solution (if it exists) is definetly not worth efforts.

这篇关于我如何获得一个.NET位图和OpenCV的图像指向相同的内存块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆