树莓派OpenCV+CMake开发QR检测器遇链接错误:QRCodeDetector未找到
问题描述
在树莓派上使用OpenCV和CMake开发QR码检测器,已成功编译OpenCV,VideoCapture等功能可正常使用,但添加QRCodeDetector时,链接器报错找不到对应库(libopencv_objdetect已存在于指定目录)。
报错信息
undefined reference to `cv::QRCodeDetector::QRCodeDetector()'
目录文件列表
ls -la /usr/local/lib/arm-linux-gnueabihf/ lrwxrwxrwx 1 root root 26 Sep 20 09:58 libopencv_objdetect.so -> libopencv_objdetect.so.405 lrwxrwxrwx 1 root root 28 Sep 20 09:58 libopencv_objdetect.so.405 -> libopencv_objdetect.so.4.5.5
C++代码
#include <iostream> #include <opencv2/core.hpp> #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> #include <opencv2/objdetect.hpp> //using namespace cv; //using namespace std; int detectQR(cv::Mat inputImage) { //QRCodeDetector qrDecoder = new QRCodeDetector(); cv::Mat bbox, rectifiedImage; cv::QRCodeDetector qrDecoder = cv::QRCodeDetector(); std::string data = qrDecoder.detectAndDecode(inputImage, bbox, rectifiedImage); int length = data.length(); if(length>0) { std::cout << "Decoded Data : " << data << std::endl; } delete &qrDecoder; return length; }
CMake配置文件
cmake_minimum_required(VERSION 3.18) project(untitled2) set(CMAKE_CXX_STANDARD 11) find_package( OpenCV REQUIRED core highgui imgproc ) include_directories( ${OpenCV_INCLUDE_DIRS} ) add_executable(sift main.cpp) target_link_libraries(sift ${OpenCV_LIBS} ${OPENCV_EXTRA_MODULES_PATH} /usr/local/lib/arm-linux-gnueabihf/libopencv_dnn_objdetect.so)
解决方案
1. 修正CMake的OpenCV依赖声明
QRCodeDetector属于objdetect模块,你的find_package里没包含这个模块,导致CMake没有链接对应的库。修改为:
find_package( OpenCV REQUIRED core highgui imgproc objdetect )
2. 清理无效的链接项
${OPENCV_EXTRA_MODULES_PATH}是路径变量,不是库文件,不能放到target_link_libraries中;libopencv_dnn_objdetect.so和当前QR码检测无关,可直接移除。修正后的链接语句:
target_link_libraries(sift ${OpenCV_LIBS})
3. 修复代码中的错误
delete &qrDecoder;是错误写法——qrDecoder是栈上创建的对象,不需要手动调用delete,直接删除这一行即可。同时对象初始化可以简化:
cv::QRCodeDetector qrDecoder;
(默认构造函数会自动执行,无需显式调用cv::QRCodeDetector())
4. 确认OpenCV模块编译状态
虽然你用的OpenCV 4.5.5版本支持QRCodeDetector,但要确保编译OpenCV时objdetect模块是启用状态(默认启用,除非编译时手动关闭)。
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

