YOLOV----- ONNX 推理过程、可视化图片、保存检测到的目标

2024-09-03 04:12

本文主要是介绍YOLOV----- ONNX 推理过程、可视化图片、保存检测到的目标,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、代码

import os
import cv2
import numpy as np
import onnxruntime
import timeCLASSES = ['person']  # coco80类别class YOLOV5():def __init__(self, onnxpath):self.onnx_session = onnxruntime.InferenceSession(onnxpath)self.input_name = self.get_input_name()self.output_name = self.get_output_name()# -------------------------------------------------------#   获取输入输出的名字# -------------------------------------------------------def get_input_name(self):input_name = []for node in self.onnx_session.get_inputs():input_name.append(node.name)return input_namedef get_output_name(self):output_name = []for node in self.onnx_session.get_outputs():output_name.append(node.name)return output_name# -------------------------------------------------------#   输入图像# -------------------------------------------------------def get_input_feed(self, img_tensor):input_feed = {}for name in self.input_name:input_feed[name] = img_tensorreturn input_feed# -------------------------------------------------------#   1.cv2读取图像并resize#	2.图像转BGR2RGB和HWC2CHW#	3.图像归一化#	4.图像增加维度#	5.onnx_session 推理# -------------------------------------------------------# def inference(self, img_path):#     img = cv2.imread(img_path)#     or_img = cv2.resize(img, (640, 640))#     img = or_img[:, :, ::-1].transpose(2, 0, 1)  # BGR2RGB和HWC2CHW#     img = img.astype(dtype=np.float32)#     img /= 255.0#     img = np.expand_dims(img, axis=0)#     input_feed = self.get_input_feed(img)#     pred = self.onnx_session.run(None, input_feed)[0]#     return pred, or_img# def inference(self, img_path):#     try:#         img = cv2.imread(img_path)#         or_img = cv2.resize(img, (640, 640))#         img = or_img[:, :, ::-1].transpose(2, 0, 1)  # BGR2RGB和HWC2CHW#         img = img.astype(dtype=np.float32) / 255.0#         img = np.expand_dims(img, axis=0)#         input_feed = self.get_input_feed(img)#         pred = self.onnx_session.run(None, input_feed)[0]#         return pred, or_img#     except Exception as e:#         print(f"Error during inference: {e}")#         return None, Nonedef inference(self, img):try:img = cv2.imread(img)or_img = img.copy()resized_img = cv2.resize(img, (640, 640))  # 根据模型要求进行resizeresized_img = resized_img[:, :, ::-1].transpose(2, 0, 1)  # BGR2RGB和HWC2CHWresized_img = resized_img.astype(dtype=np.float32) / 255.0resized_img = np.expand_dims(resized_img, axis=0)input_feed = self.get_input_feed(resized_img)pred = self.onnx_session.run(None, input_feed)[0]return pred, or_img, resized_imgexcept Exception as e:print(f"Error during inference: {e}")return None, None, None# dets:  array [x,6] 6个值分别为x1,y1,x2,y2,score,class
# thresh: 阈值
def nms(dets, thresh):x1 = dets[:, 0]y1 = dets[:, 1]x2 = dets[:, 2]y2 = dets[:, 3]# -------------------------------------------------------#   计算框的面积#	置信度从大到小排序# -------------------------------------------------------areas = (y2 - y1 + 1) * (x2 - x1 + 1)scores = dets[:, 4]keep = []index = scores.argsort()[::-1]while index.size > 0:i = index[0]keep.append(i)# -------------------------------------------------------#   计算相交面积#	1.相交#	2.不相交# -------------------------------------------------------x11 = np.maximum(x1[i], x1[index[1:]])y11 = np.maximum(y1[i], y1[index[1:]])x22 = np.minimum(x2[i], x2[index[1:]])y22 = np.minimum(y2[i], y2[index[1:]])w = np.maximum(0, x22 - x11 + 1)h = np.maximum(0, y22 - y11 + 1)overlaps = w * h# -------------------------------------------------------#   计算该框与其它框的IOU,去除掉重复的框,即IOU值大的框#	IOU小于thresh的框保留下来# -------------------------------------------------------ious = overlaps / (areas[i] + areas[index[1:]] - overlaps)idx = np.where(ious <= thresh)[0]index = index[idx + 1]return keepdef xywh2xyxy(x):# [x, y, w, h] to [x1, y1, x2, y2]y = np.copy(x)y[:, 0] = x[:, 0] - x[:, 2] / 2y[:, 1] = x[:, 1] - x[:, 3] / 2y[:, 2] = x[:, 0] + x[:, 2] / 2y[:, 3] = x[:, 1] + x[:, 3] / 2return ydef filter_box(org_box, conf_thres, iou_thres):  # 过滤掉无用的框# -------------------------------------------------------#   删除为1的维度#	删除置信度小于conf_thres的BOX# -------------------------------------------------------org_box = np.squeeze(org_box)conf = org_box[..., 4] > conf_thresbox = org_box[conf == True]# -------------------------------------------------------#	通过argmax获取置信度最大的类别# -------------------------------------------------------cls_cinf = box[..., 5:]cls = []for i in range(len(cls_cinf)):cls.append(int(np.argmax(cls_cinf[i])))all_cls = list(set(cls))# -------------------------------------------------------#   分别对每个类别进行过滤#	1.将第6列元素替换为类别下标#	2.xywh2xyxy 坐标转换#	3.经过非极大抑制后输出的BOX下标#	4.利用下标取出非极大抑制后的BOX# -------------------------------------------------------output = []for i in range(len(all_cls)):curr_cls = all_cls[i]curr_cls_box = []curr_out_box = []for j in range(len(cls)):if cls[j] == curr_cls:box[j][5] = curr_clscurr_cls_box.append(box[j][:6])curr_cls_box = np.array(curr_cls_box)# curr_cls_box_old = np.copy(curr_cls_box)curr_cls_box = xywh2xyxy(curr_cls_box)curr_out_box = nms(curr_cls_box, iou_thres)for k in curr_out_box:output.append(curr_cls_box[k])output = np.array(output)return outputdef draw(image, box_data):# -------------------------------------------------------#	取整,方便画框# -------------------------------------------------------boxes = box_data[..., :4].astype(np.int32)scores = box_data[..., 4]classes = box_data[..., 5].astype(np.int32)for box, score, cl in zip(boxes, scores, classes):top, left, right, bottom = boxprint('class: {}, score: {}'.format(CLASSES[cl], score))print('box coordinate left,top,right,down: [{}, {}, {}, {}]'.format(top, left, right, bottom))cv2.rectangle(image, (top, left), (right, bottom), (0, 0, 255), 2) #红色#cv2.rectangle(image, (top, left), (right, bottom), (255, 0, 0), 2) #蓝色cv2.putText(image, '{0} {1:.2f}'.format(CLASSES[cl], score),(top, left),cv2.FONT_HERSHEY_SIMPLEX,0.6, (0, 0, 255), 2)#可能存在多个人体,提取置信度最高的人体框
def extract_person(image, box_data):image = np.squeeze(image, axis=0)  # 形状变为 (3, 640, 640)# 转换为 (H, W, C) 格式image = np.transpose(image, (1, 2, 0))print(f"Resized image shape: {image.shape}")cv2.imshow('read Image',image)cv2.waitKey(0)cv2.destroyAllWindows()boxes = box_data[..., :4].astype(np.int32)scores = box_data[..., 4]classes = box_data[..., 5].astype(np.int32)if len(boxes) > 0:max_index = np.argmax(scores)#top, left, right, bottom = boxes[max_index]left,top,  right, bottom = boxes[max_index]# 打印原始坐标print(f"Original Box coordinates: top={top}, left={left}, right={right}, bottom={bottom}")# 提取目标区域person = image[top:bottom, left:right]print(f"Extracted person image size: {person.shape}")cv2.imshow('extracted person',person)cv2.waitKey(0)cv2.destroyAllWindows()# 保存图像cv2.imwrite('extract.png', person*255)return personif __name__ == "__main__":onnx_path = r'E:\detect_person\person.onnx'model = YOLOV5(onnx_path)output, or_img, resize_img = model.inference(r"G:\depth_detect\huang2\huang1.png")outbox = filter_box(output, 0.35, 0.35)if len(outbox) > 0:#原图画框可视化#draw(or_img, outbox)#提取目标区域extract = extract_person(resize_img,outbox)else:print("No objects detected.")

