将多个图像加载到4D张量

时间:2017-08-06 16:16:12

标签: tensorflow

我想从目录中加载多个图像,然后将它们堆叠在 4D tensor 中。我写了以下代码:

Python 3.8.0a0 (heads/master:077059e0f0, Aug 10 2018, 21:36:32)

图像数量为134.每张图像的高度为65,宽度为147.它们有一个通道。 我运行我的代码并出现以下错误:

import tensorflow as tf
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import os
img=tf.Variable(tf.zeros([134,65,147,1]),dtype=tf.float32)
sess=tf.Session()
model=tf.global_variables_initializer()
dir_path = os.path.dirname('C:\\Users\\E6410\\Documents\\Masterarbeit\\specconvneu\\')
for i in range(134):
    filename = dir_path + "\\Spec_Test("+str(i+1)+").png"
    image = mpimg.imread(filename)
    image = tf.Variable(image,dtype=tf.float32)
    sess.run(model)
    image=tf.reshape(image,[65,147,1])
    img[i+1,:,:,:].assign(image)
    sess.run(img)
    sess.run(image)

我知道编译器在初始化变量之前尝试读取变量。我尝试用不同的方式初始化它,但始终是相同的错误。你能帮忙纠正错误吗?

2 个答案:

答案 0 :(得分:0)

我在这里遇到过类似的问题。我认为你应该在开头明确初始化所有变量。

您可以尝试以下

init_op = tf.initialize_all_variables()

sess = tf.Session() sess.run(init_op)

请参阅以下答案

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

答案 1 :(得分:0)

您正在执行大量冗余计算,以下行将解决此问题。

# I don't understand why are you using variable here?
image = tf.Variable(image,dtype=tf.float32)
# just convert the array to tensor
image = tf.convert_to_tensor(image,dtype=tf.float32)

#Also move the initialization line before for loop
sess.run(model)
for i in range(134)