【opencv基础】linux系统opencv以及opencv_contrib的安装与使用

前言

本文主要介绍如何在linux系统安装使用opencv.

具体步骤可参考opencv官网here.

步骤

编译源码之前需要安装相关依赖库;

1.下载源码;

2.解压源码;

3.配置cmake;

注意将配置的错误文件删除,以及cmake目录;

4.编译链接;

编译过程涉及到opencv的编译选项;

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc -D CMAKE_INSTALL_PREFIX=/usr/local  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules/  -D CUDA_CUDA_LIBRARY=/usr/local/cuda/lib64/stubs/libcuda.so   -D CUDA_ARCH_BIN=6.1  -D CUDA_ARCH_PTX="" -D WITH_CUDA=ON -D WITH_TBB=ON  -D WITH_FFMPEG=ON  -D BUILD_PYTHON_SUPPORT=ON -D BUILD_NEW_PYTHON_SUPPORT=ON  -D BUILD_OPENCV_PYTHON3=ON  -D PYTHON_INCLUDE_DIR=/home/xxx/anaconda3/include/python3.8  -D PYTHON_PACKAGES_PATH=/home/xxx/anaconda3/lib/python3.8/site-packages   -D WITH_V4L=ON  -D INSTALL_C_EXAMPLES=ON  -D INSTALL_PYTHON_EXAMPLES=ON  -D BUILD_EXAMPLES=ON  -D WITH_QT=ON  -D WITH_GSTREAMER=ON  -D WITH_OPENGL=ON  -D ENABLE_FAST_MATH=1   -D CUDA_FAST_MATH=1  -D OPENCV_GENERATE_PKGCONFIG=ON   -D OPENCV_PC_FILE_NAME=opencv.pc  -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda  -D CMAKE_LIBRARY_PATH=/usr/local/cuda/lib64/stubs   -D WITH_CUBLAS=ON   -D WITH_NVCUVID=ON  -D BUILD_opencv_cudacodec=ON  -D OPENCV_DNN_CUDA=ON -D WITH_CUDNN=ON  -D OPENCV_ENABLE_NONFREE=ON -D WITH_GSTREAMER=ON -D BUILD_EXAMPLES=ON ..

cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_C_COMPILER=/usr/bin/gcc -D CMAKE_INSTALL_PREFIX=/usr/local  -D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules/  -D CUDA_CUDA_LIBRARY=/usr/local/cuda/lib64/stubs/libcuda.so   -D CUDA_ARCH_BIN=8.6  -D CUDA_ARCH_PTX="" -D WITH_CUDA=ON -D WITH_TBB=ON  -D WITH_FFMPEG=ON  -D BUILD_PYTHON_SUPPORT=ON -D BUILD_NEW_PYTHON_SUPPORT=ON  -D BUILD_OPENCV_PYTHON3=ON  -D PYTHON_INCLUDE_DIR=/usr/include/python3.8 -D PYTHON_LIBRARY=/usr/lib/python3.8/config-3.8-x86_64-linux-gnu/libpython3.8.so -D WITH_V4L=ON  -D INSTALL_C_EXAMPLES=ON  -D INSTALL_PYTHON_EXAMPLES=ON -D BUILD_EXAMPLES=ON -D WITH_QT=ON  -D WITH_GSTREAMER=ON  -D WITH_OPENGL=ON  -D ENABLE_FAST_MATH=1   -D CUDA_FAST_MATH=1  -D OPENCV_GENERATE_PKGCONFIG=ON   -D OPENCV_PC_FILE_NAME=opencv.pc  -D CUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda  -D CMAKE_LIBRARY_PATH=/usr/local/cuda/lib64/stubs   -D WITH_CUBLAS=ON   -D WITH_NVCUVID=ON  -D BUILD_opencv_cudacodec=ON  -D OPENCV_DNN_CUDA=ON -D WITH_CUDNN=ON  -D OPENCV_ENABLE_NONFREE=ON -D WITH_GSTREAMER=ON -D BUILD_EXAMPLES=ON ..

