Unity shader學習之屏幕后期處理效果之高斯模糊


高斯模糊,見 百度百科

也使用卷積來實現,每個卷積元素的公式為:

其中б是標准方差,一般取值為1。

x和y分別對應當前位置到卷積中心的整數距離。

由於需要對高斯核中的權重進行歸一化,即使所有權重相加為1,因此e前面的系數實際不會對結果產生任何影響。

轉載請注明出處:http://www.cnblogs.com/jietian331/p/7238032.html

綜上,公式簡化為:

G(x,y) = e-(x*x+y*y)/2

 

因此,高斯核計算代碼如下:

  1 using System;
  2 
  3 namespace TestShell
  4 {
  5     class Program
  6     {
  7         static void Main(string[] args)
  8         {
  9             Console.WriteLine("輸入需要得到的高斯卷積核的維數(如3,5,7...):");
 10 
 11             string input = Console.ReadLine();
 12             int size;
 13 
 14             if (!int.TryParse(input, out size))
 15             {
 16                 Console.WriteLine("不是數字...");
 17                 return;
 18             }
 19 
 20             // 計算
 21             double[] r2 = null;
 22             double[,] r = null;
 23             try
 24             {
 25                 r = CalcGaussianBlur(size, out r2);
 26             }
 27             catch (Exception ex)
 28             {
 29                 Console.WriteLine("錯誤: " + ex.Message);
 30             }
 31 
 32             if (r != null && r2 != null)
 33             {
 34                 // 卷積如下:
 35                 Console.WriteLine();
 36                 Console.WriteLine("{0}x{0}的高斯卷積核如下:", size);
 37                 for (int i = 0; i < r.GetLongLength(0); i++)
 38                 {
 39                     for (int j = 0; j < r.GetLongLength(1); j++)
 40                     {
 41                         Console.Write("{0:f4}\t", r[i, j]);
 42                     }
 43                     Console.WriteLine();
 44                 }
 45                 Console.WriteLine();
 46 
 47                 Console.WriteLine("可拆成2個一維的數組:");
 48                 for (int i = 0; i < r2.Length; i++)
 49                 {
 50                     Console.Write("{0:f4}\t", r2[i]);
 51                 }
 52                 Console.WriteLine();
 53                 Console.WriteLine();
 54 
 55                 Console.WriteLine("驗證,使用這2個一維的數組也可以得到同樣的結果:");
 56                 for (int i = 0; i < size; i++)
 57                 {
 58                     for (int j = 0; j < size; j++)
 59                     {
 60                         Console.Write("{0:f4}\t", r2[i] * r2[j]);
 61 
 62                     }
 63                     Console.WriteLine();
 64                 }
 65             }
 66 
 67             Console.WriteLine();
 68             Console.WriteLine("按任意鍵結束...");
 69             Console.ReadKey();
 70         }
 71 
 72         static double[,] CalcGaussianBlur(int size, out double[] r2)
 73         {
 74             if (size < 3)
 75                 throw new ArgumentException("size < 3");
 76             if (size % 2 != 1)
 77                 throw new ArgumentException("size % 2 != 1");
 78 
 79             double[,] r = new double[size, size];
 80             r2 = new double[size];
 81             int center = (int)Math.Floor(size / 2f);
 82             double sum = 0;
 83 
 84             for (int i = 0; i < size; i++)
 85             {
 86                 for (int j = 0; j < size; j++)
 87                 {
 88                     int x = Math.Abs(i - center);
 89                     int y = Math.Abs(j - center);
 90                     double d = CalcItem(x, y);
 91                     r[i, j] = d;
 92                     sum += d;
 93                 }
 94             }
 95 
 96             for (int i = 0; i < size; i++)
 97             {
 98                 for (int j = 0; j < size; j++)
 99                 {
100                     r[i, j] /= sum;
101                     if (i == j)
102                         r2[i] = Math.Sqrt(r[i, i]);
103                 }
104             }
105 
106             return r;
107         }
108 
109         static double CalcItem(int x, int y)
110         {
111             return Math.Pow(Math.E, -(x * x + y * y) / 2d);
112         }
113     }
114 }
View Code

 

工具在: http://files.cnblogs.com/files/jietian331/CalcGaussianBlur.zip

 

一個5 x 5的高斯核如下:

 

使用2個一維數組可簡化計算量,提高性能,通過觀察可知,只需要計3個數:

 

使用unity shader屏幕后期處理來實現高斯模糊,代碼如下。

子類:

 1 using UnityEngine;
 2 
 3 public class GaussianBlurRenderer : PostEffectRenderer
 4 {
 5     [Range(1, 8)]
 6     [SerializeField]
 7     public int m_downSample = 2;      // 降采樣率
 8     [Range(0, 4)]
 9     [SerializeField]
10     public int m_iterations = 3;        // 迭代次數
11     [Range(0.2f, 3f)]
12     [SerializeField]
13     public float m_blurSpread = 0.6f;        // 模糊擴散量
14 
15     protected override void OnRenderImage(RenderTexture src, RenderTexture dest)
16     {
17         int w = (int)(src.width / m_downSample);
18         int h = (int)(src.height / m_downSample);
19         RenderTexture buffer0 = RenderTexture.GetTemporary(w, h);
20         RenderTexture buffer1 = RenderTexture.GetTemporary(w, h);
21         buffer0.filterMode = FilterMode.Bilinear;
22         buffer1.filterMode = FilterMode.Bilinear;
23         Graphics.Blit(src, buffer0);
24 
25         for (int i = 0; i < m_iterations; i++)
26         {
27             Mat.SetFloat("_BlurSpread", 1 + i * m_blurSpread);
28 
29             Graphics.Blit(buffer0, buffer1, Mat, 0);
30             Graphics.Blit(buffer1, buffer0, Mat, 1);
31         }
32 
33         Graphics.Blit(buffer0, dest);
34         RenderTexture.ReleaseTemporary(buffer0);
35         RenderTexture.ReleaseTemporary(buffer1);
36     }
37 
38     protected override string ShaderName
39     {
40         get { return "Custom/Gaussian Blur"; }
41     }
42 }
GaussianBlurRenderer

 

shader:

 1 // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClipPos(*)'
 2 
 3 Shader "Custom/Gaussian Blur"
 4 {
 5     Properties
 6     {
 7         _MainTex("Main Texture", 2D) = "white" {}
 8         _BlurSpread("Blur Spread", float) = 1
 9     }
10 
11     SubShader
12     {
13         CGINCLUDE
14         
15         sampler2D _MainTex;
16         float4 _MainTex_TexelSize;
17         uniform float _BlurSpread;
18 
19         struct appdata
20         {
21             float4 vertex : POSITION;
22             float2 uv : TEXCOORD0;
23         };
24 
25         struct v2f
26         {
27             float4 pos : SV_POSITION;
28             float2 uv[5] : TEXCOORD0;
29         };
30 
31         v2f vertHorizontal(appdata v)
32         {
33             v2f o;
34             o.pos = UnityObjectToClipPos(v.vertex);
35             float tsx = _MainTex_TexelSize.x * _BlurSpread;
36             o.uv[0] = v.uv + float2(tsx * -2, 0);
37             o.uv[1] = v.uv + float2(tsx * -1, 0);
38             o.uv[2] = v.uv;
39             o.uv[3] = v.uv + float2(tsx * 1, 0);
40             o.uv[4] = v.uv + float2(tsx * 2, 0);
41             return o;
42         }
43 
44         v2f vertVertical(appdata v)
45         {
46             v2f o;
47             o.pos = UnityObjectToClipPos(v.vertex);
48             float tsy = _MainTex_TexelSize.y * _BlurSpread;
49             o.uv[0] = v.uv + float2(0, tsy * -2);
50             o.uv[1] = v.uv + float2(0, tsy * -1);
51             o.uv[2] = v.uv;
52             o.uv[3] = v.uv + float2(0, tsy * 1);
53             o.uv[4] = v.uv + float2(0, tsy * 2);
54             return o;
55         }
56 
57         fixed4 frag(v2f i) : SV_TARGET
58         {
59             float g[3] = {0.0545, 0.2442, 0.4026};
60             fixed4 col = tex2D(_MainTex, i.uv[2]) * g[2];
61             for(int k = 0; k < 2; k++)
62             {
63                 col += tex2D(_MainTex, i.uv[k]) * g[k];
64                 col += tex2D(_MainTex, i.uv[4 - k]) * g[k];
65             }
66             return col;
67         }
68 
69         ENDCG
70 
71         Pass
72         {
73             Name "HORIZONTAL"
74             ZTest Always
75             ZWrite Off
76             Cull Off
77 
78             CGPROGRAM
79             #pragma vertex vertHorizontal
80             #pragma fragment frag
81             ENDCG
82         }
83 
84         Pass
85         {
86             Name "VERTICAL"
87             ZTest Always
88             ZWrite Off
89             Cull Off
90 
91             CGPROGRAM
92             #pragma vertex vertVertical
93             #pragma fragment frag
94             ENDCG
95         }
96     }
97 
98     Fallback Off
99 }
Custom/Gaussian Blur

 

調整參數:

DownSample,即降采樣率,越大性能越好,圖像越模糊,但過大可能會使圖像像素化。

Iteraitions, 即迭代次數,越大圖像模糊效果越好,但性能也會下降。

BlurSpread,即模糊擴散量,越大圖像越模糊,但過大會造成虛影。

 

 

效果如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM