Linux MintUbuntu Based

How To Install OpenCV on Linux Mint 22

Install OpenCV on Linux Mint 22

OpenCV stands as one of the most powerful and versatile computer vision libraries available today. This comprehensive guide will walk you through multiple methods to install OpenCV on Linux Mint 22, ensuring you can harness the full potential of computer vision development on your system.

Whether you’re a beginner starting your journey in machine learning or an experienced developer working on complex image processing projects, this tutorial provides detailed instructions for every skill level. We’ll explore three distinct installation approaches, each suited for different use cases and requirements.

Understanding OpenCV and System Requirements

What is OpenCV?

OpenCV (Open Source Computer Vision Library) represents a comprehensive toolkit for computer vision, machine learning, and image processing applications. This powerful library supports real-time image and video processing, making it indispensable for developers working on projects involving object detection, facial recognition, motion tracking, and augmented reality applications.

The library offers extensive language support, including Python, C++, Java, and MATLAB bindings. Its modular architecture allows developers to use only the components they need, optimizing both performance and resource usage. OpenCV integrates seamlessly with popular machine learning frameworks like TensorFlow and PyTorch, making it an essential tool in modern AI development workflows.

Modern applications of OpenCV span across various industries, from autonomous vehicles using computer vision for navigation to medical imaging systems analyzing diagnostic scans. The library’s robust algorithms handle complex tasks such as feature detection, template matching, and geometric transformations with remarkable efficiency.

Linux Mint 22 Compatibility and Prerequisites

Linux Mint 22 provides an excellent foundation for OpenCV development, offering stability and compatibility with the latest OpenCV releases. The system requirements are modest, but certain specifications ensure optimal performance during compilation and runtime operations.

Minimum system requirements include:

  • 4GB RAM (8GB recommended for source compilation)
  • 2GB free disk space
  • Multi-core processor (compilation benefits significantly from multiple cores)
  • Active internet connection for downloading dependencies

Software prerequisites:

  • Python 3.8 or newer
  • GCC compiler version 7.0 or higher
  • CMake 3.12 or later for source compilation
  • Git for repository management

Before proceeding with any installation method, verify your system meets these requirements. Insufficient resources during compilation can lead to build failures or system instability.

Pre-Installation Preparation

System Updates and Essential Tools

Maintaining an updated system prevents compatibility issues and ensures access to the latest security patches. Begin by refreshing your package repositories and upgrading existing software:

sudo apt update && sudo apt upgrade -y

Install essential development tools that OpenCV requires for various installation methods:

sudo apt install -y build-essential git cmake pkg-config

Verify your Python installation and ensure pip is available:

python3 --version
pip3 --version

Critical requirement: Ensure your pip version meets the minimum requirement of 19.3. Older versions cause significant compatibility issues with OpenCV packages:

pip3 install --upgrade pip

Install Python development headers, which are essential for building Python bindings:

sudo apt install -y python3-dev python3-pip python3-numpy

Understanding Installation Methods

  • Method 1: pip installation offers the fastest and most straightforward approach. This method downloads pre-compiled wheels, making it ideal for beginners and rapid prototyping. However, it provides limited customization options and may not include all OpenCV modules.
  • Method 2: Source compilation provides maximum flexibility and optimization opportunities. This approach allows custom module selection, processor-specific optimizations, and access to the latest features. The trade-off involves longer installation time and increased complexity.
  • Method 3: System package manager installation offers stability and integration with the system package management. While this method provides excellent stability, it often includes older OpenCV versions with limited module availability.

Choose your installation method based on your specific requirements. Development environments benefit from source compilation, while production systems might prefer the stability of package manager installations.

Method 1: Installing OpenCV via pip (Quick Installation)

Package Selection and Installation

The pip installation method provides immediate access to OpenCV functionality without compilation overhead. Two primary packages are available, each serving different needs and requirements.

opencv-python contains core OpenCV modules sufficient for basic computer vision tasks:

pip3 install opencv-python

opencv-contrib-python includes additional contributed modules, providing extended functionality for advanced applications:

pip3 install opencv-contrib-python

Important: Never install both packages simultaneously. They share the same namespace (cv2) and will create conflicts. If you’ve installed multiple packages, remove them all before proceeding:

pip3 uninstall opencv-python opencv-contrib-python
pip3 install opencv-contrib-python

Virtual environment best practices significantly improve project management and prevent dependency conflicts:

python3 -m venv opencv_env
source opencv_env/bin/activate
pip3 install opencv-contrib-python

This approach isolates OpenCV installations per project, preventing version conflicts and maintaining clean development environments.

Verification and Testing

After installation, verify OpenCV functionality by importing the cv2 module:

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

This command should display the installed OpenCV version without errors. If import errors occur, check for conflicting installations or missing dependencies.

Common verification tests:

import cv2
import numpy as np

# Test basic functionality
img = np.zeros((100, 100, 3), dtype=np.uint8)
cv2.imshow('Test Window', img)
cv2.waitKey(1000)
cv2.destroyAllWindows()
print("OpenCV installation successful!")

Troubleshooting import errors:

  • Ensure virtual environment activation
  • Verify pip installation in correct Python environment
  • Check for conflicting OpenCV installations
  • Confirm numpy compatibility

Method 2: Installing Required Dependencies for Source Compilation

Core Build Dependencies

Source compilation requires extensive build tools and libraries. Install fundamental compilation dependencies:

sudo apt install -y build-essential cmake git pkg-config

CMake configuration serves as the build system orchestrator, managing compilation flags and dependency resolution. Install the latest version for optimal compatibility:

sudo apt install -y cmake-gui cmake-data

GCC compiler suite handles the actual code compilation. Verify your compiler version supports C++11 standards:

gcc --version
g++ --version

Python development environment requires specific headers and tools for binding generation:

sudo apt install -y python3-dev python3-pip python3-numpy python3-distutils

OpenCV-Specific Dependencies

OpenCV’s multimedia capabilities require numerous specialized libraries. Install image format support libraries:

sudo apt install -y libjpeg-dev libpng-dev libtiff-dev libwebp-dev libopenexr-dev

Video processing capabilities depend on codec libraries and multimedia frameworks:

sudo apt install -y libavcodec-dev libavformat-dev libswscale-dev libv4l-dev libxvidcore-dev libx264-dev

GUI and display support enables window management and user interface functionality:

sudo apt install -y libgtk-3-dev libqt5gui5 libqt5webkit5-dev libqt5test-dev

Mathematical optimization libraries enhance performance for complex calculations:

sudo apt install -y libatlas-base-dev liblapack-dev gfortran libeigen3-dev

Threading and parallel processing support maximizes multi-core processor utilization:

sudo apt install -y libtbb-dev

Method 2: Compiling OpenCV from Source

Downloading Source Code

Create a dedicated workspace for OpenCV compilation:

mkdir ~/opencv_build && cd ~/opencv_build

Clone the main OpenCV repository:

git clone https://github.com/opencv/opencv.git

Clone OpenCV contrib modules for extended functionality:

git clone https://github.com/opencv/opencv_contrib.git

The contrib repository contains additional modules like face recognition, text detection, and advanced feature descriptors. These modules significantly expand OpenCV’s capabilities beyond core functionality.

Version selection considerations:

  • Master branch: Latest development features (potentially unstable)
  • Tagged releases: Stable, tested versions recommended for production
  • LTS versions: Long-term support with extended maintenance

For production environments, check out a specific stable release:

cd opencv && git checkout 4.8.0
cd ../opencv_contrib && git checkout 4.8.0

CMake Configuration

Create and navigate to the build directory:

cd ~/opencv_build/opencv
mkdir build && cd build

Configure the build with comprehensive options for maximum functionality:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
      -D PYTHON_EXECUTABLE=/usr/bin/python3 \
      -D BUILD_opencv_python3=ON \
      -D BUILD_opencv_python2=OFF \
      -D CMAKE_INSTALL_PREFIX=/usr/local \
      -D OPENCV_GENERATE_PKGCONFIG=ON \
      -D BUILD_EXAMPLES=ON \
      -D INSTALL_PYTHON_EXAMPLES=ON \
      -D INSTALL_C_EXAMPLES=ON \
      -D WITH_TBB=ON \
      -D WITH_V4L=ON \
      -D WITH_QT=ON \
      -D WITH_GTK=ON \
      -D WITH_OPENGL=ON \
      -D ENABLE_CXX11=ON \
      ..

Critical configuration verification:
Examine the CMake output carefully. Ensure the following components show “YES”:

  • Python3: For Python bindings
  • NumPy: Required for array operations
  • GTK/QT: GUI support
  • FFMPEG: Video processing
  • TBB: Threading support

Common configuration issues:

  • Missing dependencies show as “NO” in output
  • Python path misdetection requires explicit specification
  • Library version mismatches require dependency updates

Compilation and Installation Process

Initiate the compilation process using all available CPU cores:

make -j$(nproc)

The $(nproc) command automatically detects available processor cores, significantly reducing compilation time. On modern systems, this process typically takes 30-60 minutes depending on hardware specifications.

Monitor compilation progress:

  • Watch for error messages indicating missing dependencies
  • Memory usage may spike; ensure adequate system resources
  • Compilation generates extensive output; errors appear in red text

Install the compiled library:

sudo make install
sudo ldconfig

The ldconfig command updates the system’s shared library cache, ensuring OpenCV libraries are properly registered with the system.

Post-Installation Configuration and Verification

System Library Configuration

Update the library search path to include OpenCV installations:

echo '/usr/local/lib' | sudo tee -a /etc/ld.so.conf.d/opencv.conf
sudo ldconfig

Configure environment variables for development tools:

echo 'export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig' >> ~/.bashrc
source ~/.bashrc

Python path verification ensures proper module detection:

python3 -c "import sys; print('\n'.join(sys.path))"

The output should include paths where OpenCV Python bindings are installed, typically /usr/local/lib/python3.x/site-packages.

Comprehensive Testing and Verification

Basic functionality test:

import cv2
import numpy as np

print(f"OpenCV version: {cv2.__version__}")
print(f"NumPy version: {np.__version__}")

# Test image operations
img = np.zeros((300, 300, 3), dtype=np.uint8)
cv2.rectangle(img, (50, 50), (250, 250), (0, 255, 0), 2)
cv2.putText(img, 'OpenCV Test', (70, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

# Display and save test
cv2.imshow('OpenCV Test Window', img)
cv2.waitKey(3000)
cv2.destroyAllWindows()
cv2.imwrite('/tmp/opencv_test.jpg', img)
print("Test completed successfully!")

Camera access verification:

import cv2

cap = cv2.VideoCapture(0)
if cap.isOpened():
    print("Camera access: SUCCESSFUL")
    ret, frame = cap.read()
    if ret:
        print(f"Frame shape: {frame.shape}")
    cap.release()
else:
    print("Camera access: FAILED")

Performance benchmarking helps verify optimization effectiveness:

import cv2
import numpy as np
import time

# Create test data
img = np.random.randint(0, 255, (1000, 1000, 3), dtype=np.uint8)

# Benchmark basic operations
start_time = time.time()
for _ in range(100):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (15, 15), 0)
    edges = cv2.Canny(blur, 50, 150)

end_time = time.time()
print(f"100 iterations completed in {end_time - start_time:.2f} seconds")

Troubleshooting Common Installation Issues

pip Installation Problems

Package conflict resolution addresses multiple OpenCV installation issues:

pip3 uninstall opencv-python opencv-contrib-python opencv-python-headless
pip3 cache purge
pip3 install opencv-contrib-python

Virtual environment isolation prevents system-wide conflicts:

python3 -m venv --clear opencv_fresh
source opencv_fresh/bin/activate
pip3 install --upgrade pip
pip3 install opencv-contrib-python

NumPy version compatibility issues require specific version matching:

pip3 install numpy==1.21.0
pip3 install opencv-python==4.5.3.56

Dependency resolution for older systems:

pip3 install --only-binary=all opencv-contrib-python

Source Compilation Issues

CMake configuration failures often indicate missing dependencies:

# Install missing development packages
sudo apt install -y libgtk-3-dev libavcodec-dev libavformat-dev
# Re-run CMake with verbose output
cmake -D CMAKE_BUILD_TYPE=RELEASE .. --debug-output

Memory limitations during compilation require build optimization:

# Limit parallel jobs to prevent memory exhaustion
make -j2  # Use only 2 cores instead of all available
# Monitor memory usage during compilation

Python binding compilation problems:

# Explicitly specify Python paths
cmake -D PYTHON3_EXECUTABLE=/usr/bin/python3 \
      -D PYTHON3_INCLUDE_DIR=/usr/include/python3.9 \
      -D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.9.so \
      ..

Permission and installation path issues:

# Install to user directory instead of system-wide
cmake -D CMAKE_INSTALL_PREFIX=$HOME/.local ..
make install  # No sudo required for user installation

Library conflict resolution:

# Remove conflicting system packages
sudo apt remove libopencv-dev python3-opencv
# Clean build directory and restart
rm -rf build && mkdir build && cd build

Performance Optimization and Advanced Configuration

Optimization Settings

CPU-specific optimizations maximize performance on your hardware:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
      -D CMAKE_CXX_FLAGS="-O3 -march=native -mtune=native" \
      -D WITH_TBB=ON \
      -D BUILD_TBB=ON \
      ..

GPU acceleration configuration enables CUDA support for compatible systems:

cmake -D WITH_CUDA=ON \
      -D CUDA_ARCH_BIN="6.0 6.1 7.0 7.5 8.0 8.6" \
      -D CUDA_ARCH_PTX="" \
      -D WITH_CUBLAS=ON \
      -D WITH_CUFFT=ON \
      ..

Memory optimization strategies improve performance on resource-constrained systems:

cmake -D BUILD_PERF_TESTS=OFF \
      -D BUILD_TESTS=OFF \
      -D BUILD_DOCS=OFF \
      -D BUILD_EXAMPLES=OFF \
      ..

Integration with Development Environments

IDE configuration for optimal development experience requires proper include paths:

For Visual Studio Code, create .vscode/c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/local/include/opencv4"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17"
        }
    ]
}

Jupyter Notebook integration enables interactive computer vision development:

pip3 install jupyter matplotlib
jupyter notebook

Version management allows multiple OpenCV installations:

# Create environment-specific installations
python3 -m venv opencv_4_8
source opencv_4_8/bin/activate
pip3 install opencv-contrib-python==4.8.0.74

Congratulations! You have successfully installed OpenCV. Thanks for using this tutorial to install the latest version of OpenCV on the Linux Mint 22 system. For additional help or useful information, we recommend you check the official OpenCV website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button