I tried:
test_image = tf.convert_to_tensor(img, dtype=tf.float32)
Then following error appears:
ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'
You can cast generally using:
tf.cast(my_tensor, tf.float32)
Replace tf.float32 with your desired type.
Edit: It seems at the moment at least, that tf.cast won't cast to an unsigned dtype (e.g. tf.uint8). To work around this, you can cast to the signed equivalent and used tf.bitcast to get all the way. e.g.
tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)
Oops, I find the function in the API...
tf.to_float(x, name='ToFloat')
You can use either tf.cast(x, tf.float32) or tf.to_float(x), both of which cast to float32.
Example:
sess = tf.Session()
# Create an integer tensor.
tensor = tf.convert_to_tensor(np.array([0, 1, 2, 3, 4]), dtype=tf.int64)
sess.run(tensor)
# array([0, 1, 2, 3, 4])
# Use tf.cast()
tensor_float = tf.cast(tensor, tf.float32)
sess.run(tensor_float)
# array([ 0., 1., 2., 3., 4.], dtype=float32)
# Use tf.to_float() to cast to float32
tensor_float = tf.to_float(tensor)
sess.run(tensor_float)
# array([ 0., 1., 2., 3., 4.], dtype=float32)
imagetype cast you can use tf.image.convert_image_dtype() which convert image range [0 255] to [0 1]:
img_uint8 = tf.constant([1,2,3], dtype=tf.uint8)
img_float = tf.image.convert_image_dtype(img_uint8, dtype=tf.float32)
with tf.Session() as sess:
_img= sess.run([img_float])
print(_img, _img.dtype)
output:
[0.00392157 0.00784314 0.01176471] float32
if you only want to cast type and keep value range use tf.cast or tf.to_float as @stackoverflowuser2010 and @Mark McDonald answered
来源:https://stackoverflow.com/questions/35596629/how-to-convert-tf-int64-to-tf-float32