cmake -DPYTHON_INCLUDE_DIR=/usr/include/python3.8 -DPYTHON_LIBRARY=/usr/lib/python3.8/config-3.8-x86_64-linux-gnu/libpython3.8.so 

 

5.安装库;

Required Packages

[compiler] sudo apt-get install build-essential
[required] sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
[optional] sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev

 注意,安装opencv之前尽量将所需依赖项安装好!!!!!

Bash

/opt$ sudo unzip opencv-3.3.1.zip
/opt$cd opencv-3.3.1
/opt/opencv-3.3.1$sudo mkdir build
/opt/opencv-3.3.1$cd build
/opt/opencv-3.3.1/build$sudo cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
/opt/opencv-3.3.1/build$sudo make -j8(wait long time/opt/opencv-3.3.1/build$sudo make install

注意事项

1. 注意你要安装的opencv的版本以及cv12、cv14等;

2.首先需要安装opencv的依赖库,而且必须是在安装opencv之前优先安装依赖库,可参考here

3.测试程序完成之后,需要CMakeLists.txt进行编译,可参考here

CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
PROJECT(test_opencv)
SET(OpenCV_DIR /lib/opencv2413/opencv-2.4.13.4/build)
INCLUDE_DIRECTORIES(/lib/opencv2413/opencv-2.4.13.4/build/include)
FIND_PACKAGE(OpenCV REQUIRED)  
ADD_EXECUTABLE(test_opencv test_opencv.cpp)  
TARGET_LINK_LIBRARIES(test_opencv ${OpenCV_LIBS})

FIND_PACKAGE可以设置为多个opencv版本之间的切换;

FIND_PACKAGE(OpenCV 3.3.1 REQUIRED)  

example

find_package( OpenCV 3.1.0 REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} ) 
message("OpenCV_INCLUDE_DIRS: ${OpenCV_INCLUDE_DIRS}") 
message("OpenCV_LIBS: ${OpenCV_LIBS}") 
target_link_libraries( demo ${OpenCV_LIBS} )

4.其他多是调试代码;

如何卸载

cd build
sudo make uninstall 
cd .. 
sudo rm -r build 
sudo rm -r /usr/local/include/opencv2 /usr/local/include/opencv /usr/include/opencv /usr/include/opencv2 /usr/local/share/opencv /usr/local/share/OpenCV /usr/share/opencv /usr/share/OpenCV /usr/local/bin/opencv* /usr/local/lib/libopencv*
cd ..
rm -r opencv3.3.1

添加opencv_contrib

to build with modules from opencv_contrib set OPENCV_EXTRA_MODULES_PATH to <path to opencv_contrib/modules/>

command

/opt/opencv-3.3.1/build$ sudo cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules/ .. 

error

CMake Error at cmake/OpenCVModule.cmake:296 (add_subdirectory):
  The binary directory

    /opt/opencv-3.3.1/build/modules/cudaarithm/.cudaarithm

  is already used to build a source directory.  It cannot be used to build
  source directory

    /opt/opencv-3.3.1/opencv_contrib/modules/cudaarithm

  Specify a unique binary directory name.
Call Stack (most recent call first):
  modules/CMakeLists.txt:7 (ocv_glob_modules)

都是类似以上的错误,过程参考herehere,还没有解决。

最后发现是系统有些文件不合适,删除之后再编译就ok啦。。。。发现这个不能解决根本问题。

编译通过但是编译测试程序的时候还是有问题,没有找到对应的文件,个人觉得应该注意opencv_contrib的版本here问题,正在测试。

最后还是两者的版本问题,两个版本一定要一致。

还有就是cmake那个步骤,这次使用的是绝对路径,不知道使用相对路径是否会出问题,试过的童鞋可以回答一下这个问题。

后来使用相同的版本安装编译之后,使用opencv_contrib中的samples中的例程进行测试,可以正常运行,即说明安装成功。

如果还有问题,可能是本身程序有什么BUG引起的,可以进行调试。

test code

/*----------------------------------------------
 * Usage:
 * ./test 0 
 *--------------------------------------------------*/

#include <opencv2/core/utility.hpp>
#include <opencv2/tracking.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <cstring>
#include "samples_utility.hpp"

using namespace std;
using namespace cv;