这篇关于YOLOV----- ONNX 推理过程、可视化图片、保存检测到的目标的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

作业提交过程之HDFSMapReduce

作业提交全过程详解 (1)作业提交 第1步:Client调用job.waitForCompletion方法,向整个集群提交MapReduce作业。 第2步:Client向RM申请一个作业id。 第3步:RM给Client返回该job资源的提交路径和作业id。 第4步:Client提交jar包、切片信息和配置文件到指定的资源提交路径。 第5步:Client提交完资源后,向RM申请运行MrAp

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

综合安防管理平台LntonAIServer视频监控汇聚抖动检测算法优势

LntonAIServer视频质量诊断功能中的抖动检测是一个专门针对视频稳定性进行分析的功能。抖动通常是指视频帧之间的不必要运动,这种运动可能是由于摄像机的移动、传输中的错误或编解码问题导致的。抖动检测对于确保视频内容的平滑性和观看体验至关重要。 优势 1. 提高图像质量 - 清晰度提升:减少抖动,提高图像的清晰度和细节表现力,使得监控画面更加真实可信。 - 细节增强:在低光条件下,抖

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss

烟火目标检测数据集 7800张 烟火检测 带标注 voc yolo

一个包含7800张带标注图像的数据集,专门用于烟火目标检测,是一个非常有价值的资源,尤其对于那些致力于公共安全、事件管理和烟花表演监控等领域的人士而言。下面是对此数据集的一个详细介绍: 数据集名称:烟火目标检测数据集 数据集规模: 图片数量:7800张类别:主要包含烟火类目标,可能还包括其他相关类别,如烟火发射装置、背景等。格式:图像文件通常为JPEG或PNG格式;标注文件可能为X

