Skip to content

Webcam: Capture Single Image

SUMMARY

Connect to a USB webcam, capture a single color frame, and visualize the result with Rerun.

Example

Single image capture output

Code

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

Please run this example from a terminal to avoid issues with rerun's spawn mode.
"""
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()

        image = camera.capture_single_color_frame()

        rr.log(
            "Single_Image_Capture",
            rr.Image(image)
        )
    except Exception as e:
        logger.error(
            f"Unable to capture image. "
            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.

A Webcam camera object is created by supplying a unique name and the camera_id integer index of the device as reported by the OS — 0 selects the first available camera.

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 and verifies that frames can be read. All subsequent operations require an active connection.

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

capture_single_color_frame reads one frame from the camera, converts it from BGR to RGB, and returns a NumPy array. The frame is then logged to Rerun under the path "Single_Image_Capture" for immediate visual inspection.

python
image = camera.capture_single_color_frame()

rr.log("Single_Image_Capture", rr.Image(image))

The finally block guarantees that camera.disconnect() is always called — regardless of whether an exception occurred. It releases the VideoCapture device and shuts down any BabyROS nodes registered inside the Webcam instance.

python
finally:
    camera.disconnect()

Run

bash
python capture_image_example.py

A Rerun viewer opens automatically. The captured frame appears under Single_Image_Capture once acquisition completes.