Setting up OpenCV for Python 3 on macOS Sierra with 5 easy steps

At SuitApp we’re making a couple of things related with computer vision and of course we’re using OpenCV for that tasks. Earlier I had to make a lot of efforts to setup OpenCV with mine Python 3.5: Download sources, configure, find solutions to make it compile well… And after upgrading to macOS Sierra I had to make this setup again, but fortunately I found more convenient way to do it.

But no worries, I will share shortcut with you.

We need homebrew, virtualenv, some additional formulas and a bit of console.

Step 1 (if you have no homebrew)

Installing homebrew by running command in console:

/usr/bin/ruby -e "$(curl -fsSL"

Step 2 (optional)

This step is optional if you already have python3

brew install python3

Step 3

Obtaining formulas for science

brew tap homebrew/science

Step 4

Installing opencv3 with all options we need

brew install opencv3 --with-contrib --with-python3

Those options with-contrib and with-python3 just for my setup. Here is a list of available ones which may be useful for you.

Build 32-bit only
Build using C++11 mode
Build "extra" contributed modules
Build with CUDA support
Build with ffmpeg support
Build with gphoto2 support
Build with gstreamer support
Build with jasper support
Build with Java support
Build with libdc1394 support
Build with OpenGL support (must use --with-qt5)
Build with openni support
Build with openni2 support
Build with python3 support
Build the Qt4 backend to HighGUI
Build the Qt5 backend to HighGUI
Use QuickTime for Video I/O instead of QTKit
Enable parallel code in OpenCV using Intel TBB
Build without eigen support
Use a numpy you've installed yourself instead of a Homebrew-packaged numpy
Disable GPU code in OpenCV using OpenCL
Build without openexr support
Build without Python support
Build without accuracy & performance tests
Install HEAD version

Step 5

All that we have left to do now is to add opencv3 to our virtualenv (if we’ve created one).

We need to rename compiled cv2 module to appropriate one.

By locating console to opencv dir:

cd /usr/local/opt/opencv3/lib/python3.5/site-packages
mv ./

Then we’re just adding path to this lib to our virtualenv

echo '/usr/local/opt/opencv3/lib/python3.5/site-packages' >> ~/.virtualenvs/suitapp/lib/python3.5/site-packages/opencv3.pth

Where ~/.virtualenvs/suitapp/lib/python3.5/site-packages/ is path to your own virtualenv.

And now we can activate our virtualenv and try to import cv2 to check that everything is working.

workon suitapp
python -c "import cv2"

If there is no error, my congratulations — we did it!

P.S. Feel free to fix my English, or any other mistakes.