RidgeRun Linux Camera Drivers - Jetson OpenCV Examples

From RidgeRun Developer Wiki

Preferred Partner Logo 3 Preferred Partner Logo 3





OpenCV Examples

The following examples shows some basic Python code using OpenCV to capture from either a USB camera or a MIPI CSI camera. To use the code make sure you have OpenCV installed in your Jetson board, use this command to install it:

sudo apt-get install python3-opencv

After the installation was completed, simply run the command (camera_capture.py contains the code shown below):

python3 camera_capture.py

USB camera

The following Python code shows a basic example using OpenCV to capture from a USB camera:







import cv2


CAMERA_INDEX = 0
TOTAL_NUM_FRAMES = 100
FRAMERATE = 30.0


def is_camera_available(camera_index=0):
    cap = cv2.VideoCapture(camera_index)
    if not cap.isOpened():
        return False
    cap.release()
    return True


def main():

    if is_camera_available(CAMERA_INDEX):
        print(f"Camera {CAMERA_INDEX} is available.")
    else:
        print(f"Camera {CAMERA_INDEX} is not available.")
        exit()
    
    cap = cv2.VideoCapture(CAMERA_INDEX)
    
    if not cap.isOpened():
        print("Error: Could not open video stream.")
        exit()
    
    print("Camera opened successfully.")
    
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('output.mp4', fourcc, FRAMERATE, (frame_width, frame_height))

    num_frames = 0
    
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Failed to capture image.")
            break
    
        out.write(frame)

        print(f"Recording: {num_frames} / {TOTAL_NUM_FRAMES}", end='\r')

        if num_frames >= TOTAL_NUM_FRAMES:
            print("\nCapture duration reached, stopping recording.")
            break

        num_frames += 1
    
    # Release the camera and the VideoWriter
    cap.release()
    out.release()


if __name__ == '__main__':
    main()

MIPI CSI camera

The following Python code shows a basic example using OpenCV to capture from a MIPI CSI camera:

import cv2


TOTAL_NUM_FRAMES = 100
FRAMERATE = 30.0
PIPELINE = "nvarguscamerasrc ! video/x-raw(memory:NVMM), width=(int)1920, height=(int)1080,format=(string)NV12, framerate=(fraction)30/1 ! nvvidconv ! video/x-raw, format=(string)BGRx ! videoconvert !  appsink"


def is_camera_available():
    cap = cv2.VideoCapture(PIPELINE)
    if not cap.isOpened():
        return False
    cap.release()
    return True


def main():

    if is_camera_available():
        print("A camera is available.")
    else:
        print("No camera available.")
        exit()
    
    cap = cv2.VideoCapture(PIPELINE)
    
    if not cap.isOpened():
        print("Error: Could not open video stream.")
        exit()
    
    print("Camera opened successfully.")
    
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter('output.mp4', fourcc, FRAMERATE, (frame_width, frame_height))

    num_frames = 0
    
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Failed to capture image.")
            break
    
        out.write(frame)

        print(f"Recording: {num_frames} / {TOTAL_NUM_FRAMES}", end='\r')

        if num_frames >= TOTAL_NUM_FRAMES:
            print("\nCapture duration reached, stopping recording.")
            break

        num_frames += 1
    
    # Release the camera and the VideoWriter
    cap.release()
    out.release()


if __name__ == '__main__':
    main()
Note

For this example to work, GStreamer must be enabled in OpenCV. You can verify this by running the following command:

python3 -c 'import cv2; print(cv2.getBuildInformation())'

In the output, the Video I/O section should indicate GStreamer: YES.

  Video I/O:
    DC1394:                      YES (2.2.6)
    FFMPEG:                      YES
      avcodec:                   YES (58.134.100)
      avformat:                  YES (58.76.100)
      avutil:                    YES (56.70.100)
      swscale:                   YES (5.9.100)
      avresample:                NO
    GStreamer:                   YES (1.19.90)
    PvAPI:                       NO
    v4l/v4l2:                    YES (linux/videodev2.h)
    gPhoto2:                     YES


Info
Visit our NVIDIA Jetpack Reference guide wiki for more information about Jetson boards and NVIDIA Jetpack.