I need to write an automatic white balance shader for a project, and for it to work, I need the whitest point of the image. I already tried to copy the RenderTexture into a Texture2D, but I got down to 7 FPS, since I’m doing this for every rendered image. I have to do this for every rendred image since it is a realtime realistic camera simulation, and performances are an important aspect of the project.
I thought using the shader’s properties to do so, and getting the white point in the C# using GetFloat after browsing the whole image, and sending it to the shader for the balancing in another pass, but since the RGB values needed change in the vertex shader, I have no way to keep the modified property and send it to the C# script, as the modified value stays on the GPU.
This question might be confusing, and I apologize for that.
Thanks in advance for your answers.
Well, found a way to do it, without a significant loss of performances, and it’s quite easy.
You need to copy the RenderTexture into a Texture2D, then create a Color32 array that you fill with GetPixels32, and you navigate through this array.
Here’s a code example of how to do it :
RenderTexture.active = src;
tex.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
Color32[] col = tex.GetPixels32();
int counter = -1;
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
counter++;
if (((float)(col[counter].r + col[counter].g + col[counter].b) / 3.0f) > average) {
r = col[counter].r;
g = col[counter].g;
b = col[counter].b;
average = (col[counter].r + col[counter].g + col[counter].b) /3.0f;
}
}
With r, g and b being bytes initialiazed to 0 in the Start() method, and w and h being the width and height of the image. Since GetPixels32 returns a 1D array, I used a counter to get the index, and in my case it’s not important to get the pixel coordinates. There is a better way to get the index of the pixel in the array, but for my use, this (really bad) method is fine. Of course, this will take more time as the image gets bigger, but for my use, it’s acceptable, I hope this can help people.
With this method, I lost around 5-8 frames per second.