Tensorflow:从 TFRecords 文件中提取图像和标签

2024-05-04

我有一个 TFRecords 文件,其中包含图像及其标签、名称、大小等。我的目标是将标签和图像提取为 numpy 数组。

我执行以下操作来加载文件:

def extract_fn(data_record):
    features = {
        # Extract features using the keys set during creation
        "image/class/label":    tf.FixedLenFeature([], tf.int64),
        "image/encoded":        tf.VarLenFeature(tf.string),
    }
    sample = tf.parse_single_example(data_record, features)
    #sample = tf.cast(sample["image/encoded"], tf.float32)
    return sample

filename = "path\train-00-of-10"
dataset = tf.data.TFRecordDataset(filename)
dataset = dataset.map(extract_fn)
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()

with tf.Session() as sess:
    while True:
        data_record = sess.run(next_element)
        print(data_record)

图像保存为字符串。我怎样才能将图像转换为float32?我试过sample = tf.cast(sample["image/encoded"], tf.float32)这是行不通的。我想data_record是一个列表,其中包含作为 numpy 数组的图像和作为np.int32数字。我怎样才能做到这一点?

现在data_record看起来像这样:

{'image/encoded': SparseTensorValue(indices=array([[0]]), values=array([b'\xff\xd8\ ... 8G\xff\xd9'], dtype=object), dense_shape=array([1])), 'image/class/label': 394}

我不知道如何处理它。我将不胜感激任何帮助

EDIT

如果我打印sample and sample['image/encoded'] in extract_fn()我得到以下信息:

print(sample) = {'image/encoded': <tensorflow.python.framework.sparse_tensor.SparseTensor object at 0x7fe41ec15978>, 'image/class/label': <tf.Tensor 'ParseSingleExample/ParseSingleExample:3' shape=() dtype=int64>}

