1 linux上编译使用OpenCV的程序出现undefined reference to cv::VideoCapture::VideoCapture()错误

最近在linux上编写程序的时候使用了以下代码:

    cv::VideoCapture video_capture;
    video_capture.open(video_path);

    if (!video_capture.isOpened())
        return ;

    while (video_capture.isOpened())
    {
        cv::Mat frame;
        video_capture.read(frame);

        if (frame.empty())
            break;

        // 水平翻转
        cv::flip(frame, frame,1);

    }
    video_capture.release();

但是在使用cmake编译程序时出现了错误:

xxxxxxxxxxxx.cpp: undefined reference to `cv::VideoCapture::VideoCapture()'
xxxxxxxxxxxx.cpp:(.text+0x499c): undefined reference to `cv::VideoCapture::open(cv::String const&)'
xxxxxxxxxxxx.cpp:(.text+0x49ac): undefined reference to `cv::VideoCapture::isOpened() const'
xxxxxxxxxxxx.cpp:(.text+0x49c8): undefined reference to `cv::VideoCapture::isOpened() const'
xxxxxxxxxxxx.cpp:(.text+0x49f4): undefined reference to `cv::VideoCapture::read(cv::_OutputArray const&)'
xxxxxxxxxxxx.cpp:(.text+0x4ad0): undefined reference to `cv::VideoCapture::release()'
xxxxxxxxxxxx.cpp:(.text+0x4c50): undefined reference to `cv::VideoCapture::~VideoCapture()'
xxxxxxxxxxxx.cpp:(.text+0x4ce8): undefined reference to `cv::VideoCapture::~VideoCapture()'
collect2: error: ld returned 1 exit status

从上述编译错误可以发现可以发现是某个opencv库没有被动态链接,而库opencv_video,opencv_videoio包含了上述出错的cv::VideoCapture,所以只需要在CMakeLists.txt链接未被链接的动态库即可。

将CMakeLists.txt修改如下,

target_link_libraries(main stdc++ opencv_core opencv_imgproc opencv_imgcodecs opencv_dnn opencv_video opencv_videoio dl rt)

增加了opencv_videoopencv_videoio库。

重新编译程序,编译成功。