Website Vidya
Linux & ServersStep-by-Step Guide

How to Install OpenCV on Ubuntu 24.04

Learn how to install OpenCV on Ubuntu 24.04 LTS from official repositories and compile from source with Python bindings, GTK, and CUDA GPU support.

RR
Rajesh RayLead Systems Educator
Published:
6 min read
PDF Cheat Sheet
How to Install OpenCV on Ubuntu 24.04
AI Executive SummaryWebsiteVidya AI

6 min read

Learn how to install OpenCV on Ubuntu 24.04 LTS from official repositories and compile from source with Python bindings, GTK, and CUDA GPU support.

Key Highlights
  • Prerequisites and Supported Releases
  • Method 1: Installing OpenCV via Official Ubuntu APT Repositories (Quick)
  • Step 2: Verifying the APT Installation
Grounded in full engineering runbookWebsiteVidya AI Engine

Real-time object detection, facial recognition, autonomous robotics navigation, and medical image segmentation depend heavily on accelerated computer vision algorithms. When you install opencv on ubuntu 24.04, you deploy a battle-tested library containing over 2,500 optimized algorithms engineered to process camera video feeds, analyze matrices, and execute deep neural network (DNN) inference models.

Ubuntu 24.04 LTS offers two distinct installation approaches depending on your project requirements. The standard Ubuntu APT repositories provide pre-compiled packages (python3-opencv and libopencv-dev), allowing rapid deployment for standard educational and scripting tasks. Alternatively, compiling OpenCV directly from source alongside the opencv_contrib repository enables hardware-specific AVX2/NEON vectorization, proprietary video codecs, Intel TBB parallelization, and optional NVIDIA CUDA GPU acceleration.

In this production guide, you will learn how to deploy OpenCV using both avenues. You will install necessary media and mathematical libraries, configure Python 3 virtual environments with NumPy, execute CMake compilation pipelines, and verify your installation by executing an image manipulation script.

Advertisement

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat). The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

  • A desktop or server running Ubuntu 24.04 LTS (64-bit architecture).
  • A user account with active sudo administrative privileges.
  • Python 3 and pip installed (or ready to install).
  • At least 15 GB of free disk space and 4 GB RAM if compiling from source.

Method 1: Installing OpenCV via Official Ubuntu APT Repositories (Quick)

The fastest method to get started with OpenCV on Ubuntu 24.04 LTS is installing the pre-compiled distribution packages. Ubuntu includes stable OpenCV builds in its universe repository with bindings for both Python 3 and C++.

First, refresh your APT package database and install python3-opencv for Python developers and libopencv-dev for C++ software engineers.

Advertisement
# Refresh package repository index
sudo apt update

# Install OpenCV for Python and C++ development
sudo apt install -y python3-opencv libopencv-dev

Step 2: Verifying the APT Installation

Confirm that Python can import the OpenCV library module (cv2) and check its reported version string.

For C++ developers, query pkg-config to inspect include paths and compiler linking flags.

# Verify OpenCV version in Python 3
python3 -c "import cv2; print('OpenCV Version:', cv2.__version__)"

# Inspect C++ compilation flags
pkg-config --modversion --cflags opencv4

Method 2: Compiling OpenCV from Source with Extra Contrib Modules

Compiling OpenCV from source gives you complete control over build options, allowing you to incorporate bleeding-edge features from opencv_contrib (such as specialized feature detectors, text detection, and tracking algorithms) and hardware CPU vector optimizations.

Begin by installing compilation toolchains (build-essential, cmake), image format codecs (JPEG, PNG, TIFF), video streaming libraries, and GTK3 graphical window interfaces.

Advertisement
# Install build tools and multimedia development headers
sudo apt update
sudo apt install -y build-essential cmake git pkg-config \
  libjpeg-dev libtiff-dev libpng-dev libavcodec-dev libavformat-dev \
  libswscale-dev libv4l-dev libxvidcore-dev libx264-dev libgtk-3-dev \
  libatlas-base-dev gfortran python3-dev

Step 3: Setting Up a Dedicated Python Virtual Environment

In modern Ubuntu releases like Ubuntu 24.04 LTS, PEP 668 restricts installing Python packages globally outside virtual environments. Create an isolated virtual environment named cv-env to host your OpenCV Python installation.

Activate the environment and install numpy, which provides high-performance multidimensional array structures required by OpenCV.

# Install python3-venv if not already present
sudo apt install -y python3-venv

# Create project directory and virtual environment
mkdir -p ~/opencv_project && cd ~/opencv_project
python3 -m venv cv-env

# Activate virtual environment
source cv-env/bin/activate

# Install NumPy within the virtual environment
pip install --upgrade pip
pip install numpy

Step 4: Cloning OpenCV and OpenCV Contrib Repositories

