Is CreateImageFromPointer available for .Net?

Sorry if it’s obvious, but I haven’t found it. I don’t think Image.FromHandle is exactly the same?

CreateImageFromPointer is what is behind the WrappedImage ctors. Note that the buffers should be either unmanaged or fixed, otherwise you’ll quickly see access violations :wink:

I don’t see any ctors for MappedImage though :frowning:

For context: I’m trying to do the conversion from OpenCV back to :cvb: (because I created the OpenCV.Mat using a pointer, so it thinks my RGB data is BGR, and will invert it if I use Mat.Save, so I want to map back to Image so I can save!), so I’m looking for the C# equivalent of what the CVBInterop.pdf describes.

My bad :man_facepalming:
It’s WrappedImage, not MappedImage

I’m just trying roundtripping (which may be dangerous) and have an AccessViolationException on the last line. Is it because of what I’m trying to do, or because of misuse of the parameters?

//Image img from camera (PixelFormat = RGB8)
var access = img.Planes[0].GetLinearAccess();
var mat = new Mat(img.Height, img.Width, DepthType.Cv8U, img.Planes.Count, 
                  access.BasePtr, (int)access.YInc);
var size = mat.Cols * mat.Rows * mat.ElementSize;
WrappedImage.FromRgbPixels(mat.Ptr, size, mat.Cols, mat.Rows, PixelDataType.UInt, 
                           8, 3, mat.Step, 1);

Haha!
I found my bug already mat.Ptr is a pointer to the start of the object, you need to use mat.DataPointer for the start of the data. So the corrected code is:

//Image img from camera (PixelFormat = RGB8)
var access = img.Planes[0].GetLinearAccess();
var mat = new Mat(img.Height, img.Width, DepthType.Cv8U, img.Planes.Count, 
                  access.BasePtr, (int)access.YInc);
var size = mat.Cols * mat.Rows * mat.ElementSize;
WrappedImage.FromRgbPixels(mat.DataPointer, size, mat.Cols, mat.Rows, 
                           PixelDataType.UInt, 8, 3, mat.Step, 1);

Now I just need to clear up some of those magic numbers…

3 Likes

:smile:
sorry, did not get around to looking at this earlier - and thanks for sharing the solution! :+1:

1 Like