You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MTCNN检测的JSON格式人脸关键点保存到TXT文件

将MTCNN人脸检测结果保存到TXT文件的实现方法

你可以通过Python的文件操作结合json模块来实现检测结果的保存,以下是修改后的完整代码(同时修复了原代码的缩进问题):

from mtcnn.mtcnn import MTCNN
import cv2
import json

# 读取目标图像
image = cv2.imread('figure.jpg')
# 初始化MTCNN检测器
detector = MTCNN()
# 执行人脸检测,得到包含box、置信度、关键点的结果列表
faces = detector.detect_faces(image)

# 将检测结果写入TXT文件
with open('face_detection_results.txt', 'w', encoding='utf-8') as f:
    # 遍历每张检测到的人脸
    for idx, face in enumerate(faces):
        # 把字典转为格式化的JSON字符串,提升可读性
        face_content = json.dumps(face, indent=4, ensure_ascii=False)
        f.write(f"第{idx+1}张人脸检测结果:\n")
        f.write(face_content + '\n\n')

# 人脸可视化函数(已修复缩进)
def create_bbox(image):
    faces = detector.detect_faces(image)
    if not faces:
        return 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)
cv2.destroyAllWindows()

核心逻辑说明

  • 用json.dumps()将MTCNN返回的字典对象转为格式化字符串,避免直接写入字典导致的格式混乱,同时保证内容易读。
  • 使用with open()上下文管理器自动处理文件的打开/关闭,避免资源泄漏。
  • 支持多人脸场景,每张人脸的检测结果会单独标注序号后写入文件。

保存后的TXT文件示例内容

第1张人脸检测结果:
{
    "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]
    }
}

内容的提问来源于stack exchange,提问作者Kreative Zombie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:30:54