如何将JSON对象保存为文本文件



这是我试图运行的完整代码

from mtcnn.mtcnn import MTCNN
import cv2
image = cv2.imread('figure.jpg')
detector = MTCNN()
face = detector.detect_faces(image)
for face in faces:
print(face)

这是结果JSON对象:

{'box': [141, 106, 237, 292], 'confidence': 0.9988177418708801, 'keypoints': {'left_eye': (211, 218), 'right_eye': (321, 219), 'nose': (265, 278), 'mouth_left': (209, 319), 'mouth_right': (319, 324)}}

import json
json_result = {}
with open("result.txt,"w") as result_file:
for n,face in enumerate(faces):
json_result[str(n)] = face
json_string = json.dumps(json_result, indent=4, sort_keys=True)
result_file.write(json_string)

我得到一个结果文本文件,看起来像这样:

{
"0": {
"box": [
142,
109,
237,
289
],
"confidence": 0.9997594952583313,
"keypoints": {
"left_eye": [
212,
221
],
"mouth_left": [
209,
322
],
"mouth_right": [
319,
327
],
"nose": [
265,
280
],
"right_eye": [
323,
223
]
}
}
}

但是我需要的是一个像这样的结果:

142.84  207.18
222.02  203.9
159.24  253.57
146.59  290.93
227.52  284.74

我如何将我的关键点翻译成2列的格式,同时省略'box'和'confidence' ?

我试图从mtcnn生成的JSON对象中获得包含5个地标的文本文件。

首先省略boxconfidence:

faces = faces['keypoints']

这将给你一个JSON对象:

{'left_eye': (211, 218), 'right_eye': (321, 219), 'nose': (265, 278), 'mouth_left': (209, 319), 'mouth_right': (319, 324)}

然后写入文件:

with open("result.txt","w") as result_file:
for face in faces:
json_string = faces[face]
json_string = " ".join([str(i) for i in json_string])
result_file.write(json_string)

输出:

211 218
321 219
...

相关内容

  • 没有找到相关文章

最新更新