How To

Install OpenCV on Ubuntu 24.04 / Debian 13

OpenCV (Open Source Computer Vision Library) is a powerful library for real-time computer vision, image processing, and machine learning. It supports C++, Python, and Java, and runs on Linux, Windows, and macOS. OpenCV is widely used in face detection, object tracking, video analysis, and AI-powered image recognition systems.

Original content from computingforgeeks.com - post 58300

This guide covers multiple ways to install OpenCV on Ubuntu 24.04 and Debian 13 – from the quick apt package to building the latest OpenCV 4.13.0 from source with full module support. We also cover Python bindings, C++ compilation, face detection with Haar cascades, and GPU acceleration with CUDA.

Prerequisites

Before starting, make sure you have the following in place:

  • Ubuntu 24.04 LTS or Debian 13 (Trixie) server or workstation
  • Root or sudo access
  • At least 4GB RAM (8GB+ recommended for building from source)
  • 10GB free disk space for source builds
  • Python 3 installed (included by default on both distros)
  • NVIDIA GPU with proprietary drivers (only for Step 8 – CUDA support)

Step 1: Install OpenCV from Ubuntu / Debian Repositories

The fastest way to get OpenCV running is through the system package manager. Ubuntu 24.04 ships OpenCV 4.6.0, while Debian 13 provides OpenCV 4.10.0. This method works well for general use, though it may not include the latest features.

Update the package index and install OpenCV development libraries along with the Python bindings:

sudo apt update
sudo apt install -y libopencv-dev python3-opencv

This pulls in the core OpenCV library, development headers, and the Python 3 bindings. Verify the installed version with Python:

python3 -c "import cv2; print(cv2.__version__)"

On Ubuntu 24.04, you should see:

4.6.0

On Debian 13 (Trixie), the output will show:

4.10.0

If you need a newer version with all the latest features, proceed to Step 2 to build from source.

Step 2: Build OpenCV 4.13.0 from Source

Building from source gives you the latest OpenCV 4.13.0 release with all modules, optimizations, and contrib packages (extra algorithms for face recognition, object tracking, and more). This is the recommended approach for production computer vision workloads.

Install Build Dependencies

Install the compiler toolchain, CMake, and all required development libraries:

sudo apt update
sudo apt install -y build-essential cmake git pkg-config \
  libgtk-3-dev libavcodec-dev libavformat-dev libswscale-dev \
  libv4l-dev libxvidcore-dev libx264-dev libjpeg-dev \
  libpng-dev libtiff-dev gfortran openexr libatlas-base-dev \
  python3-dev python3-numpy libtbb2 libtbb-dev libdc1394-dev \
  libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev

Download OpenCV Source Code

Clone both the main OpenCV repository and the contrib modules for the 4.13.0 release:

mkdir ~/opencv_build && cd ~/opencv_build
git clone --depth 1 --branch 4.13.0 https://github.com/opencv/opencv.git
git clone --depth 1 --branch 4.13.0 https://github.com/opencv/opencv_contrib.git

Configure the Build with CMake

Create a build directory and run CMake with optimized settings. This configures OpenCV with Python 3 support, contrib modules, and performance optimizations:

cd ~/opencv_build/opencv
mkdir build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D INSTALL_C_EXAMPLES=OFF \
  -D INSTALL_PYTHON_EXAMPLES=OFF \
  -D OPENCV_GENERATE_PKGCONFIG=ON \
  -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
  -D BUILD_EXAMPLES=OFF ..

At the end of the CMake output, check the summary to confirm Python 3 and the contrib modules are detected. Look for lines showing the Python 3 interpreter path and “Extra modules” listing the contrib packages.

Compile and Install

Start the build using all available CPU cores. This takes 15-45 minutes depending on your hardware:

make -j$(nproc)

Once the build completes without errors, install the libraries system-wide:

sudo make install
sudo ldconfig

The ldconfig command updates the shared library cache so the system can find the newly installed OpenCV libraries.

Verify the source-built version:

pkg-config --modversion opencv4

The output should confirm version 4.13.0:

4.13.0

Step 3: Install OpenCV Python Bindings with pip

If you only need the Python bindings and do not require C++ development headers, pip provides the simplest installation method. The opencv-python package on PyPI ships pre-compiled binaries that work immediately.

Create a virtual environment to keep your project dependencies isolated:

python3 -m venv ~/opencv-env
source ~/opencv-env/bin/activate

Install the main OpenCV package. Use opencv-contrib-python to get the full library with contrib modules (face recognition, ArUco markers, etc.):

pip install opencv-contrib-python

If you only need the core OpenCV modules without extras, install the lighter package instead:

pip install opencv-python

Both packages include NumPy as a dependency. Confirm the installation by checking the version:

python3 -c "import cv2; print(cv2.__version__)"

This should show the latest PyPI release version, which tracks closely with official OpenCV releases.

