当使用Tensorflow与Python绑定时,如何将一个张量转换为numpy数组?


当前回答

你需要:

将图像张量以某种格式(jpeg, png)编码为二进制张量 在一个会话中计算(运行)二进制张量 将二进制文件转换为流文件 馈送PIL图像 (可选)使用matplotlib显示图像

代码:

import tensorflow as tf
import matplotlib.pyplot as plt
import PIL

...

image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)

这对我很管用。你可以在ippython笔记本上试试。别忘了加上下面这行:

%matplotlib inline

其他回答

TensorFlow 1.倍

文件夹特遣部队。1、只需使用以下命令:

a = tf.constant([[1, 2], [3, 4]])                 
b = tf.add(a, 1)
out = tf.multiply(a, b)
out.eval(session=tf.Session())

输出将是:

# array([[ 2,  6],
#       [12, 20]], dtype=int32)

也许你可以试试这个方法:

import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)

要将张量转换回numpy数组,只需在转换后的张量上运行.eval()。

我已经面对并解决了张量->ndarray转换在张量表示(对抗)图像的特定情况下,通过cleverhans库/教程获得。

我认为我的问题/答案(在这里)也可能是一个有用的例子,对其他情况。

我是TensorFlow的新手,我的结论是经验的:

看起来为了成功,tensor.eval()方法可能还需要输入占位符的值。 Tensor可以像一个函数一样工作,需要它的输入值(提供给feed_dict)来返回一个输出值,例如:

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

请注意,在我的例子中,占位符的名称是x,但我认为您应该为输入占位符找出正确的名称。 X_input是一个包含输入数据的标量值或数组。

在我的案例中,提供sess也是强制性的。

我的示例还包括matplotlib图像可视化部分,但这是OT。

你可以用以下方法将tensorflow中的张量转换为numpy数组。

第一: 使用np.array (your_tensor)

第二: 使用your_tensor.numpy