文章目录
- 基本环境
- Ubuntu安装Opencv
- 从源码安装opencv-4.x
- 从源码安装opencv-3.x
- 直接pkg包安装
- CLion工程cmake文件写法
- demo
基本环境
(1)安装WSL;
(2)安装cmake:
wget https://github.com/Kitware/CMake/releases/download/v3.20.0/cmake-3.20.0-linux-x86_64.tar.gz
tar -xzvf cmake-3.20.0-linux-x86_64.tar.gz
sudo ln -sf $(pwd)/cmake-3.20.0-linux-x86_64/bin/* /usr/bin/
(3)安装gcc++:
# 如果 Ubuntu 版本 < 18.04,需要加入仓库
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc
sudo apt-get install g++
(4)安装GDB:
sudo apt install gdb
(5)clion建立空工程后选择toolchains如下:
Ubuntu安装Opencv
从源码安装opencv-4.x
依赖:
sudo apt install build-essential cmake git pkg-config libgtk-3-dev \
libavcodec-dev libavformat-dev libswscale-dev libv4l-dev \
libxvidcore-dev libx264-dev libjpeg-dev libpng-dev libtiff-dev \
gfortran openexr libatlas-base-dev python3-dev python3-numpy \
libtbb2 libtbb-dev libdc1394-22-dev libopenexr-dev \
libgstreamer-plugins-base1.0-dev libgstreamer1.0-dev
去github下载最新包:https://github.com/opencv/opencv.git
或者去官网下载 一个版本:https://opencv.org/releases/
cd opencv-4.x
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE ..
make -j8
sudo make install
从源码安装opencv-3.x
方法同opencv-4.x,但安装路径有区别,得注意。
直接pkg包安装
不想编译也ok,直接:
sudo apt-get install -y libopencv-dev
CLion工程cmake文件写法
# 声明要求的 cmake 最低版本
cmake_minimum_required( VERSION 3.8 )
# 声明一个 cmake 工程
project( cpptest )
# 设置编译模式
set( CMAKE_BUILD_TYPE "Debug" )
#set(OpenCV_DIR "/usr/local/share/OpenCV")
set(OpenCV_DIR "/usr/local/share/opencv4") # 给一个安装路径
find_package( OpenCV REQUIRED ) # 找包
#添加OpenCV头文件
include_directories(${OpenCV_INCLUDE_DIRS})
message(STATUS "OpenCV_INCLUDE_DIRS: ${OpenCV_INCLUDE_DIRS}")
message(STATUS "OpenCV_LIBS: ${OpenCV_LIBS}")
# 添加一个可执行程序
# 语法:add_executable( 程序名 源代码文件 )
add_executable( cpptest main.cpp)
# 将库文件链接到可执行程序上
target_link_libraries( cpptest ${OpenCV_LIBS})
demo
#include <iostream>
#include<opencv2/opencv.hpp>//opencv简单程序标配头文件
using namespace cv;//使用cv命名空间
int main()
{
Mat src=imread("/mnt/c/Users/kevin/Desktop/img.png");//读取图片,要提前将图片放在程序路径下
imwrite("/mnt/c/Users/kevin/Desktop/img2.jpg",src);//保存结果图片
return 0;
}