Title: How to install OpenCV 4 on Ubuntu - PyImageSearch

URL Source: https://pyimagesearch.com/2018/08/15/how-to-install-opencv-4-on-ubuntu/

Published Time: 2018-08-15T14:00:02+00:00

Markdown Content:
![Image 1](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20338'%3E%3C/svg%3E)

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.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

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.

Let’s begin.

### 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](https://github.com/opencv/opencv) and [opencv\_contrib](https://github.com/opencv/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 `opencv` and `opencv_contrib` code:

$ 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](https://opencv.org/opencv-4-0-0.html)_ _is released and I have updated the respective `wget` URLs._

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.

Now that `opencv` and `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.

If you would like more information about Python virtual environments take a look at this [article on RealPython](https://realpython.com/blog/python/python-virtual-environments-a-primer/) or read the first half of the [this blog post on PyImageSearch](https://pyimagesearch.com/2016/05/02/accessing-rpi-gpio-and-gpio-zero-with-opencv-python/).

_**Note:** My preferred way to work with Python virtual environment is via the `virtualenv` and `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 `virtualenv` and `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 `~/.bashrc` file.

Using a terminal text editor such as `vi` /`vim` or `nano` , add the following lines to your `~/.bashrc` :

\# 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 `~/.bashrc` file:

$ 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 `cv` .

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`
*   `py3cv3`
*   `py2cv2`
*   etc.

Here my `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` command:

$ workon cv

[![Image 3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20400%20121'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/06/install-opencv-ubuntu-virtualenv.png)

**Figure 1:** We use the `workon` command to activate our `cv` virtual environment on Ubuntu prior to installing NumPy and OpenCV 4.

#### Install NumPy

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 `build` directory:

$ 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 `OPENCV_EXTRA_MODULES_PATH` and `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:

[![Image 4](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20451'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/06/install-opencv-ubuntu-cmake.jpg)

**Figure 2:** It is critical to inspect your CMake output when installing OpenCV 4 on Ubuntu prior to kicking off the compile process.

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.

[![Image 5](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20448'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/08/opencv4-ubuntu-nonfree.png)

**Figure 3:** Be sure to check the CMake output to ensure that the “Non-free algorithms” will be installed.

#### 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:

[![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20449'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2018/06/install-opencv4-ubuntu-makecomplete.jpg)

**Figure 4:** When compiling OpenCV 4 for Ubuntu, once the `make` output reaches 100% we can move on.

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 `cv2.so` :

$ 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
----------------------------------------------------

[![Image 7](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20531%20317'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/09/ball-tracking-animated-02.gif)

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**](https://pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/).

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 `mkvirtualenv`  or `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:**

1.  First, ensure you have installed `virtualenv`  and `virtualenvwrapper`  properly using the `pip`  package manager. Verify by running `pip freeze` , and ensure that you see both `virtualenv`  and `virtualenvwrapper`  in the list of installed packages.
2.  Your `~/.bashrc`  file may have mistakes. View the contents of your `~/.bashrc`  file to see the proper `export`  and `source`  commands are present (check **Step #3** for the commands that should be appended to `~/.bashrc` ).
3.  You might have forgotten to `source`  your `~/.bashrc` . Make sure you run `source ~/.bashrc`  after editing it to ensure you have access to the `mkvirtualenv`  and `workon`  commands.

_**Q.**_ When I open a new terminal, logout, or reboot my Ubuntu system, I cannot execute the `mkvirtualenv`  or `workon`  commands.

_**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:

1.  Ensure your `cv`  virtual environment is active by using the `workon cv`  command. If this command gives you an error, then verify that `virtualenv`  and `virtualenvwrapper`  are properly installed.
2.  Try investigating the contents of the `site-packages`  directory in your `cv`  virtual environment. You can find the `site-packages`  directory in `~/.virtualenvs/cv/lib/python3.5/site-packages/`  depending on your Python version. Make sure (1) there is a `cv2`  directory in the `site-packages`  directory and (2) it’s properly sym-linked to a valid directory.
3.  Be sure to check the `site-packages`  (and even `dist-packages` ) directory for the system install of Python located in `/usr/local/python/` , respectively. Ideally, you should have a `cv2`  directory there.
4.  As a last resort, check in your `build/lib`  directory of your OpenCV build. There _should_ be a `cv2`  directory there (if both `cmake`  and `make`  executed without error). If the `cv2.so`  file is not present, _manually copy it_ into both the system `site-packages`  directory as well as the `site-packages`  directory for the `cv`  virtual environment.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
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.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

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!**

![Image 8](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### 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!