In an earlier post I outlined how to get set up for computer vision in Python. There, I skipped over one important component: installing OpenCV.
Partly, I've separated this to its own post because it's large enough to be a topic of its own. But mainly it's because you can actually get quite far without ever needing OpenCV. However, as I found out this weekend, if you want to do any work with video, you will pretty much be forced to use OpenCV.1 OpenCV makes it really easy to both extract individual frames of the video and draw visualizations on top of them.
Installing OpenCV is highly system-dependent, so here I will focus on OS X (as usual). The official documentation covers Windows and Linux well enough, anyway.
Two caveats here:
- You must install NumPy globally in order to install OpenCV with Homebrew.
- It's 2014 and OpenCV still doesn't work with Python 3!!2
Homebrew may warn you that you need NumPy installed first. Unfortunately you will be forced to install NumPy globally. Most scientists who hack together vision systems probably don't give a hoot about this, but I like to keep my system clean with virtualenvs. It's not a big deal though, because admittedly it would be useful to have NumPy available on the global level. Plus, I can always uninstall NumPy later; we just need it for the duration of the build process.
I tried installing while under a virtualenv, but for some reason the build did not create the necessary shared object (.so) files in my site-packages. So, we'll install both NumPy and OpenCV globally, and then copy cv to wherever we need it. Unfortunately we'll have to do this every time we create a new virtualenv for OpenCV. :-/ 3
So, make sure you are not inside a virtualenv, then issue the following commands:
# You should use Homebrew's Python if you're not already:
$ brew install python
$ pip install numpy
$ brew install opencv
# Or, you might want to include some of the optional items such as:
$ brew install --with-eigen --with-ffmpeg --with-openni opencv
# Now let's copy the cv files to our virtualenv:
$ cp /usr/local/lib/python2.7/site-packages/cv* /lib/python2.7/site-packages
Let's see if it works:
>>> import cv2
>>> print cv2.__version__
If that didn't elicit any errors, then you're golden!
- Your other two options are using ffmpeg by manually calling out to the command line, or to do the video parsing yourself (which is actually pretty easy if it's an .avi file). There used to be python bindings for ffmpeg, but those are now defunct.
- But it's coming in version 3.0—which at the time of writing is already a month and a half late.
- Someone on StackOverflow told me that they had no problems quarantining OpenCV to a virtualenv. So maybe you should try it yourself and see if it works?