Ubuntu 18.04 安装OpenCV C++
构建并安装
仅构建核心模块
# 更新并安装依赖
# 更新并安装依赖
sudo apt update && sudo apt install -y cmake g++ wget unzip
# 下载并解压包
wget -O opencv.zip https://github.com/opencv/opencv/archive/master.zip
unzip opencv.zip
# 创建构建目录
mkdir build
# 配置
cmake ../opencv-master
# 编译
cmake --build . -j20
含有opencv-contrib构建
# 更新并安装依赖
sudo apt update && sudo apt install -y cmake g++ wget unzip
# 下载并解压包
wget -O opencv.zip https://github.com/opencv/opencv/archive/master.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/master.zip
unzip opencv.zip
unzip opencv_contrib.zip
# 创建并进入编译目录
mkdir -p build && cd build
# 配置
cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib-master/modules ../opencv-master
# 编译
cmake --build . -j20
安装
构建完成之后,还需要进行安装,直接在build
目录下安装即可:
sudo make install
默认情况下,OpenCV 将安装到该/usr/local
目录,所有文件将被复制到以下位置:
/usr/local/bin
- 可执行文件/usr/local/lib
- lib (.so) 共享库/usr/local/cmake/opencv4
- cmake 包/usr/local/include/opencv4
- 头文件/usr/local/share/opencv4
- 其他文件(例如 XML 格式的训练级联)
由于/usr/local
由 root 用户拥有,因此需要 sudo
执行安装。
测试是否安装成功
我们简单地用Canny边缘检测算子来验证OpenCV的安装是否成功。
创建并进入一个测试目录:
mkdir demo && cd demo
并在demo
目录随意放一张测试图像demo.jpg
。
创建CMakeLists.txt
文件并写入以下内容:
cmake_minimum_required(VERSION 2.8)
project( demo )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( demo demo.cpp )
target_link_libraries( demo ${OpenCV_LIBS} )
创建demo.cpp
文件并写入以下内容:
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv){
Mat img = imread("./demo.jpg");
Mat DstPic, edge, grayImage;
DstPic.create(img.size(), img.type());
cvtColor(img, grayImage, COLOR_BGR2GRAY);
blur(grayImage, edge, Size(3, 3));
//运行canny算子
Canny(edge, edge, 3, 4, 3);
imwrite("Canny.jpg", edge);
}
然后执行:
cmake .
make
./demo
可以在demo
目录下看到原图和边缘图像:
将OpenCV目录添加到环境变量
想要在任何目录下使用opencv,需在cmake之前将opencv的build目录添加到环境变量OpenCV_DIR
:
export OpenCV_DIR=[YOUR_PATH]/build
Ref:
https://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html
https://blog.csdn.net/weixin_43953829/article/details/96473891
https://blog.csdn.net/qq_41323996/article/details/109469148?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163297708716780255277403%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=163297708716780255277403&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-109469148.pc_search_ecpm_flag&utm_term=%E5%8F%B2%E4%B8%8A%E6%9C%80%E5%85%A8OpenCV%E5%AE%89%E8%A3%85%E5%8F%8A%E9%94%99%E8%AF%AF%E8%A7%A3%E5%86%B3&spm=1018.2226.3001.4187
https://stackoverflow.com/questions/8711109/could-not-find-module-findopencv-cmake-error-in-configuration-process