Ubuntu20.04安装C++版Opencv4

1 更新

sudo apt-get update
sudo apt-get upgrade

2 安装依赖项

$ sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev 
$ sudo apt-get install libjpeg-dev libpng-dev libtiff5-dev libjasper-dev libdc1394-22-dev libeigen3-dev libtheora-dev libvorbis-dev libxvidcore-dev libx264-dev sphinx-common libtbb-dev yasm libfaac-dev libopencore-amrnb-dev libopencore-amrwb-dev libopenexr-dev libgstreamer-plugins-base1.0-dev libavutil-dev libavfilter-dev libavresample-dev

3 下载opencv
进入这个网址:https://github.com/opencv/opencv/releases 选择对应的版本。`

sudo su # change to root
cd /opt # 3rd party software install dir, not necessary
git clone https://github.com/opencv/opencv.git
cd opencv 
git checkout 4.5.3
cd ..
 
git clone https://github.com/opencv/opencv_contrib.git
cd opencv_contrib
git checkout 4.5.3
cd ..

4 编译和安装opencv

/opt$ cd opencv
/opt/opencv$ mkdir release
/opt/opencv$ cd release
/opt/opencv/release$ cmake -D BUILD_TIFF=ON -D WITH_CUDA=OFF -D ENABLE_AVX=OFF -D WITH_OPENGL=OFF -D WITH_OPENCL=OFF -D WITH_IPP=OFF -D WITH_TBB=ON -D BUILD_TBB=ON -D WITH_EIGEN=OFF -D WITH_V4L=OFF -D WITH_VTK=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=/opt/opencv_contrib/modules /opt/opencv/
/opt/opencv/release$ make -j4 # multi task
/opt/opencv/release$ make install
/opt/opencv/release$ ldconfig
/opt/opencv/release$ exit # exit root
/opt/opencv/release$ cd ~

5 检查安装是否成功

pkg-config --modversion opencv

pkg-config --modversion opencv4 #opencv4版本

如果报错:"No package” “opencv4.pc” “found”
OpenCV4以上版本默认不使用pkg-config,但是可以通过相应的编译选项开启该功能。
在第4步cmake命令后添加

-D OPENCV_GENERATE_PKGCONFIG=ON

安装成功会显示对应的版本号

4.5.3

6 测试程序时候的一些错误

6.1 报错"fatal error:opencv2/core.hpp:没有那个文件目录"
这个时候进入/usr/local/include/ 目录里面,你能看到只有opencv4这个文件,这个时候把opencv4里面opencv2复制到/usr/local/include/目录里面。

/usr/local/include/opencv4$ sudo mv opencv2 /usr/local/include/

6.2 报错"error while loading shared libraries: libopencv_imgcodecs.so.4.5: cannot open shared object file"

找到该文件的路径

find -name "libopencv_imgcodecs.so.4.5"

显示

./opencv/release/lib/libopencv_imgcodecs.so.4.5

将整个lib文件路径添加到 LD_LIBRARY_PATH 即可。
LD_LIBRARY_PATH是Linux环境变量名,该环境变量主要用于指定查找共享库(动态链接库)时除了默认路径之外的其他路径。

gedit ~/.bashrc

在最后一行添加后

export LD_LIBRARY_PATH=/opt/opencv/release/lib

保存退出
使环境变量生效

source ~/.bashrc

7 最后编译测试

g++ main.cpp -o output `pkg-config --cflags --libs opencv4`
./output

参考
https://blog.csdn.net/weixin_44278406/article/details/103619191
https://blog.csdn.net/jcl314159/article/details/118672258
https://blog.csdn.net/chengyq116/article/details/104302959

总结
主要参考上面大佬的博客进行的安装学习,记录一些遇到的报错
c++版opencv学习记录。
这是不带GPU的版本,下次装下带GPU的。

你可能感兴趣的:(Opencv学习记录(C++),opencv,c++)