近期Mr.Xi要开始“C++从入门到精通"之旅了,作为一个python用户,前面学了无数次都没学好,这次我相信一定能够学有所成!那么今天从opencv的安装以及Cmakelist.txt的编写开始学起。
Opencv3.4.0 ubuntu安装
- 压缩包下载
wget https://github.com/opencv/opencv/archive/3.4.0.zip
- 解压缩
unzip 3.4.0.zip
cd opencv-3.4.0
- 安装依赖库和cmake
sudo apt-get install update
apt-get install cmake
apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtiff4.dev libswscale-dev libjasper-dev
- 建立build文件夹
mkdir build && cd build
- Cmake
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
CMAKE_BUILD_TYPE是指编译的模式,可以选Debug或者Release, CMAKE_INSTALL_PREFIX是指Cmake的安装地址。下图是Cmake成功的界面。
- make
这时build文件夹里应该出现了makefile文件,下面执行编译命令(这一段时间很长):
sudo make
- 安装
sudo make install
- 安装完成以后,需要配置环境变量
sudo gedit /etc/ld.so.conf.d/opencv.conf
打开以后应该是个空白文件,直接添加
/usr/local/lib
- 使配置路径生效
sudo ldconfig
- 配置bash
sudo gedit /etc/bash.bashrc
在最末尾添加
PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
export PKG_CONFIG_PATH
- 使配置生效
source /etc/bash.bashrc
- 更新
sudo updatedb
- 测试是否安装成功
cd opencv-3.4.0/samples/cpp/example_cmake #opencv官方例子
cmake .
make
./opencv_example
若成功安装,屏幕右下角将出现hello opencv的摄像头
查看opencv版本
pkg-config opencv --modversion
- 卸载opencv
如果想要把之前版本的opencv卸载干净,并安装新的版本的opencv
- 删除build文件夹
cd XXXXX/opencv/build #进入opencv build目录
sudo make uninstall
cd ..
sudo rm -r build
2.删除/usr中的opencv相关项
sudo rm -r /usr/local/include/opencv2 /usr/local/include/opencv /usr/include/opencv /usr/include/opencv2 /usr/local/share/opencv /usr/local/share/OpenCV /usr/share/opencv /usr/share/OpenCV /usr/local/bin/opencv* /usr/local/lib/libopencv*
cd /usr
find . -name "*opencv*" | xargs sudo rm -rf
cd /home/*** #切换到opencv路径
chmod a+x /home/***/opencv #赋予opencv可执行权限
rm -r /home/***/opencv #删除Opencv文件夹
至此Opencv安装以及卸载部分已经介绍完了。
Opencv项目Cmakelist.txt的配置
cmake_minimum_required(VERSION 2.8)
project(xi)
find_package( OpenCV 3 REQUIRED )
set(CMAKE_CXX_STANDARD 14)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(xi main.cpp)
target_link_libraries(xi ${OpenCV_LIBS})
如果不配置好Cmakelist,那么在编辑器内是找不到opencv库的。下面以此介绍各行的用途:
- cmake_minimum_required(VERSION 2.8)规定了系统所需最低版本的cmake
- project(XXX)是项目的名字
- find_package( OpenCV 3 REQUIRED )用来在系统里寻找Opencv包,找到以后赋予 ${OpenCV_INCLUDE_DIRS}及{OpenCV_LIBS}相应的值。
- set是赋值的指令,这里是指定C++版本为14
- include_directories(${OpenCV_INCLUDE_DIRS}) 这里是添加opencv的头文件
- add_executable(xi main.cpp) 用来指定哪些cpp用来生成最终的可执行文件
- target_link_libraries(xi ${OpenCV_LIBS}) 用来链接导入库,用在add_executable以后。
Cmakelist的详细语法可以参照链接