ubuntu24 c++ 自定义目录编译opencv4.12
目录结构 在opencv-4.12.0文件
编译之前一定要安装好必须的库,否则即使提示编译成功,调用opencv后也可能会有问题
sudo apt-get update
sudo apt-get upgradesudo apt-get install -y g++
sudo apt-get install -y cmake
sudo apt-get install -y make
sudo apt-get install -y wget
sudo apt-get install -y unzip
sudo apt-get install -y gitsudo apt-get install build-essential pkg-config sudo apt-get install libgtk2.0-dev libgtk-3-dev libglib2.0-dev libavcodec-dev libavformat-dev libswscale-dev libavutil-dev libv4l-dev liblapacke-dev libxvidcore-dev libx264-devsudo apt-get install python-dev python-numpysudo apt-get install libgstreamer-plugins-base1.0-dev libgstreamer1.0-devsudo apt-get install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper1 libjasper-dev libdc1394-22-dev libopenexr-dev libwebp-devsudo apt-get install libatlas-base-dev gfortran sudo apt-get install ffmpeg
以下是编译opencv4.12的命令(有更多的参数待研究)
sudo cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local/opencv4.12 -D OPENCV_ENABLE_NONFREE=ON -D OPENCV_GENERATE_PKGCONFIG=YES -D OPENCV_EXTRA_MODULES_PATH=/home/mwj/pycode/opencv4.12/opencv-4.12.0/opencv_contrib-4.12.0/modules ..
可进入build目录后,右键打开终端
重要备注:
这一条参数是最终opencv生成的位置,默认是/usr/local/,此次我指定了一个文件夹opencv4.12
-D CMAKE_INSTALL_PREFIX=/usr/local/opencv4.12
自定义生成opencv目录的话这个参数建议加上,不然Clion中的CmakeLists.txt可能找不到opencv
-D OPENCV_GENERATE_PKGCONFIG=YES
cmake之后,就是编译
sudo make -j6
sudo make install
正常情况下 Clion CMakeLists.txt中设置成以下内容就可以了
cmake_minimum_required(VERSION 3.28)
project(untitled8)set(CMAKE_CXX_STANDARD 17)add_executable(untitled8 main.cpp)find_package(OpenCV REQUIRED)include_directories(${OpenCV_INCLUDE_DIRS})
Clion如果没有下载可以用命令下载 sudo snap install clion --classic
Clion现在有免费版本了
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>using namespace cv;
using namespace std;int main() {// 创建一个空白图像const int width = 800;const int height = 600;Mat image = Mat::zeros(height, width, CV_8UC3);image.setTo(Scalar(255, 255, 255)); // 设置背景为白色// 圆的参数Point center(width/2, height/2);int radius = 200;Scalar circleColor(0, 0, 255); // 红色int thickness = 3;// 绘制圆circle(image, center, radius, circleColor, thickness);// 计算内嵌等边三角形的三个顶点vector<Point> trianglePoints;for (int i = 0; i < 3; i++) {double angle = CV_PI/2 + i * 2 * CV_PI / 3; // 从垂直向上开始,每隔120度一个点int x = center.x + radius * cos(angle);int y = center.y - radius * sin(angle); // 注意y轴向下为正trianglePoints.push_back(Point(x, y));}// 绘制三角形vector<vector<Point>> contours;contours.push_back(trianglePoints);Scalar triangleColor(0, 255, 0); // 绿色drawContours(image, contours, 0, triangleColor, thickness);// 显示图像namedWindow("Circle with Inscribed Triangle", WINDOW_NORMAL);imshow("Circle with Inscribed Triangle", image);// 等待按键退出waitKey(0);return 0;
}
#include <opencv2/opencv.hpp>#include <opencv2/xfeatures2d.hpp>//SIFT SURF#include<iostream>
#include<vector>constexpr auto path0 = "1.jpg";
constexpr auto path1 = "2.jpg";int main() {cv::Mat image0 = cv::imread(path0, 1);cv::Mat image1 = cv::imread(path1, 1);cv::imshow("image0", image0);cv::imshow("image1", image1);/*step1:特征检测器*/cv::Ptr<cv::xfeatures2d::SURF> detector;detector = cv::xfeatures2d::SURF::create(800); //800为海塞矩阵阈值,越大越精准/*-----SURF----cv::Ptr<cv::xfeatures2d::SURF> detector;detector = cv::xfeatures2d::SURF::create(800); //800为海塞矩阵阈值,越大越精准-----SIFT-----cv::Ptr<cv::xfeatures2d::SIFT> detector;detector = cv::xfeatures2d::SIFT::create(800);//800为保留的点数-----ORB------cv::Ptr<cv::ORB> detector;detector = cv::ORB::create(800);//保留点数-----STAR-----cv::Ptr<cv::xfeatures2d::StarDetector> detector;detector = cv::xfeatures2d::StarDetector::create();-----MSD-----cv::Ptr<cv::xfeatures2d::MSDDetector> detector;detector = cv::xfeatures2d::MSDDetector::create();*/std::vector <cv::KeyPoint > key0;std::vector <cv::KeyPoint > key1;detector->detect(image0,key0,cv::noArray());detector->detect(image1, key1, cv::noArray());/*step2:描述子提取器*/cv::Ptr<cv::xfeatures2d::SURF> Extractor;Extractor = cv::xfeatures2d::SURF::create(800);/*以下都是xfeature2d中的提取器-----SURF----------SIFT----------LUCID---------BriefDescriptorExtractor---------VGG----------BoostDesc-----*/cv::Mat descriptor0, descriptor1;Extractor->compute(image0, key0, descriptor0);Extractor->compute(image1, key1, descriptor1);/*step3:匹配器*/cv::BFMatcher matcher;//暴力匹配器std::vector<cv::DMatch> matches; // 存放匹配结果std::vector<cv::DMatch> good_matches; //存放好的匹配结果matcher.match(descriptor0, descriptor1, matches);std::sort(matches.begin(), matches.end()); //筛选匹配点,根据match里面特征对的距离从小到大排序int ptsPairs = std::min(50, (int)(matches.size() * 0.15));std::cout << "匹配点数为" << ptsPairs << std::endl;for (int i = 0; i < ptsPairs; i++){good_matches.push_back(matches[i]); //距离最小的50个压入新的DMatch}cv::Mat result;cv::drawMatches(image0, key0,image1, key1,good_matches, result,cv::Scalar::all(-1), cv::Scalar::all(-1),std::vector<char>(),cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); //绘制匹配点cv::imshow("result", result);cv::waitKey(0);
}
如果Clion中找不到opencv,可以设置变量
先打开 sudo gedit ~/.bashrc
export PKG_CONFIG_PATH=/usr/local/opencv4.12/lib/pkgconfig
export LD_LIBRARY_PATH=/usr/local/opencv4.12/lib
保存之后,再执行命令source ~/.bashrc
以下是vscode中调用c++ opencv
.vscode文件夹下面创建3个json (参考,根据实际路径修改)
c_cpp_properties.json
{"configurations": [{"name": "Linux","includePath": ["${workspaceFolder}/**","/usr/local/opencv4.12/include/opencv4"],"defines": [],"compilerPath": "/usr/bin/gcc","cStandard": "gnu11","cppStandard": "gnu++14","intelliSenseMode": "linux-gcc-x64"}],"version": 4
}
launch.json
{// Use IntelliSense to learn about possible attributes.// Hover to view descriptions of existing attributes.// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387"version": "0.2.0","configurations": [{"name": "g++ - Build and debug active file","type": "cppdbg","request": "launch","program": "${fileDirname}/${fileBasenameNoExtension}", //程序文件路径"args": [], //程序运行需传入的参数"stopAtEntry": false,"cwd": "${fileDirname}","environment": [],"externalConsole": true, //运行时是否显示控制台窗口"MIMode": "gdb","setupCommands": [{"description": "Enable pretty-printing for gdb","text": "-enable-pretty-printing","ignoreFailures": true}],"preLaunchTask": "C/C++: g++ build active file","miDebuggerPath": "/usr/bin/gdb"}]
}
tasks.json
{"tasks": [{"type": "cppbuild","label": "C/C++: g++ build active file", /* 与launch.json文件里的preLaunchTask的内容保持一致 */"command": "/usr/bin/g++","args": ["-std=c++11","-g","${file}", /* 编译单个文件 */// "${fileDirname}/*.cpp", /* 编译多个文件 */"-o","${fileDirname}/${fileBasenameNoExtension}", /* 输出文件路径 *//* 项目所需的头文件路径 */"-I","${workspaceFolder}/","-I","/usr/local/opencv4.12/include/","-I","/usr/local/opencv4.12/include/opencv4/","-I","/usr/local/opencv4.12/include/opencv4/opencv2",/* 项目所需的库文件路径 */"-L", "/usr/local/opencv4.12/lib",/* OpenCV的lib库 */"/usr/local/opencv4.12/lib/libopencv_*"],"options": {"cwd": "${fileDirname}"},"problemMatcher": ["$gcc"],"group": {"kind": "build","isDefault": true},"detail": "Task generated by Debugger."}],"version": "2.0.0"
}