Search code examples
unity-game-enginetexture2d

How to change texture format from Alpha8 to RGBA in Unity3d?


I have been trying to change the format from a camera that give a texture in Alpha8 to RGBA and have been unsuccessful so far.

This is the code I've tried:

   public static class TextureHelperClass
    {
        public static Texture2D ChangeFormat(this Texture2D oldTexture, TextureFormat newFormat)
        {
            //Create new empty Texture
            Texture2D newTex = new Texture2D(2, 2, newFormat, false);
            //Copy old texture pixels into new one
            newTex.SetPixels(oldTexture.GetPixels());
            //Apply
            newTex.Apply();

            return newTex;
        }
    }

And I'm calling the code like this:

  Texture imgTexture = Aplpha8Texture.ChangeFormat(TextureFormat.RGBA32);

But the image gets corrupted and isn't visible.

Does anyone know how to change this Alpha8 to RGBA so I can process it like any other image in OpenCV?


Solution

  • A friend provided me with the answer:

        Color[] cs =oldTexture.GetPixels();
        for(int i = 0; i < cs.Length; i++){//we want to set the r g b values to a
            cs[i].r = cs[i].a;
            cs[i].g = cs[i].a;
            cs[i].b = cs[i].a;
            cs[i].a = 1.0f;                                                
        }
        //set the pixels in the new texture
        newTex.SetPixels(cs);
        //Apply
        newTex.Apply();
    

    This will take alot of resources but it will work for sure. If you know a better way to make this change please add an answer to this thread.