为 Python 3.3 安装 opencv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20953273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Install opencv for Python 3.3
提问by tim
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.pydfile to C:\Program Files (x86)\Python333\Lib\site-packagesthis still yields the error in Python IDLE:
OpenCV 仍然不适用于 Python 3.3,我真的必须降级到 Python 2.7 才能使用它吗?我在互联网上没有找到太多关于它的信息,只有 2012 年的一些帖子表明 OpenCV 尚未移植到 Python 3.x 中使用。但是现在是 2014 年,在尝试安装最新的 OpenCV 2.4.x 并将cv2.pyd文件复制到C:\Program Files (x86)\Python333\Lib\site-packages 之后,这仍然会在 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.
采纳答案by midopa
EDIT: first try the new pip method:
编辑:首先尝试新的 pip 方法:
Windows: pip3 install opencv-python opencv-contrib-python
视窗: pip3 install opencv-python opencv-contrib-python
Ubuntu: sudo apt install python3-opencv
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 + Python 3.3 + Windows。从那时起,Python 3.5 已经发布。此外,我将 Ubuntu 用于大多数开发,因此不幸的是,此答案将侧重于该设置
OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 is possible! Here's how.
OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 是可能的!就是这样。
These steps are copied (and slightly modified) from:
这些步骤是从以下位置复制(并稍作修改):
- http://docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html
- https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.html#install-opencv-python-in-fedora
- http://docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html
- https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.html#install-opencv-python-in-fedora
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
构建 OpenCV
CMake Flags
CMake 标志
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 cmakecommand:
有几个标志和选项可以调整您的 OpenCV 构建。可能有关于它们的综合文档,但这里有一些可能有用的有趣标志。它们应该包含在cmake命令中:
# 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
使用非系统级 Python 版本
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 cmakecommand seen later in the script. Actual values will depend on your setup. I use pyenv:
如果您有多个 Python 版本(例如,使用 pyenv 或 virtualenv),那么您可能希望针对某个 Python 版本进行构建。默认情况下,OpenCV 将为系统的 Python 版本构建。您可以通过将这些参数添加到cmake脚本后面看到的命令来更改它。实际值将取决于您的设置。我使用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
CMake Python 错误消息
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.
CMakeLists 文件将尝试检测要构建的各种 Python 版本。如果你在这里有不同的版本,它可能会感到困惑。上述参数可能只能“修复”一个 Python 版本的问题,而不能“修复”另一个版本的问题。如果您只关心那个特定版本,那么就没有什么可担心的。
This is the case for me so unfortunately, I haven't looked into how to resolve the issues with other Python versions.
不幸的是,我就是这种情况,我还没有研究如何解决其他 Python 版本的问题。
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 installscript 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:
默认情况下,install脚本会将 Python 绑定放在某个系统位置,即使您已指定要使用的 Python 的自定义版本。解决方法很简单:在本地绑定中放置一个符号链接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.
第一个路径将取决于您设置要构建的 Python 版本。第二个取决于您的自定义 Python 版本所在的位置。
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)
回答by Pawel Miech
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.
是的,对 Python 3 的支持在当前版本中仍然不可用,但从3.0版开始即可使用(请参阅此票证)。如果你真的想让 python 3 尝试使用开发版,你可以从 GitHub下载。
EDIT (18/07/2015): version 3.0 is now released and python 3 support is now officially available
编辑 (18/07/2015):3.0 版现已发布,python 3 支持现已正式可用
回答by James Fletcher
I can't comment on midopa's excellent answerdue to lack of reputation.
由于缺乏声誉,我无法评论 midopa 的出色答案。
On a Mac I (finally) successfully installed opencv from sourceusing the following commands:
在 Mac 上,我(最终)使用以下命令从源代码成功安装了 opencv :
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
将机器可以处理的线程数更改为 8,以加快速度
sudo make install
I added a PYTHONPATHenvironment variable to my ~/.bash_profilefile so that Python could find cv2.so:
我PYTHONPATH在我的~/.bash_profile文件中添加了一个环境变量,以便 Python 可以找到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]
[对于那些使用 PyCharm 的人,我必须转到 Preferences > Project Structure > Add Content Root,并将路径添加到cv2.so的父目录:/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
Could NOT find PythonLibs,通过显式声明python库路径
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
通过显式指向 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'
如果你没有得到一切都很好 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.
这适用于 Macbook Pro Retina 15" 2013、Mavericks 10.9.4、Python 3.4.1(之前从官方下载安装)、源代码中的 opencv3。希望这对某人有所帮助。
回答by Ross R
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.
我在使用 python3 绑定和虚拟环境让 opencv 3.0 在 OSX 上工作时遇到了很多麻烦。其他答案有很大帮助,但仍然需要一点时间。希望这会帮助下一个人。将此保存到build_opencv.sh. 然后下载opencv,修改下面shell脚本中的变量,交叉手指,运行它(. ./build_opencv.sh)。对于调试,请使用其他帖子,尤其是James Fletchers。
Don't forget to add the opencv lib dir to your PYTHONPATH.
不要忘记将 opencv lib 目录添加到您的 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.
注意 - 这也会下载 opencv-contrib,其中许多功能已被移动。而且它们现在也由与文档不同的命名空间引用 - 例如 SIFT 现在位于 cv2.xfeatures2d.SIFT_create 下。呃。
#!/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.
回答by user3731622
Here a solution for (I believe as seen by 'cp34' on the link below) Python 3.4.
这是 Python 3.4 的解决方案(我相信如以下链接中的“cp34”所示)。
Go to to http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv.
转到http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv。
Download the appropriate .whl.
下载相应的 .whl。
Go to the directory where the .whl is saved.
转到保存 .whl 的目录。
Use pip to install the .whl. e.g. pip install opencv_python-3.0.0-cp34-none-win_amd64.whl
使用 pip 安装 .whl。例如pip install opencv_python-3.0.0-cp34-none-win_amd64.whl
Then just use import cv2.
然后只需使用import cv2.
回答by Dima Lituiev
A full instruction relating to James Fletcher's answer can be found here
可以在此处找到与 James Fletcher 的答案相关的完整说明
Particularly for Anaconda distribution I had to modify it this way:
特别是对于 Anaconda 发行版,我必须这样修改它:
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)
最后一行可以省略(见上面的链接)
回答by jamescampbell
I know this is an old thread, but just in case anyone is looking, here is how I got it working on El Capitan:
我知道这是一个旧线程,但以防万一有人在看,这是我在 El Capitan 上工作的方式:
brew install opencv3 --with-python3
brew install opencv3 --with-python3
and wait a while for it to finish.
并等待它完成。
Then run the following as necessary:
然后根据需要运行以下命令:
brew unlink opencv
brew unlink opencv
Then run the following as the final step:
然后运行以下作为最后一步:
brew ln opencv3 --force
brew ln opencv3 --force
Now you should be able to run import cv2no problem in a python 3.x script.
现在您应该能够import cv2在 python 3.x 脚本中运行没有问题。
回答by gesell
Spent 3 hours trying the various options on Ubuntu 14.04LTS mentioned here and in another referenced tutorialto no avail. For a while tried with OpenCV3.0.0 but eventually switched to 3.1.0. The following worked:
花了 3 个小时尝试此处和另一个参考教程中提到的 Ubuntu 14.04LTS 上的各种选项无济于事。有一段时间尝试使用 OpenCV3.0.0,但最终切换到 3.1.0。以下工作:
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:
并使用 virtualenv 使用以下 cmake 选项:
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:
如果您对 ffmpeg 有问题,请添加以下内容以删除视频支持:
-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
还要注意 cmake 关于使用make clean. 如果您运行 make clean 您可能必须重新解压缩原始包。Cmake 已死,Cmake 万岁
回答by Ninga
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:
无论您是手动安装 opencv3 还是从 Gohlke 的 whl 包安装,我发现需要在 site_packages 中创建/编辑文件 cv.py 如下,以使其与旧代码兼容:
import cv2 as cv
回答by Allan Galdino
Use the pip application. On windows you find it in Python3/Scripts/pip.exeand On Ubuntu you can install with apt-get install python3-pip.
and so, use the command line:
使用 pip 应用程序。在 Windows 上你可以找到它Python3/Scripts/pip.exe,在 Ubuntu 上你可以用apt-get install python3-pip. 因此,使用命令行:
pip3 install --upgrade pip
pip3 install --upgrade pip
pip3 install opencv-python
pip3 install opencv-python
On Windows use only pip.exe instead pip3
在 Windows 上只使用 pip.exe 而不是 pip3

