Install opencv for Python 3.3
Asked Answered
B

15

62

Is OpenCV still not available for Python 3.3 and do I really have to downgrade to Python 2.7 to use it? I didn't find much about it on the internet, only some posts from 2012 that OpenCV wasn't yet ported to be used in Python 3.x. But now it's 2014 and after trying to install the latest OpenCV 2.4.x and copying the cv2.pyd file to C:\Program Files (x86)\Python333\Lib\site-packages this still yields the error in Python IDLE:

>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ImportError: DLL load failed: %1 ist keine zulässige Win32-Anwendung.
Balmoral answered 6/1, 2014 at 15:29 Comment(5)
This is a duplicate of #26490367, which was admittedly posted later.Loss
and re-links to this one :DArticulator
This solution https://mcmap.net/q/82996/-install-opencv-for-python3 finally worked for me.Crelin
TRY THIS FIRST! If running Anaconda: conda install -c menpo opencv3 from step one of Scivision's Tutorial. If that doesn't work, then try step 2. Note that the ...win_amd64.whl wheels packages from step 2 are meant for AMD chips.Chenab
Check the building from source for python3.6 here: https://mcmap.net/q/82997/-installing-opencv-for-python-on-ubuntu-getting-importerror-no-module-named-cv2-cvShermy
P
54

EDIT: first try the new pip method:

Windows: pip3 install opencv-python opencv-contrib-python

Ubuntu: sudo apt install python3-opencv

or continue below for build instructions

Note: The original question was asking for OpenCV + Python 3.3 + Windows. Since then, Python 3.5 has been released. In addition, I use Ubuntu for most development so this answer will focus on that setup, unfortunately

OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 is possible! Here's how.

These steps are copied (and slightly modified) from:

Prerequisites

Install the required dependencies and optionally install/update some libraries on your system:

# Required dependencies
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
# Dependencies for Python bindings
# If you use a non-system copy of Python (eg. with pyenv or virtualenv), then you probably don't need to do this part
sudo apt install python3.5-dev libpython3-dev python3-numpy
# Optional, but installing these will ensure you have the latest versions compiled with OpenCV
sudo apt install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

Building OpenCV

CMake Flags

There are several flags and options to tweak your build of OpenCV. There might be comprehensive documentation about them, but here are some interesting flags that may be of use. They should be included in the cmake command:

# Builds in TBB, a threading library
-D WITH_TBB=ON
# Builds in Eigen, a linear algebra library
-D WITH_EIGEN=ON

Using non-system level Python versions

If you have multiple versions of Python (eg. from using pyenv or virtualenv), then you may want to build against a certain Python version. By default OpenCV will build for the system's version of Python. You can change this by adding these arguments to the cmake command seen later in the script. Actual values will depend on your setup. I use pyenv:

-D PYTHON_DEFAULT_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_INCLUDE_DIRS=$HOME/.pyenv/versions/3.5.2/include/python3.5m
-D PYTHON_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1

CMake Python error messages

The CMakeLists file will try to detect various versions of Python to build for. If you've got different versions here, it might get confused. The above arguments may only "fix" the issue for one version of Python but not the other. If you only care about that specific version, then there's nothing else to worry about.

This is the case for me so unfortunately, I haven't looked into how to resolve the issues with other Python versions.

Install script

# Clone OpenCV somewhere
# I'll put it into $HOME/code/opencv
OPENCV_DIR="$HOME/code/opencv"
OPENCV_VER="3.1.0"
git clone https://github.com/opencv/opencv "$OPENCV_DIR"
# This'll take a while...

# Now lets checkout the specific version we want
cd "$OPENCV_DIR"
git checkout "$OPENCV_VER"

# First OpenCV will generate the files needed to do the actual build.
# We'll put them in an output directory, in this case "release"
mkdir release
cd release

# Note: This is where you'd add build options, like TBB support or custom Python versions. See above sections.
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local "$OPENCV_DIR"

# At this point, take a look at the console output.
# OpenCV will print a report of modules and features that it can and can't support based on your system and installed libraries.
# The key here is to make sure it's not missing anything you'll need!
# If something's missing, then you'll need to install those dependencies and rerun the cmake command.

# OK, lets actually build this thing!
# Note: You can use the "make -jN" command, which will run N parallel jobs to speed up your build. Set N to whatever your machine can handle (usually <= the number of concurrent threads your CPU can run).
make
# This will also take a while...

# Now install the binaries!
sudo make install

By default, the install script will put the Python bindings in some system location, even if you've specified a custom version of Python to use. The fix is simple: Put a symlink to the bindings in your local site-packages:

ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so $HOME/.pyenv/versions/3.5.2/lib/python3.5/site-packages/

