yolov4 c++ ubuntu cmake

tech2024-08-23  81

首先根据github上面的说明,安装和训练模型,此处略去。

编写c++代码,参考"darknet/src/yolo_consle_dll.cpp"文件生成自己的c++代码。

简单的读取一张图片并输出预测结果:类别 类别索引 x y w h s. 文件名test.cpp

#include <iostream> #include "yolo_v2_class.hpp" //引用动态链接库中的头文件 #include <opencv2/opencv.hpp> #include "opencv2/highgui/highgui.hpp" #include <fstream> #pragma comment(lib, "yolo_cpp_dll.lib") //引入YOLO动态链接库 //读classes_name std::vector<std::string> objects_names_from_file(std::string const filename) { std::ifstream file(filename); std::vector<std::string> file_lines; if (!file.is_open()) return file_lines; for(std::string line; getline(file, line);) file_lines.push_back(line); std::cout << "object names loaded \n"; return file_lines; } int main() { std::string names_file = "/darknet/cfg/cs.names"; std::string cfg_file = "/darknet/cfg/yolov4-cs.cfg"; std::string weights_file = "/darknet/backup/yolov4-cs_best.weights"; Detector detector(cfg_file, weights_file); std::vector<std::string> obj_names; std::ifstream ifs(names_file.c_str()); std::string line; while (getline(ifs, line)) obj_names.push_back(line); cv::Mat mat_img = cv::imread("test.jpg"); //std::cout << detector.cur_gpu_id<< std::endl; std::vector<bbox_t> result_vec = detector.detect(mat_img); for(auto &i:result_vec) { std::cout << obj_names[i.obj_id] << " - "; std::cout << "obj_id = " << i.obj_id << ", x = " << i.x << ", y = " << i.y << ", w = " << i.w << ", h = " << i.h << std::setprecision(3) << ", prob = " << i.prob << std::endl; } return 0; }

编写cmake文件

cmake_minimum_required(VERSION 2.8) # 最低版本需求 project(yolov4) #项目名 #opencv add_definitions(-std=c++11) ADD_DEFINITIONS(-DOPENCV) ADD_DEFINITIONS(-DGPU) ######### opencv ######### set(OpenCV_DIR "../opencv-4.4.0") find_package( OpenCV REQUIRED ) include_directories( ${OpenCV_INCLUDE_DIRS} ) ######### darknet ######### include_directories(/home/feng/darknet/include) find_library(darknet libdarknet.so /home/feng/darknet) add_executable(${PROJECT_NAME} "test.cpp" ) target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS} ${darknet})

然后编译

cmake . make

最后执行 ./yolov4 即可

最新回复(0)