在 tf.where() 给出的索引处设置张量的值 [英] Setting values of a tensor at the indices given by tf.where()

查看:37
本文介绍了在 tf.where() 给出的索引处设置张量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向保存图像灰度像素值的张量添加噪声.我想将像素值的随机数设置为 255.

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.

我在想一些事情:

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

然后我试图弄清楚如何为 mask 的每个索引将 input 的像素值设置为 255.

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

推荐答案

tf.where() 也可以用于此,在掩码元素为 True 时分配噪声值code>,否则为原始input值:

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

这篇关于在 tf.where() 给出的索引处设置张量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