I am trying to use Deep3DFaceRecon_pytorch and the first step is to get your image trough MTCNN in order to get the landmarks for the face. I use the general demo code from MTCNN. It works great and i get what i expected but i also need to save the json file results to a txt file.
from mtcnn.mtcnn import MTCNN
import cv2
image = cv2.imread('figure.jpg')
cv2.imshow('',image)
cv2.waitKey(0)
cv2.destroyAllWindows()
detector = MTCNN()
faces = detector.detect_faces(image)
for face in faces:
print(face)
{'box': [142, 109, 237, 289], 'confidence': 0.9997594952583313, 'keypoints': {'left_eye': (212, 221), 'right_eye': (323, 223), 'nose': (265, 280), 'mouth_left': (209, 322), 'mouth_right': (319, 327)}}
def create_bbox(image):
faces = detector.detect_faces(image)
bounding_box = faces[0]['box']
keypoints = faces[0]['keypoints']
cv2.rectangle(image,
(bounding_box[0], bounding_box[1]),
(bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),
(0,155,255),
2)
cv2.circle(image,(keypoints['left_eye']), 2, (0,155,255), 2)
cv2.circle(image,(keypoints['right_eye']), 2, (0,155,255), 2)
cv2.circle(image,(keypoints['nose']), 2, (0,155,255), 2)
cv2.circle(image,(keypoints['mouth_left']), 2, (0,155,255), 2)
cv2.circle(image,(keypoints['mouth_right']), 2, (0,155,255), 2)
return image
marked_image = create_bbox(image)
cv2.imshow('',marked_image)
cv2.waitKey(0)
and i get this json file
**"{'box': [142, 109, 237, 289], 'confidence': 0.9997594952583313, 'keypoints': {'left_eye': (212, 221), 'right_eye': (323, 223), 'nose': (265, 280), 'mouth_left': (209, 322), 'mouth_right': (319, 327)}}" **
It works perfectly, but i need to save these values to a txt file.
How do i do that?
You can convert the array of json into a single json object and write it into a file. Below shows how you can achieve that.
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)
result_file.write(json_string)