This tutorial is an addendum to Adrian Rosebrock’s fantastic tutorial on installing OpenCV from source on Mac OS.1 His tutorial does an excellent job showing you how to install OpenCV for a Homebrew Python virtual environment. However, I prefer to use Anaconda to manage my Python virtual environments, so I wrote this tutorial for others who are looking to install OpenCV for Anaconda Python.
Follow the steps in Adrian’s tutorial up until executing the
cmake command. Instead, execute the following commands (adjusting the Python version as necessary):
export CPLUS_INCLUDE_PATH=<path to conda env>/lib/python3.6 cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D OPENCV_EXTRA_MODULES_PATH=<path to conda opencv_contrib>/opencv_contrib/modules \ -D PYTHON3_LIBRARY=<path to conda env>/lib/python3.6m.dylib \ -D PYTHON3_INCLUDE_DIR=<path to conda env>/include/python3.6m \ -D PYTHON3_EXECUTABLE=<path to conda env>/bin/python \ -D PYTHON3_PACKAGES_PATH=<path to conda env>/lib/python3.6/site-packages \ -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 ..
The first line tells
cmake where to find C++ headers for your virtual environment. On my system, compiling OpenCV (from source directories in my home directory) for a Conda virtual environment called
cv for a Miniconda installation located in my home directory looks like this:
export CPLUS_INCLUDE_PATH=~/miniconda3/envs/cv/lib/python3.6 cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D PYTHON3_LIBRARY=~/miniconda3/envs/cv/lib/python3.6m.dylib \ -D PYTHON3_INCLUDE_DIR=~/miniconda3/envs/cv/include/python3.6m \ -D PYTHON3_EXECUTABLE=~/miniconda3/envs/cv/bin/python \ -D PYTHON3_PACKAGES_PATH=~/miniconda3/envs/cv/lib/python3.6/site-packages \ -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 ..
From here, execute the
make command with the appropriate flag for the number of cores to use:
make finishes, install OpenCV:
sudo make install
From there, symlink OpenCV into your Anaconda environment:
cd <path to conda env>/lib/python3.6 ln -s /usr/local/python/cv2 cv2
And you should be good to go! The Python code below demonstrates that OpenCV is successfully installed with non-free algorithms included.
import cv2 import matplotlib.pyplot as plt # load image img = cv2.imread('rameses.jpg') # convert to grayscale img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # instantiate SURF surf = cv2.xfeatures2d.SURF_create(7000) # compute keypoints kp = surf.detect(img_gray, None) # plot keypoints plt.imshow(cv2.drawKeypoints(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), kp, None, (0,255,0), 4)) plt.show()