Search Unity

Retrieve pixel RGB data without resorting to Texture2D.ReadPixels()

Discussion in 'Shaders' started by eco_bach, Nov 26, 2015.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Hi I know this is a common problem but still was hoping someone has found an answer.

    I'm trying to retrieve the pixel RGB values as seen by the current live camera. In my OnRenderImage (or OnPostrender) I have

    tex2D.ReadPixels(rect, 0, 0);

    where tex2D is a Texture2D instance and rect is a Rect instance.

    ReadPixels is the bottleneck!

    I'm posting in the Shader sub forum because I'm actually trying to capture a 'pixellate' shader effect in terms of rgb or brightness values.
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    I'm not entirely sure what your final goal is, but ReadPixels world by copying the screen texture back to the CPU from the GPU, then sending the new texture back. If you're doing this as part of your rendering it is essentially stalling the GPU until it's done.

    It's better to try to do everything with render to texture, shaders, and blit commands. Pretty much anything else requires and copy back from the GPU (which is the slow part) and possibly stalling the GPU (also slow).
     
  3. StevenGerrard

    StevenGerrard

    Joined:
    Jun 1, 2015
    Posts:
    97
    Your goal : capture a 'pixellate' shader effect output.
    Steps:
    => First create a camera, setup it's render texture.
    => Render your scene color to this render texture.
    => Then use Graphics.Blit with your 'pixellate' shader on this render texture.
    => Now you retrieve the pixelate result, use it as any shader input program as you want.
     
  4. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    Thanks for the great replies. My next step is to do everything as suggested but for now am using ReadPixels on a very small (160 x90) webcamtexture which both reduces impact on performance and removes the need for any pixellate shader.