Search Unity

Saving the output of a blur shader?

Discussion in 'Shaders' started by TestSubject06, Sep 21, 2014.

  1. TestSubject06

    TestSubject06

    Joined:
    Sep 4, 2014
    Posts:
    2
    So I have a RawImage on my screen that I want to apply a blur shader to, but then instead of just blurring the final image before it goes to the screen - I want to save that blurred image so that on the next iteration(after it's been drawn to again) I can blur it again.

    I have this, but it's CPU code and once the image gets larger than say 200x200, it's too slow to be useful:
    Code (CSharp):
    1. private void Blur(Texture2D image, int blurSize)
    2. {
    3.     Color[] blurred = image.GetPixels ();
    4.    
    5.     // look at every pixel in the blur rectangle
    6.     for (int xx = 0; xx < image.width; xx++)
    7.     {
    8.         for (int yy = 0; yy < image.height; yy++)
    9.         {
    10.             float avgR = 0, avgG = 0, avgB = 0;
    11.             int blurPixelCount = 0;
    12.            
    13.             // average the color of the red, green and blue for each pixel in the
    14.             // blur size while making sure you don't go outside the image bounds
    15.             for (int x = xx; (x <= xx + blurSize && x < image.width); x++)
    16.             {
    17.                 for (int y = yy; (y < yy + blurSize && y < image.height); y++)
    18.                 {
    19.                     Color pixel = blurred[y*image.width + x];
    20.                    
    21.                     avgR += pixel.r;
    22.                     avgG += pixel.g;
    23.                     avgB += pixel.b;
    24.                    
    25.                     blurPixelCount++;
    26.                 }
    27.             }
    28.            
    29.             avgR = avgR / blurPixelCount;
    30.             avgG = avgG / blurPixelCount;
    31.             avgB = avgB / blurPixelCount;
    32.            
    33.             // now that we know the average for the blur size, set each pixel to that color
    34.             for (int x = xx; x < xx + blurSize && x < image.width; x++)
    35.                 for (int y = yy; y < yy + blurSize && y < image.height; y++)
    36.                     blurred[y*image.width + x] = new Color(avgR/1.1f-0.002f, avgG/1.1f-0.002f, avgB/1.1f-0.002f);
    37.         }
    38.     }
    39.    
    40.     image.SetPixels (blurred);
    41. }
    What I want to do is this same effect, but with a shader instead. Is there a way to save the final image back into something like _MainTex?
     
  2. TestSubject06

    TestSubject06

    Joined:
    Sep 4, 2014
    Posts:
    2
    Alternatively, and probably more in line with what I want, can I modify a texture from within a shader, so that I can access(and draw to) that texture later.