Gaussian Blur Filter Shader

There are different ways to perform blur and this is one of the most common way to do it in a shader. It’s a two step method with first a horizontal blur and then a vertical blur. By splitting the work in two directions (two passes) you can save a lot of computation.

The method can be divided in the following parts:

  1. Render the scene you want to blur to a texture (could be downsampled)
  2. Render a screen aligned quad with the horizontal blur shader to a texture
  3. Render a screen aligned quad with the vertical blur shader to the screen or texture depending on what you want to use it for

The following image shows how the blur works when splitted up in two directions.

Separable blur filter

Here’s the horizontal blur shader.

Vertex Shader (GLSL) . This shader screen align a quad with width 1. Any method to render a screen aligned quad will work. So you’re free to use other shaders.

varying vec2 vTexCoord;
 
// remember that you should draw a screen aligned quad
void main(void)
{
   gl_Position = ftransform();;
  
   // Clean up inaccuracies
   vec2 Pos;
   Pos = sign(gl_Vertex.xy);
 
   gl_Position = vec4(Pos, 0.0, 1.0);
   // Image-space
   vTexCoord = Pos * 0.5 + 0.5;
}

Fragment Shader (GLSL) 

uniform sampler2D RTScene; // the texture with the scene you want to blur
varying vec2 vTexCoord;
 
const float blurSize = 1.0/512.0; // I've chosen this size because this will result in that every step will be one pixel wide if the RTScene texture is of size 512x512
 
void main(void)
{
   vec4 sum = vec4(0.0);
 
   // blur in y (vertical)
   // take nine samples, with the distance blurSize between them
   sum += texture2D(RTScene, vec2(vTexCoord.x - 4.0*blurSize, vTexCoord.y)) * 0.05;
   sum += texture2D(RTScene, vec2(vTexCoord.x - 3.0*blurSize, vTexCoord.y)) * 0.09;
   sum += texture2D(RTScene, vec2(vTexCoord.x - 2.0*blurSize, vTexCoord.y)) * 0.12;
   sum += texture2D(RTScene, vec2(vTexCoord.x - blurSize, vTexCoord.y)) * 0.15;
   sum += texture2D(RTScene, vec2(vTexCoord.x, vTexCoord.y)) * 0.16;
   sum += texture2D(RTScene, vec2(vTexCoord.x + blurSize, vTexCoord.y)) * 0.15;
   sum += texture2D(RTScene, vec2(vTexCoord.x + 2.0*blurSize, vTexCoord.y)) * 0.12;
   sum += texture2D(RTScene, vec2(vTexCoord.x + 3.0*blurSize, vTexCoord.y)) * 0.09;
   sum += texture2D(RTScene, vec2(vTexCoord.x + 4.0*blurSize, vTexCoord.y)) * 0.05;
 
   gl_FragColor = sum;
}

And here’s the vertical blur shader.

Vertex Shader (GLSL) (the same as for the blur in horizontal direction)

varying vec2 vTexCoord;
 
// remember that you should draw a screen aligned quad
void main(void)
{
   gl_Position = ftransform();;
  
   // Clean up inaccuracies
   vec2 Pos;
   Pos = sign(gl_Vertex.xy);
 
   gl_Position = vec4(Pos, 0.0, 1.0);
   // Image-space
   vTexCoord = Pos * 0.5 + 0.5;
}

Fragment Shader (GLSL) 

uniform sampler2D RTBlurH; // this should hold the texture rendered by the horizontal blur pass
varying vec2 vTexCoord;
 
const float blurSize = 1.0/512.0;
 
void main(void)
{
   vec4 sum = vec4(0.0);
 
   // blur in y (vertical)
   // take nine samples, with the distance blurSize between them
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y - 4.0*blurSize)) * 0.05;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y - 3.0*blurSize)) * 0.09;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y - 2.0*blurSize)) * 0.12;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y - blurSize)) * 0.15;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y)) * 0.16;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y + blurSize)) * 0.15;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y + 2.0*blurSize)) * 0.12;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y + 3.0*blurSize)) * 0.09;
   sum += texture2D(RTBlurH, vec2(vTexCoord.x, vTexCoord.y + 4.0*blurSize)) * 0.05;
 
   gl_FragColor = sum;
}