print(sample['image/encoded'] = SparseTensor(indices=Tensor("ParseSingleExample/ParseSingleExample:0", shape=(?, 1), dtype=int64), values=Tensor("ParseSingleExample/ParseSingleExample:1", shape=(?,), dtype=string), dense_shape=Tensor("ParseSingleExample/ParseSingleExample:2", shape=(1,), dtype=int64))

看起来图像是一个稀疏张量并且tf.image.decode_image抛出错误。将图像提取为图像的正确方法是什么tf.float32 tensor?


我相信您存储编码为 JPEG 或 PNG 或其他格式的图像。所以,在阅读的时候,你必须解码它们:

def extract_fn(data_record):
    features = {
        # Extract features using the keys set during creation
        "image/class/label":    tf.FixedLenFeature([], tf.int64),
        "image/encoded":        tf.VarLenFeature(tf.string),
    }
    sample = tf.parse_single_example(data_record, features)
    image = tf.image.decode_image(sample['image/encoded'], dtype=tf.float32) 
    label = sample['image/class/label']
    return image, label

...

with tf.Session() as sess:
    while True:
        image, label = sess.run(next_element)
        image = image.reshape(IMAGE_SHAPE)

Update:看来您的数据是稀疏张量中的单个单元格值。尝试将其转换回密集并在解码前后进行检查:

def extract_fn(data_record):
    features = {
        # Extract features using the keys set during creation
        "image/class/label":    tf.FixedLenFeature([], tf.int64),
        "image/encoded":        tf.VarLenFeature(tf.string),
    }
    sample = tf.parse_single_example(data_record, features)
    label = sample['image/class/label']
    dense = tf.sparse_tensor_to_dense(sample['image/encoded'])

    # Comment it if you got an error and inspect just dense:
    image = tf.image.decode_image(dense, dtype=tf.float32) 

    return dense, image, label
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Tensorflow:从 TFRecords 文件中提取图像和标签 的相关文章

随机推荐

  • 如何在Linux中打开端口[关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我已经安装了 Web 应用程序 该应用程序在 RHEL centOS 上的端口 8080 上运行 我只能通过命令行访问该机器 我尝试从我的
  • 角度 ng-messages 仅在 $touched 为 true 时显示

    我并没有做任何太特别的事情 我有一个输入 需要在每次击键时进行验证 如果验证失败 则显示错误 不要等待模糊事件来触发 touched 我以为这是默认情况 但显然不是 我正在使用有角度的材料和有角度的消息 我这样做是为了大写锁定检测 标记
  • 如何播放直播FLV流?

    我正在从 PC 中的网络摄像头捕获视频 并即时将其转换为 FLV 使用 ffmpeg 因此 我的 FLV 文件不断增长 现在我想以直播的形式播放它 我正在尝试 VLC 但它播放文件的时间不超过初始化时从文件读取的持续时间 我可以使用什么播放
  • R data.table %like% 带有逻辑 AND

    我正在尝试构建一个闪亮的搜索引擎应用程序 我根据搜索关键字返回 data table DT lt data table field c A B C A C D A D A B A D B C F B D K DT field like A
  • 如何将node.js管道传输到redis?

    我有很多数据要插入 SET INCR 到redis DB 所以我正在寻找pipeline http redis io topics pipelining 质量插入 http redis io topics mass insert通过node
  • 在不运行控制台命令的情况下清理缓存的最佳方法是什么?

    在我的项目的管理面板中 我编写了更改要使用的数据库名称的功能 我把新的数据库名称写在parameters ini 之后必须清理缓存才能加载新配置 在不运行控制台命令的情况下清理缓存的最佳方法是什么 或者是否有另一种最佳实践如何更改当前数据库
  • 模糊不起作用 - Angular 2

    我试图在角度 2 中设置一个蓝色事件 如下所示 div class form group 组件 ts import Component ViewChild ElementRef Output EventEmitter from angula
  • 尝试划分数据时出现除零错误

    这是我的代码 SELECT CASHIER ID AS SERVER CONVERT VARCHAR 10 DATETIME 111 AS DATE SUM GRAND TOTAL AS TOTAL SALES SUM NUM PEOPLE
  • 如何通过单击按钮从反应状态挂钩数组中删除对象

    我正在尝试制作一个按钮 根据传递的索引从数组 即状态 中删除一个对象 我已经尝试了很多 但我的方法都不起作用 所以这是代码 希望我可以找人帮忙 state const items setItems useState name quantit
  • 即使在顶点着色器中使用,glGetUniformLocation()也会返回-1

    我正在尝试用法线渲染一个简单的立方体 我使用以下代码来初始化着色器 void initShader const char vertexShaderPath const char fragmentShaderPath cout lt lt I
  • 如何使用反射确定属性类型?

    如何测试类型的属性以查看它是否是指定类型 编辑 我的目标是检查程序集以查看该程序集中的任何类型是否包含 MyType 或从 MyType 继承 的属性 这是我走过的路 AssemblyName n new AssemblyName n Co
  • 我怎样才能找到圆的所有点? [关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 给定半径和圆心坐标 如何找到圆的所有
  • 是否可以保证枚举的 ToString 的值?

    我当前使用的数据库有一个 varchar 字段 在我的代码中 我想将潜在值映射到枚举 例如 public enum UserStatus Anonymous Enrolled SuperUser 在该列的数据库级别 它有一个限制 其值必须是
  • Python列表切片效率

    在下面的代码中 def listSum alist Get sum of numbers in a list recursively sum 0 if len alist 1 return alist 0 else return alist
  • 如何使用 ng-pattern 验证 angularJs 中的电子邮件 ID

    我正在尝试使用 ng pattern 指令验证 angularJs 中的电子邮件 id 字段 但我是 AngularJs 的新手 我需要在用户输入错误的电子邮件 ID 后立即显示错误消息 我下面的代码正在尝试解决 帮助我使用 ng patt
  • 如何对德语文本进行词形还原?

    我有一篇德语文本 我想对其应用词形还原 如果不可能进行词形还原 那么我也可以接受词干提取 Data 这是我的德语文本 mails Hallo Ich spielte am fr hen Morgen und ging dann zu ein
  • 在自引用表中查询父项和子项

    我有一个Comments如下表所示 在MySQL content created at id parent id second comment 2014 06 03T10 08 44 0000 37 1 third comment 2014
  • 按降序对数字进行排序

    我有 20 个文本框 每个都包含一个特定的数字 我希望 textbox1 到 textboxN 的数字按降序排列 如果任何文本框的值为零 那么我想保留该文本框不变 需要 vb net 中的示例代码 用于按降序对元素进行排序 dim arra
  • Pandas 滚动 std 会产生不一致的结果并且与 value.std 不同

    使用 pandas v1 0 1 和 numpy 1 18 1 我想计算时间序列上不同窗口大小的滚动平均值和标准差 在我正在处理的数据中 某些后续点的值可以是恒定的 这样 根据窗口大小 滚动平均值可能等于窗口中的所有值 并且相应的 std
  • Tensorflow:从 TFRecords 文件中提取图像和标签

    我有一个 TFRecords 文件 其中包含图像及其标签 名称 大小等 我的目标是将标签和图像提取为 numpy 数组 我执行以下操作来加载文件 def extract fn data record features Extract fea