如何解决OpenCV C++代码中cv::face::LBPHFaceRecognizer的链接错误?
OpenCV LBPHFaceRecognizer 链接错误排查
问题背景
编写了一个用于处理人脸图像目录的OpenCV C++训练器代码,运行环境为OpenCV 4.2.0 + OpenCV contrib 4.2.0,使用最新版Visual Studio。
代码实现
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <filesystem> #include <opencv2/opencv.hpp> #include <opencv2/face.hpp> #include <opencv2/face/facerec.hpp> using namespace cv; using namespace cv::face; using namespace std; namespace fs = std::filesystem; void assurePathExists(const string& path) { fs::create_directories(fs::path(path).parent_path()); } int main() { Ptr<LBPHFaceRecognizer> recognizer = LBPHFaceRecognizer::create(); CascadeClassifier detector; detector.load("C:/Users/781932/Downloads/haarcascade_frontalface_default.xml"); string datasetPath = "C:/Users/781932/Documents/STEMVisageVision"; vector<Mat> faceSamples; vector<int> ids; vector<string> imagePaths; for (const auto& entry : fs::directory_iterator(datasetPath)) { if (entry.is_regular_file()) { imagePaths.push_back(entry.path().string()); } } for (const auto& imagePath : imagePaths) { Mat img = imread(imagePath, IMREAD_GRAYSCALE); int id = stoi(fs::path(imagePath).stem().string().substr(1)); vector<Rect> faces; detector.detectMultiScale(img, faces); for (const auto& face : faces) { faceSamples.push_back(img(face)); ids.push_back(id); } } recognizer->train(faceSamples, ids); string trainerPath = "trainer/trainer.yml"; assurePathExists(trainerPath); recognizer->write(trainerPath); return 0; }
编译错误
清理并重建解决方案后,代码无语法错误,但触发链接错误:
Build started... 1>------ Build started: Project: 5_30_Trainer, Configuration: Debug x64 ------ 1>5_30_Trainer.obj : error LNK2019: **unresolved external symbol "public: static struct cv::Ptr<class cv::face::LBPHFaceRecognizer> __cdecl cv::face::LBPHFaceRecognizer::create(int,int,int,int,double)" (?create@LBPHFaceRecognizer@face@cv@@SA?AU?$Ptr@VLBPHFaceRecognizer@face@cv@@@3@HHHHN@Z) referenced in function main** 1>C:\Users\781932\source\repos\5_30_Trainer\x64\Debug\5_30_Trainer.exe : fatal error LNK1120: 1 unresolved externals 1>Done building project "5_30_Trainer.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ========== Build started at 9:21 AM and took 02.605 seconds ==========
问题原因及解决方向
该错误属于未解析外部符号,说明链接器无法找到LBPHFaceRecognizer::create的实现,可从以下几点排查:
- 未添加contrib face模块依赖库:OpenCV 4.2.0的contrib face模块,Debug版本库文件为
opencv_face420d.lib,Release版本为opencv_face420.lib,需在项目属性的链接器->输入->附加依赖项中添加对应编译模式的库文件。 - 编译模式/架构不匹配:确保项目的编译模式(Debug/Release)、平台架构(x64/x86)与本地OpenCV及contrib库的编译参数完全一致,比如Debug模式不能链接Release版本的库。
- contrib模块未正确编译:若自行编译OpenCV与contrib,需确认face模块编译成功并生成了对应库文件;若使用预编译包,需下载包含contrib组件的完整版本。
- 包含/库目录配置不全:检查项目属性的VC++目录->包含目录是否包含OpenCV contrib的
include文件夹,库目录是否包含contrib库文件所在路径。
内容的提问来源于stack exchange,提问作者Francis RE
相关产品推荐
相关产品推荐