Clone both the core opencv repository and the opencv_contrib repository from GitHub into a temporary build workspace. Ensure you checkout identical version tags across both repositories to maintain ABI compatibility.

Create a dedicated build directory inside the core repository.

# Define release version tag
OPENCV_VER="4.9.0"

# Clone core OpenCV repository
cd ~/opencv_project
git clone https://github.com/opencv/opencv.git --depth 1 --branch ${OPENCV_VER}

# Clone extra contrib modules repository
git clone https://github.com/opencv/opencv_contrib.git --depth 1 --branch ${OPENCV_VER}

# Create and enter build directory
cd ~/opencv_project/opencv
mkdir build && cd build

Step 5: Configuring the Build with CMake

Execute cmake to generate build makefiles. Specify the installation prefix (/usr/local), link the extra contrib modules directory, and configure Python virtual environment interpreter paths.

Review the CMake summary output to ensure Python 3 target bindings and GTK support are marked as enabled.

# Run CMake configuration
cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_EXTRA_MODULES_PATH=~/opencv_project/opencv_contrib/modules \
      -D OPENCV_ENABLE_NONFREE=ON \
      -D WITH_GTK=ON \
      -D WITH_V4L=ON \
      -D WITH_OPENGL=ON \
      -D BUILD_EXAMPLES=OFF \
      -D PYTHON3_EXECUTABLE=$(which python3) \
      ..

Step 6: Compiling and Installing OpenCV

Compile the codebase using make. Utilizing the -j$(nproc) flag instructs the compiler to parallelize compilation across all available CPU cores, substantially reducing build time.

Once compilation completes without errors, install the binaries and update shared dynamic library links using ldconfig.

# Compile OpenCV using all CPU cores
make -j$(nproc)

# Install compiled libraries and headers into /usr/local
sudo make install

# Update system dynamic linker cache
sudo ldconfig

Step 7: Testing OpenCV with a Verification Python Script

Verify your OpenCV installation by writing and executing a minimal Python script that creates a synthetic image array, applies Gaussian blur filtering, and computes Canny edge contours.

Execute the script in your terminal to confirm that the numerical matrix engine and core computer vision pipelines operate without error.

# Create test script
cat << 'EOF' > test_vision.py
import cv2
import numpy as np

# Create a synthetic 400x400 black canvas
canvas = np.zeros((400, 400, 3), dtype="uint8")

# Draw a blue rectangle and green circle
cv2.rectangle(canvas, (50, 50), (350, 350), (255, 0, 0), -1)
cv2.circle(canvas, (200, 200), 100, (0, 255, 0), -1)

# Apply Gaussian Blur
blurred = cv2.GaussianBlur(canvas, (11, 11), 0)

# Detect edges using Canny
edges = cv2.Canny(blurred, 30, 150)

print("OpenCV build verification succeeded!")
print("Canvas shape:", canvas.shape)
print("Edges detected shape:", edges.shape)
print("OpenCV version in use:", cv2.__version__)
EOF

# Run test script
python3 test_vision.py

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

ModuleNotFoundError: No module named 'cv2' in Python virtual environment

Resolution: If compiled from source, verify that cv2.cpython-*.so was installed into your Python environment's site-packages directory. If not present, create a symbolic link: ln -s /usr/local/lib/python3.12/site-packages/cv2/python-3.12/cv2.cpython-312-x86_64-linux-gnu.so ~/opencv_project/cv-env/lib/python3.12/site-packages/cv2.so.

Compiler runs out of memory (OOM) during 'make -j$(nproc)'

Resolution: Compiling template-heavy C++ vision libraries consumes extensive RAM per thread. Limit compilation parallelism to 2 threads: make -j2, or create a temporary swap file: sudo fallocate -l 4G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile.

cv2.imshow() crashes with error: 'The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.'

Resolution: Ensure libgtk-3-dev is installed and rerun CMake with -D WITH_GTK=ON. Recompile and reinstall OpenCV.

Security Best Practices and Hardening

Be cautious when parsing untrusted image or video files from remote sources, as buffer overflows in legacy media codecs can lead to arbitrary code execution.

Keep OpenCV updated regularly using sudo apt update or recompiling newer stable tags to patch published image decompression CVEs.

Isolate computer vision applications inside dedicated non-privileged user accounts or Docker containers when deploying automated video pipelines.

Do not execute OpenCV build and compilation commands directly under the root user account.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

3 FAQs
Install via APT (sudo apt install python3-opencv) if you need a quick, reliable setup for standard scripts. Compile from source if you require CUDA acceleration, non-free algorithms, or the latest OpenCV version.
Yes. Inside an isolated Python virtual environment, running pip install opencv-python or pip install opencv-contrib-python installs pre-built binary wheels with bundled dependencies.
Yes. By installing the NVIDIA CUDA Toolkit and building OpenCV from source with -D WITH_CUDA=ON, OpenCV offloads vision processing directly to your GPU.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout