Can I use a shader to find the “difference” between two textures? (XNA / HLSL)

I created a simple webcam that detects “motion edges”, so I draw a texture that shows where the pixels of the current frame are significantly different from the previous frame. This is my code:

// LastTexture is a Texture2D of the previous frame.
// CurrentTexture is a Texture2D of the current frame.
// DifferenceTexture is another Texture2D.
// Variance is an int, default 100;

Color[] differenceData = new Color[CurrentTexture.Width * CurrentTexture.Height];
Color[] currentData = new Color[CurrentTexture.Width * CurrentTexture.Height];
Color[] lastData = new Color[LastTexture.Width * LastTexture.Height];

CurrentTexture.GetData<Color>(currentData);
LastTexture.GetData<Color>(lastData);

for (int i = 0; i < currentData.Length; i++)
{
    int sumCD = ColorSum(currentData[i]); // ColorSum is the same as c.R + c.B + c.G where c is a Color.
    int sumLD = ColorSum(lastData[i]);
    if ((sumCD > sumLD - Variance) && (sumCD < sumLD + Variance))
        differenceData[i] = new Color(0, 0, 0, 0); // If the current pixel is within the range of +/- the Variance (default: 100) variable, it has not significantly changes so is drawn black.
    else
        differenceData[i] = new Color(0, (byte)Math.Abs(sumCD - sumLD), 0); // This has changed significantly so is drawn a shade of green.
}

DifferenceTexture = new Texture2D(game1.GraphicsDevice, CurrentTexture.Width, CurrentTexture.Height);
DifferenceTexture.SetData<Color>(differenceData);

LastTexture = new Texture2D(game1.GraphicsDevice,CurrentTexture.Width, CurrentTexture.Height);
LastTexture.SetData<Color>(currentData);

Is there a way to offload this calculation to a GPU using shaders (it can go at about 25/26 frames per second using the above method, but it's a bit slower)? I have a basic understanding of how HLSL shaders work and do not wait for a complete solution, I just want to know if it will be possible and how to get the "difference" texture data from the shader, and if it will actually be faster.

Thanks in advance.

+3
3

, .Net Parallel Extensions CTP Microsoft. microsoft.com

XBox360, XNA, .

, :

for (int i = 0; i < currentData.Length; i++)
{
    // ...
}

:

Parallel.For(0, currentData.Length, delegate(int i)
{
   // ...
});

​​ . .

!

+2

, . Render Target, , , .

, , .

* edit - , , , , . , , .

+3

Sobel - . .

0

Source: https://habr.com/ru/post/1713530/


All Articles