Installing OpenCV 4 on macOS

In this post I will provide a bash script to install OpenCV 4.1.0 (with Python 3.6) on macOS Mojave and High Sierra.

OpenCV 4 was released on 20 November 2018. There have been many bug fixes and other changes in these versions.

First, we will install Xcode and Homebrew.

From there, we will set up Python virtual environments.

Then we will compile OpenCV 4 from source. Compiling from source gives us full control over the compilation and build, and lets us install the full version of OpenCV 4.

Step 1: Install Xcode

First, install Xcode. This installs the C compiler on the Mac, and the easiest way to install Xcode is through the App Store. Open the Apple App Store, search for the Xcode app and install it. It will take a while. In the meantime, you can make yourself a coffee.

Install Xcode

Once Xcode is installed, we need to accept a license agreement. Open a terminal and enter the following command:

Bash
$ sudo xcodebuild -license

To accept the license, scroll down and accept it. Press space to scroll down and type "agree" to accept.

Xcode Accept The License

After that, install the Xcode Command Line Tools with the following command.

Bash
$ sudo xcode-select --install

Install Xcode Command Line Tools

Step 2: Install Homebrew

In this step we will install Homebrew, the Mac community's package manager. Homebrew lets us install packages with just a few commands.

Bash
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Let's update Homebrew:

Bash
$ brew update

Update Homebrew

Let's edit your Mac's bash_profile. This script runs every time you open a terminal. I use the nano text editor.

Bash
$ nano ~/.bash_profile

Add the following lines at the end to update your path:

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

Save the profile [control + o].

Homebrew Bash Profile

Then use the source command to load the changes from the file (or close and reopen your terminal).

Bash
$ source ~/.bash_profile

Step 3: Install the OpenCV prerequisites with Homebrew

In this section we will make sure Python 3.6 is installed. We will also install the prerequisites for compiling OpenCV from source.

It's very important to use Python 3.6. By default, High Sierra and Mojave come with Python 3.7. But Python 3.7 isn't supported by Keras / TensorFlow (we will use both later for deep learning).

Install Python 3.6.5:

Bash
$ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
$ brew switch python 3.6.5_1

If you didn't get any errors, perfect! Please continue below.

Info: you may get an error like:

Text
Error: python contains a recursive dependency on itself:
python depends on sphinx-doc
sphinx-doc depends on python

Python Depends On Sphinx Doc

The problem is that sphinx-doc depends on Python 3.7, and Python 3.6.5 depends on sphinx-doc, which depends on Python 3.7.

Let's fix the circular dependency.

First, install Python 3.7 (which we will downgrade later):

Bash
$ brew install python3

Now we need to remove the circular dependency.
Edit the Homebrew formula for sphinx-doc, since that's where the problem is:

Bash
$ nano /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/sphinx-doc.rb

Now find the Python dependency and comment it out by putting a # in front of it:

Remove The Python Dependency

Once you've added the # to comment out that line, save and exit.

From there, just reinstall sphinx-doc:

Bash
$ brew reinstall sphinx-doc

Install Python 3.6.5. The first step is to unlink Python:

Bash
$ brew unlink python

And from there, we can install Python 3.6:

Bash
$ brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb

You should check which Python is being used:

Bash
$ which python3
/usr/local/bin/python3
$ python3 --version
Python 3.6.5

Python3 Version

Look at the output of the first command: you should see local/ between /usr/ and bin/python3.

We are using Python 3.6.5!

Check that we are using the right Python:

Bash
$ which python3

If you see /usr/local/bin/python3, you are using the Homebrew Python (which is good). If you see /usr/bin/python3, you are using the system Python and you need to fix your bash profile and/or source it.

Install the other OpenCV prerequisites

These packages are build and compilation tools, libraries for image manipulation, or optimisation libraries.

To install these prerequisites for OpenCV on macOS, run the following commands:

Bash
$ brew install cmake
$ brew install pkg-config
$ brew install jpeg
$ brew install libpng
$ brew install libtiff
$ brew install openexr
$ brew install eigen tbb
$ brew install wget

Step 4: Install the Python dependencies for OpenCV 4

In this step we will install the Python dependencies for OpenCV 4.

With the wget tool we just installed, let's download and install pip:

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

pip: a Python package manager

Now that pip is installed, we can install virtualenv and virtualenvwrapper, two tools for managing virtual environments.

Python virtual environments are a best practice for Python development, and I strongly encourage you to take full advantage of them.

Let's install virtualenv and virtualenvwrapper:

Bash
$ sudo pip3 install virtualenv virtualenvwrapper
$ sudo rm -rf ~/get-pip.py ~/.cache/pip

From there, we need to edit our bash_profile again so these two tools work properly.

Bash
$ nano ~/.bash_profile