The first path will depend on the Python version you setup to build. The second depends on where your custom version of Python is located.

Test it!

OK lets try it out!

ipython

Python 3.5.2 (default, Sep 24 2016, 13:13:17) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import cv2

In [2]: img = cv2.imread('derp.png')
i
In [3]: img[0]
Out[3]: 
array([[26, 30, 31],
       [27, 31, 32],
       [27, 31, 32],
       ..., 
       [16, 19, 20],
       [16, 19, 20],
       [16, 19, 20]], dtype=uint8)
Potboy answered 19/1, 2014 at 1:12 Comment(8)
Good to see that you had success getting OpenCV to work with Python3. I have been struggling to compile OpenCV with Python3.4 on CentOS 6.5... I get to 86% where errors begin to pour: In file included from /usr/local/lib/python3.4/site-packages/numpy/core/include/numpy/ndarraytypes.h:4, from /usr/local/lib/python3.4/site-packages/numpy/core/include/numpy/ndarrayobject.h:17, from /tmp/opencv/modules/python/src2/cv2.cpp:10: /usr/local/lib/python3.4/site-packages/numpy/core/include/numpy/npy_common.h:268:2: error: #error Must use Python with unicodeHonorable
I'm stuck with cmake not finding the Python3 "Libraries: NO". This is on Ubuntu 14.04lts. Attempting "-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so" fails. Cmake is dirsturbingMoldy
The link in step 3 is broken. That's why you include the crucial information inside the answer, not link to it.Shaunta
@Potboy can you please have a look at here github.com/opencv/opencv/issues/7045Mispleading
Updated to fix stale links and new versions of Ubuntu, Python, and OpenCV. Sorry for the super late response!Potboy
I had the python libraries installed to a different location and spent hours. Follow the docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html guide.Stanhope
There is a simpler way. pip3 install opencv-python opencv-contrib-python .Preterition
@Potboy you awesome. Thank you. God bless you. I spend a decade trying to build OpenCV with freetype support. (and Jonathan)Bellyful
H
15

Here a solution for (I believe as seen by 'cp34' on the link below) Python 3.4.

Go to to http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv.

Download the appropriate .whl.

Go to the directory where the .whl is saved.

Use pip to install the .whl. e.g. pip install opencv_python-3.0.0-cp34-none-win_amd64.whl

Then just use import cv2.

Hedvige answered 19/8, 2015 at 1:9 Comment(6)
Can you please give the link for the wheel file for Python3.5.2, opencv3 for OSX El Capitan 64 bit? I couldn't find it on that page!Mispleading
@MonaJalal Sorry, I don't know where to find those. The link I posted is "provides 32- and 64-bit Windows binaries of many scientific open-source extension packages for the official CPython distribution of the Python programming language." If you find a link (or another answer) for oppencv for OSX, please share it.Hedvige
didn't find one! OSX El Capitan with Python3.5.2 had me disappointed! Resorted to Ubuntu 16.04 and Python3.5.2 for now.Mispleading
@Hedvige I was able to download and install successfully opencv using the .whl file as you said. But when I try to do import cv2 I get the following error ImportError: bumpy.core.multiarray failed to import. Do you how can I fix that? I'm on Windows 64-bit, I use Python 3.5.1 32-bits. ThanksPolymeric
@Polymeric Do you mean numpy.core.multiarray failed to import? If so, then you might have a problem with the numpy module. Did you install numpy?Hedvige
@Hedvige you are right I haven't install numpy.Polymeric
G
13

Yes support for Python 3 it is still not available in current version, but it will be available from version 3.0, (see this ticket). If you really want to have python 3 try using development version, you can download it from GitHub.

EDIT (18/07/2015): version 3.0 is now released and python 3 support is now officially available

