Skip to content

Webcam: Stream Live Video

SUMMARY

Connect to a USB webcam, stream continuous color frames for 10 seconds, and visualize the live feed with Rerun.

Example

Code

python
"""
A simple example demonstrating how to connect to a webcam camera, stream a video
and disconnect from the camera when finished.

Please run this example from a terminal to avoid issues with rerun's spawn mode.
"""
import time
from loguru import logger

import rerun as rr

from medulla.cameras import webcam


def main():
    camera = webcam.Webcam(
        name="my_webcam",
        camera_id=0,
    )
    try:
        rr.init("Webcam_Example", spawn=True)
        camera.connect()

        end_time = time.time() + 10
        while time.time() < end_time:
            image = camera.capture_video_color_frame()
            rr.log(
                "Continuous_Image_Capture",
                rr.Image(image)
            )
    except Exception as e:
        logger.error(
            f"Unable to stream video. "
            f"Caught exception: {type(e).__name__}: {e}"
        )
    finally:
        camera.disconnect()


if __name__ == "__main__":
    main()

Explanation

Now, let's break down the code piece by piece.

The camera object is created the same way as in the single-image example — with a name and a camera_id integer index.

python
camera = webcam.Webcam(
    name="my_webcam",
    camera_id=0,
)

A Rerun viewer is opened with rr.init(..., spawn=True), then camera.connect() opens the device via OpenCV's VideoCapture. All subsequent frame reads require an active connection.

python
rr.init("Webcam_Example", spawn=True)
camera.connect()

The streaming loop runs for 10 seconds using a wall-clock deadline rather than a fixed frame counter, so the actual number of frames captured depends on the camera's native frame rate. Each call to capture_video_color_frame reads the next available frame and returns it as an RGB NumPy array. The frame is logged to Rerun under "Continuous_Image_Capture" on every iteration.

python
end_time = time.time() + 10
while time.time() < end_time:
    image = camera.capture_video_color_frame()
    rr.log(
        "Continuous_Image_Capture",
        rr.Image(image)
    )

The finally block disconnects the camera exactly as in the single-image example, releasing the VideoCapture device and all resources.

python
finally:
    camera.disconnect()

Run

bash
python capture_video_example.py

A Rerun viewer opens automatically. Frames stream under Continuous_Image_Capture for 10 seconds, then the camera disconnects cleanly.