当前位置: 首页 > news >正文

【目标检测】YOLOv5算法实现(九):模型预测

  本系列文章记录本人硕士阶段YOLO系列目标检测算法自学及其代码实现的过程。其中算法具体实现借鉴于ultralytics YOLO源码Github,删减了源码中部分内容,满足个人科研需求。
  本系列文章主要以YOLOv5为例完成算法的实现,后续修改、增加相关模块即可实现其他版本的YOLO算法。

文章地址:
YOLOv5算法实现(一):算法框架概述
YOLOv5算法实现(二):模型加载
YOLOv5算法实现(三):数据集加载
YOLOv5算法实现(四):正样本匹配与损失计算
YOLOv5算法实现(五):预测结果后处理
YOLOv5算法实现(六):评价指标及实现
YOLOv5算法实现(七):模型训练
YOLOv5算法实现(八):模型验证
YOLOv5算法实现(九):模型预测

本文目录

  • 引言
  • 模型预测(predict.py)

引言

  本篇文章综合之前文章中的功能,实现模型的预测。模型预测的逻辑如图1所示。

在这里插入图片描述

图1 模型预测流程

模型预测(predict.py)

def predice():img_size = 640  # 必须是32的整数倍 [416, 512, 608]file = "yolov5s"cfg = f"cfg/models/{file}.yaml"  # 改成生成的.cfg文件weights_path = f"weights/{file}/{file}.pt"  # 改成自己训练好的权重文件json_path = "data/dataset.json"  # json标签文件img_path = "test.jpg"save_path = f"results/{file}/test_result8.jpg"assert os.path.exists(cfg), "cfg file {} dose not exist.".format(cfg)assert os.path.exists(weights_path), "weights file {} dose not exist.".format(weights_path)assert os.path.exists(json_path), "json file {} dose not exist.".format(json_path)assert os.path.exists(img_path), "image file {} dose not exist.".format(img_path)with open(json_path, 'r') as f:class_dict = json.load(f)category_index = {str(v): str(k) for k, v in class_dict.items()}input_size = (img_size, img_size)device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")device = torch.device("cpu")model = Model(cfg, ch=3, nc=3)weights_dict = torch.load(weights_path, map_location='cpu')weights_dict = weights_dict["model"] if "model" in weights_dict else weights_dictmodel.load_state_dict(weights_dict, strict=False)model.to(device)model.eval()with torch.no_grad():# initimg = torch.zeros((1, 3, img_size, img_size), device=device)model(img)img_o = cv2.imread(img_path)  # BGRassert img_o is not None, "Image Not Found " + img_pathimg = letterbox(img_o, new_shape=input_size, auto=True, color=(0, 0, 0))[0]# Convertimg = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416img = np.ascontiguousarray(img)img = torch.from_numpy(img).to(device).float()img /= 255.0  # scale (0, 255) to (0, 1)img = img.unsqueeze(0)  # add batch dimensiont1 = torch_utils.time_synchronized()pred = model(img)[0]  # only get inference resultt2 = torch_utils.time_synchronized()print("inference time: {}s".format(t2 - t1))print('model: {}'.format(file))pred = utils.non_max_suppression(pred, conf_thres=0.1, iou_thres=0.6, multi_label=True)[0]t3 = time.time()print("post-processing time: {}s".format(t3 - t2))# process detectionspred[:, :4] = utils.scale_coords(img.shape[2:], pred[:, :4], img_o.shape).round()bboxes = pred[:, :4].detach().cpu().numpy()scores = pred[:, 4].detach().cpu().numpy()classes = pred[:, 5].detach().cpu().numpy().astype(np.int) + 1pil_img = Image.fromarray(img_o[:, :, ::-1])plot_img = draw_objs(pil_img,bboxes,classes,scores,category_index=category_index,box_thresh=0.2,line_thickness=3,font='arial.ttf',font_size=30)plt.imshow(plot_img)plt.show()# 保存预测的图片结果plot_img.save(save_path)if __name__ == "__main__":predict()

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 深度学习技术栈 —— 用Pytorch搭建神经网络识别数字(Kaggle实战)
  • 数据库性能优化的解决方案
  • 为何现在流行OpenStack和Docker结合?
  • 99个Python脚本实用实例
  • react 页签(自行封装)
  • 力扣每日一题---1547. 切棍子的最小成本
  • MSVS C# Matlab的混合编程系列1 - 看似简单的问题引出
  • Android学习(五):常用控件
  • 【EI会议征稿通知】2024年通信安全与信息处理国际学术会议(CSIP 2024)
  • C#调用C动态链接库
  • MicroPython核心(1):源码获取、编译构建
  • GO 中如何防止 goroutine 泄露
  • Spring Boot各类变量的使用
  • Redis原理篇(String)
  • MVC的设计理念
  • 【剑指offer】让抽象问题具体化
  • 2017前端实习生面试总结
  • Angularjs之国际化
  • Apache的80端口被占用以及访问时报错403
  • CSS 专业技巧
  • Java 实战开发之spring、logback配置及chrome开发神器(六)
  • JavaScript 是如何工作的:WebRTC 和对等网络的机制!
  • laravel 用artisan创建自己的模板
  • Service Worker
  • Spring技术内幕笔记(2):Spring MVC 与 Web
  • V4L2视频输入框架概述
  • windows下使用nginx调试简介
  • 从重复到重用
  • 干货 | 以太坊Mist负责人教你建立无服务器应用
  • 快速体验 Sentinel 集群限流功能,只需简单几步
  • 聊聊flink的BlobWriter
  • 区块链共识机制优缺点对比都是什么
  • 算法---两个栈实现一个队列
  • 一、python与pycharm的安装
  • gunicorn工作原理
  • raise 与 raise ... from 的区别
  • shell使用lftp连接ftp和sftp,并可以指定私钥
  • 从如何停掉 Promise 链说起
  • 选择阿里云数据库HBase版十大理由
  • ​补​充​经​纬​恒​润​一​面​
  • #APPINVENTOR学习记录
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (22)C#传智:复习,多态虚方法抽象类接口,静态类,String与StringBuilder,集合泛型List与Dictionary,文件类,结构与类的区别
  • (4)STL算法之比较
  • (4.10~4.16)
  • (6) 深入探索Python-Pandas库的核心数据结构:DataFrame全面解析
  • (动态规划)5. 最长回文子串 java解决
  • (附源码)springboot美食分享系统 毕业设计 612231
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (排序详解之 堆排序)
  • (十三)MipMap
  • (算法)区间调度问题
  • (一)utf8mb4_general_ci 和 utf8mb4_unicode_ci 适用排序和比较规则场景
  • (转)可以带来幸福的一本书
  • .Net Core缓存组件(MemoryCache)源码解析