0

I would like to load multiple images from a directory and then stack them in 4D tensor. I wrote the following code:

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)

The number of images is 134. Every image has a height of 65 and a width of 147. They have one channel. I run my code and had the following Error:

FailedPreconditionError: Attempting to use uninitialized value Variable_344
     [[Node: Variable_344/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_344"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_344)]]

I understand that the compiler is trying to read the variable before initializing the variable. I tried to initialize it with different ways but always the same error. Could you help to correct the error?

Abdelsalam Shahlol
  • 1,621
  • 1
  • 20
  • 31

2 Answers2

0

I have come across a similar issue here. I think you should explicitly initialise all the variables in the beginning.

You can try the following

init_op = tf.initialize_all_variables()

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

Please refer to the following answer

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

user338558
  • 13
  • 3
0

You are performing lot of redundant computations here, following lines will solve the issue.

# 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)
Ishant Mrinal
  • 4,898
  • 3
  • 29
  • 47