0
\$\begingroup\$

I'm trying to use a non-shader method to convert a (single-frame) Texture2D to one with different brightness/contrast.

Attempt so far uses: https://stackoverflow.com/posts/15408608/revisions

I'm not quite sure how to convert their 2 dimensional array to work with Color32[] or Color[] - here is an attempt so far, but it does not compile because there is no * operator defined between float[][] and Color32[].


    public static Texture2D BrightnessContrast(Texture2D tex,float brightness=1f,float contrast=1f,float gamma=1f)
    { 

        float adjustedBrightness = brightness - 1.0f;
        // create matrix that will brighten and contrast the image
        float[][] ptsArray ={
        new float[] {contrast, 0, 0, 0, 0}, // scale red
        new float[] {0, contrast, 0, 0, 0}, // scale green
        new float[] {0, 0, contrast, 0, 0}, // scale blue
        new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha
        new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}};

        Color32[] pixels = tex.GetPixels32();

        for (int i = 0; i < pixels.Length; i++)
            pixels[i] = ptsArray * pixels[i];


        tex.SetPixels32(pixels);
        tex.Apply();

        return tex;
    }
```
\$\endgroup\$
0
1
\$\begingroup\$

This is not a good use of a matrix. Just write it as a plain old float multiplication / addition (or power, if you're using gamma, which cannot be represented as a matrix operation).

public static float AdjustChannel(float colour, 
           float brightness, float contrast, float gamma) {
    return Mathf.Pow(colour, gamma) * contrast + brightness;
}

public static Texture2D BrightnessContrast(Texture2D tex,
           float brightness=1f, float contrast=1f, float gamma=1f)
{ 
    float adjustedBrightness = brightness - 1.0f;

    Color[] pixels = tex.GetPixels();

    for (int i = 0; i < pixels.Length; i++) {
        var p = pixels[i];
        p.r = AdjustChannel(p.r, adjustedBrightness, contrast, gamma);
        p.g = AdjustChannel(p.g, adjustedBrightness, contrast, gamma);
        p.b = AdjustChannel(p.b, adjustedBrightness, contrast, gamma);
        pixels[i] = p;
    }

    tex.SetPixels(pixels);
    tex.Apply();

    return tex;
}
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .