我正在嘗試使用 Deep3DFaceRecon_pytorch,第一步是通過 MTCNN 獲取您的影像,以獲得面部的地標。我使用 MTCNN 的通用演示代碼。它作業得很好,我得到了我的預期,但我還需要將 json 檔案結果保存到 txt 檔案。
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)
我得到了這個 json 檔案
**"{'box': [142, 109, 237, 289], 'confidence': 0.9997594952583313, 'keypoints': {'left_eye': (212, 221), 'right_eye': (323, 223), '鼻子': (265, 280), 'mouth_left': (209, 322), 'mouth_right': (319, 327)}}" **
它作業得很好,但我需要將這些值保存到一個 txt 檔案中。
我怎么做?
uj5u.com熱心網友回復:
您可以將 json 陣列轉換為單個 json 物件并將其寫入檔案。下面顯示了如何實作這一目標。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535511.html
