You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用编译生成的Yolov4 yolo_cpp_dll.dll实现自定义模型检测

Windows下C++调用YoloV4的yolo_cpp_dll实现自定义目标检测

准备工作

  • 确认已编译出yolo_cpp_dll.dll和yolo_cpp_dll.lib,将这两个文件放到C++项目目录,或配置项目的库搜索路径指向\build\darknet\x64
  • 将自定义的yolov4-custom_best.cfg、yolo.data、yolov4-custom_best.weights放到项目可访问路径(比如项目根目录下的ball_config文件夹)

VS项目配置(以Visual Studio为例)

  • 右键项目 → 属性 → 配置属性 → VC++目录:
    • 包含目录:添加Darknet源码根目录下的include和src文件夹路径
    • 库目录:添加\build\darknet\x64的路径
  • 配置属性 → 链接器 → 输入:附加依赖项添加yolo_cpp_dll.lib
  • 确保项目为x64 Release模式(与编译dll的模式一致)

核心代码实现

头文件引入

#include <iostream>
#include <opencv2/opencv.hpp>
#include "yolo_v2_class.hpp" // 来自darknet的src文件夹

初始化检测器

Detector* detector = nullptr;

int main() {
    // 配置文件路径,注意用双反斜杠或正斜杠
    std::string cfg_path = "ball_config/yolov4-custom_best.cfg";
    std::string weights_path = "ball_config/yolov4-custom_best.weights";
    std::string data_path = "ball_config/yolo.data";

    // 初始化检测器:参数依次为cfg、weights、data路径,最后是GPU设备号(-1=CPU,0+=GPU)
    detector = new Detector(cfg_path, weights_path, data_path, 0);

    if (!detector) {
        std::cerr << "检测器初始化失败!" << std::endl;
        return -1;
    }

处理摄像头/视频检测

// 打开默认摄像头,可替换为视频文件路径
    cv::VideoCapture cap(0);
    if (!cap.isOpened()) {
        std::cerr << "无法打开摄像头/视频!" << std::endl;
        delete detector;
        return -1;
    }

    cv::Mat frame;
    while (true) {
        cap >> frame;
        if (frame.empty()) break;

        // 执行检测,返回所有检测框结果
        std::vector<bbox_t> detection_results = detector->detect(frame);

        // 绘制检测框与类别信息
        std::vector<std::string> class_names = detector->get_class_names(); // 从data文件自动获取类别名
        for (auto& bbox : detection_results) {
            std::string label = class_names[bbox.obj_id] + " " + std::to_string(bbox.confidence);
            cv::rectangle(frame, cv::Point(bbox.x, bbox.y), cv::Point(bbox.x + bbox.w, bbox.y + bbox.h), cv::Scalar(0, 255, 0), 2);
            cv::putText(frame, label, cv::Point(bbox.x, bbox.y - 5), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
        }

        cv::imshow("YoloV4 目标检测", frame);
        if (cv::waitKey(1) == 27) break; // ESC键退出
    }

资源释放

// 清理资源
    cap.release();
    cv::destroyAllWindows();
    delete detector;
    return 0;
}

关键注意事项

  • 路径正确性:确保配置、权重文件的路径可被程序访问,推荐用相对路径或绝对路径
  • GPU/CPU切换:初始化Detector时最后一个参数填0即可启用GPU(与你之前darknet.exe的GPU环境匹配),填-1则用CPU
  • 依赖匹配:需确保项目能访问OpenCV库(用于图像/视频处理),以及CUDA、CUDNN库(GPU模式下)
  • 编译一致性:项目的编译模式(x64/Release)必须与编译yolo_cpp_dll时的模式完全一致,避免链接错误

内容的提问来源于stack exchange,提问作者berkouille

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:16:28