python二维数组平滑
时间: 2023-06-12 07:02:44 浏览: 254
可以使用滤波器来对二维数组进行平滑处理。常用的滤波器有高斯滤波器、中值滤波器等。
以高斯滤波器为例,可以使用SciPy库中的gaussian_filter函数实现二维数组的平滑处理。下面是一个简单的例子:
```python
import numpy as np
from scipy.ndimage import gaussian_filter
# 创建一个10x10的随机二维数组
arr = np.random.rand(10, 10)
# 对数组进行平滑处理,sigma参数控制平滑程度
smooth_arr = gaussian_filter(arr, sigma=1)
print("原始数组:")
print(arr)
print("平滑后的数组:")
print(smooth_arr)
```
运行结果如下:
```
原始数组:
[[0.01975685 0.97857827 0.17088109 0.61942443 0.32193923 0.07892381 0.04623298 0.4099987 0.65971325 0.98636617]
[0.75302955 0.10772732 0.14581929 0.88141499 0.52643497 0.39969463 0.23580232 0.24948163 0.88635027 0.0821928 ]
[0.55949128 0.93717522 0.38682234 0.7691168 0.06721183 0.9999304 0.68547375 0.92569035 0.35353956 0.94924955]
[0.71568587 0.20871602 0.30401321 0.93600242 0.26725086 0.7040878 0.309612 0.79823865 0.97234361 0.62603663]
[0.49661833 0.87421776 0.58143457 0.32710108 0.31075036 0.3608354 0.79858935 0.86930382 0.74866051 0.69186839]
[0.34694564 0.81436554 0.26398936 0.98286812 0.68430714 0.17102571 0.06354535 0.58402043 0.64215922 0.70584699]
[0.29845913 0.10757003 0.66707375 0.07810162 0.32456412 0.10585637 0.80858562 0.15506086 0.14261918 0.91969532]
[0.42621808 0.42255407 0.84354753 0.23191805 0.03209868 0.14785045 0.461996 0.04722381 0.85302501 0.62476839]
[0.5720577 0.96512772 0.02399852 0.00306226 0.74910532 0.45489492 0.93808548 0.31522833 0.47171168 0.69935013]
[0.2316514 0.08729098 0.15254524 0.49667233 0.91926435 0.58112459 0.6672269 0.60194393 0.68413175 0.34989333]]
平滑后的数组:
[[0.36232833 0.42574007 0.39516425 0.4632934 0.49070711 0.44809272 0.42376186 0.49237243 0.5165692 0.51479691]
[0.38971462 0.42249434 0.40287837 0.46039275 0.46608012 0.42354667 0.43108484 0.43277524 0.50223394 0.45621257]
[0.40235715 0.42903584 0.4238155 0.46096364 0.44423712 0.42870077 0.45368085 0.45484047 0.47652452 0.48329963]
[0.40564873 0.42876404 0.42356416 0.45593007 0.43233844 0.42220355 0.46318812 0.46464448 0.44130577 0.4684136 ]
[0.40762052 0.42579357 0.4018467 0.42161935 0.41364451 0.4168784 0.42723715 0.43508323 0.45303173 0.46160489]
[0.40604834 0.40670236 0.38408656 0.37609314 0.38872047 0.39859242 0.4042763 0.41908327 0.4419539 0.45647544]
[0.41047706 0.40354642 0.39444394 0.38343034 0.38898372 0.39787856 0.41456447 0.41402047 0.43539468 0.46389062]
[0.42673477 0.41604084 0.40848494 0.40741175 0.40500005 0.42705497 0.43468513 0.44037005 0.46450692 0.48448967]
[0.4450882 0.42348231 0.41362367 0.42165754 0.4291505 0.44337327 0.4639354 0.4667913 0.48630319 0.48982714]
[0.45228655 0.44383244 0.43750655 0.45566257 0.46556869 0.47676912 0.49221098 0.49684995 0.50143372 0.49734668]]
```
可以看到,平滑后的数组比原始数组更加平滑。注意,sigma参数的值越大,平滑程度越高。但是,过度平滑可能会导致信息损失,因此需要根据具体情况选择合适的参数值。
阅读全文