TFRecords: изображение и метка не совпадают при чтении - PullRequest
0 голосов
/ 16 сентября 2018

Я попытался преобразовать данные изображения с его метками в файл TFRecords.Вот код для преобразования.

def read_image(path):
    img = cv2.imread(path)
    img = cv2.resize(img, (101,101), interpolation=cv2.INTER_CUBIC) # keep the original size
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img.astype(np.uint8)
    return img

def _float_feature(value):
    return tf.train.Feature(float_list = tf.train.FloatList(value = [value]))

def _bytes_feature(value):
    return tf.train.Feature(bytes_list = tf.train.BytesList(value = [value]))

tffile_name = "11.tfrecords"

writer = tf.python_io.TFRecordWriter(tffile_name)

for i in range(len(series)):
    if not i % 100:
        print("Data Samples: {}/{}".format(i, len(series)))

    img = read_image(addrs[i])
    label = series[i]

    Feature = {"ThermalConductiviy": _float_feature(label), 
               "image": _bytes_feature(tf.compat.as_bytes(img.tostring()))}

    example = tf.train.Example(features = tf.train.Features(feature = Feature))
    writer.write(example.SerializeToString())

writer.close()

В котором я уверен, что элементы в addrs и series совпадают по порядку.Проблема в том, что когда я читаю преобразованный файл, чтобы проверить, совпадают ли изображения и метки, он фактически выводит несопоставленные пары изображений и меток.

Вот код, который я использовал для чтения и вывода изображений, а также меток из файла TFrecords.

def read_and_decode(filename_queue):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue) # return key and value: filename and the image in this case.
    features = {"ThermalConductiviy": tf.FixedLenFeature([],tf.float32),"image": tf.FixedLenFeature([], tf.string)
               } # the defined features in conversion process.
    parse_example = tf.parse_single_example(serialized_example, features = features) # parsing the examples
    image = tf.decode_raw(parse_example['image'], tf.uint8)
    Ther_cond = parse_example['ThermalConductiviy']
    image = tf.reshape(image, [101,101,3])
    img, ther = tf.train.shuffle_batch([image, Ther_cond], batch_size=100, capacity=30,num_threads=2,min_after_dequeue=10)
    return img, ther

filename = "11.tfrecords"
filename_queue = tf.train.string_input_producer([filename], num_epochs=num_epochs) # generate filename queue.
# initialize variables
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) 
with tf.Session() as sess:
    sess.run(init_op)
    image, Ther_cond = read_and_decode(filename_queue)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    print(Ther_cond[0].eval()) # here this label should match the image
    plt.figure()               # but it seems like the images and 
    plt.imshow(image[0].eval())# labels are shuffled separately
    plt.show()

Я не смог выяснить, что здесь пошло не так.Я проверил код чтения в другом файле TFrecords, и он, кажется, работает хорошо.Так что может быть что-то не так произошло во время конвертации.Я довольно новичок в TFrecords и его механизме.Было бы здорово, если бы вы, ребята, могли бы мне помочь.Спасибо за ваше время и терпение.

...