Ubuntu_opencv4.5.3_opencv_contrib4.5.3_libtorch1.8.1_yolov5

2023-12-08 19:18

本文主要是介绍Ubuntu_opencv4.5.3_opencv_contrib4.5.3_libtorch1.8.1_yolov5,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

ubuntu_libtorch_opencv_yolov5

文章目录

  • 一、下载链接一:
    • 1.1、下载libtorch_yolov5:
    • 1.2、修改CMakeLists.txt
    • 1.3、准备模型文件
    • 1.4、源文件.cpp
    • 1.4、编译
    • 1.5、执行
  • 二、下载链接二:
    • 2.1、下载YOLOv5-LibTorch:
    • 2.2、修改CMakeLists.txt
    • 2.3、准备模型文件
    • 2.4、源文件.cpp
    • 2.4、编译
    • 2.5、执行


1、下载libtorch_yolov5:

一、下载链接一:

1.1、下载libtorch_yolov5:

https://github.com/yasenh/libtorch-yolov5

1.2、修改CMakeLists.txt

cmake_minimum_required(VERSION 3.5.1)
project(libtorch-yolov5)set(CMAKE_CXX_STANDARD 14)
# It prevents the decay to C++98 when the compiler does not support C++14
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# It disables the use of compiler-specific extensions
# e.g. -std=c++14 rather than -std=gnu++14
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")# Try to find OpenCV
# set(OpenCV_DIR ....)
find_package(OpenCV REQUIRED)
if (OpenCV_FOUND)# If the package has been found, several variables will# be set, you can find the full list with descriptions# in the OpenCVConfig.cmake file.# Print some message showing some of themmessage(STATUS "OpenCV library status:")message(STATUS "    version: ${OpenCV_VERSION}")message(STATUS "    include path: ${OpenCV_INCLUDE_DIRS}" \n)
else ()message(FATAL_ERROR "Could not locate OpenCV" \n)
endif()set(Torch_DIR /xxx/libtorch/share/cmake/Torch)
#find_package(Torch PATHS ${Torch_DIR} NO_DEFAULT REQUIRED)
find_package(Torch REQUIRED)
if (Torch_FOUND)message(STATUS "Torch library found!")message(STATUS "    include path: ${TORCH_INCLUDE_DIRS}" \n)
else ()message(FATAL_ERROR "Could not locate Torch" \n)
endif()include_directories(${PROJECT_SOURCE_DIR}/include)file(GLOB SOURCE_FILES src/*.cpp)add_executable(${CMAKE_PROJECT_NAME} ${SOURCE_FILES})target_link_libraries (${CMAKE_PROJECT_NAME}${OpenCV_LIBS}${TORCH_LIBRARIES}
)

其中的
set(Torch_DIR /xxx/libtorch/share/cmake/Torch)
改为自己libtorch的路径

1.3、准备模型文件

在工程目录下新建build文件夹后,工程目录如下:
在这里插入图片描述准备模型.torchscript.pt模型:
从https://github.com/ultralytics/yolov5下载yolov5-master,下载yolov5s.pt,并生成yolov5s.torchscript.pt
(其中https://github.com/ultralytics/yolov5/releases包含发布的yolov5的各个版本,以及模型,可以从上面下载。
源文件.cpp)
将生成的yolov5s.torchscript.pt模型文件放到weights文件夹下。

1.4、源文件.cpp

src文件夹下的main.cpp文件:

#include <iostream>
#include <memory>
#include <chrono>#include "detector.h"
#include "cxxopts.hpp"std::vector<std::string> LoadNames(const std::string& path) {// load class namesstd::vector<std::string> class_names;std::ifstream infile(path);if (infile.is_open()) {std::string line;while (getline (infile,line)) {class_names.emplace_back(line);}infile.close();}else {std::cerr << "Error loading the class names!\n";}return class_names;
}void Demo(cv::Mat& img,const std::vector<std::vector<Detection>>& detections,const std::vector<std::string>& class_names,bool label = true) {if (!detections.empty()) {for (const auto& detection : detections[0]) {const auto& box = detection.bbox;float score = detection.score;int class_idx = detection.class_idx;cv::rectangle(img, box, cv::Scalar(0, 0, 255), 2);if (label) {std::stringstream ss;ss << std::fixed << std::setprecision(2) << score;std::string s = class_names[class_idx] + " " + ss.str();auto font_face = cv::FONT_HERSHEY_DUPLEX;auto font_scale = 1.0;int thickness = 1;int baseline=0;auto s_size = cv::getTextSize(s, font_face, font_scale, thickness, &baseline);cv::rectangle(img,cv::Point(box.tl().x, box.tl().y - s_size.height - 5),cv::Point(box.tl().x + s_size.width, box.tl().y),cv::Scalar(0, 0, 255), -1);cv::putText(img, s, cv::Point(box.tl().x, box.tl().y - 5),font_face , font_scale, cv::Scalar(255, 255, 255), thickness);}}}cv::namedWindow("Result", cv::WINDOW_AUTOSIZE);cv::imshow("Result", img);cv::waitKey(0);
}int main(int argc, const char* argv[]) {cxxopts::Options parser(argv[0], "A LibTorch inference implementation of the yolov5");// TODO: add other argsparser.allow_unrecognised_options().add_options()("weights", "model.torchscript.pt path", cxxopts::value<std::string>())("source", "source", cxxopts::value<std::string>())("conf-thres", "object confidence threshold", cxxopts::value<float>()->default_value("0.4"))("iou-thres", "IOU threshold for NMS", cxxopts::value<float>()->default_value("0.5"))("gpu", "Enable cuda device or cpu", cxxopts::value<bool>()->default_value("false"))("view-img", "display results", cxxopts::value<bool>()->default_value("false"))("h,help", "Print usage");auto opt = parser.parse(argc, argv);if (opt.count("help")) {std::cout << parser.help() << std::endl;exit(0);}// check if gpu flag is setbool is_gpu = opt["gpu"].as<bool>();// set device type - CPU/GPUtorch::DeviceType device_type;// if (torch::cuda::is_available() && is_gpu) {//     device_type = torch::kCUDA;// } else {//     device_type = torch::kCPU;// }//设置为CUDAdevice_type = torch::kCUDA;//根据需要修改//设置为CPU//device_type = torch::kCPU;//根据需要修改//但不可以使用上面的if..else..的选择cuda还是cpu,不然在执行make命令时会出现如下错误://RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!// load class names from dataset for visualizationstd::vector<std::string> class_names = LoadNames("../weights/coco.names");if (class_names.empty()) {return -1;}// load networkstd::string weights = opt["weights"].as<std::string>();auto detector = Detector(weights, device_type);// load input imagestd::string source = opt["source"].as<std::string>();cv::Mat img = cv::imread(source);if (img.empty()) {std::cerr << "Error loading the image!\n";return -1;}// run once to warm upstd::cout << "Run once on empty image" << std::endl;auto temp_img = cv::Mat::zeros(img.rows, img.cols, CV_32FC3);detector.Run(temp_img, 1.0f, 1.0f);// set up thresholdfloat conf_thres = opt["conf-thres"].as<float>();float iou_thres = opt["iou-thres"].as<float>();// inferenceauto result = detector.Run(img, conf_thres, iou_thres);// visualize detectionsif (opt["view-img"].as<bool>()) {Demo(img, result, class_names);}cv::destroyAllWindows();return 0;
}

1.4、编译

进入build文件夹下,执行命令:

cmake .. && make

1.5、执行

命令:

 ./libtorch-yolov5 --source ../images/bus.jpg --weights ../weights/yolov5s.torchscript.pt --gpu --view-img

运行结果如下:
在这里插入图片描述
在这里插入图片描述以上步骤完成

二、下载链接二:

2.1、下载YOLOv5-LibTorch:

https://github.com/Nebula4869/YOLOv5-LibTorch

2.2、修改CMakeLists.txt

cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(YOLOv5LibTorch)
SET(CMAKE_BUILD_TYPE Release)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)find_package(OpenCV REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
set(CMAKE_PREFIX_PATH /home/xxx/software/libtorch)
find_package(Torch REQUIRED)
add_executable(YOLOv5LibTorch src/YOLOv5LibTorch.cpp)include_directories(
${PROJECT_SOURCE_DIR}/include
${OpenCV_INCLUDE_DIRS}
)target_link_libraries(YOLOv5LibTorch ${OpenCV_LIBS} ${TORCH_LIBRARIES})
set_property(TARGET YOLOv5LibTorch PROPERTY CXX_STANDARD 14)

其中的
set(CMAKE_PREFIX_PATH /home/xxx/software/libtorch)
改为自己libtorch的路径

2.3、准备模型文件

下载的文件目录里已经有yolov5s.torchscript.pt模型文件,无需再下载。

2.4、源文件.cpp

src文件夹下的main.cpp文件:
因为原来的文件里是读取摄像头图像,此处改为读取图像。

#include <opencv2/opencv.hpp>
#include <torch/script.h>
#include <algorithm>
#include <iostream>
#include <time.h>std::vector<torch::Tensor> non_max_suppression(torch::Tensor preds, float score_thresh=0.5, float iou_thresh=0.5)
{std::vector<torch::Tensor> output;for (size_t i=0; i < preds.sizes()[0]; ++i){torch::Tensor pred = preds.select(0, i);// Filter by scorestorch::Tensor scores = pred.select(1, 4) * std::get<0>( torch::max(pred.slice(1, 5, pred.sizes()[1]), 1));pred = torch::index_select(pred, 0, torch::nonzero(scores > score_thresh).select(1, 0));if (pred.sizes()[0] == 0) continue;// (center_x, center_y, w, h) to (left, top, right, bottom)pred.select(1, 0) = pred.select(1, 0) - pred.select(1, 2) / 2;pred.select(1, 1) = pred.select(1, 1) - pred.select(1, 3) / 2;pred.select(1, 2) = pred.select(1, 0) + pred.select(1, 2);pred.select(1, 3) = pred.select(1, 1) + pred.select(1, 3);// Computing scores and classesstd::tuple<torch::Tensor, torch::Tensor> max_tuple = torch::max(pred.slice(1, 5, pred.sizes()[1]), 1);pred.select(1, 4) = pred.select(1, 4) * std::get<0>(max_tuple);pred.select(1, 5) = std::get<1>(max_tuple);torch::Tensor  dets = pred.slice(1, 0, 6);torch::Tensor keep = torch::empty({dets.sizes()[0]});torch::Tensor areas = (dets.select(1, 3) - dets.select(1, 1)) * (dets.select(1, 2) - dets.select(1, 0));std::tuple<torch::Tensor, torch::Tensor> indexes_tuple = torch::sort(dets.select(1, 4), 0, 1);torch::Tensor v = std::get<0>(indexes_tuple);torch::Tensor indexes = std::get<1>(indexes_tuple);int count = 0;while (indexes.sizes()[0] > 0){keep[count] = (indexes[0].item().toInt());count += 1;// Computing overlapstorch::Tensor lefts = torch::empty(indexes.sizes()[0] - 1);torch::Tensor tops = torch::empty(indexes.sizes()[0] - 1);torch::Tensor rights = torch::empty(indexes.sizes()[0] - 1);torch::Tensor bottoms = torch::empty(indexes.sizes()[0] - 1);torch::Tensor widths = torch::empty(indexes.sizes()[0] - 1);torch::Tensor heights = torch::empty(indexes.sizes()[0] - 1);for (size_t i=0; i<indexes.sizes()[0] - 1; ++i){lefts[i] = std::max(dets[indexes[0]][0].item().toFloat(), dets[indexes[i + 1]][0].item().toFloat());tops[i] = std::max(dets[indexes[0]][1].item().toFloat(), dets[indexes[i + 1]][1].item().toFloat());rights[i] = std::min(dets[indexes[0]][2].item().toFloat(), dets[indexes[i + 1]][2].item().toFloat());bottoms[i] = std::min(dets[indexes[0]][3].item().toFloat(), dets[indexes[i + 1]][3].item().toFloat());widths[i] = std::max(float(0), rights[i].item().toFloat() - lefts[i].item().toFloat());heights[i] = std::max(float(0), bottoms[i].item().toFloat() - tops[i].item().toFloat());}torch::Tensor overlaps = widths * heights;// FIlter by IOUstorch::Tensor ious = overlaps / (areas.select(0, indexes[0].item().toInt()) + torch::index_select(areas, 0, indexes.slice(0, 1, indexes.sizes()[0])) - overlaps);indexes = torch::index_select(indexes, 0, torch::nonzero(ious <= iou_thresh).select(1, 0) + 1);}keep = keep.toType(torch::kInt64);output.push_back(torch::index_select(dets, 0, keep.slice(0, 0, count)));}return output;
}int main()
{// Loading  Moduletorch::jit::script::Module module = torch::jit::load("../yolov5s.torchscript.pt");std::vector<std::string> classnames;std::ifstream f("../coco.names");std::string name = "";while (std::getline(f, name)){classnames.push_back(name);}// cv:: VideoCapture cap = cv::VideoCapture(0);// cap.set(cv::CAP_PROP_FRAME_WIDTH, 1920);// cap.set(cv::CAP_PROP_FRAME_HEIGHT, 1080);cv::Mat img;cv::Mat frame = cv::imread("../bus.jpg");// while(cap.isOpened()){clock_t start = clock();//cap.read(frame);if(frame.empty()){std::cout << "Read frame failed!" << std::endl;//break;return 0;}// Preparing input tensorcv::resize(frame, img, cv::Size(640, 384));cv::cvtColor(img, img, cv::COLOR_BGR2RGB);torch::Tensor imgTensor = torch::from_blob(img.data, {img.rows, img.cols,3},torch::kByte);imgTensor = imgTensor.permute({2,0,1});imgTensor = imgTensor.toType(torch::kFloat);imgTensor = imgTensor.div(255);imgTensor = imgTensor.unsqueeze(0);// preds: [?, 15120, 9]torch::Tensor preds = module.forward({imgTensor}).toTuple()->elements()[0].toTensor();std::vector<torch::Tensor> dets = non_max_suppression(preds, 0.4, 0.5);if (dets.size() > 0){// Visualize resultfor (size_t i=0; i < dets[0].sizes()[0]; ++ i){float left = dets[0][i][0].item().toFloat() * frame.cols / 640;float top = dets[0][i][1].item().toFloat() * frame.rows / 384;float right = dets[0][i][2].item().toFloat() * frame.cols / 640;float bottom = dets[0][i][3].item().toFloat() * frame.rows / 384;float score = dets[0][i][4].item().toFloat();int classID = dets[0][i][5].item().toInt();cv::rectangle(frame, cv::Rect(left, top, (right - left), (bottom - top)), cv::Scalar(0, 255, 0), 2);cv::putText(frame,classnames[classID] + ": " + cv::format("%.2f", score),cv::Point(left, top),cv::FONT_HERSHEY_SIMPLEX, (right - left) / 200, cv::Scalar(0, 255, 0), 2);}}cv::putText(frame, "FPS: " + std::to_string(int(1e7 / (clock() - start))),cv::Point(50, 50),cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(0, 255, 0), 2);cv::imshow("", frame);cv::waitKey(0);//if(cv::waitKey(1)== 27) break;}return 0;
}

2.4、编译

进入build文件夹下,执行命令:

cmake .. && make

2.5、执行

命令:

  ./../bin/YOLOv5LibTorch

这篇关于Ubuntu_opencv4.5.3_opencv_contrib4.5.3_libtorch1.8.1_yolov5的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/471037

相关文章

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

在PyCharm中安装PyTorch、torchvision和OpenCV详解

《在PyCharm中安装PyTorch、torchvision和OpenCV详解》:本文主要介绍在PyCharm中安装PyTorch、torchvision和OpenCV方式,具有很好的参考价值,... 目录PyCharm安装PyTorch、torchvision和OpenCV安装python安装PyTor

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

Ubuntu中远程连接Mysql数据库的详细图文教程

《Ubuntu中远程连接Mysql数据库的详细图文教程》Ubuntu是一个以桌面应用为主的Linux发行版操作系统,这篇文章主要为大家详细介绍了Ubuntu中远程连接Mysql数据库的详细图文教程,有... 目录1、版本2、检查有没有mysql2.1 查询是否安装了Mysql包2.2 查看Mysql版本2.

opencv图像处理之指纹验证的实现

《opencv图像处理之指纹验证的实现》本文主要介绍了opencv图像处理之指纹验证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录一、简介二、具体案例实现1. 图像显示函数2. 指纹验证函数3. 主函数4、运行结果三、总结一、

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

新特性抢先看! Ubuntu 25.04 Beta 发布:Linux 6.14 内核

《新特性抢先看!Ubuntu25.04Beta发布:Linux6.14内核》Canonical公司近日发布了Ubuntu25.04Beta版,这一版本被赋予了一个活泼的代号——“Plu... Canonical 昨日(3 月 27 日)放出了 Beta 版 Ubuntu 25.04 系统镜像,代号“Pluc

Ubuntu中Nginx虚拟主机设置的项目实践

《Ubuntu中Nginx虚拟主机设置的项目实践》通过配置虚拟主机,可以在同一台服务器上运行多个独立的网站,本文主要介绍了Ubuntu中Nginx虚拟主机设置的项目实践,具有一定的参考价值,感兴趣的可... 目录简介安装 Nginx创建虚拟主机1. 创建网站目录2. 创建默认索引文件3. 配置 Nginx4

Ubuntu 22.04 服务器安装部署(nginx+postgresql)

《Ubuntu22.04服务器安装部署(nginx+postgresql)》Ubuntu22.04LTS是迄今为止最好的Ubuntu版本之一,很多linux的应用服务器都是选择的这个版本... 目录是什么让 Ubuntu 22.04 LTS 变得安全?更新了安全包linux 内核改进一、部署环境二、安装系统