Install OpenCV on Ubuntu 22.04 with Easy Steps – OrcaCore

Posted on

Install OpenCV on Ubuntu 22.04 with Easy Steps - OrcaCore

Install OpenCV on Ubuntu 22.04 with Easy Steps – OrcaCore

This guide, brought to you by Orcacore, will walk you through the process of installing Install OpenCV on Ubuntu 22.04 from both the Ubuntu repository and from source. OpenCV, which stands for Open Source Computer Vision, is a powerful and versatile library extensively used for image processing and computer vision tasks.

Essentially, it’s a vast open-source library catering to computer vision applications, particularly those driven by Artificial Intelligence or Machine Learning algorithms. It’s crucial for tasks that necessitate real-time image processing, making it increasingly significant in contemporary systems. OpenCV enables the processing of images and videos to detect objects, faces, and even handwriting.

To successfully complete this guide for Install OpenCV on Ubuntu 22.04, ensure you’re logged into your server as a non-root user with sudo privileges. If needed, refer to our guide on Initial Server Setup with Ubuntu 22.04 for assistance.

Install OpenCV from Ubuntu Repository

The simplest method to install OpenCV Python is directly from the Ubuntu repository. Begin by updating your local package index:

sudo apt update

Next, install OpenCV Python using the following command:

sudo apt install python3-opencv libopencv-dev

This command will install all the necessary packages required to run OpenCV.

Note: If you need OpenCV with Python 2 bindings, install the python-opencv package instead. However, Python 2 is deprecated, so using Python 3 is strongly recommended.

Verify your installation using the following command:

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

Install OpenCV from Source on Ubuntu 22.04

Installing OpenCV from source offers greater control and optimization for your specific system. It’s generally the recommended approach. This section provides a step-by-step guide.

First, update your local package index:

sudo apt update

Then, install the required dependencies:

sudo apt install git cmake gcc g++ python3-dev python3-numpy libavcodec-dev libavformat-dev libswscale-dev libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev libgtk2.0-dev libgtk-3-dev -y

Now, create a directory for OpenCV Python on Ubuntu 22.04 and navigate into it:

sudo mkdir ~/opencv_build && sudo cd ~/opencv_build

Clone OpenCV Repositories

Clone the OpenCV and OpenCV contrib repositories using the following commands:

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

Once the download is complete, create a temporary build directory within the OpenCV directory and switch to it:

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

Compile and Build OpenCV

Set up the OpenCV build using CMake:

sudo cmake ../

The output will resemble the following:

Now, initiate the compilation process:

make -j2

Adjust the -j flag according to the number of cores in your processor. Use the nproc command to determine the number of cores.

This compilation process may take several minutes or longer to complete.

The output will resemble the following:

Finally, install OpenCV using the following command:

sudo make install

Verify the successful installation:

python3 -c "import cv2; print(cv2.__version__)"
**Output**
4.7.0-dev

Congratulations! You have successfully Install OpenCV on Ubuntu 22.04.

Conclusion

This guide has demonstrated how to Install OpenCV on Ubuntu 22.04 from both the Ubuntu repository and from source. Choosing the right method depends on your needs and desired level of control.

Hope you enjoy it. You may also interested in these articles:

Set up SFTP Server on Ubuntu 22.04

Install Monit Manager on Ubuntu 22.04

Install ProFTPD Ubuntu 22.04

Install Chromium Browser Ubuntu 22.04

Okular Document Viewer Install Ubuntu 22.04

Clang LLVM Setup For Ubuntu 22.04

Alternative Installation Methods for OpenCV on Ubuntu 22.04

While the guide outlines installation via the Ubuntu repository and building from source, two other methods can be employed to Install OpenCV on Ubuntu 22.04: using pip and using a Docker container. Each offers unique advantages and disadvantages.

1. Installing OpenCV with pip

pip is the package installer for Python. It allows you to easily install and manage Python packages, including OpenCV. This method is generally simpler than building from source, but it may not offer the same level of optimization or access to the very latest features. It’s also dependent on having the correct dependencies installed system-wide.

Explanation:

pip retrieves pre-built OpenCV packages from the Python Package Index (PyPI). These packages are compiled for common architectures and include necessary bindings. It handles the dependency management, making the installation process relatively straightforward. However, the pip version might lag behind the absolute latest release available by compiling from source. This approach is ideal for quick setups and scenarios where bleeding-edge performance isn’t crucial.

Steps:

  1. Update pip: It’s always good practice to update pip before installing any package.

    python3 -m pip install --upgrade pip
  2. Install OpenCV: Use pip to install OpenCV.

    pip3 install opencv-python
  3. Verify Installation: Similar to the other methods, verify the installation.

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

Code Example:

This method doesn’t require a separate code example beyond the installation and verification steps. The core OpenCV usage remains the same regardless of the installation method. The import cv2 statement within your Python script will leverage the opencv-python package installed via pip.

Advantages:

  • Simple and quick installation.
  • Automatically handles dependencies.

Disadvantages:

  • May not be the latest version.
  • Less control over build options and optimization.
  • Relies on pre-built binaries which might not be perfectly optimized for your specific hardware.

2. Using Docker to Run OpenCV

Docker provides a containerization platform that allows you to package an application and its dependencies into a standardized unit for software development. This ensures consistent execution across different environments. Using Docker is an excellent approach for Install OpenCV on Ubuntu 22.04 while maintaining isolation and reproducibility.

Explanation:

Docker creates isolated environments called containers. Within a container, you can install OpenCV and all its dependencies without affecting the host system. This eliminates dependency conflicts and ensures that the OpenCV environment is consistent regardless of the underlying operating system. This is especially useful when deploying OpenCV applications across different servers or collaborating with others who may have different system configurations.

Steps:

  1. Install Docker: If you don’t have Docker installed, follow the instructions on the official Docker website: https://docs.docker.com/engine/install/ubuntu/

  2. Create a Dockerfile: Create a file named Dockerfile (without any extension) in a directory. Add the following content, which defines the environment for your OpenCV application:

    FROM ubuntu:22.04
    
    RUN apt-get update && apt-get install -y 
        python3 
        python3-pip 
        python3-opencv 
        libopencv-dev 
        && rm -rf /var/lib/apt/lists/*
    
    WORKDIR /app
    
    COPY . /app
    
    CMD ["python3", "your_script.py"] # Replace your_script.py with your actual Python file
  3. Build the Docker Image: Navigate to the directory containing the Dockerfile and run the following command to build the Docker image:

    docker build -t opencv-app .
  4. Run the Docker Container: Run the Docker image to create a container:

    docker run -it --rm -v $(pwd):/app opencv-app
    • -it: Allocates a pseudo-TTY and keeps STDIN open, allowing interactive sessions.
    • --rm: Automatically removes the container when it exits.
    • -v $(pwd):/app: Mounts the current directory as a volume inside the container, so you can access your code from within the container.
    • opencv-app: The name of the image you built in the previous step.

Code Example:

Create a simple Python script named your_script.py in the same directory as the Dockerfile:

import cv2

print("OpenCV version:", cv2.__version__)

# Example: Read and display an image (replace 'image.jpg' with your image)
try:
    img = cv2.imread("image.jpg")
    if img is not None:
        cv2.imshow("Image", img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    else:
        print("Could not read image. Ensure 'image.jpg' exists and is a valid image file.")
except Exception as e:
    print(f"An error occurred: {e}")

Note: Make sure you have an image file named image.jpg in the same directory or adjust the path in the script accordingly.

Advantages:

  • Isolated environment, preventing dependency conflicts.
  • Reproducible builds across different systems.
  • Easy deployment.

Disadvantages:

  • Requires familiarity with Docker.
  • Slightly more overhead compared to native installation.
  • Larger disk space usage due to the image.

By providing these alternative methods, you can choose the approach that best suits your project’s requirements and your comfort level. Remember to always verify your installation after using any method. The process to Install OpenCV on Ubuntu 22.04 can be adapted to suit various needs and scenarios.