0

我正在使用 .NET 编写一个简单的 OpenCV 应用程序,其目标是在一个简单的窗口上呈现网络摄像头流。

这是我用来执行此操作的代码:

private static BitmapSource ToBitmapSource(IImage image)
{
    using (System.Drawing.Bitmap source = image.Bitmap)
    {
        IntPtr ptr = source.GetHbitmap();
        BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            ptr,
            IntPtr.Zero,
            Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
        DeleteObject(ptr);
        return bs;
    }
}

private void CameraShow()
{
    ImageViewer viewer = new Emgu.CV.UI.ImageViewer(); //create an image viewer
    Capture capture = new Capture(); //create a camera captue

    this.isCamOff = false;
    while (this.CamStat != eCamRun.CamStop)
    {
        Thread.Sleep(60);
        viewer.Image = capture.QueryFrame(); //draw the image obtained from camera
        System.Windows.Application.Current.Dispatcher.Invoke(
            DispatcherPriority.Normal,
            (ThreadStart)delegate
        {
            this.ImageStream.Source = ToBitmapSource(viewer.Image); //BitmapSource
        });
    }

    viewer.Dispose();
    capture.Dispose();
    this.isCamOff = true;
    Thread.CurrentThread.Interrupt();
}

但是现在我想在控制台上显示包含在 System.Drawing.Bitmap 对象中的像素缓冲区的内容(我知道 void* 本机类型包含在 Bitmap 对象中的 IntPtr 变量中)。因此,根据我下面的源代码来恢复 IntPtr 变量,我必须编写以下代码行(进入“不安全”上下文):

IntPtr buffer = viewer.Image.Bitmap.GetHbitmap();

byte[] pPixelBuffer = new byte[16]; //16 bytes allocation
Marshal.Copy(buffer, pPixelBuffer, 0, 9); //I copy the 9 first bytes into pPixelBuffer

不幸的是,我在“复制”方法中有访问冲突异常!我不明白为什么。

有人可以帮助我吗?

非常感谢您的帮助。

4

2 回答 2

0

您可以在不安全的上下文中强制IntPtr转换为。void*你可以这样做:

unsafe
{
    var bytePtr = (byte*)(void*)buffer;

    // Here use *bytePtr to get the byte value at bytePtr, just like in C/C++
}
于 2014-07-04T21:37:05.030 回答
0

怎么用Marshal.Copy?有了这个,您可以将 的内容复制IntPtrbyte[]all 而无需进入unsafe

http://msdn.microsoft.com/en-us/library/ms146631(v=vs.110).aspx

于 2014-07-04T23:51:11.390 回答