Title: Install OpenCV 3.0 and Python 2.7+ on OSX - PyImageSearch

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

Published Time: 2015-06-15T14:00:54+00:00

Markdown Content:
[![Image 1: face_detection_opencv3](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20375'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/face_detection_opencv3.jpg)

As I mentioned last week, **[OpenCV 3.0 is finally here](https://pyimagesearch.com/2015/06/08/opencv-3-0-released-and-the-coming-changes-to-the-pyimagesearch-blog/)**!

And if you’ve been paying attention to my [Twitter stream](https://twitter.com/PyImageSearch), you may have noticed a bunch of tweets regarding [installing](https://twitter.com/PyImageSearch/status/606904690169683968) [OpenCV](https://twitter.com/PyImageSearch/status/606929470553923584) on [OSX](https://twitter.com/PyImageSearch/status/606875855952822272) and [Ubuntu](https://twitter.com/PyImageSearch/status/606572807573479426) (yep, I’ve been tweeting a lot lately, but that’s just because I’m so excited about the 3.0 release!)

To celebrate OpenCV 3.0, I have decided to perform a series of blog posts that detail how to **_install OpenCV 3.0 on both Python 2.7+_ and _Python 3+_**.

We’ll also be performing these Python 2.7 and Python 3+ installations on a variety of platforms including _**OSX**_, **_Ubuntu_,** and yes, the _**Raspberry Pi**_.

As I’m sure you already know, OpenCV has never been an effortless library to install. It’s not like you can let `pip` or `easy_install` to the heavy-lifting for you. In most cases you’ll be pulling down the repo, installing prerequisites, compiling by hand, and hoping that your installation goes smoothly.

With OpenCV 3.0 it doesn’t get any easier — _and there are definitely some caveats and gotchas that you need to look out for_ (such as the [opencv\_contrib](https://github.com/itseez/opencv_contrib) repository — without it, you’ll be missing out on some important features, such as SIFT, SURF, etc.)

But don’t worry, I’ve got you covered! Just keep following along with the PyImageSearch blog and I promise these tutorials will get you up and running with OpenCV 3.0 in no time.

We’ll go ahead and kick-off our OpenCV 3.0 install fest by installing v3.0 with _**Python 2.7+** **bindings**_ on the **_OSX_** platform.

If you’re an Ubuntu or Raspberry Pi user, be sure to keep an eye on PyImageSearch as I’ll be posting OpenCV 3.0 install instructions for Ubuntu and the Raspberry Pi as well.

**A quick note before we get started:** While OpenCV 3.0 is indeed compatible with Python 3+, most computer vision developers are still using Python 2.7 (since OpenCV 2.4.X is only compatible with Python 2.7). If you’re a Python 3 user and excited to give the bindings a try — _don’t worry!_ I’ll be covering OpenCV 3.0 and Python 3+ installation in a future tutorial. But for now, let’s stick with what we know and use Python 2.7.

**UPDATE:** The tutorial you are reading now covers how to install OpenCV 3.0 with Python 2.7 bindings on _**OSX Yosemite and below**_. This tutorial _**still works perfectly**_ if you are using OSX Yosemite or prior, but if you want to install OpenCV on the newer **_El Capitan and macOS Sierra_** please use [this freshly updated tutorial](https://pyimagesearch.com/2016/11/28/macos-install-opencv-3-and-python-2-7/).

This is our first tutorial in our OpenCV 3.0 install-fest series. In this tutorial I’ll be detailing how to install OpenCV 3.0 and Python 2.7+ on the OSX operating system — I’ll be covering Python 3+ in a future post.

Let’s go ahead and dive into the OpenCV 3.0 and Python 2.7+ install instructions.

Step 1:
-------

The first step we need to do is install [Xcode](https://developer.apple.com/xcode/), which is a combination of IDE and software development tools for developing applications on the OSX and iOS platforms — most of us already have Xcode installed.

But if you don’t, you’ll want to open up the _App Store_ application and search for _Xcode_. From there, just click _Get_ and _Install App_ (and when prompted, you’ll need to enter your Apple ID username and password):

[![Image 2: Figure 1: Installing Xcode on your OSX system.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20471'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/xcode_install.jpg)

**Figure 1:** Installing Xcode on your OSX system.

Step 2:
-------

Now that Xcode is installed, we need to install [Homebrew](http://brew.sh/), which is labeled as _“The missing package manager for OSX”_ (and they really are not joking about that one). Think of Homebrew as an (almost) equivalent of apt-get for Ubuntu.

To install Homebrew, simply head to the [Homebrew website](http://brew.sh/) and simply copy and paste the command underneath the _“Install Homebrew”_ section into your terminal:

$ cd ~
$ $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Now that Homebrew is installed, you’ll need to update it and grab the latest package (i.e. “formula”) definitions. These formula are simply instructions on how to install a given package or library.

To update Homebrew, simply execute:

$ brew update

Step 3:
-------

It’s bad form to use the system Python as your main interpreter. And this is especially true if you intend on using `virtualenv` and `virtualenvwrapper` (which we will be).

Let’s go ahead and use Homebrew to install our user-specific version of Python 2.7:

$ brew install python

_**Note:**_ This tutorial will be covering how to install and setup **OpenCV 3.0** with **Python 2.7**. I will be covering how to install **OpenCV 3.0** with **Python 3+** later this month.

However, before we proceed, we need to update our `PATH` in our `~/.bash_profile` file to indicate that we want to use Homebrew packages _before_ any system libraries or packages. _This is an absolutely critical step, so be sure not to skip it!_

Open up your `~/.bash_profile` file in your favorite editor (if it does not exist, **create it**), and append the following lines to the file:

\# Homebrew
export PATH=/usr/local/bin:$PATH

From there, reload your `~./bash_profile` file to ensure the changes have been made:

$ source ~/.bash\_profile

As a sanity check, let’s confirm that we are using the Homebrew version of Python rather than the system one:

$ which python
/usr/local/bin/python

If your output of `which python` is `/usr/local/bin/python` , then you are indeed using the Homebrew version of Python. And if your output is `/usr/bin/python` , then you are still using the system version of Python — and you need to go back and ensure that your `~/.bash_profile` file is updated and reloaded correctly.

**_Again, this is a very important step, so be sure not to skip it!_**

Step 4:
-------

Alright, time to get [virtualenv](https://virtualenv.pypa.io/en/latest/) and [virtualenvwrapper](https://virtualenvwrapper.readthedocs.org/en/latest/) installed and configured correctly. These packages allow us to create separate Python environments for each project we are working on. This is especially useful if you have projects that require different (or conflicting) versions of a given library.

It’s **important to note** that `virtualenv` and `virtualenvwrapper` are **_by no means required_** to install OpenCV 3.0 and Python 2.7+ on OSX. However, **_you really should be using these packages_** when doing Python development. It’s cleaner. Easier to maintain. And _**well worth**_ the upfront effort.

Anyway, to install `virtualenv` and `virtualenvwrapper` , just execute the following command:

$ pip install virtualenv virtualenvwrapper

Again, we need to update our `~/.bash_profile` file by appending the following two lines:

\# Virtualenv/VirtualenvWrapper
source /usr/local/bin/virtualenvwrapper.sh

After updating the `~/.bash_profile` file, we need to reload it:

$ source ~/.bash\_profile

At this point, both `virtualenv` and `virtualenvwrapper` are installed correctly, so we can create our `cv` virtual environment:

$ mkvirtualenv cv

This command will create a new Python environment that is _entirely sequestered_ from our system and Homebrew Python installations. The `cv` virtual environment is where we’ll be doing all of our computer vision development (and not to mention, compiling OpenCV 3.0 with Python 2.7+ support).

Step 5:
-------

Now we can start installing some Python packages. We need to install [NumPy](http://www.numpy.org/) since the OpenCV Python bindings represent images as multi-dimensional NumPy arrays:

$ pip install numpy

Step 6:
-------

Up until this point we have been mainly focusing on actually _setting up_ and _configuring_ our development environment to compile and install OpenCV — **here is where the real work starts**.

First, we’ll use brew to install the required developers tools, such as the wonderful [CMake](http://www.cmake.org/) utility:

$ brew install cmake pkg-config

And here we are going to install the necessary image I/O packages. These packages allow you to load various image file formats such as JPEG, PNG, TIFF, etc.

$ brew install jpeg libpng libtiff openexr

And finally, let’s install libraries that are used to optimize various operations within OpenCV (if we so choose):

$ brew install eigen tbb

Step 7:
-------

Alright, our system is all setup — _**time to compile and install OpenCV 3.0 with Python 2.7+ support**._

The first thing we’ll do is change directory to our home directory, followed by pulling down [OpenCV from GitHub](https://github.com/Itseez/opencv), and checking out 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._

Unlike previous versions of OpenCV that were (essentially) self-contained, we need to pull down the extra [opencv\_contrib repo](https://github.com/itseez/opencv_contrib) from GitHub as well. The `opencv_contrib` repo which contains extra modules for OpenCV, such as feature detection, local invariant descriptors (SIFT, SURF, etc.), text detection in natural images, line descriptors, and more.

$ cd ~
$ git clone https://github.com/Itseez/opencv\_contrib
$ 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.

**Note:** We don’t _have_ to pull down the `opencv_contrib` repo if we don’t want to. OpenCV will compile and install just fine without it. But if you compile OpenCV _**without**_ `opencv_contrib` , be warned that you’ll be missing out on some pretty important features, which will become very obvious, very fast, especially if you’re used to working with the 2.4.X version of OpenCV.

Step 8:
-------

Let’s setup our OpenCV build by creating the `build` directory:

$ cd ~/opencv
$ mkdir build
$ cd build

Where we’ll use CMake to configure our build:

$ cmake -D CMAKE\_BUILD\_TYPE=RELEASE -D CMAKE\_INSTALL\_PREFIX=/usr/local \\
	-D PYTHON2\_PACKAGES\_PATH=~/.virtualenvs/cv/lib/python2.7/site-packages \\
	-D PYTHON2\_LIBRARY=/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/bin \\
	-D PYTHON2\_INCLUDE\_DIR=/usr/local/Frameworks/Python.framework/Headers \\
	-D INSTALL\_C\_EXAMPLES=ON -D INSTALL\_PYTHON\_EXAMPLES=ON \\
	-D BUILD\_EXAMPLES=ON \\
	-D OPENCV\_EXTRA\_MODULES\_PATH=~/opencv\_contrib/modules ..

There are some _**very important**_ options we are supplying to CMake here, so let’s break them down:

*   `CMAKE_BUILD_TYPE` : This option indicates that we are building a release binary of OpenCV.
*   `CMAKE_INSTALL_PREFIX` : The base directory where OpenCV will be installed.
*   `PYTHON2_PACKAGES_PATH` : The **_explicit_** path to where our `site-packages` directory lives in our `cv` virtual environment.
*   `PYTHON2_LIBRARY` : Path to our Hombrew installation of Python.
*   `PYTHON2_INCLUDE_DIR` : The path to our Python header files for compilation.
*   `INSTALL_C_EXAMPLES` : Indicate that we want to install the C/C++ examples after compilation.
*   `INSTALL_PYTHON_EXAMPLES` : Indicate that we want to install the Python examples after complication.
*   `BUILD_EXAMPLES` : A flag that determines whether or not the included OpenCV examples will be compiled or not.
*   `OPENCV_EXTRA_MODULES_PATH` : **_This option is extremely important_** — here we supply the path to the `opencv_contrib` repo that we pulled down earlier, indicating that OpenCV should compile the extra modules as well.

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

Whew, that was a lot of options.

Trust me, it’s a lot easier installing OpenCV 3.0 on Ubuntu where these options are _automatically determined_ via CMake for us.

But when **using OSX you’ll need to _explicitly_ define** the `PYTHON2_PACKAGES_PATH` , `PYTHON2_LIBRARY` , and `PYTHON2_INCLUDE_DIR` yourself. It’s a real pain, but if you don’t, your compile will fail.

Here’s an example of what my CMake output looks like:

[![Image 3: Figure 2: Before compiling OpenCV 3.0 on your OSX system, make sure that cmake has picked up the correct Python interpreter, library, numpy version, and packages path.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20407'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/py2_opencv3_osx_compile_py_options.jpg)

**Figure 2:** Before compiling OpenCV 3.0 on your OSX system, make sure that cmake has picked up the correct Python interpreter, library, numpy version, and packages path.

Notice how the Python 2 Interpreter, Libraries, numpy version, and packages path have been correctly picked up.

You’ll also want to make sure that `python2` is in the list of modules **To be built**, like this:

[![Image 4: Figure 2: Ensuring the "python2" module is in our list of modules "To be built".](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20407'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/py2_opencv3_osx_compile_modules.jpg)

**Figure 2:** Ensuring the “python2” module is in our list of modules “To be built”.

If it `python2` is not in this list, and is in the **Unavailable** list, then you need to go back to the CMake step and ensure that you have correctly supplied your `PYTHON2_PACKAGES_PATH` , `PYTHON2_LIBRARY` , and `PYTHON2_INCLUDE_DIR` .

Now that CMake has properly configured the build, we can compile OpenCV:

$ make -j4

Where the _4_ can be replaced with however many cores you have available on your processor. Here’s an example of OpenCV compiling on my system:

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

**Figure 3:** OpenCV 3.0 with Python 2.7+ support compiling on my system.

And assuming that OpenCV compiled without error, you can now install it on your OSX system:

$ make install

If you get an error message related to permissions (although that really shouldn’t happen), you’ll need to run the install command as `sudo` :

$ sudo make install

Step 9:
-------

Assuming you’ve made it this far, let’s perform a sanity check and ensure OpenCV is installed:

$ cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
$ ls -l cv2.so 
-rwxr-xr-x  1 adrian  staff  2013052 Jun  5 15:20 cv2.so

Sure enough, we can see that OpenCV has been installed in our `cv` virtual environment’s `site-packages` directory!

As a quick note, you’ll be able to find the `cv2.so` file (which is your OpenCV bindings) in your `build/lib` directory as well.

Let’s verify our install by firing up a shell and importing OpenCV:

(cv)annalee:~ adrianrosebrock$ python
Python 2.7.8 (default, Jul 31 2014, 15:41:09) 
\[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)\] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> cv2.\_\_version\_\_
'3.0.0'

Doesn’t that `3.0.0` look nice?

**Congrats, you have now installed OpenCV 3.0 and Python 2.7+ on your OSX system!**

Step 10:
--------

After all this work, let’s give our OpenCV 3.0 install a test drive!

Most of my work in computer vision involves image search engines, or more formally, Content-based Image Retrieval. A critical step of CBIR is extracting features to quantify and abstractly represent the contents of an image.

OpenCV 3.0 has numerous updates and changes, but perhaps my personal favorite is an implementation of AKAZE features — _[Fast Explicit Diffusion for Accelerated Features in Nonlinear Scale Spaces](http://isit.u-clermont1.fr/~ab/Publications/Alcantarilla_etal_BMVC13.pdf)_ by Alcantarilla et al.

Since _Jurassic World_ was just released (and _Jurassic Park_ is my favorite movie of all time), let’s explore how we can compute and extract AKAZE features from the following image:

[![Image 6: Figure 4: Our Jurassic World test image that we are going to detect keypoints and extract features using AKAZE.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20333'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/jurassic_world.jpg)

**Figure 4:** Our _Jurassic World_ test image that we are going to detect keypoints and extract features in using AKAZE.

Open up a new file, name it `test_akaze.py` , and insert the following code:

\# import the necessary packages
from \_\_future\_\_ import print\_function
import cv2

# load the image and convert it to grayscale
image = cv2.imread("jurassic\_world.jpg")
gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)
cv2.imshow("Original", image)

# initialize the AKAZE descriptor, then detect keypoints and extract
# local invariant descriptors from the image
detector = cv2.AKAZE\_create()
(kps, descs) = detector.detectAndCompute(gray, None)
print("keypoints: {}, descriptors: {}".format(len(kps), descs.shape))

# draw the keypoints and show the output image
cv2.drawKeypoints(image, kps, image, (0, 255, 0))
cv2.imshow("Output", image)
cv2.waitKey(0)

And then execute it via:

$ python test\_akaze.py
keypoints: 762, descriptors: (762, 61)

Assuming you have download the `jurassic_world.jpg`  image and placed it in the same directory as your `test_akaze.py`  script, you should see the following output:

[![Image 7: Figure 5: We have successfully been able to detect keypoints, extract AKAZE features, and then draw the keypoints on our image using OpenCV 3.0 and Python 2.7+!](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20331'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/06/test_akaze.jpg)

**Figure 5:** We have successfully been able to detect keypoints, extract AKAZE features, and then draw the keypoints on our image using OpenCV 3.0 and Python 2.7+!

Notice how we have been able to detect keypoints and extract AKAZE features in our image!

Obviously we need to do a lot more work than this to build a useful project using AKAZE features — but this example demonstrates that (1) our OpenCV 3.0 install is working, and (2) we are able to use a unique OpenCV 3.0 feature using Python 2.7.

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

OpenCV 3.0 is finally here! And to celebrate the OpenCV 3.0 release, we are going to performing an _**OpenCV 3.0 install-fest**_ for both **_Python 2.7+_** and **_Python 3+_** on a variety of operating systems including **_OSX_**, **_Ubuntu_**, and the **_Raspberry Pi!_**

This article kicked-off the install fest by detailing how to setup and install OpenCV 3.0 and Python 2.7+ on the OSX operating system.

Next week, we’ll be moving over to Ubuntu and detailing the instructions to get OpenCV 3.0 and Python 2.7 installed on Ubuntu 14.04+ (_hint: it’s much easier than OSX__)._

Anyway, I hope you enjoyed this post and found it useful!

Please consider subscribing to the PyImageSearch Newsletter by entering your email address in the form below — I’ll be sending out updates as new OpenCV 3.0 + Python install instructions are released!

![Image 8](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.