Ubuntu20.04安装OpenCV并配置Clion工程
1 OpenCV安装
1.1 二进制安装
Ubuntu20.04支持apt二进制安装
sudo apt update
sudo apt install libopencv-dev python3-opencv
查看版本号
python3 -c "import cv2; print(cv2.__version__)"
安装成功返回4.2.0
1.2 源码安装
1.2.1 安装编译环境和依赖
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
1.2.2 Clone最新的OpenCV源码
截止2022.02.27,GitHub更新到OpenCV4.5.5
mkdir ~/opencv_build && cd ~/opencv_build
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
1.2.3 Cmake编译
1.2.3.1 创建临时目录
cd ~/opencv_build/opencv
mkdir -p build && cd build
1.2.3.2 设置编译选项
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_build/opencv_contrib/modules \
-D BUILD_EXAMPLES=ON ..
正常应该出现以下提示
-- Configuring done
-- Generating done
-- Build files have been written to: /home/vagrant/opencv_build/opencv/build
1.2.3.3 开始Cmake编译
make -j8
注:j后面的数字为处理器内核数,可以使用nproc 来查询
1.2.4 安装OpenCV
sudo make install
1.2.5 验证安装
C++
pkg-config --modversion opencv4
返回4.3.0
Python
python3 -c "import cv2; print(cv2.__version__)"
返回4.3.0-dev
2 Clion工程配置
新建工程,本文选择C++11标准
编辑CmakeList.txt
cmake_minimum_required(VERSION 3.21)
project(OpenCV_Test)
set(CMAKE_CXX_STANDARD 11)
add_executable(OpenCV_Test main.cpp)
find_package(OpenCV REQUIRED)
target_link_libraries(OpenCV_Test ${OpenCV_LIBS})
到运行调试配置中修改工作目录为$ProjectFileDir$ (或手动输入当前main.cpp所在目录)
在工作目录下放置一个图片命名为test.jpg
编写测试程序
#include <iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
int main() {
std::cout << "Hello, World!" << std::endl;
Mat image = imread("./test.jpg");
imshow("OpenCV-Test",image);
waitKey(0);
return 0;
}
编译运行,若配置无误即可显示出图片。
|