ubuntu编译安装并测试opencv

  1. 下载opencv工程
git clone https://github.com/opencv/opencv.git
git -C opencv checkout 4.x
  1. 构建并编译opencv
  • 在build目录下使用cmake构建生成makefile
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
make -j8
  1. 在build目录下安装opencv
sudo make install
  1. 配置环境
  • 配置环境变量:PKG_CONFIG_PATH
    • 查找opencv4.pc的位置
    sudo find / -iname opencv4.pc
    
    • 切换到用户目录下,并创建pkgconfig.sh
    cd ~
    sudo vim /etc/profile.d/pkgconfig.sh
    
    • 将opencv4.pc的路径添加到环境变量PKG_CONFIG_PATH中
    export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
    
    • 使环境变量生效
    source /etc/profile
    
  • 配置Opencv的动态库环境
    sudo vim /etc/ld.so.conf.d/opencv4.conf
    
    在下面添加一行
    /usr/local/lib
    
    让环境变量生效
    source ldconfig
    
  1. 测试安装及配置是否成功
cd opencv/samples/cpp/example_camke
make
./opencv_example
  1. 通过cmake和gcc来构建c/c++程序调用OpenCV
  • 在home目录下新建一个文件夹W_CPP,
  • 在W_CPP文件夹下写一个test.cc程序,如下:
#include 
using std::cout;
using std::endl;
#include 
using namespace cv;

int main(int argc, vhar** argv){
	if(argc != 2){
		cout << "usage:DispalyImage.out \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,如下
# 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目录,依次执行以下命令
mkdir -p build
cd build
cmake ..
 make
./test shen.png

参考博客:

Linux/Ubuntu下使用VS Code配置C/C++项目环境调用OpenCV

你可能感兴趣的:(ubuntu,opencv,c++)