如何使用Dlib的多个目标检测器?已训练两人脸检测器遇报错
如何合并两个Dlib人脸检测器提升检测效果
我帮你梳理下代码里的问题,以及正确实现双检测器融合的方法:
你的代码里存在的几个关键错误:
- 未定义
detectors变量,直接调用detectors[0]会导致编译错误 object_detector<image_scanner_type> face_detector(2);的构造方式不正确,Dlib的单检测器不能直接这样初始化多个模型deserialize的参数顺序搞反了,正确的格式是deserialize("文件名") >> 检测器对象;- 文件名出现混淆,比如你提到的是
object_detector1.svm和object_detector2.svm,但代码里写了face_detector1.svm
正确的实现代码
下面是修正后的完整代码,我会在关键部分加注释说明:
#include <dlib/image_processing/frontal_face_detector.h> #include <dlib/gui_widgets.h> #include <dlib/image_io.h> #include <iostream> using namespace dlib; using namespace std; int main(int argc, char** argv) { try { if (argc == 1) { cout << "Give some image files as arguments to this program." << endl; return 0; } // 定义和训练时一致的图像扫描器类型 typedef scan_fhog_pyramid<pyramid_down<6>> image_scanner_type; // 1. 分别加载两个训练好的检测器 object_detector<image_scanner_type> detector1, detector2; deserialize("object_detector1.svm") >> detector1; deserialize("object_detector2.svm") >> detector2; // 2. 将两个检测器合并成一个组合检测器(ensemble) // 这样会同时运行两个检测器,自动合并检测结果 auto combined_detector = join_detectors(detector1, detector2); image_window win; // 处理命令行传入的所有图像 for (int i = 1; i < argc; ++i) { cout << "processing image " << argv[i] << endl; array2d<unsigned char> img; load_image(img, argv[i]); pyramid_up(img); // 3. 使用组合检测器进行检测 std::vector<rectangle> dets = combined_detector(img); cout << "Number of faces detected: " << dets.size() << endl; win.clear_overlay(); win.set_image(img); win.add_overlay(dets, rgb_pixel(255,0,0)); cout << "Hit enter to process the next image..." << endl; cin.get(); } } catch (exception& e) { cout << "\nexception thrown!" << endl; cout << e.what() << endl; } return 0; }
关键说明:
join_detectors函数是Dlib专门用来合并多个检测器的工具,它会把多个检测器的检测结果进行整合,自动去除重复或重叠度过高的检测框,提升检测的准确率和召回率- 确保你加载的两个检测器使用的是完全相同的图像扫描器类型(也就是
typedef scan_fhog_pyramid<pyramid_down<6>> image_scanner_type;这部分要和你训练检测器时的代码一致,否则会加载失败) - 如果你的两个检测器使用的是不同的扫描器参数,那不能直接用
join_detectors,需要分别检测后手动合并结果(比如用non_max_suppression函数来去除重复框)
内容的提问来源于stack exchange,提问作者Jayesh
相关产品推荐
相关产品推荐

