Tensorflow提取中间层特征npy文件并加工成tfrecord文件

提取不提取特征不重要,我的方法的出发点是将npy文件加工成tfrecord文件


加工成tfrecord文件


def _add_to_tfrecord(tfrecord_writer, split_name):
"""Loads images and writes files to a TFRecord.
Args:
  image_dir: The image directory where the raw images are stored.
  list_filename: The list file of images.
  tfrecord_writer: The TFRecord writer to use for writing.
"""
a = np.load("ttt/test_temp.npy")
b = np.load("ttt/trainlabel.npy")
print(b)

with tf.Graph().as_default():
    j = 0
    with tf.Session('') as sess:
        for line in range(a.shape[0]):
            sys.stdout.write('\r>> Converting %s image %d/%d' % (split_name, j + 1, a.shape[0]))
            sys.stdout.flush()
            j += 1
            label = int(b[line])
            image_data=a[line]
            image_data = np.reshape(image_data, [1024]).tostring()
            # print(image_data.dtype)
            png_string = image_data
            example = image_to_tfexample(png_string,b'jpg',label)
            tfrecord_writer.write(example.SerializeToString())`
def image_to_tfexample(image_data, image_format,class_id):
  print("sssssss")
  return tf.train.Example(features=tf.train.Features(feature={
      'image/encoded': bytes_feature(image_data),
      'image/format': bytes_feature1(image_format),
      'image/class/label': int64_feature(class_id),
  }))

读取tfrecord文件


def decode_from_tfrecords(filename_queue):
    print(filename_queue)
    reader = tf.TFRecordReader()
    filename_queue = tf.train.string_input_producer([filename_queue])
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'image/encoded': tf.FixedLenFeature(
                                               (), tf.string, default_value=''),
                                           'image/class/label': tf.FixedLenFeature(
                                               [], dtype=tf.int64, default_value=-1)
                                       })
    image = tf.decode_raw(features['image/encoded'], tf.float32)
    image = tf.reshape(image, [1024])
    label = tf.cast(features['image/class/label'], tf.int64)

    if True:
        batch_size = 64
        min_after_dequeue = 10
        capacity = min_after_dequeue + 3 * batch_size
        image, label = tf.train.shuffle_batch([image, label],
                                              batch_size=batch_size,
                                              num_threads=3,
                                              capacity=capacity,
                                              min_after_dequeue=min_after_dequeue)
    return image, label

有不明白的地方可以私聊我 github

你可能感兴趣的:(随笔,图像分类,深度学习,TensorFlow)