In this tutorial you will learn how to install OpenCV 4 on your Ubuntu system.
OpenCV 4 has been officially released as of 20 November 2018!
So, why bother installing OpenCV 4?
You may want to consider installing OpenCV 4 for further optimizations, C++11 support, more compact modules, and many improvements to the Deep Neural Network (DNN) module.
Don’t feel the need to upgrade immediately — but do keep these instructions in mind if and when you’re ready to make the switch to OpenCV 4.
How to install OpenCV 4 on Ubuntu
In this blog post, I’ll walk you through the six steps to install OpenCV 4 on your Ubuntu system.
I’ll also cover some Frequently Asked Questions (FAQs) that will help you troubleshoot in the event you run into an error message. I strongly urge you to read the FAQ prior to submitting a comment on this post.
Before we begin, you probably have two burning questions:
1. Which version of Ubuntu OS should I use with OpenCV 4?
Today I’ll be installing OpenCV 4 on Ubuntu 18.04. I’ve also tested these instructions with Ubuntu 16.04 as well.
If you intend on using this machine for deep learning I might suggest you use Ubuntu 16.04 as the GPU drivers are more mature. If you intend on using this machine just for OpenCV and other computer vision tasks, Ubuntu 18.04 is perfectly fine.
2. Should I use Python 2.7 or Python 3 with OpenCV 4?
Python 3 has become the standard and I highly recommend you install Python 3 with OpenCV 4.
That being said, if you’re making the conscious choice to use Python 2.7, you can of course follow these instructions, just be sure you take care to install Python 2.7 development headers and libraries as well as specifying Python 2.7 when creating your virtual environment. Everything else will be the same. Refer to the FAQs down below if you need pointers for Python 2.7.
Step #1: Install OpenCV 4 dependencies on Ubuntu
I’ll be using Ubuntu 18.04 to install OpenCV 4 with Python 3 bindings on my machine.
To get the OpenCV 4 install party started, fire up your Ubuntu machine and open a terminal. Alternatively, you may SSH into the box for the install portion.
From there, let’s update our system:
$ sudo apt-get update $ sudo apt-get upgrade
And then install developer tools:
$ sudo apt-get install build-essential cmake unzip pkg-config
Next, let’s install a handful of image and video I/O libraries.
$ sudo apt-get install libjpeg-dev libpng-dev libtiff-dev $ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev $ sudo apt-get install libxvidcore-dev libx264-dev
These libraries enable us to load image from disk as well as read video files.
From there, let’s install GTK for our GUI backend:
$ sudo apt-get install libgtk-3-dev
Followed by installing two packages which contain mathematical optimizations for OpenCV:
$ sudo apt-get install libatlas-base-dev gfortran
And finally, let’s install the Python 3 development headers:
$ sudo apt-get install python3-dev
Once you have all of these prerequisites installed you can move on to the next step.
Step #2: Download OpenCV 4
Our next step is to download OpenCV.
Let’s navigate to our home folder and download both opencv and opencv_contrib. The contrib repo contains extra modules and functions which we frequently use here on the PyImageSearch blog. You should be installing the OpenCV library with the additional contrib modules as well.
When you’re ready, just follow along to download both the
$ cd ~ $ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.0.0.zip $ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.0.0.zip
Update 2018-11-26: OpenCV 4.0.0 is released and I have updated the respective
From there, let’s unzip the archives:
$ unzip opencv.zip $ unzip opencv_contrib.zip
I also like to rename the directories:
$ mv opencv-4.0.0 opencv $ mv opencv_contrib-4.0.0 opencv_contrib
If you skip renaming the directories, don’t forget to update the CMake paths.
opencv_contrib are downloaded and ready to go, let’s set up our environment.
Step #3: Configure your Python 3 virtual environment for OpenCV 4
Let’s install pip, a Python Package Manager.
To install pip, simply enter the following in your terminal:
$ wget https://bootstrap.pypa.io/get-pip.py $ sudo python3 get-pip.py
Make use of virtual environments for Python development
Python virtual environments allow you to work on your Python projects in isolation. They are a best practice for Python development.
For example, maybe you have a Python + OpenCV project that requires an older version of scikit-learn (v0.14), but you want to keep using the latest version of scikit-learn (0.19) for all of your newer projects.
Using virtual environments, you could handle these two software version dependencies separately, something that is not possible using just the system install of Python.
Note: My preferred way to work with Python virtual environment is via the
virtualenvwrapper packages; however if you are more familiar with conda or PyEnv, feel free to use them and skip this part.
Let’s go ahead and install
virtualenvwrapper — these packages allow us to create and manage Python virtual environments:
$ sudo pip install virtualenv virtualenvwrapper $ sudo rm -rf ~/get-pip.py ~/.cache/pip
To finish the install of these tools, we need to update our
Using a terminal text editor such as
nano , add the following lines to your
# virtualenv and virtualenvwrapper export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 source /usr/local/bin/virtualenvwrapper.sh
Alternatively, you can append the lines directly via bash commands:
$ echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.bashrc $ echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bashrc $ echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.bashrc $ echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.bashrc
Next, source the
$ source ~/.bashrc
Create a virtual environment to hold OpenCV 4 and additional packages
Now we’re at the point where we can create your OpenCV 4 + Python 3 virtual environment:
$ mkvirtualenv cv -p python3
This command simply creates a Python 3 virtual environment named
You can (and should) name your environment(s) whatever you’d like — I like to keep them short and sweet while also providing enough information so I’ll remember what they are for. For example, I like to name my environments like this:
py3cv4 virtual environment can be used for Python 3 + OpenCV 4. My
py3cv3 virtual environment is used for Python 3 and OpenCV 3. And my
py2cv2 environment can be used to test legacy Python 2.7 + OpenCV 2.4 code. These virtual environment names are easy to remember and allow me to switch between OpenCV + Python versions (nearly) seamlessly.
Let’s verify that we’re in the
cv environment by using the
$ workon cv
The first package and only Python prerequisite we’ll install is NumPy:
$ pip install numpy
We can now prepare OpenCV 4 for compilation on our Ubuntu machine.
Step #4: CMake and compile OpenCV 4 for Ubuntu
For this step, we’re going to setup our compile with CMake followed by running
make to actually compile OpenCV. This is the most time-consuming step of today’s blog post.
Navigate back to your OpenCV repo and create + enter a
$ cd ~/opencv $ mkdir build $ cd build
Run CMake for OpenCV 4
Now let’s run CMake to configure the OpenCV 4 build:
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D INSTALL_C_EXAMPLES=OFF \ -D OPENCV_ENABLE_NONFREE=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python \ -D BUILD_EXAMPLES=ON ..
Update 2018-11-26: Notice the
-D OPENCV_ENABLE_NONFREE=ON flag. Setting this flag with OpenCV 4 ensures that you’ll have access to SIFT/SURF and other patented algorithms.
Be sure to update the above command to use the correct
PYTHON_EXECUTABLE in your virtual environment that you’re working in. If you’re using the same directory structure Python virtual environment names these paths should not need to be updated.
Once CMake finishes, it’s important that you inspect the output. Your output should look similar to mine below:
Take a second now to ensure that the
Interpreter points to the correct Python 3 binary. Also check that
numpy points to our NumPy package which is installed inside the virtual environment.
Compile OpenCV 4
Now we’re ready to compile OpenCV 4:
$ make -j4
Note: In the
make command above, the
-j4 argument specifies that I have 4 cores for compilation. Most systems will have 2, 4, or 8 cores. You should update the command to use the number of cores on your processor for a faster compile. If you encounter compilation failures, you could try compiling with 1 core to eliminate race conditions by skipping the optional argument altogether.
Here you can see OpenCV 4 has compiled without any errors:
And from there, let’s install OpenCV 4 with two additional commands:
$ sudo make install $ sudo ldconfig
Step #5: Link OpenCV 4 into your Python 3 virtual environment
Before we make a symbolic link to link OpenCV 4 into our Python virtual environment, let’s determine our Python version:
$ workon cv $ python --version Python 3.5
Using the Python version, we can easily navigate to the correct
site-packages directory next (although I do recommend tab-completion in the terminal).
Update 2018-12-20: The following paths have been updated. Previous versions of OpenCV installed the bindings in a different location (
/usr/local/lib/python3.5/site-packages ), so be sure to take a look at the paths below carefully.
At this point, your Python 3 bindings for OpenCV should reside in the following folder:
$ ls /usr/local/python/cv2/python-3.5 cv2.cpython-35m-x86_64-linux-gnu.so
Let’s rename them to simply
$ cd /usr/local/python/cv2/python-3.5 $ sudo mv cv2.cpython-35m-x86_64-linux-gnu.so cv2.so
Pro-tip: If you are installing OpenCV 3 and OpenCV 4 alongside each other, instead of renaming the file to
cv2.so , you might consider naming it
cv2.opencv4.0.0.so and then in the next sub-step sym-link appropriately from that file to
cv2.so as well.
Our last sub-step is to sym-link our OpenCV
cv2.so bindings into our
cv virtual environment:
$ cd ~/.virtualenvs/cv/lib/python3.5/site-packages/ $ ln -s /usr/local/python/cv2/python-3.5/cv2.so cv2.so
Step #6: Test your OpenCV 4 install on Ubuntu
Let’s do a quick sanity test to see if OpenCV is ready to go.
Open a terminal and perform the following:
$ workon cv $ python >>> import cv2 >>> cv2.__version__ '4.0.0' >>> quit()
The first command activates our virtual environment. Then we run the Python interpreter associated with the environment.
Note: It is not necessary to specify
python3 as Python 3 is the only Python executable in the environment.
If you see that you have version 4.0.0 installed, then a “Congratulations!” is in order. Have a swig of your favorite beer or bourbon and let’s get to something more fun than installing libraries and packages.
Let’s perform object tracking in video with OpenCV 4
I know you’re itching to test out your installation with a practical example. Tracking motion in video is a fun, small project to get you working with OpenCV 4 on your Ubuntu machine.
To get started, scroll to the “Downloads” section of this blog post to download the source code and example video.
From there, install the
imutils library in your fresh virtual environment:
$ workon cv $ pip install imutils
And then navigate to where you stored the zip file and unzip it. For example, you might save it in
~/Downloads and then perform the following steps:
$ cd ~/Downloads $ unzip ball-tracking.zip $ cd ball-tracking
Now we’re ready to start our OpenCV + Python script.
You can execute the script using the following command:
$ python ball_tracking.py --video ball_tracking_example.mp4
Ready to try with your own ball and your webcam? Here’s the command:
$ python ball_tracking.py
At this point, you should see yourself. Bring the ball into the frame and move it around to see the red tracking trail!
To find out how this object tracking example works, be sure to refer to this blog post.
Troubleshooting and FAQ
Did you encounter an error installing OpenCV 4 on Ubuntu?
Don’t jump ship yet. The first time you install OpenCV, it can be very frustrating and the last thing I want for you to do is to end the learning process here.
I’ve put together a short list of frequently asked questions (FAQs) and I suggest that you familiarize yourself with them.
Q. Can I use Python 2.7?
A. Python 3 is what I suggest for development these days, but I do understand the need for Python 2.7 to work with legacy code.
Starting with Ubuntu 18.04, Python 2.7 isn’t even included. If you’re on Ubuntu 18.04 (or greater) you can still install it manually at the end of Step #1:
$ sudo apt-get install python2.7 python2.7-dev
From there, when you create your virtual environment in Step #3, first install pip for Python 2.7:
$ sudo python2.7 get-pip.py
And then (also in Step #3) when you create your virtual environment, simply use the relevant Python version flag:
$ mkvirtualenv cv -p python2.7
From there everything should be the same.
Q. Why can’t I just pip to install OpenCV 4?
A. There are a number of pip-installable versions of OpenCV available depending on your operating system and architecture. The problem you may run into is that they may be compiled without various optimizations, and image/video I/O support. Use them — but use them at your own risk. This tutorial is meant to give you the full install of OpenCV 4 on Ubuntu while giving you complete control over the compile.
Q. Why can’t I just apt-get install OpenCV?
A. I’d avoid this “solution” at all costs even though it might work. You’ll end up with an older, outdated version of OpenCV on your system. Secondly, apt-get doesn’t play nice with virtual environments and you won’t have control over your compile and build.
Q. When I execute
workon , I encounter a “command not found error”. What should I do?
A. There a number of reasons why you would be seeing this error message, all of come from to Step #3:
- First, ensure you have installed
virtualenvwrapperproperly using the
pippackage manager. Verify by running
pip freeze, and ensure that you see both
virtualenvwrapperin the list of installed packages.
~/.bashrcfile may have mistakes. View the contents of your
~/.bashrcfile to see the proper
sourcecommands are present (check Step #3 for the commands that should be appended to
- You might have forgotten to
~/.bashrc. Make sure you run
source ~/.bashrcafter editing it to ensure you have access to the
Q. When I open a new terminal, logout, or reboot my Ubuntu system, I cannot execute the
A. Refer to #2 from the previous question.
Q. I’m trying to use a patented algorithm such as SURF and I see an exception about the NONFREE option. How can I use patented algorithms?
A. Be sure to refer to Step #4 (CMake command) and Figure 4 where this blog post has been updated to accomodate this change the OpenCV developers made.
Q. When I try to import OpenCV, I encounter this message:
Import Error: No module named cv2 .
A. There are several reasons this could be happening and unfortunately, it is hard to diagnose. I recommend the following suggestions to help diagnose and resolve the error:
- Ensure your
cvvirtual environment is active by using the
workon cvcommand. If this command gives you an error, then verify that
virtualenvwrapperare properly installed.
- Try investigating the contents of the
site-packagesdirectory in your
cvvirtual environment. You can find the
~/.virtualenvs/cv/lib/python3.5/site-packages/depending on your Python version. Make sure (1) there is a
cv2directory in the
site-packagesdirectory and (2) it’s properly sym-linked to a valid directory.
- Be sure to check the
dist-packages) directory for the system install of Python located in
/usr/local/python/, respectively. Ideally, you should have a
- As a last resort, check in your
build/libdirectory of your OpenCV build. There should be a
cv2directory there (if both
makeexecuted without error). If the
cv2.sofile is not present, manually copy it into both the system
site-packagesdirectory as well as the
site-packagesdirectory for the
What's next? We recommend PyImageSearch University.
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 84 courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 84 Certificates of Completion
- ✓ 114+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 536+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Today we learned how to install OpenCV 4 from source on Ubuntu.
Compiling from source allows you to have full control over the install process, including adding any additional optimizations that you may wish to use.
We then tested the installation with a simple ball tracking demo.
Do you run macOS? I’ll be back on Friday with a macOS + OpenCV 4 installation guide so stay tuned!
If you enjoyed today’s installation tutorial and ball tracking demo, be sure to fill out the form below so that you receive updates when new blog posts go live!
Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!