You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python的imageio模块为图像添加高斯噪声

高斯噪声添加函数实现

假设输入的x是通过imageio读取的图像数组(如imageio.imread()返回的numpy数组),var为高斯噪声的方差,以下是完整的函数实现:

import numpy as np
import imageio

def gaussian_noise(x, var):
    # 生成均值为0、方差为var的高斯噪声,形状与输入图像一致
    noise = np.random.normal(loc=0.0, scale=np.sqrt(var), size=x.shape)
    # 将噪声与原图像叠加
    noisy_x = x + noise
    # 根据原图像数据类型处理数值范围,避免溢出或异常
    if x.dtype == np.uint8:
        # 8位无符号整数图像固定范围0-255,裁剪后转回原类型
        noisy_x = np.clip(noisy_x, 0, 255).astype(np.uint8)
    elif x.dtype in [np.float32, np.float64]:
        # 浮点型图像根据原范围裁剪:若原图像是0-1则限制0-1,否则限制0-255
        noisy_x = np.clip(noisy_x, 0.0, 1.0) if np.max(x) <= 1 else np.clip(noisy_x, 0.0, 255.0)
    return noisy_x

关键说明

  • 用np.random.normal生成高斯噪声时,scale参数需传入方差的平方根(标准差),与输入的var对应。
  • 针对不同图像数据类型做范围裁剪:uint8类型是最常见的图像存储格式,必须限制在0-255区间;浮点型图像则适配0-1或0-255两种常见范围。

使用示例

# 读取原始图像
img = imageio.imread('test_img.png')
# 添加方差为15的高斯噪声
noisy_img = gaussian_noise(img, var=15)
# 保存加噪后的图像
imageio.imwrite('noisy_test_img.png', noisy_img)

内容的提问来源于stack exchange,提问作者jakob maxi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:50:23