Kreative Zombie
Kreative Zombie

Reputation: 3

How to save JSON object to text file

this is the full code i'm trying to run

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)

this is the resulted JSON object:

{'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)}}

than

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)

I get a result txt file that looks like this:

{
    "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
            ]
        }
    }
}

But what I need is a result that looks like this:

142.84  207.18
222.02  203.9
159.24  253.57
146.59  290.93
227.52  284.74

How can I translate my keypoints to a format in 2 columns and also omit 'box' and 'confidence' ?

I tried to get a text file containing 5 landmarks from a JSON object generated from mtcnn.

Upvotes: 0

Views: 229

Answers (1)

ilyasbbu
ilyasbbu

Reputation: 1749

First to omit box and confidence:

faces = faces['keypoints']

This will give you a JSON object as:

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

Then to write in file:

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)

will give you output:

211 218
321 219
...

Upvotes: 1

Related Questions