UnboundLocalError while trying to annotate video

Trying to annotate a video, I’m using callback function from this blog.

predictions object looks like described in the post (https://fastupload.io/2a249668b939cb4f).
Here is my code:


job_id, signed_url, expire_time = model.predict_video(
    "/content/IMG_7690.mp4",
    fps=5,
    prediction_type="batch-video",
    additional_models = ["clip"]
)

results = model.poll_until_video_results(job_id)

def callback(scene: np.ndarray, index: int) -> np.ndarray:
    result = results[index]
    detections = sv.Detections.from_ultralytics(result)

    bounding_box_annotator = sv.BoundingBoxAnnotator()
    label_annotator = sv.LabelAnnotator()

    labels = [
        result.names[class_id]
        for class_id
        in detections.class_id
    ]

    annotated_image = bounding_box_annotator.annotate(
        scene=scene, detections=detections)

    annotated_image = label_annotator.annotate(
        scene=annotated_image, detections=detections, labels=labels)

    return annotated_image


sv.process_video(
    source_path="/content/IMG_7690.mp4",
    target_path="output.mp4",
    callback=callback
)

results are created before callback function, but I get the following error:

UnboundLocalError: local variable 'results' referenced before assignment

Renaming first ‘results’ variable to ‘test’ within callback gives me KeyError: 0.

def callback(scene: np.ndarray, index: int) -> np.ndarray:
    test = results[index]
    detections = sv.Detections.from_ultralytics(test)

    bounding_box_annotator = sv.BoundingBoxAnnotator()
    label_annotator = sv.LabelAnnotator()

    labels = [
        test.names[class_id]
        for class_id
        in detections.class_id
    ]

    annotated_image = bounding_box_annotator.annotate(
        scene=scene, detections=detections)

    annotated_image = label_annotator.annotate(
        scene=annotated_image, detections=detections, labels=labels)

    return annotated_image

What can I do to complete video annotation?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.