将ColorImageStream转换为Emgu cv Image

时间:2014-02-25 00:27:33

标签: c# visual-studio-2010 kinect emgucv

我在使用WPF的visual stdio 2010中使用带有emgucv的kinect!我想从kinect获取帧并使用emgucv将其转换为灰度我有这个!

void myKinect_ColorFrameReady(object sender,ColorImageFrameReadyEventArgs e)         {

        using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
        {

            if (colorFrame == null) return;

            if (colorData == null)
                colorData = new byte[colorFrame.PixelDataLength];

            colorFrame.CopyPixelDataTo(colorData);

                if (colorImageBitmap == null)
                {
                    this.colorImageBitmap = new WriteableBitmap(
                        colorFrame.Width,
                        colorFrame.Height,
                        96,  // DpiX
                        96,  // DpiY
                        PixelFormats.Bgr32,
                        null);
                }

                this.colorImageBitmap.WritePixels(
                    new Int32Rect(0, 0, colorFrame.Width, colorFrame.Height),
                    colorData, // video data
                    colorFrame.Width * colorFrame.BytesPerPixel, // stride,
                    0   // offset into the array - start at 0
                    );


                Image<Gray, Byte> My_Image = new Image<Gray, byte>(BitmapFromSource(colorImageBitmap));
                kinectVideo.Source = ToBitmapSource(My_Image);


        }
    }


    private System.Drawing.Bitmap BitmapFromWriteableBitmap(WriteableBitmap writeBmp)
    {
        System.Drawing.Bitmap bmp;
        using (MemoryStream outStream = new MemoryStream())
        {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create((BitmapSource)writeBmp));
            enc.Save(outStream);
            bmp = new System.Drawing.Bitmap(outStream);
        }
        return bmp;
    }

    private System.Drawing.Bitmap BitmapFromSource(BitmapSource bitmapsource)
    {
        System.Drawing.Bitmap bitmap;
        using (MemoryStream outStream = new MemoryStream())
        {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapsource));
            enc.Save(outStream);
            bitmap = new System.Drawing.Bitmap(outStream);

        }
        return bitmap;

    }

     [DllImport("gdi32")]
    private static extern int DeleteObject(IntPtr o);


     public static BitmapSource ToBitmapSource(IImage image)
    {
        using (System.Drawing.Bitmap source = image.Bitmap)
        {
            IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap

            BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                ptr,
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

            DeleteObject(ptr); //release the HBitmap
            return bs;
        }
    }

0 个答案:

没有答案