Setting values of a tensor at the indices given by tf.where()

陌路散爱 提交于 2021-02-10 17:57:24

问题


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:


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.]]


来源:https://stackoverflow.com/questions/51382175/setting-values-of-a-tensor-at-the-indices-given-by-tf-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!