And this is a scene without blur.

Scene before bluring

And this is the same scene but with gaussian blur.

Blured Scene

You can tweak the blur radius to change the size of the blur and change the number of samples in each direction.

Cost for separable blur shader : 9+9 = 18 (number of texture samples)
Cost for shader if blured in one pass: 9*9 = 81 (number of texture samples)
So splitting up in two directions saves a lot.

The gaussian weights are calculated accordingly to the gaussian function with standard deviation of 2.7. These calculations were done in the excel document found [2].

Here’s a description of blur shaders and other image processing shaders in DirectX:
[1] http://ati.amd.com/developer/shaderx/ShaderX2_AdvancedImageProcessing.pdf

More info about calculating weights for separable gaussian blur:
[2] http://theinstructionlimit.com/?p=40

Be Sociable, Share!

35 thoughts on “Gaussian Blur Filter Shader

    1. admin Post author

      Sorry for confusing you, this vertex shader might not be useful for everyone since it’s goal is to align a simple quad to the view and stretch it to cover the entire screen. If you’re already sending in a screen aligned quad, you can skip the vertex shader!

  1. Justin

    Isn’t this just a box filter blur? Gaussian blurs are weighted based on their distance from the center. In your pixel shader you just take the average of all the pixels. This works fine in practice, but calling it a Gaussian blur is misleading.

  2. Justin

    I take that back. You ARE weighting the neighbors based on their distance. Sorry about that. However, their weight is based on a linear decay, not a Gaussian function.

    1. admin Post author

      Yes, I’m using the distance, but as you say, the weights are not really gaussian weights. But they are actually close enough to look good. I will add the “true” gaussian weights to this example since it’s more correct that way.

      Thanks for the feedback!

  3. Promit Roy

    Your filter weights are wrong somewhere.
    2 * (0.05 + 0.09 + 0.12 + 0.15) + 0.16 = 0.98
    This is probably the reason for #2′s darkness problem, and if you try to use this blur with VSM for example the results will be completely wrong.

  4. John

    Thanks for this, I’m looking for a good blur effect to blur a particle system so that I can make stuff like fire, fireworks, pulsating clouds etc …. I reckon this might do the trick!

  5. Luke

    I am a student and doing Image Processing Coursework

    Do you apply the Gaussian mask to the RGB components ot the YCbCr components of the image?

    I have tried and both seem to produce the same result.

  6. Chris

    What happens at the borders when texture2D is trying to read pixels outside the image? For example when vTexCoord.x is 0 and you call texture2D to access pixels at vTexCoord.x – 4 * blursize? What is the texture2D return value in this case and how does it contribute to the filter kernel?

  7. Pingback: ND2D – Blur - nulldesign // lars gerckens

  8. Pingback: Faster Gaussian Blur in GLSL | xissburg

  9. court reporter u quiz site

    Hey there! I know this is kinda off topic however , I’d figured I’d
    ask. Would you be interested in exchanging links
    or maybe guest writing a blog article or vice-versa? My website covers a lot of the same subjects as yours and
    I believe we could greatly benefit from each other.
    If you are interested feel free to send me an e-mail. I look forward to
    hearing from you! Fantastic blog by the way!

  10. Nick Wiggill

    Hi admin,

    You mentioned that vertex shaders are not necessary if you’re already passing in a screen-aligned quad. In that case, how would you make the draw call? As you surely do not need to pass any geometry in for the blur passes?

    Thanks,

    Nick

  11. Nick Wiggill

    Not to worry, I’m just being silly. Of course I will be passing in the fullscreen quad’s geometry via glDrawElements.

  12. Pingback: Desfoque Gaussiano Mais Rápido em GLSL | xissburg

  13. Pingback: Custom Blur Shader for Unity3D | Ana Todor Blog Journey | blur shader

  14. miliatry android smartphone

    I have been browsing online more than 2 hours today, yet I never found any
    interesting article like yours. It’s pretty worth enough for me.
    In my opinion, if all site owners and bloggers made good content as you did, the net will be a
    lot more useful than ever before.|
    I could not resist commenting. Exceptionally well written!|
    I will right away take hold of your rss feed as I can’t find your e-mail subscription hyperlink or e-newsletter service.
    Do you have any? Kindly permit me realize in order that I may subscribe.
    Thanks.|
    It’s perfect time to make some plans for the future and
    it’s time to be happy. I’ve read this post and if I could I wish to suggest you few interesting things or suggestions.
    Maybe you can write next articles referring to this article.
    I want to read even more things about it!|
    It is appropriate time to make a few plans for the future and it’s time to be happy.
    I’ve read this submit and if I may I want to recommend you some interesting things or tips.

    Maybe you can write subsequent articles relating to this article.
    I wish to learn more things about it!|
    I’ve been browsing on-line greater than 3 hours lately,
    but I never found any fascinating article like yours. It’s lovely worth sufficient for
    me. In my opinion, if all web owners and
    bloggers made just right content material as you probably did, the internet will be a lot more helpful than ever before.|
    Ahaa, its nice dialogue concerning this piece of writing at this place at
    this blog, I have read all that, so now me also commenting at this place.|
    I am sure this post has touched all the internet visitors, its really really pleasant
    piece of writing on building up new webpage.|
    Wow, this post is good, my sister is analyzing these things, so
    I am going to inform her.|
    Saved as a favorite, I really like your website!|
    Way cool! Some very valid points! I appreciate you writing this article
    and also the rest of the site is really good.|
    Hi, I do believe this is an excellent blog. I stumbledupon it ;) I am
    going to revisit yet again since I saved as a favorite it.
    Money and freedom is the best way to change, may you
    be rich and continue to help other people.|
    Woah! I’m really loving the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s challenging to get that “perfect balance” between superb usability and appearance.
    I must say you have done a amazing job with this. Also, the blog loads very fast for me
    on Opera. Superb Blog!|
    These are in fact impressive ideas in on the topic of blogging.
    You have touched some fastidious things here.
    Any way keep up wrinting.|
    I really like what you guys are usually up too. This type of clever work and exposure!
    Keep up the good works guys I’ve included you guys to blogroll.|
    Hey! Someone in my Myspace group shared this website with us so I came to look it over.
    I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers!

    Superb blog and brilliant design.|
    I like what you guys tend to be up too. Such clever work and coverage!
    Keep up the excellent works guys I’ve included you guys to my personal blogroll.|
    Hello would you mind stating which blog platform you’re using?
    I’m planning to start my own blog soon but I’m having a difficult time selecting between BlogEngine/Wordpress/B2evolution and
    Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something unique.

    P.S Apologies for getting off-topic but I had to ask!|
    Hey would you mind letting me know which hosting company you’re utilizing?
    I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most.
    Can you suggest a good internet hosting provider at a honest price?

    Thank you, I appreciate it!|
    Everyone loves it when people get together and share
    views. Great blog, stick with it!|
    Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from you! However, how can we communicate?|
    Hi there just wanted to give you a quick heads up.
    The words in your article seem to be running off the screen in Chrome.
    I’m not sure if this is a formatting issue or something
    to do with browser compatibility but I figured I’d post to let you know.
    The design and style look great though! Hope you get the problem fixed soon.
    Many thanks|
    This is a topic that is near to my heart… Take care!

    Where are your contact details though?|
    It’s very trouble-free to find out any topic on web as compared to books, as I found this post at this website.|
    Does your site have a contact page? I’m having trouble locating it but, I’d like to send
    you an email. I’ve got some recommendations for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing
    it grow over time.|
    Hello! I’ve been following your web site for a while now and finally
    got the bravery to go ahead and give you a shout out from Houston Texas!

    Just wanted to say keep up the fantastic job!|
    Greetings from Florida! I’m bored to tears at work so I decided to check
    out your site on my iphone during lunch break. I enjoy the info you present here and can’t
    wait to take a look when I get home. I’m surprised at how quick your
    blog loaded on my mobile .. I’m not even using WIFI, just 3G ..
    Anyways, superb blog!|
    Its like you learn my thoughts! You appear to grasp so much about this, like you wrote the
    e book in it or something. I feel that you just could do with a few percent to pressure
    the message house a little bit, but other than that, that is
    fantastic blog. A fantastic read. I will certainly be back.|
    I visited several web pages however the audio quality for audio songs present at this web page is
    in fact excellent.|
    Howdy, i read your blog occasionally and i own a similar one and i was just curious if you
    get a lot of spam feedback? If so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me crazy so any assistance is very much appreciated.|
    Greetings! Very helpful advice within this post! It’s the
    little changes that produce the greatest changes. Thanks for sharing!|
    I really love your site.. Very nice colors & theme. Did you make this amazing site yourself?
    Please reply back as I’m planning to create my own personal website and want
    to know where you got this from or what the theme is named.
    Thanks!|
    Howdy! This blog post could not be written much better! Looking through this post reminds me of my previous roommate!

    He always kept talking about this. I most certainly will forward
    this article to him. Fairly certain he’s going to have a great read.
    Many thanks for sharing!|
    Amazing! This blog looks just like my old one!
    It’s on a totally different topic but it has pretty much the same layout and design.
    Excellent choice of colors!|
    There is definately a lot to know about this topic. I really like all the points you have made.|
    You made some really good points there. I looked on the net for additional information
    about the issue and found most people will
    go along with your views on this website.|
    Hi, I log on to your new stuff like every week. Your writing style is awesome,
    keep doing what you’re doing!|
    I simply couldn’t depart your site prior to suggesting that I
    actually enjoyed the standard info a person supply to
    your visitors? Is gonna be back regularly in order to inspect new posts|
    I want to to thank you for this good read!! I absolutely enjoyed every bit of it.
    I have you book marked to check out new stuff you post…|
    What’s up, just wanted to say, I liked this article.
    It was helpful. Keep on posting!|
    I drop a leave a response when I like a article on a site or I have something to contribute to the discussion.
    Usually it’s caused by the sincerness displayed in the article I browsed.
    And on this article Gaussian Blur Filter Shader | Game Rendering.
    I was actually moved enough to drop a thought ;
    ) I actually do have a couple of questions for you if you do not mind.
    Is it simply me or does it look like like some of these comments come across
    as if they are written by brain dead individuals?
    :-P And, if you are writing on additional social sites, I would like to keep up with anything fresh you
    have to post. Could you list every one of your social sites like your linkedin profile, Facebook page or twitter feed?|
    Hello, I enjoy reading through your post. I wanted to write a little comment
    to support you.|
    I constantly spent my half an hour to read this blog’s articles or reviews every
    day along with a mug of coffee.|
    I for all time emailed this weblog post page to
    all my associates, because if like to read it next my contacts will too.|
    My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on numerous websites for
    about a year and am anxious about switching
    to another platform. I have heard excellent things about blogengine.net.
    Is there a way I can import all my wordpress content into it?
    Any kind of help would be really appreciated!|
    Hello there! I could have sworn I’ve visited this web site before but after browsing
    through some of the articles I realized it’s new to me.
    Nonetheless, I’m certainly happy I discovered it and I’ll be bookmarking it and checking back often!|
    Terrific article! This is the kind of info that are supposed to be shared across the web.
    Disgrace on Google for no longer positioning this publish higher!

    Come on over and seek advice from my site . Thanks =)|
    Heya i am for the first time here. I came across this
    board and I find It really useful & it helped me out much.
    I hope to give something back and help others like you helped me.|
    Hi, I think your blog may be having web browser compatibility issues.
    When I look at your site in Safari, it looks fine but when
    opening in IE, it has some overlapping issues. I just wanted to provide you with a quick heads up!

    Besides that, excellent site!|
    A person essentially lend a hand to make seriously articles I would state.
    This is the first time I frequented your
    website page and up to now? I amazed with the analysis
    you made to create this actual submit amazing. Great process!|
    Heya i’m for the primary time here. I came across this board and I
    find It truly helpful & it helped me out much. I’m hoping
    to provide something back and aid others such as you helped me.|
    Hello! I just wish to give you a big thumbs up for
    your great info you’ve got here on this post. I am returning to your web site for more soon.|
    I all the time used to study piece of writing in news papers but now as I am a user of internet so from now I am using net
    for articles, thanks to web.|
    Your means of explaining everything in this post is actually fastidious, every one be
    capable of effortlessly be aware of it, Thanks
    a lot.|
    Hi there, I found your blog via Google while searching for
    a related topic, your site got here up, it seems good.
    I have bookmarked it in my google bookmarks.
    Hello there, just changed into alert to your weblog through Google,
    and located that it is really informative.
    I’m going to watch out for brussels. I’ll appreciate in the event you continue
    this in future. Many other folks shall be benefited from your writing.
    Cheers!|
    I’m curious to find out what blog platform you are using?
    I’m having some small security problems with my latest site
    and I would like to find something more safeguarded. Do you
    have any recommendations?|
    I’m really impressed with your writing skills and also with the layout on your blog.
    Is this a paid theme or did you customize it yourself?
    Anyway keep up the nice quality writing, it’s rare to see a nice blog like this one nowadays.|
    I am really inspired with your writing talents
    and also with the format on your weblog. Is that this a paid topic
    or did you customize it yourself? Anyway keep up the nice high quality writing, it is rare to look a great
    blog like this one these days..|
    Hi, Neat post. There is a problem with your site in web explorer,
    would check this? IE nonetheless is the marketplace leader and
    a big section of other people will pass over your fantastic writing because of this problem.|
    I am not sure where you are getting your information,
    but good topic. I needs to spend some time learning more or understanding more.
    Thanks for fantastic information I was looking for this info for my
    mission.|
    Hi, i think that i saw you visited my blog so i came to “return the favor”.I’m trying to find things to enhance my website!I suppose its ok to use {some of|a \

  15. which way to rotate in summer ceiling fans

    Hey great website! Does running a blog similar to this take a large amount of
    work? I’ve no expertise in programming but I had been hoping to start my own blog
    in the near future. Anyway, if you have any suggestions or techniques for new blog owners please share.
    I know this is off topic nevertheless I just had to
    ask. Cheers!

  16. Hotels in Hollywood Walk of Fameinn dealslast minute resort hotel offers.

    Hello I am so glad I found your blog page, I really found you by accident, while I
    was looking on Google for something else, Anyhow I am here now and would just
    like to say thanks for a marvelous post and a all round entertaining blog (I also
    love the theme/design), I don’t have time to read through it all at the moment but I have saved it and also added in your RSS feeds, so when I have time I will be back
    to read more, Please do keep up the great jo.

  17. Louboutin Ireland

    Hi! I could have sworn I’ve visited this web site before but after browsing through some of
    the articles I realized it’s new to me. Anyhow, I’m definitely happy I stumbled
    upon it and I’ll be book-marking it and checking back often!

  18. ของเล่นเด็ก

    Appreciating the hard work you put into your blog and in depth information you provide.
    It’s great to come across a blog every once in a while that isn’t the same outdated rehashed information.
    Excellent read! I’ve saved your site and I’m including your RSS feeds to my
    Google account.

  19. http://www.youtube.com

    After activating, you will find their website link and get the activation code from their website.
    Good pay, better working conditions and atmosphere, and
    fast growth rate are some other reasons which caused many professionals switching side towards this recession free industry.
    Have you ever observed or played poker in real betting environment.

  20. Carx Drift Racing hack android

    Millions of people around the world are big fans of the latest smartphones being released.
    Android OS is not certified to a single cell phone making company,
    the mobile phones themselves can differ to an excessive degree with regards
    to features and components features. If you have an android phone or
    tablet, you can enjoy the applications without spending money
    from your credit card.

    Also visit my webpage – Carx Drift Racing hack android

  21. Beats By Dr. Dre

    I almost never comment, however i did some
    searching and wound up here Gaussian Blur Filter Shader | Game Rendering.
    And I do have a couple of questions for you if it’s allright.
    Could it be only me or does it look as if like
    a few of the responses come across like they are coming from brain dead
    people? :-P And, if you are posting on additional
    social sites, I would like to keep up with everything new you have
    to post. Would you make a list of all of all your communal pages
    like your twitter feed, Facebook page or linkedin profile?

  22. woodworking plans

    As the ceremony drew ever closer, the Luxembourg royal family finally arrived.
    Then you may determine which just one an individual need to
    purchase. In addition, a real handbag is exclusive to Hermes.

Comments are closed.