总结一下这两天在macOS上装OpenCV的血泪史
Requirement
Xcode
VScode
OpenCV官网 下载最新版source file
brew install cmake
编译OpenCV的source file cd到opencv-4.0.1
文件夹下(目前最新版是4.0.1)
mkdir build
用于存放后面生成的文件
1 2 3 4 cd build cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local .. #会生成一堆文件在build文件夹以及/usr/local文件夹 make # compile sudo make install
这时候OpenCV已经安装好了
VScode配置 Demo cpp如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include <stdio.h> #include <opencv2/opencv.hpp> #include <chrono> #include <thread> using namespace cv; int main(int argc, char** argv ) { printf("HEllo World!\n"); if ( argc != 2 ) { printf("usage: DisplayImage.out <Image_Path>\n"); return -1; } printf("%s\n", argv[1]); Mat image = imread( argv[1], 1 ); if ( !image.data ) { printf("No image data \n"); return -1; } namedWindow("Display Image", WINDOW_AUTOSIZE ); imshow("Display Image", image); waitKey(0); std::this_thread::sleep_for(std::chrono::milliseconds(10000)); return 0; }
配置c_cpp_properties.json:增加opencv安装位置的路径
1 2 3 4 "includePath": [ "${workspaceFolder}/**", "/usr/local/include/opencv4" ]
这时候code里面就可以用opencv的代码提示了
用cmake compile程序 在main.cpp所在目录新建一个文件CMakeLists.txt
,指定编译时需要用的库
1 2 3 4 5 6 7 8 cmake_minimum_required(VERSION 3.13.4) set(CMAKE_CXX_STANDARD 11) //c++标准 cv4需要c11 set(CMAKE_CXX_STANDARD_REQUIRED ON) project( CV ) //自定义project名称为CV find_package( OpenCV REQUIRED ) //搜索opencv库 include_directories( ${OpenCV_INCLUDE_DIRS} ) //include opencv add_executable( CV main.cpp ) //生成的可执行命令,自定义为CV target_link_libraries( CV ${OpenCV_LIBS} )
然后
1 2 3 mkdir build #可自定义 cd build cmake ..
这时候已经vscode全部配置好了
Usage cpp代码写好之后,在build
文件夹里面执行make
就会编译cpp文件了。
1 2 3 4 5 6 7 -- Configuring done -- Generating done -- Build files have been written to: /Users/T5eng/Desktop/CV/build Scanning dependencies of target CV [ 50%] Building CXX object CMakeFiles/CV.dir/main.cpp.o [100%] Linking CXX executable CV [100%] Built target CV
这时候会生成一个可执行命令CV
如无意外,会输出一个hello world同时显示图片。
大功告成