Step 4: Verify OpenCV Installation

Regardless of which installation method you used, verify that OpenCV works correctly in both Python and C++.

Python Verification

Run a quick Python check that lists the available OpenCV modules and build information:

python3 -c "
import cv2
print('OpenCV version:', cv2.__version__)
print('Build info:', cv2.getBuildInformation().split('General configuration')[0][:200])
print('Available modules:', len(dir(cv2)), 'symbols')
"

You should see the version number, partial build information, and a count of available symbols. A source build with contrib modules typically shows 1000+ symbols.

C++ Verification

If you installed from source or via the apt development package, test the C++ bindings. Create a test file:

cat > /tmp/opencv_test.cpp

Add the following test program:

#include <opencv2/core.hpp>
#include <iostream>
int main() {
    std::cout << "OpenCV version: " << CV_VERSION << std::endl;
    cv::Mat mat = cv::Mat::zeros(3, 3, CV_8UC1);
    std::cout << "Created 3x3 matrix successfully" << std::endl;
    return 0;
}

Compile and run the test program using pkg-config to locate the OpenCV headers and libraries:

g++ /tmp/opencv_test.cpp -o /tmp/opencv_test $(pkg-config --cflags --libs opencv4)
/tmp/opencv_test

The output confirms that the C++ bindings are working and the correct version is linked:

OpenCV version: 4.13.0
Created 3x3 matrix successfully

Step 5: Basic Image Operations with OpenCV

With OpenCV installed, here are common image operations you will use in most computer vision projects – reading, resizing, and applying filters.

Read and Display Image Info

Load an image and inspect its dimensions and color channels. First, download a sample image to work with:

wget -q -O /tmp/sample.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png

Now read the image and print its properties:

python3 -c "
import cv2
img = cv2.imread('/tmp/sample.jpg')
if img is not None:
    print(f'Image shape: {img.shape}')
    print(f'Width: {img.shape[1]}, Height: {img.shape[0]}')
    print(f'Channels: {img.shape[2]}')
    print(f'Data type: {img.dtype}')
else:
    print('Failed to load image')
"

The shape attribute returns (height, width, channels). A standard color image has 3 channels (BGR in OpenCV, not RGB).

Resize an Image

Resizing is one of the most frequent operations in image processing pipelines, especially when preparing data for machine learning models:

python3 -c "
import cv2
img = cv2.imread('/tmp/sample.jpg')
resized = cv2.resize(img, (640, 480))
print(f'Original: {img.shape}')
print(f'Resized: {resized.shape}')
cv2.imwrite('/tmp/resized.jpg', resized)
print('Saved resized image to /tmp/resized.jpg')
"

Apply Image Filters

OpenCV provides dozens of filters for noise reduction, edge detection, and image enhancement. Here are three commonly used filters:

python3 -c "
import cv2
img = cv2.imread('/tmp/sample.jpg')

# Gaussian blur - reduces noise
blurred = cv2.GaussianBlur(img, (7, 7), 0)
cv2.imwrite('/tmp/blurred.jpg', blurred)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('/tmp/grayscale.jpg', gray)

# Canny edge detection
edges = cv2.Canny(gray, 100, 200)
cv2.imwrite('/tmp/edges.jpg', edges)

print('Saved: blurred.jpg, grayscale.jpg, edges.jpg')
"

The Gaussian blur kernel size (7,7) controls the blur intensity – larger values produce stronger blur. Canny edge detection thresholds (100, 200) determine edge sensitivity – lower values detect more edges.

Step 6: Video Capture from Webcam

OpenCV handles video input from webcams, IP cameras, and video files through the VideoCapture class. This is the foundation for real-time computer vision applications.

Create a script that captures frames from your webcam and saves a snapshot:

python3 -c "
import cv2

cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print('Error: Cannot open webcam')
    exit(1)

# Get camera properties
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
print(f'Camera: {width}x{height} at {fps} FPS')

# Capture a single frame
ret, frame = cap.read()
if ret:
    cv2.imwrite('/tmp/webcam_snapshot.jpg', frame)
    print('Saved snapshot to /tmp/webcam_snapshot.jpg')

cap.release()
print('Camera released')
"

For continuous video processing (displaying a live window), use a loop with cv2.imshow(). This requires a display server (X11 or Wayland) and does not work over SSH without X forwarding:

python3 -c "
import cv2

cap = cv2.VideoCapture(0)
print('Press q to quit')

while True:
    ret, frame = cap.read()
    if not ret:
        break
    cv2.imshow('Webcam Feed', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
"

To capture from a video file instead of a webcam, replace VideoCapture(0) with the file path: VideoCapture('/path/to/video.mp4').

Step 7: Face Detection with Haar Cascades

OpenCV ships with pre-trained Haar cascade classifiers for detecting faces, eyes, and other objects. These XML models work without any additional downloads when OpenCV is installed properly.

First, locate the cascade files on your system. The path depends on your installation method:

python3 -c "import cv2; print(cv2.data.haarcascades)"

This prints the directory containing all Haar cascade XML files. The most commonly used is haarcascade_frontalface_default.xml.

Run face detection on an image file:

python3 -c "
import cv2

# Load the face detector
face_cascade = cv2.CascadeClassifier(
    cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
)

# Load and convert image to grayscale
img = cv2.imread('/tmp/sample.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Detect faces
faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30)
)

print(f'Detected {len(faces)} face(s)')

# Draw rectangles around detected faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)

cv2.imwrite('/tmp/faces_detected.jpg', img)
print('Saved result to /tmp/faces_detected.jpg')
"

The scaleFactor parameter controls the image scaling at each detection pass – 1.1 means the image is reduced by 10% each time. The minNeighbors value filters out weak detections – higher values reduce false positives but may miss some faces.

For real-time face detection from a webcam, combine the VideoCapture code from Step 6 with the face detection code above inside the frame capture loop. If you are working on more advanced projects like face recognition or deep learning-based detection, the TensorFlow and OpenCV DNN modules provide better accuracy than Haar cascades.

Step 8: Install OpenCV with CUDA Support for GPU Acceleration

If you have an NVIDIA GPU, building OpenCV with CUDA support dramatically speeds up operations like DNN inference, image filtering, and video processing. This requires the NVIDIA CUDA toolkit and cuDNN libraries installed on your system.

Install CUDA Prerequisites

Install the NVIDIA CUDA toolkit and cuDNN. The CUDA toolkit is available from the NVIDIA package repository:

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64/cuda-keyring_1.1-1_all.deb
sudo dpkg -i cuda-keyring_1.1-1_all.deb
sudo apt update
sudo apt install -y cuda-toolkit libcudnn9-dev

Verify CUDA is working by checking the compiler version:

nvcc --version

The output should show the CUDA compiler version. Also confirm your GPU is detected:

nvidia-smi

Build OpenCV with CUDA Enabled

Follow the same source download steps from Step 2, then configure CMake with CUDA flags. The key difference is enabling CUDA modules and specifying your GPU architecture:

cd ~/opencv_build/opencv/build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local \
  -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
  -D OPENCV_GENERATE_PKGCONFIG=ON \
  -D WITH_CUDA=ON \
  -D WITH_CUDNN=ON \
  -D OPENCV_DNN_CUDA=ON \
  -D ENABLE_FAST_MATH=ON \
  -D CUDA_FAST_MATH=ON \
  -D WITH_CUBLAS=ON \
  -D CUDA_ARCH_BIN="7.5 8.0 8.6 8.9 9.0" \
  -D BUILD_EXAMPLES=OFF \
  -D INSTALL_C_EXAMPLES=OFF \
  -D INSTALL_PYTHON_EXAMPLES=OFF ..

The CUDA_ARCH_BIN value specifies which GPU compute capabilities to compile for. Common values are 7.5 (RTX 2000 series), 8.0 (A100), 8.6 (RTX 3000 series), 8.9 (RTX 4000 series), and 9.0 (H100). Check your GPU’s compute capability on the NVIDIA developer site and include only the architectures you need – fewer targets means faster compilation.

Build with all CPU cores. The CUDA build takes significantly longer (30-90 minutes):

make -j$(nproc)
sudo make install
sudo ldconfig

Verify CUDA Support in OpenCV

Confirm that OpenCV was built with CUDA support:

python3 -c "
import cv2
print('CUDA devices:', cv2.cuda.getCudaEnabledDeviceCount())
build = cv2.getBuildInformation()
cuda_section = [l for l in build.split('\n') if 'CUDA' in l]
for line in cuda_section:
    print(line.strip())
"

If CUDA is properly configured, the output shows at least 1 CUDA device and multiple CUDA-related build flags set to YES. A zero device count means the CUDA toolkit was not found during the build.

Conclusion

OpenCV is now installed on your Ubuntu 24.04 or Debian 13 system. The repo package works for basic tasks, but building from source with contrib modules gives you access to the full 4.13.0 feature set including advanced algorithms for face recognition, object tracking, and deep learning inference. For production deployments, consider running OpenCV workloads inside Python virtual environments to isolate dependencies, and add GPU acceleration with CUDA if your workload involves real-time video processing or DNN inference at scale.

Related Articles

Email Install Kolab 16 on Ubuntu 18.04 With Let’s Encrypt SSL Monitoring Install Observium on Ubuntu 20.04|18.04 with Nginx Ubuntu Install Concrete CMS with Apache on Ubuntu 24.04|22.04 Arch Linux Fix Slow SSH Login – Disable Reverse DNS Lookups on Linux

Leave a Comment

Press ESC to close