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

ArgumentException 未处理

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

4

2 回答 2

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);
    }
于 2013-07-24T13:57:51.533 回答
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);
于 2013-07-24T04:25:05.033 回答