- 下载opencv工程
bash
git clone https://github.com/opencv/opencv.git
git -C opencv checkout 4.x
- 构建并编译opencv
- 在build目录下使用cmake构建生成makefile
bash
cd opencv
mkdir -p build && cd build
cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=ON -D WITH_FFMPEG=ON ..
- 在build目录下使用make编译opencv
bash
make -j8
- 在build目录下安装opencv
bash
sudo make install
- 配置环境
-
配置环境变量:PKG_CONFIG_PATH
- 查找opencv4.pc的位置
bashsudo find / -iname opencv4.pc
- 切换到用户目录下,并创建pkgconfig.sh
bashcd ~ sudo vim /etc/profile.d/pkgconfig.sh
- 将opencv4.pc的路径添加到环境变量PKG_CONFIG_PATH中
bashexport PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
- 使环境变量生效
bashsource /etc/profile
-
配置Opencv的动态库环境
bashsudo vim /etc/ld.so.conf.d/opencv4.conf
在下面添加一行
bash/usr/local/lib
让环境变量生效
bashsource ldconfig
- 测试安装及配置是否成功
bash
cd opencv/samples/cpp/example_camke
make
./opencv_example
- 通过cmake和gcc来构建c/c++程序调用OpenCV
- 在home目录下新建一个文件夹W_CPP,
- 在W_CPP文件夹下写一个test.cc程序,如下:
cpp
#include <iostream>
using std::cout;
using std::endl;
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, vhar** argv){
if(argc != 2){
cout << "usage:DispalyImage.out <Image_Path>\n" << endl;
return -1;
}
Mat image;
image = imread(argv[1], IMREAD_COLOR);
if(!image.data){
cout << "No image data \n" << endl;
return -1;
}
namedWindow("Display Image",WINDOW_AUTOSIZE);
imshow("Display Image",image);
WaitKey(0);
return 0;
}
- 在同一文件夹下写一个CMakeLists.txt,如下
bash
# cmake needs this line
cmake_minimum_required(VERSION 3.10)
# Define project name
project(W_CPP)
# Find OpenCV, you may need to set OpenCV_DIR variable
# to the absolute path to the directory containing OpenCVConfig.cmake file
# via the command line or GUI
find_package(OpenCV REQUIRED)
# If the package has been found, several variables will
# be set, you can find the full list with descriptions
# in the OpenCVConfig.cmake file.
# Print some message showing some of them
message(STATUS "OpenCV library status:")
message(STATUS " config: ${OpenCV_DIR}")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
# set "-std=c++11"
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# Add OpenCV headers location to your include paths
# include_directories(${OpenCV_INCLUDE_DIRS})
# Declare the executable target built from your sources
add_executable(test test.cc)
# Link your application with OpenCV libraries
target_link_libraries(test PRIVATE ${OpenCV_LIBS})
- 在同一文件夹下放一张图片,比如 shen.png
- 命令行切换到W_CPP目录下,创建build文件夹并进入build目录,依次执行以下命令
bash
mkdir -p build
cd build
cmake ..
make
./test shen.png
参考博客: