【问题标题】:image and its name mismatch after read images from TFRecords file从 TFRecords 文件中读取图像后图像及其名称不匹配
【发布时间】:2017-09-11 09:28:59
【问题描述】:

我用 TensorFlow 写了两个方法:

  • convert_imgs_to_TFRecords,将./dataset中的所有图像转换为TFRecords文件img.tfrecords

  • read_imgs_from_TFRecords,读取img.tfrecords,获取images及其信息,包括heightweightchannelname

但图像与它们的名称不匹配。

例如,名为001.jpg 的A 图像和名为002.jpg 的B 图像被转换为​​img.tfrecords,但A 图像得到名称002.jpg,B 图像在read_imgs_from_TFRecords 之后得到001.jpg

两种方法如下:

def convert_imgs_to_TFRecords(imgs_dir='./dataset', tfrecords_name='img.tfrecords'):

    img_filenames_list = os.listdir(imgs_dir)

    writer = tf.python_io.TFRecordWriter(tfrecords_name)

    for item in img_filenames_list:
        file_extension = item.split('.')[-1]
        if(file_extension == 'jpg'):
            img_filename = os.path.join('./dataset', item)
            print("writing {0}".format(item))
            img = cv2.imread(img_filename)# uint8 dtype
            rows = img.shape[0]
            cols = img.shape[1]
            channels = img.shape[2]
            example = tf.train.Example(features = tf.train.Features(feature={
                'name': _bytes_feature(item.encode('utf-8')), # str to bytes
                'height': _int64_feature(rows),
                'width': _int64_feature(cols),
                'channel': _int64_feature(channels),
                'img': _bytes_feature(img.tostring())
                }))
            writer.write(example.SerializeToString())

    writer.close()

def read_imgs_from_TFRecords(tfrecords_file='./img.tfrecords'):
    filename_queue = tf.train.string_input_producer(string_tensor=[tfrecords_file], 
                                                num_epochs=None, 
                                                shuffle=False, 
                                                seed=None, 
                                                capacity=32, 
                                                shared_name=None, 
                                                name=None, 
                                                cancel_op=None)
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example, features={
        'name': tf.FixedLenFeature([], tf.string),
        'height': tf.FixedLenFeature([], tf.int64),
        'width': tf.FixedLenFeature([], tf.int64),
        'channel': tf.FixedLenFeature([], tf.int64),
        'img': tf.FixedLenFeature([], tf.string)
            })    
    image = tf.decode_raw(features['img'], tf.uint8)
    # normalize
    # normalize_op = tf.cast(image, tf.float32) * (1.0/255) - 0.5

    height = features['height']
    width = features['width']
    channel = features['channel']
    name = features['name']
    print("ready to run session")
    init_op = tf.group(tf.local_variables_initializer(), 
                   tf.global_variables_initializer())
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(22):
            img = image.eval()
            h, w, c = [height.eval(), width.eval(), channel.eval()]
            title = name.eval()
            title = title.decode()#bytes to str
            img = img.reshape([h, w, c])
            # pil_image = Image.fromarray(img)
            # pil_image.show()
            print('showing ' + title)
            cv2.imwrite(title, img)
        coord.request_stop()
        coord.join(threads)

【问题讨论】:

  • 您的imghwctitle似乎都指的是不同的样本。我无法确定这一点,因为我无法运行您的代码,但我相当确定对 sess.run() 的一次调用(这是 eval() 在内部所做的)从输入中读取一项并返回该值该特定运行的张量。试试img, h, w, c, title = sess.run([ image, height, width, channel, name ]) 看看是否还有问题。
  • 您应该将单个示例的所有部分分组到单个 sess.run 中,例如 sess.run([height, width, image])

标签: python image tensorflow


【解决方案1】:

正如 Gphilo 和 Jie.Zhou 在评论中所说,我们应该将单个示例的所有部分组合到一个 sess.run 中。 所以,我更正

img = image.eval()
h, w, c = [height.eval(), width.eval(), channel.eval()]
title = name.eval()

img, h, w, c, title = sess.run([image, height, width, channel, name])

这两种方法只是尝试tf.TFRecord,一种最好在你的项目中使用Datasets API

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 2015-11-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2012-09-05
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多