Computer vision technology powers many modern applications, from image editors to facial scanners. OpenCV (Open Source Computer Vision Library) is a popular open source library used for image processing and computer vision tasks. It is written in C++ but works with Python and other popular programming languages.
This guide will show you how to install OpenCV on Ubuntu 18.04. We will cover two ways: a fast install using pip, and a build from source for advanced users.
If you are developing a Python application, using the package manager pip is the easiest path.
Open your terminal and run the install command. If you do not need graphical display features on a headless server, install this package:
bashpip3 install opencv-python-headless
If you are working on a desktop system and need to display windows and output images to the screen, install this package instead:
bashpip3 install opencv-python
Verify the installation by running Python:
pythonimport cv2print(cv2.__version__)
The terminal will print the installed version number. This method is fast but does not let you customize build modules.
Building from source is recommended if you need hardware optimization or extra modules that are not included in the standard package.
First, update your package lists and install the build tools:
bashsudo apt updatesudo apt install build-essential cmake git pkg-config
Install the image and video libraries required to decode files:
bashsudo apt install libjpeg-dev libtiff-dev libpng-dev \ libavcodec-dev libavformat-dev libswscale-dev \ libv4l-dev libxvidcore-dev libx264-dev
Install the window manager and mathematical acceleration packages:
bashsudo apt install libgtk-3-dev libatlas-base-dev gfortran python3-dev
Download the OpenCV source repositories from GitHub:
bashgit clone https://github.com/opencv/opencv.gitgit clone https://github.com/opencv/opencv_contrib.git
Create a build folder and configure the installation with CMake:
bashmkdir -p opencv/build && cd opencv/buildcmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \ -D BUILD_EXAMPLES=OFF ..
Compile the code using all available CPU cores:
bashmake -j$(nproc)sudo make installsudo ldconfig
Test the build by importing the module:
bashpython3 -c "import cv2; print(cv2.__version__)"
You have installed the OpenCV library on your system. Using pip is perfect for rapid development, while building from source is best for high-performance production workloads. Leave a comment below if you run into any compilation errors.