int main( int argc, char** argv ){
  // show help
  if(argc<2){
    cout<<
      " Usage: example_tracking_kcf <video_name>\n"
      " examples:\n"
      " example_tracking_kcf Bolt/img/%04.jpg\n"
      " example_tracking_kcf faceocc2.webm\n"
      << endl;
    return 0;
  }

  // create the tracker
  Ptr<Tracker> tracker = TrackerKCF::create();

  // set input video
  std::string video = argv[1];
  VideoCapture cap(0);

  Mat frame;

  // get bounding box
  cap >> frame;
  Rect2d roi= selectROI("tracker", frame, true, false);

  //quit if ROI was not selected
  if(roi.width==0 || roi.height==0)
    return 0;

  // initialize the tracker
  tracker->init(frame,roi);

  // do the tracking
  printf("Start the tracking process, press ESC to quit.\n");
  for ( ;; ){
    // get frame from the video
    cap >> frame;

    // stop the program if no more images
    if(frame.rows==0 || frame.cols==0)
      break;

    // update the tracking result
    bool isfound = tracker->update(frame,roi);
    if(!isfound)
    {
        cout << "The target has been lost...\n";
        waitKey(0);
        return 0;
    }

    // draw the tracked object
    rectangle( frame, roi, Scalar( 255, 0, 0 ), 2, 1 );

    // show image with the tracked object
    imshow("tracker",frame);

    //quit on ESC button
    if(waitKey(1)==27)break;
  }

}
View Code

总结

1.准备安装的opencvopencv_contrib的版本一定要一致,切记!!!

2.按照官网的步骤一步步执行相应的操作,一定要注意cmake那个步骤。

3.安装完成之后可以使用源码中的一些samples代码进行测试。

4.测试的程序一定要没有bug哈~

update 20220714

编译opencv_contrib时候发现没有编译出opencv_world.so,需要cmake开启开关:

-D BUILD_opencv_world=ON

缺点:只生成一个opencv_world.so,其他的.so都没有!

 错误

opencv_4.5.2/opencv/modules/gapi/src/executor/gtbbexecutor.cpp:231:35: error: ‘ittTbbAddReadyBlocksToQueue’ was not declared in this scope; did you mean ‘cv::gimpl::parallel::detail::tasking::{anonymous}::ittTbbAddReadyBlocksToQueue’?
231 | GAPI_ITT_AUTO_TRACE_GUARD(ittTbbAddReadyBlocksToQueue);

原因

#ifdef OPENCV_WITH_ITT
namespace {
    static __itt_string_handle* ittTbbAddReadyBlocksToQueue   = __itt_string_handle_create("add ready blocks to queue");
    static __itt_string_handle* ittTbbSpawnReadyBlocks        = __itt_string_handle_create("spawn ready blocks");
    static __itt_string_handle* ittTbbEnqueueSpawnReadyBlocks = __itt_string_handle_create("enqueueing a spawn of ready blocks");
    static __itt_string_handle* ittTbbUnlockMasterThread      = __itt_string_handle_create("Unlocking master thread");
}
#endif // OPENCV_WITH_ITT

所以取消WITH_ITT即可;

-D WITH_ITT=OFF

 最后还是有问题,直接使用cmake gui进行编译,参考here

编译时ippicv有问题,可以先下载ippicv_2020_lnx_intel64_20191018_general.tgz文件,然后修改配置文件重新make即可;

配置文件:opencv-4.6.0/3rdparty/ippicv/ippicv.cmake

  set(THE_ROOT "${OpenCV_BINARY_DIR}/3rdparty/ippicv")
  ocv_download(FILENAME ${OPENCV_ICV_NAME}
               HASH ${OPENCV_ICV_HASH}
               URL
                 "${OPENCV_IPPICV_URL}"
                 "$ENV{OPENCV_IPPICV_URL}"
                 "https://raw.githubusercontent.com/opencv/opencv_3rdparty/${IPPICV_COMMIT}/ippicv/"  # 修改为下载文件所在路径即可
               DESTINATION_DIR "${THE_ROOT}"
               ID IPPICV
               STATUS res
               UNPACK RELATIVE_URL)