基于 YOLOv5 的积水检测系统:打造高效智能的智慧城市应用

在城市发展中,积水问题日益严重,特别是在大雨过后,积水往往会影响交通甚至威胁人们的安全。通过现代计算机视觉技术,我们能够智能化地检测和识别积水区域,减少潜在危险。本文将介绍如何使用 YOLOv5 和 PyQt5 搭建一个积水检测系统,结合深度学习和直观的图形界面,为用户提供高效的解决方案。 源码地址: PyQt5+YoloV5 实现积水检测系统 预览: 项目背景

JavaFX应用更新检测功能(在线自动更新方案)

JavaFX开发的桌面应用属于C端,一般来说需要版本检测和自动更新功能,这里记录一下一种版本检测和自动更新的方法。 1. 整体方案 JavaFX.应用版本检测、自动更新主要涉及一下步骤: 读取本地应用版本拉取远程版本并比较两个版本如果需要升级,那么拉取更新历史弹出升级控制窗口用户选择升级时,拉取升级包解压,重启应用用户选择忽略时,本地版本标志为忽略版本用户选择取消时,隐藏升级控制窗口 2.

Android 10.0 mtk平板camera2横屏预览旋转90度横屏拍照图片旋转90度功能实现

1.前言 在10.0的系统rom定制化开发中,在进行一些平板等默认横屏的设备开发的过程中,需要在进入camera2的 时候,默认预览图像也是需要横屏显示的,在上一篇已经实现了横屏预览功能,然后发现横屏预览后,拍照保存的图片 依然是竖屏的,所以说同样需要将图片也保存为横屏图标了,所以就需要看下mtk的camera2的相关横屏保存图片功能, 如何实现实现横屏保存图片功能 如图所示: 2.mtk

Spring MVC 图片上传

引入需要的包 <dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-