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

如何用Python脚本生成JSON文件?附目标检测场景示例

Generating JSON Files from Your Python Object Detection Script

Hey there! Since you're new to working with JSON in Python, let's break this down simply—you don't need any fancy external tools or software. Python's built-in json module is all you need to generate JSON files directly from your object detection code. Let's walk through how to apply this to your specific use case.

Step 1: Decide What Data to Store

First, outline which parts of your detection workflow you want to save in the JSON file. For your trolley detection script, this might include:

  • Template details (name, dimensions)
  • Input image filename
  • Matching threshold value
  • Coordinates of all matched target locations

Step 2: Integrate the json Module into Your Code

The json module lets you convert Python data structures (like dictionaries and lists) into valid JSON format, and write them directly to a file. Here's how to adapt your existing code to generate JSON:

Modified Code with JSON Generation

import numpy as np
import cv2
import json  # Import Python's built-in json module

# Your existing object detection logic
inputImage = cv2.imread("Trolley_Problem.jpg")
inputImageGray = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)
tramTemplate = cv2.imread("tram1.jpg")
tramTemplateGray = cv2.cvtColor(tramTemplate, cv2.COLOR_BGR2GRAY)
h1, w1 = tramTemplateGray.shape
tramResult = cv2.matchTemplate(inputImageGray, tramTemplateGray, cv2.TM_CCOEFF_NORMED)
threshold = 0.75
loc1 = np.where(tramResult >= threshold)

# Organize your detection data into a Python dictionary
detection_results = {
    "input_image": "Trolley_Problem.jpg",
    "template_info": {
        "name": "tram1",
        "width": int(w1),
        "height": int(h1)
    },
    "matching_threshold": threshold,
    "detected_locations": [
        {"x": int(x_coord), "y": int(y_coord)} 
        for y_coord, x_coord in zip(loc1[0], loc1[1])
    ]
}

# Write the data to a JSON file
with open("trolley_detection_results.json", "w") as output_file:
    json.dump(detection_results, output_file, indent=4)

print("JSON file generated successfully!")

Key Notes:

  • Numpy Type Conversion: JSON can't serialize numpy integers directly, so we convert values like w1 and coordinates to Python's native int type with int().
  • Readable Format: The indent=4 argument formats the JSON file with line breaks and indentation, making it easy to read manually.
  • Structured Data: Using a dictionary to group related info (like template details) and a list for multiple detected positions maps perfectly to JSON's object and array structures.

Step 3: (Optional) Load the JSON File Later

If you need to retrieve the saved data back into Python, use json.load():

with open("trolley_detection_results.json", "r") as input_file:
    loaded_data = json.load(input_file)

# Access the data like a regular Python dictionary
print(f"Found {len(loaded_data['detected_locations'])} trolley positions")

Do You Need External Tools?

For most use cases (including your object detection workflow), Python's built-in json module is more than sufficient. You'd only need external libraries (like ijson for streaming large files) if you're working with extremely large datasets or specialized data types—but that's unlikely here.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:58:45