1. 安装前置依赖
sudo apt update
sudo apt upgrade
sudo apt install build-essential cmake git pkg-config
sudo apt install libjpeg-dev libtiff-dev libpng-dev # Image libraries
sudo apt install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev # Video libraries
sudo apt install libxvidcore-dev libx264-dev # Video codecs
sudo apt install libgtk-3-dev # GUI support
sudo apt install libatlas-base-dev gfortran # Optimization libraries
sudo apt install libhdf5-dev libhdf5-serial-dev libhdf5-103 # HDF5 support
sudo apt install libprotobuf-dev protobuf-compiler # Protocol Buffers
sudo apt install libgoogle-glog-dev libgflags-dev # Logging libraries
sudo apt install libgphoto2-dev libeigen3-dev libhdf5-dev doxygen # Misc dependencies
2. 下载 OpenCV 源码
cd ~
git clone https://github.com/opencv/opencv.git
git clone https://github.com/opencv/opencv_contrib.git
3. Configure 和 Build OpenCV
cd ~/opencv
mkdir build
cd build
Run cmake
with necessary flags to configure the build. Replace <path_to_opencv_contrib>
with the actual path to your opencv_contrib/modules
directory:
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D WITH_CUDA=OFF \
-D OPENCV_GENERATE_PKGCONFIG=ON \
-D WITH_GTK=ON \
-D WITH_FFMPEG=ON \
-D OPENCV_EXTRA_MODULES_PATH=/home/mps/opencv_contrib/modules \
-D BUILD_JAVA=OFF \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=OFF \
-D BUILD_EXAMPLES=OFF ..
4. 编译和安装
编译
make -j$(nproc)
安装
sudo make install
sudo ldconfig
5. 验证安装结果
pkg-config --modversion opencv4
mps@ubuntu:~/opencv/build$ pkg-config --modversion opencv4
4.10.0
6. 设置环境变量
添加环境变量到~/.bashrc 或者 ~/.bash_profile:
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig:$PKG_CONFIG_PATH
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
source ~/.bashrc # or source ~/.bash_profile
7. 测试安装结果
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
cv::Mat img = cv::imread("path_to_your_image.jpg");
if (img.empty()) {
std::cerr << "Failed to load image" << std::endl;
return 1;
}
cv::imshow("Image", img);
cv::waitKey(0);
return 0;
}
编译使用:
g++ your_program.cpp -o your_program `pkg-config --cflags --libs opencv4`
执行:
./your_program