如何在Tensorflow中读取json文件? [英] How to read json files in Tensorflow?

查看:986
本文介绍了如何在Tensorflow中读取json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数在tensorflow中读取json文件. json文件具有以下结构:

I'm trying to write a function, that reads json files in tensorflow. The json files have the following structure:

{
    "bounding_box": {
        "y": 98.5, 
        "x": 94.0, 
        "height": 197, 
        "width": 188
     }, 
    "rotation": {
        "yaw": -27.97019577026367,
        "roll": 2.206029415130615, 
        "pitch": 0.0}, 
        "confidence": 3.053506851196289, 
        "landmarks": {
            "1": {
                "y": 180.87722778320312, 
                "x": 124.47326660156205}, 
            "0": {
                "y": 178.60653686523438, 
                "x": 183.41931152343795}, 
            "2": {
                "y": 224.5936889648438, 
                "x": 141.62365722656205
}}}

我只需要边界框信息.有一些关于如何编写read_and_decode-functions的示例,我正在尝试将这些示例转换为json文件的函数,但是仍然有很多问题...:

I only need the bounding box information. There are a few examples on how to write read_and_decode-functions, and I'm trying to transform these examples into a function for json files, but there are still a lot of questions...:

def read_and_decode(filename_queue):

  reader = tf.WhichKindOfReader() # ??? 
  _, serialized_example = reader.read(filename_queue)
  features = tf.parse_single_example( 
      serialized_example,

      features={

          'bounding_box':{ 

              'y': tf.VarLenFeature(<whatstheproperdatatype>) ???
              'x': 
              'height': 
              'width': 

          # I only need the bounding box... - do I need to write 
          # the format information for the other features...???

          }
      })

  y=tf.decode() # decoding necessary?
  x=
  height=
  width= 

  return x,y,height,width

我已经在互联网上进行了数小时的研究,但找不到关于如何在tensorflow中读取json的任何真正详细的信息...

I've done research on the internet for hours, but can't find anything really detailled on how to read json in tensorflow...

也许有人可以给我一个提示...

Maybe someone can give me a clue...

推荐答案

更新

下面的解决方案确实可以完成工作,但是效率不是很高,请参阅注释以获取详细信息.

Update

The solution below does get the job done but it is not very efficient, see comments for details.

如果您使用

You can use standard python json parsing with TensorFlow if you wrap the functions with tf.py_func:

import json
import numpy as np
import tensorflow as tf

def get_bbox(str):
    obj = json.loads(str.decode('utf-8'))
    bbox = obj['bounding_box']
    return np.array([bbox['x'], bbox['y'], bbox['height'], bbox['width']], dtype='f')

def get_multiple_bboxes(str):
    return [[get_bbox(x) for x in str]]

raw = tf.placeholder(tf.string, [None])
[parsed] = tf.py_func(get_multiple_bboxes, [raw], [tf.float32])

请注意,tf.py_func返回张量的列表,而不仅仅是单个张量,这就是为什么我们需要将parsed包装在列表[parsed]中的原因.如果不是,则parsed将得到形状[1, None, 4],而不是所需的形状[None, 4](其中None是批处理大小).

Note that tf.py_func returns a list of tensors rather than just a single tensor, which is why we need to wrap parsed in a list [parsed]. If not, parsed would get the shape [1, None, 4] rather than the desired shape [None, 4] (where None is the batch size).

使用数据,您将获得以下结果:

Using your data you get the following results:

json_string = """{
    "bounding_box": {
        "y": 98.5,
        "x": 94.0,
        "height": 197,
        "width": 188
     },
    "rotation": {
        "yaw": -27.97019577026367,
        "roll": 2.206029415130615,
        "pitch": 0.0},
        "confidence": 3.053506851196289,
        "landmarks": {
            "1": {
                "y": 180.87722778320312,
                "x": 124.47326660156205},
            "0": {
                "y": 178.60653686523438,
                "x": 183.41931152343795},
            "2": {
                "y": 224.5936889648438,
                "x": 141.62365722656205
}}}"""
my_data = np.array([json_string, json_string, json_string])

init_op = tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(parsed, feed_dict={raw: my_data}))
    print(sess.run(tf.shape(parsed), feed_dict={raw: my_data}))

[[  94.    98.5  197.   188. ]
 [  94.    98.5  197.   188. ]
 [  94.    98.5  197.   188. ]]
[3 4]

这篇关于如何在Tensorflow中读取json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