修改为

file:/home/abc/workspace/utils/opencv/opencv-4.6.0/3rdparty/ippicv/”

即可,此时所下载文件在此目录下。

使用 cmake-gui配置opencv进行编译;

cmake-gui配置

1. 勾选上BUILD_opencv_world
这在有多个Opencv版本的库文件时尤其重要,这时可以通过链接libopencv_world.so.4.5.5这样的库区别其他版本的库函数。

2. 在CMAKE_BUILD_TYPE后填上:Release
这一点只要检查一下就可以了,默认就是Release的。当然如果你想调试Opencv的源码,也可以编译Debug版本。

3. 勾选上OPENCV_ENABLE_NONFREE
opencv提供了很多有意思的算法,这些算法商业上有版权,但源码是公开的,你可以编译进去。很多算法通常我也用不到,但万一想测试一下呢,那就不用重新编译了。

4. 在OPENCV_EXTRA_MODULES_PATH后填上opencv-contrib/modules的路径,比如我的是:/home/mc/opencv455/opencv_contrib-4.5.5/modules
这个附加功能模块的位置,提供相当多有意思的算法。如果你只需要opencv的核心模块的话,这个是可以不填写的。

5. WITH_GTK/ WITH_GTK_2_X/ WITH_QT

编译安装

$ cd build
$ nproc #查询线程数量
12
$ make -j12  #开始编译
$ sudo make install #安装
 
$ sudo make uninstall #如果想卸载
$ cd  ..
$ sudo rm -r  build

 错误

terminate called after throwing an instance of 'cv::Exception'
  what():  OpenCV(4.6.0) /home/abc/workspace/utils/opencv/opencv-4.6.0/modules/highgui/src/window.cpp:1250: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvNamedWindow'

需要添加配置选项;

5. WITH_GTK/ WITH_GTK_2_X/ WITH_QT

另外,还有pkg-config的问题;

OPENCV_GENERATE_PKGCONFIG

 安装完成之后,/usr/local/lib/pkconfig目录下会有一个opencv4.pc文件,export PKG_CONFIG_PATH到环境变量配置文件。

vi /home/abc/.bashrc
export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/lib/pkgconfig
source /home/abc/.bashrc
#
sudo find / -name pkgconfig
pkg-config
--cflags opencv4 pkg-config --libs opencv4 pkg-config --modversion opencv4

 重新安装 install libgtk2.0-dev and pkg-config,以及opencv;

错误

Gtk-Message: 13:52:51.233: Failed to load module "canberra-gtk-module"

解决方法:

sudo apt-get install libcanberra-gtk-module

 注意,安装opencv之前尽量将所需依赖项安装好!!!!!

update20230803

使用cmake-gui配置编译选项安装opencv470基本核心模块的过程;

cd opencv
unzip opencv-4.7.0.zip  # 解压opencv-4.7.0
# 环境准备,安装依赖项
sudo apt-get install cmake cmake-qt-gui
sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg-dev libtiff5-dev libswscale-dev pkg-config
sudo apt-get install libtiff-dev
cd ..
mkdir build_opencv470_x86_64
cmake-gui # 编译选项配置,CMAKE_INSTALL_PREFIX/ OPENCV_GENERATE_PKGCONFIG/ WITH_GTK/ WITH_GTK_2_X/ WITH_QT
# CMAKE_INSTALL_PREFIX指的是opencv库的include和lib文件,便于使用opencv.
# 其中有些文件由于网络原因不能下载,可以修改源码文件中的链接,或者直接下载复制到需要的目录.
cd build_opencv470_x86_64/
make -j16  # 有错误要一个个解决,需要重新配置编译选项
make install 
View Code

 

 

 

 

参考

1.opencv官网

2.CMakeLists编写

3.CMakeLists-practice文档

4.opencv多个版本的cmake切换

5.CSDN博客介绍

7. linux_install;

8. cmake编译opencv指南

9. cmakegui_Ubuntu20.04编译安装Opencv4.5.5;

posted on 2018-04-11 17:24  鹅要长大  阅读(1730)  评论(0编辑  收藏  举报

导航