如何可视化TFRecord?

12

我在另一个论坛上被问到了这个问题,但我想在这里发布它,以供那些在TFRecords上遇到麻烦的人参考。

如果TFRecord文件中的标签与labels.pbtxt文件中的标签不对齐,TensorFlow的目标检测API可能会产生奇怪的行为。虽然它可以运行,损失可能会下降,但网络将无法产生良好的检测结果。

此外,我经常会混淆X-Y、行列空间等概念,因此我总是喜欢仔细核对我的注释是否确实标注了图像的正确部分。

我发现最好的方法是通过解码TFRecord并使用TF工具进行绘图来实现。以下是一些代码:

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from object_detection.utils import visualization_utils as vu
from object_detection.protos import string_int_label_map_pb2 as pb
from object_detection.data_decoders.tf_example_decoder import TfExampleDecoder as TfDecoder
from google.protobuf import text_format
def main(tfrecords_filename, label_map=None):
    if label_map is not None:
        label_map_proto = pb.StringIntLabelMap()
        with tf.gfile.GFile(label_map,'r') as f:
            text_format.Merge(f.read(), label_map_proto)
            class_dict = {}
            for entry in label_map_proto.item:
                class_dict[entry.id] = {'name':entry.display_name}
    sess = tf.Session()
    decoder = TfDecoder(label_map_proto_file=label_map, use_display_name=False)
    sess.run(tf.tables_initializer())
    for record in tf.python_io.tf_record_iterator(tfrecords_filename):
        example = decoder.decode(record)
        host_example = sess.run(example)
        scores = np.ones(host_example['groundtruth_boxes'].shape[0])
        vu.visualize_boxes_and_labels_on_image_array( 
            host_example['image'],                                               
            host_example['groundtruth_boxes'],                                                     
            host_example['groundtruth_classes'],
            scores,
            class_dict,
            max_boxes_to_draw=None,
            use_normalized_coordinates=True)
plt.imshow(host_example['image'])
plt.show()
3个回答

8

1
感谢你的代码,@Steve!我在github仓库中到处寻找检查tfrecord的方法,但是找不到。
只想指出一行导入代码似乎缺失了:
from google.protobuf import text_format 

在我添加了这个之后,它对我来说运行得很好


0
我建议尝试这个:https://www.tensorflow.org/tutorials/load_data/tfrecord#read_the_tfrecord_file
import tensorflow as tf

import numpy as np
import IPython.display as display

raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')

# Create a dictionary describing the features.
image_feature_description = {
    'height': tf.io.FixedLenFeature([], tf.int64),
    'width': tf.io.FixedLenFeature([], tf.int64),
    'depth': tf.io.FixedLenFeature([], tf.int64),
    'label': tf.io.FixedLenFeature([], tf.int64),
    'image_raw': tf.io.FixedLenFeature([], tf.string),
}

def _parse_image_function(example_proto):
  # Parse the input tf.train.Example proto using the dictionary above.
  return tf.io.parse_single_example(example_proto, image_feature_description)

parsed_image_dataset = raw_image_dataset.map(_parse_image_function)
parsed_image_dataset

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接