Add these lines at the end of the file:

Text
# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

Virtualenv And Virtualenvwrapper

Source the file:

Bash
$ source ~/.bash_profile

The virtualenvwrapper tool gives us a number of terminal commands. You can read the documentation here.

Let's use the first command to create a Python virtual environment for OpenCV:

Bash
$ mkvirtualenv cv -p python3

Note that cv is the name of our environment, and that I'm creating a Python 3 environment.

Reminder: note in the output that Python 3.6 is used for the environment too. You can name your environment differently if you like, and create several environments with different names to make development easier.

The environment is already active, but just in case, let's activate it:

Bash
$ workon cv

Workon Opencv

Let's install NumPy while we're in the environment.

Bash
$ pip install numpy

Step 5: Compile OpenCV 4 for macOS

Compiling from source gives you the most control over your build, compared with package managers like pip, Homebrew and Anaconda.

Let's download OpenCV.

First, go to your home folder and download opencv and opencv_contrib. The contrib repository contains extra modules and functions that we will use often in the future.

Download opencv and opencv_contrib:

Bash
$ cd ~
$ wget -O opencv.zip https://github.com/opencv/opencv/archive/4.1.0.zip
$ wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.1.0.zip

From there, unzip the archives:

Bash
$ unzip opencv.zip
$ unzip opencv_contrib.zip

Rename the folders to make them easier to work with:

Bash
$ mv opencv-4.1.0 opencv
$ mv opencv_contrib-4.1.0 opencv_contrib

Now that opencv and opencv_contrib are downloaded and ready, let's set up our environment.

Compile OpenCV from source

Now that opencv and opencv_contrib are downloaded and ready, let's use CMake to configure our build and Make to compile it.

Go back to your OpenCV repository, then create and enter a build directory:

Bash
$ workon cv
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
-D PYTHON3_LIBRARY=`python -c 'import subprocess ; import sys ; s = subprocess.check_output("python-config --configdir", shell=True).decode("utf-8").strip() ; (M, m) = sys.version_info[:2] ; print("{}/libpython{}.{}.dylib".format(s, M, m))'` \
-D PYTHON3_INCLUDE_DIR=`python -c 'import distutils.sysconfig as s; print(s.get_python_inc())'` \
-D PYTHON3_EXECUTABLE=$VIRTUAL_ENV/bin/python \
-D BUILD_opencv_python2=OFF \ -D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D INSTALL_C_EXAMPLES=OFF \ -D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=ON ..

Reminder: OPENCV_ENABLE_NONFREE=ON is required for OpenCV 4 if you want access to patented algorithms for educational purposes.

This part is very important. If you get an error, write it in the comments so we can discuss it.

Once it's done, check the following information in your terminal.

Opencv Cmake

What you're looking for is that both your Python 3 interpreter and NumPy from the virtual environment will be used.

If you don't see that, you probably ran CMake without being "in" the cv virtual environment. If so, no problem: just delete the build folder, activate the virtual environment with the workon command, and run CMake again.

We're ready to go. Start the compilation with:

Bash
$ make -j4

Note: the -j4 argument is optional and tells make to use 4 CPU cores.

When make finishes, you should see this:

Install Opencv4

Install OpenCV 4:

Bash
$ sudo make install

Now let's create what's called a symbolic link. We need a link between our cv virtual environment's site-packages and the system site-packages where OpenCV is installed.

Bash
$ workon cv
$ python --version
Python 3.6.5

Check your Python version and adjust the lines below to match your own Python version.

Bash
$ ls /usr/local/lib/python3.6/site-packages/cv2/python-3.6/
cv2.cpython-36m-darwin.so

Let's simply rename it to cv2.so:

Bash
$ cd /usr/local/lib/python3.6/site-packages/cv2/python-3.6/
$ sudo mv cv2.cpython-36m-darwin.so cv2.so

Our last step is to sym-link our OpenCV cv2.so bindings into our cv virtual environment:

Bash
$ cd ~/.virtualenvs/cv/lib/python3.6/site-packages/
$ ln -s /usr/local/lib/python3.6/site-packages/cv2/python-3.6/cv2.so cv2.so

For the steps above, be careful with the paths. If you copy exactly the same lines, you may get errors. Instead, check your paths and make sure everything is correct.

Step 7: Test your OpenCV 4 installation

Start a Python shell in the virtual environment and check that cv2 imports without errors and that the version matches.

Bash
$ workon cv
$ python
>>> import cv2
>>> cv2.__version__
'4.1.0'
>>>

If you see no errors and OpenCV 4 is installed, you're ready to go!

If you want to build more projects with OpenCV 4, just keep following my blog!

Summary

Today we installed OpenCV 4 with Python bindings on your macOS machine.