我试过:
test_image = tf.convert_to_tensor(img, dtype=tf.float32)
接着出现以下错误:
ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'
我试过:
test_image = tf.convert_to_tensor(img, dtype=tf.float32)
接着出现以下错误:
ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int64: 'Tensor("test/ArgMax:0", shape=TensorShape([Dimension(None)]), dtype=int64)'
你可以通常使用以下方法进行投掷:
tf.cast(my_tensor, tf.float32)
使用您所需的类型替换tf.float32。
编辑:目前看来,tf.cast
无法转换为无符号数据类型(例如tf.uint8
)。要解决此问题,您可以先将其转换为相应的有符号数据类型,然后使用tf.bitcast
完成整个过程。例如:
tf.bitcast(tf.cast(my_tensor, tf.int8), tf.uint8)
糟糕,我在API中找到了该函数...
tf.to_float(x, name='ToFloat')
tf.to_float()
现已弃用,应使用tf.cast()
代替。 - Richardtf.cast(x, tf.float32)
或者 tf.to_float(x)
,两者均将类型转换为float32。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)
tf.uint8
的图像转换为 tf.float32
并使用 matplotlib
显示时,tf.float32
发生了变化。如何显示原始图像? - Tavakoliimage
类型转换可以使用tf.image.convert_image_dtype()
函数,将图像范围从[0 255]
转换为[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)
输出:
[0.00392157 0.00784314 0.01176471] float32
如果您只想进行类型转换并保持值范围,请使用tf.cast
或tf.to_float
,如@stackoverflowuser2010和@Mark McDonald所回答的。
print(dataset.dtypes)
float32
(例如):# Typecast
dataset = dataset.astype('float32')
#print them to verify
print(dataset.dtypes)