Globeflower answered 6/1, 2014 at 15:50 Comment(5)
Trying to download the binary for windows from here sourceforge.net/projects/opencvlibrary/files/opencv-win/… right now ... I'm telling you if I can get it to work with Python 3.3.3 EDIT: Damn the current tech preview still only ships with the python27 binarys :(Balmoral
(Months later) The current master on github appears to be version 3.0.0 -dev (that's what "opencv / modules / core / include / opencv2 / core / version.hpp" says). It's very unclear how to build/install this (on OS X in my case; Python 3.4). There seems to be such a thing as OpenCV 2.4.10, to judge from code.opencv.org/projects/opencv/issues?query_id=2. I assume that's the next release in the version 2 branch. I can't tell if that's Py3-compatible. Can anyone shed any light on this?Parishioner
Any word on this? I need OpenCV to work on windows for python 3.3. thxBequest
@Yosh thanks for noting this I updated answer with link you providedGlobeflower
is cv2.cv no longer available in 3.0?Donahue
J
7

Use the pip application. On windows you find it in Python3/Scripts/pip.exe and On Ubuntu you can install with apt-get install python3-pip. and so, use the command line:

pip3 install --upgrade pip

pip3 install opencv-python

On Windows use only pip.exe instead pip3

Jaggers answered 7/4, 2017 at 5:10 Comment(0)
L
6

I can't comment on midopa's excellent answer due to lack of reputation.

On a Mac I (finally) successfully installed opencv from source using the following commands:

cmake -D CMAKE_BUILD_TYPE=RELEASE 
-D CMAKE_INSTALL_PREFIX=/usr/local 
-D PYTHON_EXECUTABLE=/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 
-D PYTHON_LIBRARY=/Library/Frameworks/Python.framework//Versions/3.4/lib/libpython3.4m.dylib 
-D PYTHON_INCLUDE_DIR=/Library/Frameworks/Python.framework/Versions/3.4/include/python3.4m 
-D PYTHON_NUMPY_INCLUDE_DIRS=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/numpy/core/include/numpy 
-D PYTHON_PACKAGES_PATH=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages 
/relative/path/to/source/directory/

Then,

make -j8

change 8 for the number of threads your machine can handle, to speed things up

sudo make install

I added a PYTHONPATH environment variable to my ~/.bash_profile file so that Python could find cv2.so:

PYTHONPATH="${PYTHONPATH}:/usr/local/lib/python3.4/site-packages”
export PYTHONPATH

[For those using PyCharm, I had to go to Preferences > Project Structure > Add Content Root, and added the path to cv2.so's parent directory: /usr/local/lib/python3.4/site-packages]

This command got me past errors such as:

Could NOT find PythonLibs, by explicitly declaring the python library path

ld: can't link with a main executable for architecture x86_64
collect2: error: ld returned 1 exit status
make[2]: *** [lib/cv2.so] Error 1
make[1]: *** [modules/python2/CMakeFiles/opencv_python2.dir/all] Error 2
make: *** [all] Error 2

by explicitly pointing to the libpython3.4m.dylib

In terminal, check that it worked with:

$python3
>>> import cv2

It's all good if you don't get ImportError: No module named 'cv2'

This worked on a Macbook Pro Retina 15" 2013, Mavericks 10.9.4, Python 3.4.1 (previously installed from official download), opencv3 from source. Hope that this helps someone.

Lunatic answered 2/9, 2014 at 10:29 Comment(2)
I ended up with cv2 importing fine in the command line but not in PyCharm IDE. PyCharm complained about not being able to locate the .dylib files. To fix this, I added the DYLD_LIBRARY_PATH variable to the configuration of the startup module in PyCharm. DYLD_LIBRARY_PATH pointing to the folder with the .dylib files referenced in cv2.soClang
This is great, but you can also just use homebrew: brew install opencv3 --with-python3 and then brew ln opencv3 --force and you should be GTG to run import cv2 in a python 3.x script.Robbegrillet
R
6

I know this is an old thread, but just in case anyone is looking, here is how I got it working on El Capitan:

brew install opencv3 --with-python3

and wait a while for it to finish.

Then run the following as necessary:

brew unlink opencv

Then run the following as the final step:

brew ln opencv3 --force

Now you should be able to run import cv2 no problem in a python 3.x script.

Robbegrillet answered 3/2, 2016 at 3:50 Comment(2)
didn't work for me for python3.5.2 what is your python version?Mispleading
@MonaJalal 3.5.2. You are on OSX and running homebrew?Robbegrillet
P
3

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://mcmap.net/q/82537/-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.
Piccolo answered 5/6, 2015 at 18:29 Comment(0)
M
3

Spent 3 hours trying the various options on Ubuntu 14.04LTS mentioned here and in another referenced tutorial to no avail. For a while tried with OpenCV3.0.0 but eventually switched to 3.1.0. The following worked:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so \
-D PYTHON3_EXECUTABLE=/usr/bin/python3.4m \
-D PYTHON3_INCLUDE_DIR=/usr/include/python3.4m/ \
-D PYTHON_INCLUDE_DIR=/usr/include/python3.4m/ \
-D PYTHON3_INCLUDE_DIRS=/usr/include/python3.4m/ \
-D PYTHON_INCLUDE_DIRS=/usr/include/python3.4m/ \
-D BUILD_opencv_python3=ON \
.

output:

--   OpenCV modules:
--     To be built:                 core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d stitching videostab python3
--     Disabled:                    java world
--     Disabled by dependency:      -
--     Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev python2 viz

--   Python 3:
--     Interpreter:                 /usr/bin/python3.4m (ver 3.4.3)
--     Libraries:                   /usr/lib/x86_64-linux-gnu/libpython3.4m.so (ver 3.4.3)
--     numpy:                       /usr/lib/python3/dist-packages/numpy/core/include (ver 1.8.2)
--     packages path:               /usr/lib/python3/dist-packages
-- 
--   Python (for build):      

And with virtualenv used the following cmake options:

cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=$VIRTUAL_ENV \
-D PYTHON3_EXECUTABLE=$VIRTUAL_ENV/bin/python3 \
-D PYTHON3_PACKAGES_PATH=$VIRTUAL_ENV/lib/python3.4/site-packages \
-D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.4m.so \
-D PYTHON3_INCLUDE_DIR=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON_INCLUDE_DIR=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON3_INCLUDE_DIRS=$VIRTUAL_ENV/include/python3.4m \
-D PYTHON_INCLUDE_DIRS=$VIRTUAL_ENV/include/python3.4m \
-D BUILD_opencv_python3=ON \
.

If you have issues with ffmpeg includes add the following to remove video support:

-D WITH_FFMPEG=OFF \
-D WITH_GSTREAMER=OFF \
-D WITH_V4L=OFF \
-D WITH_1394=OFF \

Also take heed of the warning from cmake about using make clean. If you ran make clean you might have to uncompress the original package anew. Cmake is dead, long live the Cmake

Moldy answered 8/3, 2016 at 18:0 Comment(0)
P
2

A full instruction relating to James Fletcher's answer can be found here

Particularly for Anaconda distribution I had to modify it this way:

 cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D PYTHON3_PACKAGES_PATH=/anaconda/lib/python3.4/site-packages/ \
    -D PYTHON3_LIBRARY=/anaconda/lib/libpython3.4m.dylib \
    -D PYTHON3_INCLUDE_DIR=/anaconda/include/python3.4m \
    -D INSTALL_C_EXAMPLES=ON \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D BUILD_EXAMPLES=ON \
    -D BUILD_opencv_python3=ON \
    -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..

Last line can be ommited (see link above)

Pulsar answered 19/11, 2015 at 6:6 Comment(0)
C
2

If you're down here... I'm sorry the other options didn't workout. Try this:

conda install -c menpo opencv3

from Step 1 of Scivision's Tutorial. If that doesn't work, then go on to Step 2:

(Windows only) OpenCV 3.2 pip install

Download OpenCV .whl file here. The packages that mention contrib in their name include OpenCV-extra packages. For example, assuming you have Python 3.6, you might download opencv_python-3.2.0+contrib-cp36-none-win_amd64.whl to get the OpenCV-extra packages.

Then, from Command Prompt:

pip install opencv_python-3...yourVersion...win_amd64.whl

Note that the ...win_amd64.whl wheels packages from step 2 in that tutorial are meant for AMD chips.

Chenab answered 27/7, 2017 at 21:50 Comment(0)
B
1

Someone has published a docker container / file for this:

https://github.com/vipul-sharma20/docker-opencv3-python3

https://hub.docker.com/r/vipul20/docker-opencv3-python3/~/dockerfile/

You can pull the image directly from docker hub or follow the instructions in the Dockerfile to install.

Bligh answered 14/9, 2017 at 16:32 Comment(0)
S
1

Just in case you found that pip3 install opencv-python takes too long for you, you can set number of build threads:

export MAKEFLAGS="-j8"
pip3 install opencv-python --no-cache-dir

(--no-cache-dir will ignore previous build)

Subglacial answered 11/1, 2021 at 9:13 Comment(0)
B
0

Whether or not you install opencv3 manually or from Gohlke's whl package, I found the need to create/edit the file cv.py in site_packages as follows to make compatable with old code:

import cv2 as cv
Bighorn answered 23/7, 2016 at 0:31 Comment(2)
Can you explain a little more on why and how did you conclude this?Mispleading
Sorry this only gave limited functionality. Got rid of a couple of errors not the way to go.Bighorn
H
0

You can use the following command on the command prompt (cmd) on Windows:

py -3.3 -m pip install opencv-python

I made a video on how to install OpenCV Python on Windows in 1 minute here:

https://www.youtube.com/watch?v=m2-8SHk-1SM

Hope it helps!

Hollingshead answered 1/3, 2018 at 7:10 Comment(0)
N
0

For Ubuntu - pip3 install opencv-python sudo apt-get install python3-opencv

Nicholson answered 3/2, 2021 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.