如何将emgu图像转换为XNA Texture2D?

时间:2013-07-24 03:49:48

标签: c# .net opencv xna emgucv

Image<Bgr, Byte> video = cap.QueryFrame();
Texture2D t = new Texture2D(GraphicsDevice, video.Width, video.Height, false, SurfaceFormat.Color);
t.SetData<byte>(video.Bytes);
  

ArgumentException未处理

     

传入的数据大小对于此资源来说太大或太小。

2 个答案:

答案 0 :(得分:1)

我的方法是将图像“保存”到内存中,然后使用Texture2D.FromStream函数加载它。

Texture2D t;

using(MemoryStream memStream = new MemoryStream())
{
    Image<Bgr, Byte> video = cap.QueryFrame();
    cap.save(memStream, ImageFormat.PNG);
    t = Texture2D.FromStream(GraphicsDevice, memStream, video.Width, video.Height, 1f)
}

这适用于NonPremultiplied BlendStates,但是如果你想使用Premultiplied alpha,你应该通过以下函数运行Texture2D。此函数仅使用GPU快速预乘纹理的alpha,与内容处理器相同。

    static public void PreMultiplyAlpha(this Texture2D texture) {            

        //Setup a render target to hold our final texture which will have premulitplied color values
        var result = new RenderTarget2D(texture.GraphicsDevice, texture.Width, texture.Height);

        texture.GraphicsDevice.SetRenderTarget(result);
        texture.GraphicsDevice.Clear(Color.Black);

        // Using default blending function
        // (source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha)
        // Destination is zero so the reduces to
        // (source × Blend.SourceAlpha)
        // So this multiplies our color values by the alpha value and draws it to the RenderTarget
        var blendColor = new BlendState {
            ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.SourceAlpha,
            ColorSourceBlend = Blend.SourceAlpha
        };

        var spriteBatch = new SpriteBatch(texture.GraphicsDevice);
        spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
        spriteBatch.Draw(texture, texture.Bounds, Color.White);
        spriteBatch.End();

        // Simply copy over the alpha channel
        var blendAlpha = new BlendState {
            ColorWriteChannels = ColorWriteChannels.Alpha,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.One,
            ColorSourceBlend = Blend.One
        };

        spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
        spriteBatch.Draw(texture, texture.Bounds, Color.White);
        spriteBatch.End();

        texture.GraphicsDevice.SetRenderTarget(null);

        var t = new Color[result.Width * result.Height];
        result.GetData(t);
        texture.SetData(t);
    }

答案 1 :(得分:0)

视频以(蓝色,绿色,红色)格式存储图像。而texture2d也需要额外的alpha像素。

Image<Bgr, Byte> video = cap.QueryFrame();
Image<Bgra, Byte> video2 = video.Convert<Bgra, Byte>();
Texture2D t = new Texture2D(GraphicsDevice, video.Width, video.Height, false, SurfaceFormat.Color);
t.SetData<byte>(video2.Bytes);