Search Unity

Count colored pixels of RenderTexture and get this data on CPU.

Discussion in 'General Graphics' started by MUGIK, Dec 29, 2019.

  1. MUGIK

    MUGIK

    Joined:
    Jul 2, 2015
    Posts:
    481
    Hi!
    I need to calculate pixels of RenderTexture that are colored(alpha > 0). So I need to get pixels data inside C# script. My render texture is 16x16 pixels.
    I have tried many things:
    1. Texture2D.ReadPixels() - very slow.
    2. Graphics.CopyTexture() - does not work with Texture2D.
    3. AsyncGPUReadbackRequest - does not work on Android.
    4. Texture2D.ReadPixels() but on a thread - works only on the main thread.
    5. ComputeShader - does not work on low-end Android devices.
    6. Custom shader - can't read data directly from shader(GPU) so this also requires to read pixels from render texture.

    So my guess that there is no way to get pixels to C# script fast.
    But maybe there is a way to just count colored pixels of the RenderTexture.

    And again, the main problem is that reading pixels from RenderTexture to Texture is very slow. On Android it takes 10ms.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    Correct.

    Sure. Write a shader that outputs to a single pixel render texture and have that shader read the texture 128 times with offsets. Or do it in two passes where you render to a 16x1 texture that samples 16 vertical texels, and a second time that renders to the single pixel and samples all 16 texels of the previous render texture. Since your original texture is 16x16 that’s easy enough to store the count as count / 255.0 so it fits in an R8 or A8 render texture.

    This doesn’t solve the problem of getting that data back to the CPU though. If you really need it there then there’s really no choice but to eat those extra ms. You could write a native plugin that uses an OpenGL pixel buffer object to do the async readback, but AFAIK that requires GLES 3.0, so if you’re trying to do this on GLES 2.0 devices you’re plum out of luck.
     
    MUGIK likes this.