Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tensorflow tf.image.resize_images raise ValueError #4

Closed
stevechoris opened this issue Jul 23, 2016 · 2 comments
Closed

tensorflow tf.image.resize_images raise ValueError #4

stevechoris opened this issue Jul 23, 2016 · 2 comments

Comments

@stevechoris
Copy link

I used ImageFlow to create a tensorflow tfrecords file on my own images. My images are of the same size 223x334x3. I tried the cifar example on my own images. Because the cifar convnet need image of 32x32 size so i have to resize it.

My function to read tfrecords file , decode images and resize them as follow:

def read_my_file_format(filename_queue):
reader = tf.TFRecordReader()
key, serialized_example = reader.read(filename_queue)

features = tf.parse_single_example(
serialized_example,
features={
  'image_raw': tf.FixedLenFeature([], tf.string),
  'label': tf.FixedLenFeature([], tf.int64)
})

image = tf.decode_raw(features['image_raw'], tf.uint8)
image = tf.cast(image, tf.float32)
label = tf.cast(features['label'], tf.int32)

image = tf.reshape(image, [223446])
image.set_shape(223446)
print 'get shape: ',image.get_shape()

print 'image: ',image.get_shape()
print 'label: ',label.get_shape()

image = tf.image.resize_images(image, 32,32)
image = tf.reshape(image,[32,32,3])

#processed_example = some_processing(example)

processed_example = image
return processed_example, label

But when i call it, i got the following error:

Last executed 2016-07-22 23:58:40 in 71ms
get shape:  (223446,)
image:  (223446,)
label:  ()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-44cda3e31e6a> in <module>()
----> 1 tf.app.run()

/home/guanwanxian/anaconda2/envs/theano/lib/python2.7/site-packages/tensorflow/python/platform/app.pyc in run(main)
     28   f._parse_flags()
     29   main = main or sys.modules['__main__'].main
---> 30   sys.exit(main(sys.argv))

<ipython-input-7-2788f377abf1> in main(argv)
      1 def main(argv=None):
----> 2     train()

<ipython-input-31-4c9a489f07f7> in train(re_train, continue_from_pre)
      8         # Get images and labels for CIFAR-10.
      9         # images, labels = my_input.inputs()
---> 10         images, labels = input_pipeline(['../data/trainV2.tfrecords'],batch_size=128)
     11         val_images, val_labels = input_pipeline(['../data/testV2.tfrecords'],batch_size=128)
     12 

<ipython-input-3-ce4e93d1c196> in input_pipeline(filenames, batch_size, num_epochs)
      2     filename_queue = tf.train.string_input_producer(
      3                      filenames, num_epochs=num_epochs, shuffle=True)
----> 4     example, label = read_my_file_format(filename_queue)
      5     # min_after_dequeue defines how big a buffer we will randomly sample
      6     #   from -- bigger means better shuffling but slower start up and more

<ipython-input-30-8be4eeea8a06> in read_my_file_format(filename_queue)
     21     print 'label: ',label.get_shape()
     22 
---> 23     image = tf.image.resize_images(image, 32,32)
     24     image = tf.reshape(image,[32,32,3])
     25 

/home/guanwanxian/anaconda2/envs/theano/lib/python2.7/site-packages/tensorflow/python/ops/image_ops.pyc in resize_images(images, new_height, new_width, method, align_corners)
    629     images = array_ops.expand_dims(images, 0)
    630 
--> 631   _, height, width, depth = _ImageDimensions(images)
    632 
    633   # Handle tensor-valued sizes as well as Python integers.

ValueError: need more than 1 value to unpack

and My code to create tfrecords from images with littlt modification as follow:

def read_image_and_labels_from(path):
'''read images and return image and label array
'''

directories = glob.glob(os.path.join(path,'*'))
class_names = [os.path.basename(directory) for directory in directories]
class_names.sort()
num_classes = len(class_names)

file_paths = glob.glob(os.path.join(path,'*/*'))
file_paths = sorted(file_paths,
       key=lambda filename:os.path.basename(filename).split('.')[0])

images = []
labels = []
shapes = []
shape_set = set()
for filename in file_paths:
    im = Image.open(filename)
    arr = np.asarray(im, np.uint8)
    images.append(arr)

    im_shape = arr.shape
    shapes.append(im_shape) # tuple of 3
    if im_shape not in shape_set:
        shape_set.add(im_shape)
    # image_name = os.path.basename(filename).split('.')[0]

    class_name = os.path.basename(os.path.dirname(filename))
    label_num = class_names.index(class_name)
    labels.append(np.asarray(label_num, np.uint32))

images = np.array(images)
labels = np.array(labels)
shapes = np.array(shapes)
print images.shape, labels.shape, shapes.shape
print 'shape set: ', shape_set
return images, labels, shapes


def convert_images_to_tfrecords_file(images, labels, shapes, directorys, name):
num_examples = labels.shape[0]
print('labels shape is: ', labels.shape[0])
if num_examples != images.shape[0] != labels.shape[0]:
    raise ValueError("Images size %d does not match label size %d." %
                                     (images.shape[0], num_examples))

filename = os.path.join(directorys, name + '.tfrecords')
print('Writing', filename)
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
    image_raw = images[index].tostring()
    image_shape = shapes[index]
    example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(image_shape[0]),
            'width': _int64_feature(image_shape[1]),
            'depth': _int64_feature(image_shape[2]),
            'label': _int64_feature(int(labels[index])),
            'image_raw': _bytes_feature(image_raw)}))
    writer.write(example.SerializeToString())

So what's wrong with my code?

@stevechoris
Copy link
Author

I have solved it on stackoverflow. It is because you should first reshape it to a 3d tensor instead of 1d.

@HamedMP
Copy link
Owner

HamedMP commented Aug 1, 2016

@stevechoris Thank you very much for your contirbutions. Really appreciate it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants