Installing OpenCV via brew

Install Brew (Quickstart)

$ cd /usr/local
$ sudo ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ sudo ln -s /usr/local/homebrew/bin/brew /usr/local/bin/brew

Install opencv

$ sudo brew tap homebrew/science
$ sudo brew install -v opencv

Adjust PYTHONPATH to find opencv

$ export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH

Importing opencv

$ python
import cv

TROUBLESHOOTING

Disabling MacPorts and/or Fink

Brew’s “doctor” suggests we get rid of /sw and /opt/local from our environment if they exist, however this can prove to be cumbersome, especially when you have many different paths defined (most of which you’re not willing to lose). Below is a simple Python script that takes N paths and strips them from PATH. The resulting string is PATH excluding any matched patterns.

#!/usr/bin/env python
import os
import sys


if __name__ in '__main__':
    ARGS = sys.argv[1:]
    PATH = os.environ['PATH']
    PATH_NEW = []

    for arg in ARGS:
        for path in PATH.split(':'):
            if arg in path:
                continue
            PATH_NEW.append(path)   

    print("{0}".format(":".join(PATH_NEW)))

Example

Assume your standard PATH variable is defined as follows:

$ echo $PATH
/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
Purging

In order to remove the offending tree (/sw) from PATH, we execute path_purge.

$ purge_path /sw
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin

Notice that /sw is indeed missing in the output.

Putting purge_path to work

In BASH
$ export PATH=`eval purge_path /sw`
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/texbin
In TCSH
$ setenv PATH `purge_path /sw`
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/texbin

Using purge_path with brew

Create the following wrapper script(s):

#!/bin/bash
exclusion="/sw /opt/local"
export PATH=`eval /usr/local/bin/purge_path ${exclusion}`
export PYTHONPATH=/usr/local/lib/python2.7/site-packages

[Tcsh title=”~/bin/percolate.csh”]
#!/bin/tcsh
set exclusion="/sw /opt/local"
setenv PATH `/usr/local/bin/purge_path ${exclusion}`
setenv PYTHONPATH /usr/local/lib/python2.7/site-packages
[/Tcsh]

If you intend to run brew packages with Fink or Macports installed in parallel, issue (depending on your default shell) source ~/bin/percolate.sh or source ~/bin/percolate.csh after opening a fresh terminal.