Skip to content

Instantly share code, notes, and snippets.

@nickgravish
Last active August 23, 2017 15:28
Show Gist options
  • Save nickgravish/0853f7948ed967cc9c6d4fd541ba9f32 to your computer and use it in GitHub Desktop.
Save nickgravish/0853f7948ed967cc9c6d4fd541ba9f32 to your computer and use it in GitHub Desktop.

Following instructions from

  1. http://www.pyimagesearch.com/2016/12/05/macos-install-opencv-3-and-python-3-5/
  2. http://luigolas.com/blog/2014/09/15/install-opencv3-with-python-3-mac-osx/
  3. http://blog.jiashen.me/2014/12/23/build-opencv-3-on-mac-os-x-with-python-3-and-ffmpeg-support/
brew install cmake pkg-config
brew install jpeg libpng libtiff openexr libgphoto2
brew install eigen tbb

also installed ffmpeg

brew install ffmpeg

Download opencv and contrib repos

git clone https://github.com/opencv/opencv
git clone https://github.com/opencv/opencv_contrib

Find my python libraries (using python 3.6)

cd ~/anaconda/
find . -name "libpython*.dylib"

Now find the python headers

find . -name Python.h

Find the python executable

which python

Find ffmpeg after homebrew install

which ffmpeg

Find real location of ffmpeg in brew directory and find library

brew info ffmpeg | grep /usr/

Make the build directory in the opencv directory

cd ~/opencv/
mkdir build
cd build

Run CMAKE

cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D OPENCV_EXTRA_MODULES_PATH=~/source_code/opencv_contrib/modules \
    -D PYTHON3_LIBRARY=/Users/nickgravish/anaconda/lib/libpython3.6m.dylib \
    -D PYTHON3_INCLUDE_DIR=/Users/nickgravish/anaconda/include/python3.6m \
    -D PYTHON3_EXECUTABLE=/Users/nickgravish/anaconda/bin/python \
	-D FFMPEG_INCLUDE_DIR=/usr/local/bin/ffmpeg \
	-D FFMPEG_LIB_DIR=/usr/local/Cellar/ffmpeg/3.3/lib \
    -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 the library

make -j4

Install the library

sudo make install

Finally copy the .so to the anaconda libs directory (you could symlink too, not sure of the diff in this case)

cp /usr/local/lib/python3.6/site-packages/cv2.cpython-36m-darwin.so ~/anaconda/lib/python3.6/site-packages/

Finally test that we can load the library and that the ffmpeg hooks worked and can read/write h.264 videos

import cv2
import cv2

cap = cv2.VideoCapture('my_video.mp4')

frames = []
while cap.isOpened():

    # Capture frame-by-frame
    read_success, frame = cap.read()

    if not read_success:
        break

    frames.append(frame)

print('Grabbed ', len(frames), ' frames')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment