Title: Install OpenCV 3 and Python 2.7+ on Ubuntu - PyimageSearch

URL Source: https://pyimagesearch.com/2015/06/22/install-opencv-3-0-and-python-2-7-on-ubuntu/

Published Time: 2015-06-22T14:00:38+00:00

Markdown Content:
[![Image 1: opencv3_handwriting_reco](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20480'%3E%3C/svg%3E)](https://pyimagesearch.com/practical-python-opencv/?src=opencv3-install)

Last week we kicked-off the OpenCV 3.0 install fest by detailing [how to install OpenCV 3.0 and Python 2.7+ on the OSX platform](https://pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/).

Today we are going to continue the OpenCV 3.0 install instruction series by moving over to the Ubuntu operating system.

In the remainder of the post I will provide instructions on how to configure and install OpenCV 3.0 and Python 2.7+ on Ubuntu. I have _personally tested_ these instructions on Ubuntu 14.04, but they should pretty much work on any Debian-based operating system.

**A quick note before we get started:** Yes, OpenCV 3.0 is indeed compatible with Python 3+. However, the install instructions are slightly different between Python 2.7+ and Python 3+. In an effort to keep each article self-contained and easy to follow, I am creating separate OpenCV 3.0 install tutorials for Python 2.7 and Python 3+. If you would like to use OpenCV 3.0 and Python 3+ on your Ubuntu system, please keep an eye on this blog — I will be posting OpenCV 3.0 and Python 3+ install instructions later this month. But for the time being, let’s stick with Python 2.7.

**UPDATE:** The tutorial you are reading now covers how to install OpenCV 3.0 with Python 2.7+ bindings on _**Ubuntu 14.04**_. This tutorial _**still works perfectly**_, but if you want to install OpenCV on the newer _**Ubuntu 16.04**_ with OpenCV 3.1 and Python 2.7 (or Python 3.5) bindings, please use this freshly updated tutorial:

[https://pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/](https://pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/)

* * *

This is the second article in the OpenCV 3.0 install-fest series. Last week we covered how to [install OpenCV 3.0 and Python 2.7+ on OSX](https://pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/). Today we are going to perform the same OpenCV 3.0 and Python 2.7 installation, only on the Ubuntu operating system. In general, you should find installing OpenCV 3.0 and Python 2.7+ on Ubuntu much easier than installing on OSX.

Step 1:
-------

Open up a terminal and update the `apt-get` package manager followed by upgrading any pre-installed packages:

$ sudo apt-get update
$ sudo apt-get upgrade

Step 2:
-------

Now we need to install our developer tools:

$ sudo apt-get install build-essential cmake git pkg-config

The `pkg-config` is likely already installed, but be sure to include it just in case. We’ll be using `git` to pull down the OpenCV repositories from GitHub. The `cmake` package is used to configure our build.

Step 3:
-------

OpenCV needs to be able to load various image file formats from disk, including JPEG, PNG, TIFF, etc. In order to load these image formats from disk, we’ll need our image I/O packages:

$ sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-dev

Step 4:
-------

At this point, we have the ability to load a given image off of disk. But how do we display the actual image to our screen? The answer is the GTK development library, which the `highgui` module of OpenCV depends on to guild Graphical User Interfaces (GUIs):

$ sudo apt-get install libgtk2.0-dev

Step 5:
-------

We can load images using OpenCV, but what about processing video streams and accessing individual frames? We’ve got that covered here:

$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev

Step 6:
-------

Install libraries that are used to optimize various routines inside of OpenCV:

$ sudo apt-get install libatlas-base-dev gfortran

Step 7:
-------

Install `pip` , a Python package manager:

$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

Step 8:
-------

Install [virtualenv](https://virtualenv.pypa.io/en/latest/) and [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/). These two packages allow us to create **_separate Python environments_** for each project we are working on. While installing `virtualenv` and `virtualenvwrapper` is **_not a_ _requirement_** to get OpenCV 3.0 and Python 2.7+ up and running on your Ubuntu system, **_I highly recommend it_** and the rest of this tutorial _**will assume you have them installed!**_

$ sudo pip install virtualenv virtualenvwrapper
$ sudo rm -rf ~/.cache/pip

Now that we have `virtualenv` and `virtualenvwrapper` installed, we need to update our `~/.bashrc` file:

\# virtualenv and virtualenvwrapper
export WORKON\_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

This quick update will ensure that both `virtualenv` and `virtualenvwrapper` are loaded each time you login.

To make the changes to our `~/.bashrc` file take effect, you can either (1) logout and log back in, (2) close your current terminal window and open a new one, or preferably, (3) reload the contents of your `~/.bashrc` file:

$ source ~/.bashrc

Lastly, we can create our `cv` virtual environment where we’ll be doing our computer vision development and OpenCV 3.0 + Python 2.7+ installation:

$ mkvirtualenv cv

Step 9:
-------

As I mentioned above, this tutorial covers how to install OpenCV 3.0 and Python 2.7+ (I’ll have a OpenCV 3.0 + Python 3 tutorial available later this month), so we’ll need to install our Python 2.7 development tools:

$ sudo apt-get install python2.7-dev

Since OpenCV represents images as multi-dimensional NumPy arrays, we better install [NumPy](http://www.numpy.org/) into our `cv` virtual environment. We also install [imutils](https://github.com/jrosebr1/imutils) — my package of convenience functions:

$ pip install numpy
$ pip install imutils

Step 10:
--------

Our environment is now all setup — we can proceed to change to our home directory, [pull down OpenCV from GitHub](https://github.com/Itseez/opencv), and checkout the `3.0.0` version:

$ cd ~
$ git clone https://github.com/Itseez/opencv.git
$ cd opencv
$ git checkout 3.0.0

_**Update (3 January 2016):** You can replace the `3.0.0` version with whatever the current release is (as of right now, it’s `3.1.0` ). Be sure to check [OpenCV.org](http://opencv.org/category/news) for information on the latest release._

As I mentioned [last week](https://pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/), we also need the [opencv\_contrib repo](https://github.com/itseez/opencv_contrib) as well. Without this repository, we won’t have access to standard keypoint detectors and local invariant descriptors (such as SIFT, SURF, etc.) that were available in the OpenCV 2.4.X version. We’ll also be missing out on some of the newer OpenCV 3.0 features like text detection in natural images:

$ cd ~
$ git clone https://github.com/Itseez/opencv\_contrib.git
$ cd opencv\_contrib
$ git checkout 3.0.0

Again, make sure that you checkout the _**same version**_ for `opencv_contrib` that you did for `opencv` above, otherwise you could run into compilation errors.

Time to setup the build:

$ cd ~/opencv
$ mkdir build
$ cd build
$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE \\
	-D CMAKE\_INSTALL\_PREFIX=/usr/local \\
	-D INSTALL\_C\_EXAMPLES=ON \\
	-D INSTALL\_PYTHON\_EXAMPLES=ON \\
	-D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib/modules \\
	-D BUILD\_EXAMPLES=ON ..

_**Update (3 January 2016):** In order to build OpenCV `3.1.0` , you need to set `-D INSTALL_C_EXAMPLES=OFF` (rather than `ON` ) in the `cmake` command. There is a bug in the OpenCV v3.1.0 CMake build script that can cause errors if you leave this switch on. Once you set this switch to off, CMake should run without a problem._

Notice how compared to [last week](https://pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/) our CMake command is substantially less verbose and requires less manual tweaking — this is because CMake is able to better automatically tune our install parameters (at least compared to OSX).

Now we can finally compile OpenCV:

$ make -j4

Where you can replace the _4_ with the number of available cores on your processor to speedup the compilation.

Here’s an example of OpenCV 3.0 compiling on my system:

[![Image 2: Figure 1: OpenCV 3.0 with Python 2.7+ support compiling on my Ubuntu 14.04 system.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20480'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/ubuntu_compiling_opencv3.png)

**Figure 1:** OpenCV 3.0 with Python 2.7+ support compiling on my Ubuntu 14.04 system.

Assuming that OpenCV compiled without error, you can now install it on your Ubuntu system:

$ sudo make install
$ sudo ldconfig

Step 11:
--------

If you’ve reached this step without an error, OpenCV should now be installed in `/usr/local/lib/python2.7/site-packages`

However, our `cv` virtual environment is located in our home directory — thus to use OpenCV within our `cv` environment, we first need to sym-link OpenCV into the `site-packages` directory of the `cv` virtual environment:

$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
$ ln -s /usr/local/lib/python2.7/site-packages/cv2.so cv2.so

Step 12:
--------

**Congratulations! You have successfully installed OpenCV 3.0 with Python 2.7+ bindings on** **your Ubuntu system!**

To confirm your installation, simply ensure that you are in the `cv` virtual environment, followed by importing `cv2` :

$ workon cv
$ python
>>> import cv2
>>> cv2.\_\_version\_\_
'3.0.0'

Here’s an example of demonstrating the OpenCV 3.0 and Python 2.7+ install on my own Ubuntu machine:

[![Image 3: Figure 2: OpenCV 3.0 with Python 2.7+ bindings has been successfully installed on Ubuntu!](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20480'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/ubuntu_opencv3_installed.jpg)

**Figure 2:** OpenCV 3.0 with Python 2.7+ bindings has been successfully installed on Ubuntu!

Step 13:
--------

Now that OpenCV has been configured and installed, let’s build a quick Python script to detect the **_red_** game cartridge in the image named `games.jpg` below:

[![Image 4: Figure 2: Our goal is to detect the red game cartridge (on the right) in this image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20375'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/games.jpg)

**Figure 3:** Our goal is to detect the red game cartridge (on the _right_) in this image.

Open up your favorite editor, create a new file, name it `find_game.py` , and insert the following code:

\# import the necessary packages
import numpy as np
import imutils
import cv2

# load the games image
image = cv2.imread("games.jpg")

# find the red color game in the image
upper = np.array(\[65, 65, 255\])
lower = np.array(\[0, 0, 200\])
mask = cv2.inRange(image, lower, upper)

# find contours in the masked image and keep the largest one
cnts = cv2.findContours(mask.copy(), cv2.RETR\_EXTERNAL,
	cv2.CHAIN\_APPROX\_SIMPLE)
cnts = imutils.grab\_contours(cnts)
c = max(cnts, key=cv2.contourArea)

# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.05 \* peri, True)

# draw a green bounding box surrounding the red game
cv2.drawContours(image, \[approx\], -1, (0, 255, 0), 4)
cv2.imshow("Image", image)
cv2.waitKey(0)

You’ll also need to **[download the games.jpg image](https://pyimagesearch.com/wp-content/uploads/2015/06/games.jpg)** and place it in the same directory as your `find_game.py` file. Once the `games.jpg` file has been downloaded, you can execute the script via:

$ python find\_game.py

Assuming that you have downloaded the `games.jpg` image and placed it in the same directory as our `find_game.py` script, you should see the following output:

[![Image 5: Figure 4: We have successfully detected the red game cartridge in the image!](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20480'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/ubuntu_found_game.jpg)

**Figure 4:** We have successfully detected the red game cartridge in the image!

Notice how our script was able to successfully detect the red game cartridge in the right portion of the image, followed by drawing a green bounding box surrounding it.

Obviously this isn’t the most exciting example in the world — but it has demonstrated that we have OpenCV 3.0 with Python 2.7+ bindings up and running on our Ubuntu system!

So, what’s next?
----------------

Congrats! You have a brand new, fresh install of OpenCV on your Ubuntu system — and I’m sure you’re just itching to leverage your new install to build some awesome computer vision apps.

But I’m also willing to bet that _you’re just getting started learning computer vision and OpenCV_, and you’re probably feeling a bit confused and overwhelmed on where exactly to start.

Personally, I’m a big fan of **learning by example**, so a good first step would be to read [this blog post](https://pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/) on accessing your webcam with OpenCV. This tutorial details the _exact steps_ you need to take to (1) capture photos from your webcam and (2) access the raw video stream.

And if you’re _really interested_ in leveling-up your computer vision skills, you should definitely check out my book, [_Practical Python and OpenCV + Case Studies_](https://pyimagesearch.com/practical-python-opencv/). My book not only _covers the basics of computer vision and image processing_, but also teaches you how to solve real world computer vision problems including **_face detection in images and video streams_**, **_object tracking in video_**, and **_handwriting recognition._**

[![Image 6: raspberry_pi_in_post](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20370%20247'%3E%3C/svg%3E)](https://pyimagesearch.com/practical-python-opencv/)

So let’s put your fresh install of OpenCV on your Ubuntu system to good use — [**_just click here_**](https://pyimagesearch.com/practical-python-opencv/) _**to learn more about the real-world projects you can solve using your new OpenCV install + Practical Python and OpenCV .**_

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

To celebrate the OpenCV 3.0 release, I am working my way through OpenCV 3.0 and Python 2.7/Python 3.4 installation instructions on **_OSX_**, **_Ubuntu,_** and the **_Raspberry Pi_**.

Last week I covered how to [install OpenCV 3.0 and Python 2.7+ on OSX](https://pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/).

And today we covered how to install OpenCV 3.0 with Python 2.7 bindings on Ubuntu. I have _personally_ tested these instructions on my own Ubuntu 14.04 machine, but they should work on any Debian-based system.

Next week we’ll continue the install-fest and hop back to OSX — this time installing **_OpenCV 3.0 and Python 3!_**

This will be the first time we’ve used Python 3 on the PyImageSearch blog, so you won’t want to miss it!

And please consider subscribing to the PyImageSearch Newsletter by entering your email address in the form below. As we work through the OpenCV install-fest, I’ll be sending out updates as each new OpenCV 3.0 + Python install tutorial is released!

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

#### Join the PyImageSearch Newsletter and Grab My FREE 17-page Resource Guide PDF

Enter your email address below to **join the PyImageSearch Newsletter** and **download my FREE 17-page Resource Guide PDF** on Computer Vision, OpenCV, and Deep Learning.