relot
relot

Reputation: 701

Insert Tensor into bigger tensor in Tensorflow

I am using Tensorflow 1.15 I have a Tensor that contains an image with shape (BatchsizeWidthHeight*3)

I have a Patch with size Batchsize*50*50*3 I want to specify a location in the original image in which the patch gets inserted. But to make it more simple let's say I have a 1D Array with 10 elements and want to replace a single value at a given index The beginning would looks like this.

sess = tf.Session()
array = tf.placeholder("float32",[10]) # for easier explanation a 1d array 
variable = tf.get_variable(name=var,shape=[1],intializer=init) # This variable should replace the value
index = tf.placeholder("int32",[1]) # the value on this index should be replaced
# Here The value of the image tensor at place index should be replaced with the variable

in_dict = {image: np.zeros([10],dtype="float")
           index: 4}
sess.run(...,feed_dict=in_dict)

tf.where needs two tensors that have the same size but my variable and array have different sizes.

Upvotes: 0

Views: 644

Answers (1)

moodoki
moodoki

Reputation: 109

You could do this with a padded smaller tensor.

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, [10])
x_sub = tf.placeholder(tf.float32, [2])
idx = tf.placeholder(tf.int32, ())


def assign_slice(x, y, idx):
  '''return x with x[r:r+len(y)] assigned values from y'''
  x_l = x.shape[0]
  y_l = y.shape[0]
  #pad the smaller tensor accordingly with shapes and index using NaNs
  y_padded = tf.pad(y, [[idx, x_l-y_l-idx]], constant_values=float('NaN'))
  #if value in padded tensor is NaN, use x, else use y
  return tf.where(tf.is_nan(y_padded), x, y_padded)


y = assign_slice(x, x_sub, idx)

with tf.Session() as sess:
  print(sess.run(y, feed_dict={x:np.ones([10]), x_sub:np.zeros([2]), idx:2}))

This should print [1. 1. 0. 0. 1. 1. 1. 1. 1. 1.].

Another approach might be to feed same sized tensors with a mask, i.e.: out = x * mask + y * (1-mask)

Upvotes: 1

Related Questions