繁体   English   中英

在没有 numpy 的图像中添加高斯噪声

[英]Add Gaussian Noise to an image without numpy

我正在尝试使用 Python 向图像添加高斯噪声。 我正在使用下面的代码来定义我的 function 添加噪声。 到目前为止,它工作正常,但我必须在没有来自 numpy 的现成命令的情况下这样做。 我只想使用 cv2。 代码如下:

def add_noise(img):
  
    mean = 0
    var = 10
    sigma = var ** 1.5
    gaussian = np.random.normal(mean, sigma, (512,512)) 
    #np.zeros((224, 224), np.float32

    noisy_image = np.zeros(img.shape, np.float32)

    if len(img.shape) == 2:
        noisy_image = img + gaussian
    else:
        noisy_image[:, :, 0] = img[:, :, 0] + gaussian
        noisy_image[:, :, 1] = img[:, :, 1] + gaussian
        noisy_image[:, :, 2] = img[:, :, 2] + gaussian

    cv2.normalize(noisy_image, noisy_image, 0, 255, cv2.NORM_MINMAX, dtype=-1)
    noisy_image = noisy_image.astype(np.uint8)
    return noisy_image

我可以在不使用 numpy 尤其是 np.random.normal 或其他就绪命令的情况下编写它吗? 或者如何在没有 numpy 的情况下实现 np.random.normal;

先感谢您!

给定 function nextDouble()生成高斯噪声的标准技巧(来自 Knuth 的计算机编程艺术),它生成 0 和 1 之间的统一随机数。

while True:
   # Calculate a random point inside a unit sphere
   # nextDouble() is whatever random number generate you want that generates
   # a uniformly distributed random number between 0 and 1
   v1 = 2 * nextDouble() - 1 # between -1.0 and 1.0
   v2 = 2 * nextDouble() - 1 # between -1.0 and 1.0
   s = v1 * v1 + v2 * v2
   if (s < 1):  # This succeeds π/4 of the time, so > 75%
      break
norm = math.sqrt(-2 * math.log(s) / s)

# value1 and value2 are two non-correlated gaussian values with average 0
# and standard deviation 1
value1 = v1 * norm
value2 = v2 * norm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM