python3之opencv安装

一、安装

pip3 install numpy
pip3 install opencv-python

以上在ubunt上安装成功,但是在树莓派安装失败,在树莓派上Python2可以使用apt install python-opencv安装成功,Python3只能自己编译

二、树莓派在python3中安装opencv

参考网页:https://www.cnblogs.com/lynsyklate/p/7719500.html

1. 获取源码

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

这里需要注意,opencv和contrib必须对应否则编译会失败,因此我此处clone了最新的

2. 使用CMAKE从源码构建项目

1. 创建临时目录用来存储我们编译后的opencv库

	cd opencv
	mkdir build
	cd build

2. 构建项目

	cmake -D CMAKE_BUILD_TYPE=Release 
	-D CMAKE_INSTALL_PREFIX=/usr/local 
	-D OPENCV_EXTRA_MODULES=../../opencv_contrib/modules 
	PYTHON3_EXECUTABLE = /usr/bin/python3
	PYTHON_INCLUDE_DIR = /usr/include/python3.5
	PYTHON_INCLUDE_DIR2 = /usr/include/arm-linux-gnueabihf/python3.5m
	PYTHON_LIBRARY = /usr/lib/arm-linux-gnueabihf/libpython3.5m.so
	PYTHON3_NUMPY_INCLUDE_DIRS = /home/pi/.local/lib/python3.5/site-packages/numpy/core/include/
	..


Python的libraries,numpy,packages Path都没有,说明Python环境不正常,不会生成Python的opencv库,到时候会报ImportError: No module named cv2的错误。

网上教程害死人,打开opencv的CMAKELists.txt,发现许多变量名是错的,下面是opencv的CMAKELists.txt部分代码。

status("  Python 3:")
status("    Interpreter:"     PYTHON3INTERP_FOUND  THEN "${PYTHON3_EXECUTABLE} (ver ${PYTHON3_VERSION_STRING})"       ELSE NO)
if(BUILD_opencv_python3)
  if(PYTHON3LIBS_VERSION_STRING)
    status("    Libraries:"   HAVE_opencv_python3  THEN  "${PYTHON3_LIBRARIES} (ver ${PYTHON3LIBS_VERSION_STRING})"   ELSE NO)
  else()
    status("    Libraries:"   HAVE_opencv_python3  THEN  "${PYTHON3_LIBRARIES}"                                      ELSE NO)
  endif()
  status("    numpy:"         PYTHON3_NUMPY_INCLUDE_DIRS THEN "${PYTHON3_NUMPY_INCLUDE_DIRS} (ver ${PYTHON3_NUMPY_VERSION})" ELSE "NO (Python3 wrappers can not be generated)")
  status("    packages path:" PYTHON3_EXECUTABLE         THEN "${PYTHON3_PACKAGES_PATH}"                                    ELSE "-")
endif()

按照opencv的CMAKELists.txt修改配置命令:

cmake -D BUILD_opencv_python3=YES -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES=../../opencv_contrib/modules -D PYTHON3_LIBRARIES=/usr/lib/arm-linux-gnueabihf/libpython3.5m.so -D PYTHON3_NUMPY_INCLUDE_DIRS=/home/pi/.local/lib/python3.5/site-packages/numpy/core/include/ ..

终于配置成功了,犯了以下错误:

1. 指定参数的时候有些没加-D。
2. 没有启用BUILD_opencv_python3。
3. 部分变量名错了

配置成功后应该如下图所示:

3. 编译与安装

make -j4
sudo make install
//更新动态库
sudo ldconfig

注:报错ImportError: numpy.core.multiarray failed to import,import numpy也失败报错libblas.so.3: cannot open shared object file: No such file or directory。

解决:sudo apt-get install libatlas3-base

最终安装成功

三、在树莓派上安装c语言的opencv

​ sudo apt-get install libcv-dev

写一个小程序查看版本:

	#include <stdio.h>
	#include <opencv/cv.h>
	
	int main(void){
		printf("%s\n", CV_VERSION);
	}

可以发现我们安装的是2.4.9.1版本,并不是最新的版本

扩展

  1. 支持ffmpeg,参考我的文档--opencv读写视频流

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×