I had a lot of trouble getting opencv 3.0 to work on OSX with python3 bindings and virtual environments. The other answers helped a lot, but it still took a bit. Hopefully this will help the next person. Save this to build_opencv.sh
. Then download opencv, modify the variables in the below shell script, cross your fingers, and run it (. ./build_opencv.sh
). For debugging, use the other posts, especially James Fletchers.
Don't forget to add the opencv lib dir to your PYTHONPATH.
Note - this also downloads opencv-contrib, where many of the functions have been moved. And they are also now referenced by a different namespace than the documentation - for instance SIFT is now under cv2.xfeatures2d.SIFT_create. Uggh.
#!/bin/bash
# Install opencv with python3 bindings: https://stackoverflow.com/questions/20953273/install-opencv-for-python-3-3/21212023#21212023
# First download opencv and put in OPENCV_DIR
#
# Edit this section
#
PYTHON_DIR=/Library/Frameworks/Python.framework/Versions/3.4
OPENCV_DIR=/usr/local/Cellar/opencv/3.0.0
NUM_THREADS=8
CONTRIB_TAG="3.0.0" # This will also download opencv_contrib and checkout the appropriate tag https://github.com/Itseez/opencv_contrib
#
# Run it
#
set -e # Exit if error
cd ${OPENCV_DIR}
if [[ ! -d opencv_contrib ]]
then
echo '**Get contrib modules'
[[ -d opencv_contrib ]] || mkdir opencv_contrib
git clone [email protected]:Itseez/opencv_contrib.git .
git checkout ${CONTRIB_TAG}
else
echo '**Contrib directory already exists. Not fetching.'
fi
cd ${OPENCV_DIR}
echo '**Going to do: cmake'
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D PYTHON_EXECUTABLE=${PYTHON_DIR}/bin/python3 \
-D PYTHON_LIBRARY=${PYTHON_DIR}/lib/libpython3.4m.dylib \
-D PYTHON_INCLUDE_DIR=${PYTHON_DIR}/include/python3.4m \
-D PYTHON_NUMPY_INCLUDE_DIRS=${PYTHON_DIR}/lib/python3.4/site-packages/numpy/core/include/numpy \
-D PYTHON_PACKAGES_PATH=${PYTHON_DIR}lib/python3.4/site-packages \
-D OPENCV_EXTRA_MODULES_PATH=opencv_contrib/modules \
-D BUILD_opencv_legacy=OFF \
${OPENCV_DIR}
echo '**Going to do: make'
make -j${NUM_THREADS}
echo '**Going to do: make install'
sudo make install
echo '**Add the following to your .bashrc: export PYTHONPATH=${PYTHONPATH}:${OPENCV_DIR}/lib'
export PYTHONPATH=${PYTHONPATH}:${OPENCV_DIR}/lib
echo '**Testing if it worked'
python3 -c 'import cv2'
echo 'opencv properly installed with python3 bindings!' # The script will exit if the above failed.