利用正态分布(高斯分布)绘制噪点图

最近开发项目中,需要自己绘制一张离散的噪点图。研究了好久,终于实现了。

其中我们使用了正态分布。正态分布(英语:normal distribution)又名高斯分布(英语:Gaussian distribution),是一个非常常见的连续概率分布。

这里就不过多介绍了,对正态分布不了解的,可以自己百度一下https://baike.baidu.com/item/%E6%AD%A3%E6%80%81%E5%88%86%E5%B8%83/829892?fr=aladdin

正态分布公式如下:
首先,我们要做的就是,把上面的公式转换成可执行代码,如下:

 1     /// <summary>
 2     /// 高斯分布概率模型
 3     /// </summary>
 4     /// <param name="_x">随机变量</param>
 5     /// <param name="_μ">位置参数</param>
 6     /// <param name="_σ">尺度参数</param>
 7     /// <returns></returns>
 8     private static float NormalDistribution(float _x, float _μ, float _σ)
 9     {
10         float _inverseSqrt2PI = 1 / Mathf.Sqrt(2 * Mathf.PI);
11         float _powOfE = -(Mathf.Pow((_x - _μ), 2) / (2 * _σ * _σ));
12         float _result = (_inverseSqrt2PI / _σ) * Mathf.Exp(_powOfE);
13         return _result;
14     }

假设我们要绘制一张大小为1024*1024,从中心向四周逐渐稀疏,并且颜色越来越淡的噪点图,代码如下:

 1     /// <summary>
 2     /// 通过高斯分布公式绘制一张离散效果图
 3     /// </summary>
 4     /// <param name="_centerPoint">中心点坐标</param>
 5     /// <param name="_consi">图颜色的阿尔法值</param>
 6     /// <returns></returns>
 7     public Texture2D CreateTeture2D(Vector2 _centerPoint, float _consi)
 8     {
 9         Texture2D _newTex = new Texture2D(1024, 1024, TextureFormat.ARGB32, true);
10         Color[] _colorBase = new Color[1024 * 1024];
11         int _hwidth = (int)(1024 * _centerPoint.x);
12         int _hheight = (int)(1024 * _centerPoint.y);
13 
14         float _per;
15         int _index;
16         for (int i = 0; i < 1024; i++)
17         {
18             for (int j = 0; j < 1024; j++)
19             {
20                 _per = (Mathf.Sqrt((i - _hwidth) * (i - _hwidth) + (j - _hheight) * (j - _hheight))) / 512;
21                 float _tr = NormalDistribution(_per, 0, 1); //float _tr = NormalDistribution(0, 0, 1)=0.3989423f;也就是说中心点的概率为0.3989423f,即最大概率
22                 bool _drawing = Random.Range(0, 0.3989423f) < _tr ? true : false;
23                 if (_drawing)
24                 {
25                     _index = i * 1024 + j;
26                     _colorBase[_index] = new Color(1, 0, 0, _tr * _consi);
27                 }
28                 else
29                 {
30                     _colorBase[i * 1024 + j] = new Color(0, 0, 0, 0);
31                 }
32             }
33         }
34         _newTex.SetPixels(_colorBase);
35         _newTex.Apply();
36         _colorBase = null;
37         System.GC.Collect();
38         return _newTex;
39     }

当中心点坐标为(0.5,,05),颜色阿尔法值为1时,效果如下:

当中心点坐标为(0.2,0.3)时,效果如下:

我们可以将 _colorBase[_index] = new Color(1, 0, 0, _tr * _consi );这句代码更改为:_colorBase[_index] = new Color(1, 0, 0, _tr * _consi * (1 - _per));这样绘制的图,颜色从中心点渐变到边缘时,会完全透明,效果如下:

原文地址:https://www.cnblogs.com/xiaoyulong/p/11334977.html