v8ntage
v8ntage

Reputation: 13

setPixels32() in unity creates blank textures

I have an array of Texture2D's, which gets populated by the webcamtexture for a few seconds. That part works, all 50 or so frames show up in the inspector fine.

Now we modify those images by calling .GetPixels32() to get a Color32[] for each frame. as an example we can try to set each channel to the Math.Max of each pixel between the current frame and the frame prior (essentially a 'lighten' blend), and replace the texture in the array with the newly modified texture. (this code starts from the second frame, the problem is not from array out of bounds)

    Color32[] previousColors = previousFrame.GetPixels32();
    Color32[] currentColors = currentFrame.GetPixels32();
    Color32[] outColors = new Color32[colors.Length];
    int i = 0;
    while (i < currentColors .Length)
    {
        outColors[i].b = Math.Max(previousColors[i].b, currentColors[i].b);
        outColors[i].r = Math.Max(previousColors[i].r, currentColors[i].r);
        outColors[i].g = Math.Max(previousColors[i].g, currentColors[i].g);
    }
    bufferedPics[frameIndex].SetPixels32(outColors);
    bufferedPics[frameIndex].Apply();

Here's where the problem occurs: In the inspector, the frames in the array all now show up blank. But clicking the circle to the right of them, it shows the properly modified, lightened frame. Trying to use those frames elsewhere, they show up blank and transparent.

Upvotes: 1

Views: 1692

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

Color32 has four channels: red, green, blue and alpha. By default, alpha is 0 (meaning transparent). You have to set alpha to 255 to let the image be opaque.

Color32[] previousColors = previousFrame.GetPixels32();
Color32[] currentColors = currentFrame.GetPixels32();
Color32[] outColors = new Color32[colors.Length];
int i = 0;
while (i < currentColors .Length)
{
    outColors[i].b = Math.Max(previousColors[i].b, currentColors[i].b);
    outColors[i].r = Math.Max(previousColors[i].r, currentColors[i].r);
    outColors[i].g = Math.Max(previousColors[i].g, currentColors[i].g);
    outColors[i].a = 255;  // set the alpha channel to opaque
}
bufferedPics[frameIndex].SetPixels32(outColors);
bufferedPics[frameIndex].Apply();

Upvotes: 1

Related Questions