简体   繁体   中英

Add Gaussian Noise to an image without numpy

I am trying to add gaussian noise to an image using Python. I am using this code below to define my function Add noise. So far, it works fine but I have to do it without ready commands from numpy. I want to only use cv2. The code is the one below:

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

Can I write it without using numpy and specifically np.random.normal or another ready command; Or how can I implement the np.random.normal without numpy;

Thank you in advance!

There is a standard trick (from Knuth's Art of Computer Programming) for generating Gaussian noise given a function nextDouble() that generates a uniform random number between 0 and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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