如何有效地从EmguCV(OpenCV)图像获取流

时间:2021-06-24 08:59:16

I have an EmguCV.Image<Brg, Byte>() instance and another 3rd party API, that requires Stream that represents the image data.

我有一个EmguCV.Image ()实例和另一个第三方API,它需要Stream来表示图像数据。 ,byte>

I was able to convert the EmguCV image to the stream and pass it to the 3rd party API using System.Drawing.Bitmap.Save but that is not very efficient.

我能够将EmguCV图像转换为流并使用System.Drawing.Bitmap.Save将其传递给第三方API,但效率不高。

How to get the stream as afficietnly as possible?

如何尽可能有效地获取流?

This code works:

此代码有效:

var image = new Image<Rgb, byte>("photo.jpg");
var bitmap = image.Bitmap// System.Drawing - this takes 108ms!
using (var ms = new MemoryStream())
{
   bitmap.Save(ms, ImageFormat.Bmp); //not very efficient neither
   ms.Position = 0;
   return ImageUtils.load(ms); //the 3rd party API
}

I have tried to create UnmanagedMemoryStream directly from the image:

我试图直接从图像创建UnmanagedMemoryStream:

byte* pointer = (byte*)image.Ptr.ToPointer();
int length = image.Height*image.Width*3;
var unmanagedMemoryStream = new UnmanagedMemoryStream(pointer, length);

but when i try to read from it, it throws an AccessViolationException: Attempted to read or write protected memory.

但是当我尝试从它读取时,它会抛出一个AccessViolationException:尝试读取或写入受保护的内存。

for (int i = 0; i < length; i++)
{
   //throw AccessViolationException at random interation, e.g i==82240, 79936, etc
   unmanagedMemoryStream.ReadByte();     
}

the length is 90419328 in this case and it shoudl be correct, because it has the same value as image.ManagedArray.Length;

在这种情况下长度为90419328并且它应该是正确的,因为它具有与image.ManagedArray.Length相同的值;

How to get the stream without copying the data?

如何在不复制数据的情况下获取流?

1 个解决方案

#1


0  

Ok, there is Bytes property of type byte[] on the Image() so the answer is very easy:

好的,在Image()上有类型为byte []的Bytes属性,所以答案非常简单:

new MemoryStream(image.Bytes)

#1


0  

Ok, there is Bytes property of type byte[] on the Image() so the answer is very easy:

好的,在Image()上有类型为byte []的Bytes属性,所以答案非常简单:

new MemoryStream(image.Bytes)