在Ubuntu上安装OpenCV并使用C++进行快速开发,你可以遵循以下步骤:
1 更新系统包索引并安装必要的包:
sudo apt update
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
2克隆OpenCV的GitHub仓库(这一步可能git clone会卡住,直接将地址粘贴到网页上直接到git网页上下zip包然后解压,解压后可能是opencv_4x 或opencv_contrib_4x,把这两个文件夹的名字中的_4x去掉,最后把opencv和opencv_contrib这两个文件夹拷贝到~/opencv_build中:
mkdir ~/opencv_build && cd ~/opencv_build
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
3.编译OpenCV:
cd ~/opencv_build/opencv
mkdir build && cd build
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 ..
make -j$(nproc)
sudo make install
sudo ldconfig
4 验证安装是否成功,运行一个简单的C++ OpenCV程序:
// main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
cv::Mat image = cv::imread("test.jpg"); // 确保当前目录有test.jpg图片
if (image.empty()) {
std::cout << "Could not open or find the image" << std::endl;
return -1;
}
cv::namedWindow("Display window", cv::WINDOW_AUTOSIZE);
cv::imshow("Display window", image);
cv::waitKey(0);
return 0;
}
Makefile中添加
LIBS := -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_video -lopencv_highgui -lopencv_calib3d\
-lopencv_features2d -lopencv_flann -lopencv_imgcodecs -lopencv_videoio\
-lm -lpthread
INC := -I/usr/include/opencv4/
在命令行中执行如下:
sudo ln -s /usr/include/opencv4/opencv2 /usr/include/
FR:徐海涛(hunkxu)