Contents
  1. Download OpenCV and Build the Libraries
  2. Switch opencv Versions

Assume that this computer already has opencv4.0 installed and now needs opencv3 (the same applies to other versions).

Download OpenCV and Build the Libraries

To avoid conflicts, under /usr/local/, create a new opencv3 directory.

sudo mkdir -p /usr/local/opencv3

As usual, download another version of opencv from the opencv official website, then use the following commands to build it.

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=RELEASE -DWITH_TBB=ON  -DWITH_V4L=ON -DCMAKE_INSTALL_PREFIX=/usr/local/opencv3 ..  

After entering the build folder, enter a cmake command in the format shown below. Modify the command parameters below according to your actual setup; do not copy and run it as-is.

cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local/opencv3 -D OPENCV_EXTRA_MODULES_PATH=~/ros/sitepackages/opencv-3.4.2/opencv_contrib/modules/ -DPYTHON_INCLUDE_DIR=/usr/include/python2.7 -DPYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython2.7 ..

Compile and install it.

make -j4
sudo make install

Switch opencv Versions

Open ~/.bashrc.

gedit ~/.bashrc

Add the following content at the end of the file.

# Change OpenCV3
export PKG_CONFIG_PATH=/usr/local/opencv3/lib/pkgconfig
export LD_LIBRARY_PATH=/usr/local/opencv3/lib

Reload ~/.bashrc.

source ~/.bashrc 

Check the OpenCV version.

pkg-config --modversion opencv

If the output is 3.4.2, the configuration was successful.

To use the previous version, comment out the added content in ~/.bashrc, then run source ~/.bashrc.

If only one version of OpenCV is installed, the following statement in CMakeList.txt is sufficient.

FIND_PACKAGE(OpenCV REQUIRED)

After OpenCV has been compiled, an OpenCVConfig.cmake file is generated in its directory. This file specifies where CMake should look for OpenCV, where its .h files are located, and so on.

When multiple versions of OpenCV are installed, locate the OpenCVConfig.cmake file corresponding to the required version and add its path to the project’s CMakeLists.txt. An example follows:

set(OpenCV_INCLUDE_DIRS "/usr/local/opencv3/include")
set(OpenCV_LIB_DIR "/usr/local/opencv3/lib")
set(OpenCV_LIBS opencv_core opencv_highgui opencv_imgproc)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
target_link_libraries(your_target_name ${OpenCV_LIBS})

References

  1. Liu Quanxiang. Configuring OpenCV on Ubuntu and Running Multiple OpenCV Versions Side by Side
  2. W_Tortoise. Coexistence and Switching of Multiple OpenCV Versions on Ubuntu