Blogs

Ronie Martinez

August 01, 2017

Starting Computer Vision: Building OpenCV 3 and Python 3.6 on macOS

I recently acquired a book from PyImageSearch and started reading it. The bundle comes with an Ubuntu image that includes all essential computer vision libraries pre-installed. I would say the virtual machine was cool but "developer experience"-wise, it is not enough. The layer between the "real machine" and the "virtual machine" does not improve software development. Currently, I am still at the "beginner" chapter but I wanted to share how I built OpenCV 3 and Python 3.6 on my preferred environment (macOS).

Note: Most of the instructions will be taken from macOS: Install OpenCV 3 and Python 3.5.

Xcode

sudo xcodebuild -license  # read and type "accept"
sudo xcode-select --install

Install Homebrew

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

Update .bash_profile

Append the following lines to your ~/.bash_profile.

export PATH=/usr/local/bin:$PATH

Install Python 3.6 (via Homebrew)

As of this writing, Python 3 version on Homebrew is 3.6.2.

brew install python3
brew linkapps python3

Create a Python 3.6 virtual environment

Python 3.6 comes with venv.

python3 -m venv ~/computer_vision/
source ~/computer_vision/bin/activate
python -V

Install OpenCV prerequisites

pip install numpy
brew install cmake pkg-config
brew install jpeg libpng libtiff openexr
brew install eigen tbb

Build OpenCV (from source)

cd ~
git clone https://github.com/opencv/opencv
git clone https://github.com/opencv/opencv_contrib
cd ~/opencv/
mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
    -D PYTHON3_LIBRARY=/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/libpython3.6.dylib \
    -D PYTHON3_INCLUDE_DIR=/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/include/python3.6m \
    -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 BUILD_EXAMPLES=ON ..
make -j4
sudo make install

Note: Homebrew installs Python 3.6 in /usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6.

Create link to cv2.so to you Python 3.6 virtual environment

cd ~/computer_vision/lib/python3.6/site-packages/
ln -s /usr/local/lib/python3.6/site-packages/cv2.so cv2.so

Verify cv2 package

Open a Python console by simply typing python into the terminal.

import cv2
cv2.__version__

References: