Saving X and Y coordinates of detected objects in video to CSV or JSON?

Project type: Object detection
OS/browser: macOS / Google Chrome
Workspace/project ID: Sign in to Roboflow

Hi there, I’ve used the following link to successfully infer a video by processing it frame by frame.

I just can’t figure out how to record the x and y coordinates of each frame’s prediction to a CSV or JSON file. Is there a code I can add to the python file that will do this?

Thank you!

Sure, you can definitely record the x and y coordinates of each frame’s prediction to a CSV or JSON file. Here’s a basic example of how you might do this in Python, using the csv and json libraries. This code is based on the information provided in the extracts, particularly the structure of the prediction response from the Roboflow API.

import csv
import json

# Assuming 'predictions' is your list of predictions
predictions = [
    {"x": 1113.0, "y": 880.0, "width": 138, "height": 330, "class": "white-bishop", "confidence": 0.642},
    # More predictions...
]

# To write to a CSV file
with open('predictions.csv', 'w', newline='') as csvfile:
    fieldnames = ['x', 'y', 'width', 'height', 'class', 'confidence']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for prediction in predictions:
        writer.writerow(prediction)

# To write to a JSON file
with open('predictions.json', 'w') as jsonfile:
    json.dump(predictions, jsonfile)

This code will create a CSV file and a JSON file in the same directory as your Python script, each containing the x and y coordinates (as well as width, height, class, and confidence) of each prediction.

Please note that this is a basic example and you might need to adjust it to fit your specific needs, such as appending to the file for each frame instead of writing all at once.

For more information on how to use the Roboflow API for object detection, you can refer to the Roboflow Inference API documentation.


Hi! I’m Roboflow’s AI powered bot. This is an automated response powered using AI with knowledge from our docs, blog, knowledge base, and previous forum responses. If you find this to be a helpful answer, please mark it as the solution using the checkbox icon below. If this doesn’t solve your issue, please follow up with what you’ve tried/why, and the community will continue to chime in as usual.

Thanks, Lenny. I’m not quite getting the result yet. This following is my current code. Is anyone able to see how I can get the x,y coordinate for each frame into a CSV or JSON? Thank you!

import supervision as sv
import numpy as np
import roboflow
import cv2
import csv
import json

INPUT_VIDEO = "red.mov"

roboflow.login()

rf = roboflow.Roboflow()

project = rf.workspace().project("redbuoy-jumhy")

model = project.version(1).model

CLASSES_TO_CHECK = ["redbuoy"]

CLASS_IDX = {class_name: i for i, class_name in enumerate(CLASSES_TO_CHECK)}

CLASS_ID_TO_FILTER = [CLASS_IDX[class_name] for class_name in CLASSES_TO_CHECK]

detections_buffer = []

for i, frame in enumerate(sv.get_video_frames_generator(source_path=INPUT_VIDEO)):
    if len(detections_buffer) > 240:
        detections_buffer.pop(0)

    inference_results = model.predict(frame)

    detections = sv.Detections.from_roboflow(inference_results.json(), class_list=CLASSES_TO_CHECK)

    detections = detections[np.isin(detections.class_id, CLASS_ID_TO_FILTER)]

    detections_buffer.append(detections)

    box_annotator = sv.BoxAnnotator()

    labels = [
        f"{CLASSES_TO_CHECK[class_id]} {confidence:0.2f}"
        for _, _, confidence, class_id, _
        in detections
    ]
    
    annotated_frame = box_annotator.annotate(
        scene=frame.copy(),
        detections=detections,
        labels=labels
    )
    
    cv2.imshow("frame", annotated_frame)
    cv2.waitKey(1)

with open('predictions.csv', 'w', newline='') as csvfile:
    fieldnames = ['x', 'y', 'width', 'height', 'class', 'confidence']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for prediction in predictions:
        writer.writerow(prediction)

# To write to a JSON file
with open('predictions.json', 'w') as jsonfile:
    json.dump(predictions, jsonfile)