Is it possible to get the element from a tensor at a given index in order to obtain a scalar? For example given an image I can retrieve its shape with shape = tf.shape(image)
, but how can I retrieve its height, width and depth?
The only way I found is the following:
height = tf.reshape(tf.slice(shape, [0], [1]), [])
width = tf.reshape(tf.slice(shape, [1], [1]), [])
depth = tf.reshape(tf.slice(shape, [2], [1]), [])
Is there any other way?
The slice syntax (ie using the []
operator) is based on NumPy slicing, and gives a slightly more concise way of getting the height, width and depth from a shape
tensor:
shape = tf.shape(image)
height = shape[0] # returns a scalar
width = shape[1] # returns a scalar
depth = shape[2] # returns a scalar
Nessuno's answer will also work well if the tensor has a statically determined shape. However, variable-sized images (eg the result of tf.image.decode_jpeg()
) will typically give None
for the height and width dimensions when you use get_shape()
, because these may vary from one image to the next.
Use tf.Variable.get_shape(variable)
.
image = tf.Variable([ [ [1,2,3],[3,4,4],[1,1,1] ], [[1,2,3],[3,4,4],[1,1,1] ]])
shape = image.get_shape()
print( [shape[i].value for i in range(len(shape))] )
Outputs:
[2, 3, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.