前言
这阵子做一些小项目用到了opencv,于是在wsl ubuntu 22.04上通过源代码编译了opencv。这里记录一下安装过程。
安装依赖
1 2 3 4 5 6 7
| sudo apt-get update sudo apt-get install -y build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev sudo apt-get install -y libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libdc1394-22-dev sudo apt-get install -y libxine2-dev libv4l-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev sudo apt-get install -y libqt4-dev libgtk-3-dev libatlas-base-dev libfaac-dev libmp3lame-dev libtheora-dev sudo apt-get install -y libvorbis-dev libxvidcore-dev libopencore-amrnb-dev libopencore-amrwb-dev libavresample-dev sudo apt-get install -y python3-dev python3-numpy
|
下载源代码
1 2
| git clone https://github.com/opencv/opencv.git git clone https://github.com/opencv/opencv_contrib.git
|
有需要的话,可以切换到指定的版本:
1 2 3 4
| cd opencv git checkout 4.9.0 cd ../opencv_contrib git checkout 4.9.0
|
编译安装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| cd opencv mkdir build && cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX="/usr/local" \ # 安装路径 -D WITH_TBB=ON \ # 使用TBB(线程库) -D WITH_GTK=ON \ # 使用GTK(图形库) -D WITH_GTK_2_X=ON\ # 使用GTK2 -D BUILD_SHARED_LIBS=ON \ -D WITH_EIGEN=ON \ # (非必须)使用线性代数库eigen,需要提前编译好。 -D EIGEN_INCLUDE_PATH="/usr/include/eigen3" \ -D OPENCV_EXTRA_MODULES_PATH="/path/opencv_contrib-4.9.0/modules" \ # opencv_contrib的路径,需要自己修改 -D BUILD_ZLIB=ON \ -D ZLIB_INCLUDE_DIR="/path/opencv-4.9.0/3rdparty/zlib" \ # zlib的路径, 需要自己修改 -D OPENCV_GENERATE_PKGCONFIG=ON \ ..
make -j16 sudo make install
|
后续配置
在/etc/ld.so.conf.d/opencv.conf
文件中(没有则创建)添加:
然后执行:
这时应该配置完毕了,验证一下:
1
| pkg-config --modversion opencv4
|
应该会正常输出版本号。
如果没有,则需打开/etc/bash.bashrc文件,写入如下内容:
1 2
| PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig export PKG_CONFIG_PATH
|
然后执行:
测试
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <opencv2/opencv.hpp> #include <iostream>
int main() { cv::Mat img = cv::imread("test.jpg"); cv::Mat edges; cv::Canny(img, edges, 100, 200); cv::imwrite("test_edges.jpg", edges); return 0; }
|
使用cmake构建:
1 2 3 4 5 6 7 8 9 10 11 12
| cmake_minimum_required(VERSION 3.10) project(demo)
find_package(OpenCV REQUIRED)
add_executable(demo ./main.cpp)
target_link_libraries(demo ${OpenCV_LIBS})
|
编译运行:
1 2 3 4
| mkdir build && cd build cmake .. make ./demo
|