Libtorch c++ is not compitable with opencv 4.5?

Hi,

My code is like this:

#include<string>
#include<vector>
#include<iostream>

#include<torch/script.h>
#include<opencv2/opencv.hpp>


using std::string;
using std::cout;
using std::endl;
using std::vector;
using cv::Mat;


int main() {
    // Mat im = cv::imread("/root/47036.tif");
    Mat im = cv::imread("./res.jpg");
    return 0;
}

And my CMakeLists.txt is like this:


CMAKE_MINIMUM_REQUIRED(VERSION 3.8.2)

project(segmentation)

set(CMAKE_BUILD_TYPE Release)
set(CMAKE_CXX_FLAGS "-std=c++14 -O3")

set(CMAKE_PREFIX_PATH ~/build/libtorch)
set (OpenCV_DIR /opt/opencv/lib/cmake/opencv4/)
find_package(Torch REQUIRED)
find_package(OpenCV REQUIRED)


add_executable(run play.cpp)
target_link_libraries(run PUBLIC
     "${TORCH_LIBRARIES}"
    "${OpenCV_LIBRARIES}"
    )
set_property(TARGET run PROPERTY CXX_STANDARD 14)

libtorc is downloaded from official website, the file name is libtorch-shared-with-deps-1.8.1+cu102.zip, and opencv’s commit is 04d907fb976196df62f1259808fe98a44b874db1.

The error message is:


Scanning dependencies of target run
[ 50%] Building CXX object CMakeFiles/run.dir/play.cpp.o
[100%] Linking CXX executable run
CMakeFiles/run.dir/play.cpp.o: In function `main':
play.cpp:(.text.startup+0x43): undefined reference to `cv::imread(std::string const&, int)'
collect2: error: ld returned 1 exit status
CMakeFiles/run.dir/build.make:133: recipe for target 'run' failed
make[2]: *** [run] Error 1
CMakeFiles/Makefile2:95: recipe for target 'CMakeFiles/run.dir/all' failed
make[1]: *** [CMakeFiles/run.dir/all] Error 2
Makefile:103: recipe for target 'all' failed
make: *** [all] Error 2

I see no opencv problem if I comment part about libtorch in the code and CMakeLists.txt, so opencv works well alone, but there would be problem if I use opencv together with libtorch. How to solve this problem please ?

I don’t know what opencv you’re using but mostly they are built with c++11 ABI.
Use https://download.pytorch.org/libtorch/cu102/libtorch-cxx11-abi-shared-with-deps-1.8.1%2Bcu102.zip instead.