Hi,
You can definitely index into a tensor like this:
import tensorflow as tf masking = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32) y_min = 0 y_max = 2 x_min = 1 x_max = 3 masking[y_min:y_max, x_min:x_max]
Output:
<tf.Tensor: shape=(2, 2), dtype=float32, numpy= array([[2., 3.], [6., 7.]], dtype=float32)>
What you cannot do is indeed tensor assignment:
img = tf.constant([[9, 10, 11, 12], [13, 14, 15, 16]], dtype=tf.float32) masking[y_min:y_max, x_min:x_max] = img[y_min:y_max, x_min:x_max]
Output:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-27-482e1a48b3c5> in <cell line: 3>() 1 img = tf.constant([[9, 10, 11, 12], [13, 14, 15, 16]], dtype=tf.float32) 2 ----> 3 masking[y_min:y_max, x_min:x_max] = img[y_min:y_max, x_min:x_max] TypeError: 'tensorflow.python.framework.ops.EagerTensor' object does not support item assignment
This is because in TensorFlow tensors are immutable.
What you can do instead is wrap your tensors in Variables:
masking = tf.Variable(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=tf.float32)) img = tf.Variable(tf.constant([[9, 10, 11, 12], [13, 14, 15, 16]], dtype=tf.float32)) masking[y_min:y_max, x_min:x_max].assign(img[y_min:y_max, x_min:x_max])
Output:
<tf.Variable 'UnreadVariable' shape=(2, 4) dtype=float32, numpy= array([[ 1., 10., 11., 4.], [ 5., 14., 15., 8.]], dtype=float32)>
These allow the in place updates on sliced tensors.