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

qv7cva1a  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(181)

这是我要运行的完整代码

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)

我得到的结果txt文件如下所示:

{
    "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个地标的文本文件。

mwkjh3gx

mwkjh3gx1#

首先要省略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
...

相关问题