1
votes

I am attempting to add noise to a tensor that holds the greyscale pixel values of an image. I want to set a random number of the pixels values to 255.

I was thinking something along the lines of:

random = tf.random_normal(tf.shape(input))
mask = tf.where(tf.greater(random, 1))

and am then trying to figure out how to set the pixel values of input to 255 for every index of mask.

1

1 Answers

1
votes

tf.where() can be used for this too, assigning the noise value where mask elements are True, else the original input value:

import tensorflow as tf

input = tf.zeros((4, 4))
noise_value = 255.
random = tf.random_normal(tf.shape(input))
mask = tf.greater(random, 1.)
input_noisy = tf.where(mask, tf.ones_like(input) * noise_value, input)

with tf.Session() as sess:
    print(sess.run(input_noisy))
    # [[   0.  255.    0.    0.]
    #  [   0.    0.    0.    0.]
    #  [   0.    0.    0.  255.]
    #  [   0.  255.  255.  255.]]