2014-09-26 43 views
0

我有一個人臉檢測代碼。我想要的是以特定的順序將元數據存儲在json文件中。基本上我想寫出圖像中存在多少人臉和圖像的位置。我的代碼如下:Python中嵌套的json

data =[] 
data.append({'number_of_faces':len(faces)}) 
nested_data = [] 
for (x,y,w,h) in faces: 
    nested_data.append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w}) 
data.append(nested_data) 
with open(json_path+folder+'/'+file_name, "w") as outfile: 
     json.dump(data, outfile)  

的輸出,例如:

[ 
    { 
     "number_of_faces": 1 
    }, 
    [ 
     { 
      "face_h": 38, 
      "face_w": 38, 
      "face_x": 74, 
      "face_y": 45 
     } 
    ] 
] 

不過,我想創建一個嵌套的JSON。因此我想在number_of_faces對象之後嵌套number_of_faces {}中的所有face_location。這怎麼可能呢?

+1

這不是真的關於JSON的問題,而是關於字典和列表。 'json'庫將會把你傳遞給它的結構序列化。 – 2014-09-26 08:21:20

+0

是如何有效地將列表傳遞給json。 – 2014-09-26 08:23:10

回答

1
data = {} 
data['number_of_faces'] = len(faces) 
data['faces'] = [] 
for (x,y,w,h) in faces: 
    data['faces'].append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w}) 
with open(json_path+folder+'/'+file_name, "w") as outfile: 
    json.dump(data, outfile) 

這將有輸出:

所有的
{ 
    'number_of_faces': 4 
    'faces':[{ 
     'face_x': 'x', 
     'face_y': 'y', 
     'face_h': 'h', 
     'face_z': 'z' 
    }] 
} 
+0

該實現只存儲json中圖像的最後一張臉! – 2014-09-26 08:21:47

+0

你是什麼意思? – 2014-09-26 08:24:36

+0

面孔是包含多個面孔協調的列表。在建議的實現中,只有存儲在json文件中的最後一個面座標。 – 2014-09-26 08:25:52

1

首先,正如我在評論說,讓我們忽略了JSON的一部分。這只是一個關於列表和字典的問題。所以,我們只需要以你想要的方式建立數據。

首先,我們應該從每個形狀的字典開始,而不是僅僅追加到列表。然後,我們可以爲該字典中的每個形狀添加面部數據。

data = [] 
for shape in shapes: 
    shape = {'number_of_faces':len(faces)} 
    nested_data = [] 
    for (x,y,w,h) in faces: 
     nested_data.append({'face_x': x, 'face_y': y, 'face_h': h, 'face_w': w}) 
    shape['face_location'] = nested_data 
    data.append(shape) 
+0

實現中的形狀究竟是什麼? – 2014-09-26 08:31:15

+1

我認爲你有一個迭代的形狀列表,因爲你的原始實現是一個字典列表。如果你不這樣做,那麼不需要這個列表,也不需要我的代碼中的'data'或for循環。 – 2014-09-26 08:35:58