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

Yolov5封装detect.py面向对象

主要目标是适应摄像头rtsp流的检测

如果是普通文件夹或者图片,run中的while True去掉即可。

web_client是根据需求创建的客户端,将检测到的数据打包发送给服务器

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.Usage:$ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640
"""import argparse
import json
import os
import sys
import time
import moment
from pathlib import Pathimport cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnnFILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relativefrom models.experimental import attempt_load
from utils.datasets import LoadImages, LoadStreams
from utils.general import apply_classifier, check_img_size, check_imshow, check_requirements, check_suffix, colorstr, \increment_path, non_max_suppression, print_args, save_one_box, scale_coords, set_logging, \strip_optimizer, xyxy2xywh
from utils.plots import Annotator, colors
from utils.torch_utils import load_classifier, select_device, time_syncfrom mytools import read_yaml_all, base64_encode_img
from message_base import MessageBase
from websocket_client import WebClientclass Detect:def __init__(self, config: dict, client: WebClient):self.config = configself.weights = self.config.get("weights")  # weights pathself.source = self.config.get("source")  # source self.imgsz = self.config.get("imgsz")  # imgszself.conf_thres = self.config.get("conf_thres")self.iou_thres = self.config.get("iou_thres")self.max_det = self.config.get("max_det")self.device = self.config.get("device")  # "cpu" or "0,1,2,3"self.view_img = self.config.get("view_img")  # show resultsself.save_txt = self.config.get("save_txt")  # save results to *.txtself.save_conf = self.config.get("save_conf")  # save confidences in --save-txt labelsself.save_crop = self.config.get("save_crop")  # save cropped prediction boxesself.nosave = self.config.get("nosave")  # do not save images/videosself.classes = self.config.get("classes")  # filter by class: --class 0, or --class 0 2 3self.agnostic_nms = self.config.get("agnostic_nms")  # class-agnostic NMSself.augment = self.config.get("augment")  # augmented inferenceself.visualize = self.config.get("visualize")  # visualize featuresself.update = self.config.get("update")  # update all modelsself.save_path = self.config.get("save_path")  # save results to project/nameself.line_thickness = self.config.get("line_thickness")  # bounding box thickness (pixels)self.hide_labels = self.config.get("hide_labels")  # hide labelsself.hide_conf = self.config.get("hide_conf")  # hide confidencesself.half = self.config.get("half")  # use FP16 half-precision inferenceself.dnn = self.config.get("dnn")  # use OpenCV DNN for ONNX inferenceself.func_device = self.config.get("func_device")  # 对应功能的设备名字self.save_img = not self.nosave and not self.source.endswith('.txt')  # save inference imagesself.webcam = self.source.isnumeric() or self.source.endswith('.txt') or self.source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))set_logging()self.device = select_device(self.device)self.half = self.device.type != 'cpu'  # half precision only supported on CUDAself.model = attempt_load(self.weights, map_location=self.device)self.imgsz = check_img_size(self.imgsz, s=int(self.model.stride.max()))self.stride = int(self.model.stride.max())self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names# 获取数据if self.webcam:self.view_img = check_imshow()cudnn.benchmark = True  # set True to speed up constant image size inferenceself.dataset = LoadStreams(self.source, img_size=self.imgsz, stride=self.stride, auto=True)self.bs = len(self.dataset)  # batch_sizeelse:self.dataset = LoadImages(self.source, img_size=self.imgsz, stride=self.stride, auto=True)self.bs = 1  # batch_sizeself.client = client  # 客户端self.last_time = moment.now()self.check_time_step = 5  # 每隔多少时间检测一次os.mkdir(self.save_path) if not os.path.exists(self.save_path) else Nonedef inference(self, img):img = torch.from_numpy(img).to(self.device)img = img.half() if self.half else img.float()  # uint8 to fp16/32img /= 255.0  # 0 - 255 to 0.0 - 1.0if img.ndimension() == 3:img = img.unsqueeze(0)pred = self.model(img, augment=self.augment)[0]# NMSpred = non_max_suppression(pred, self.conf_thres, self.iou_thres,self.classes, self.agnostic_nms, max_det=self.max_det)return preddef process(self, im0s, img, pred, path):for i, det in enumerate(pred):  # per imageif self.webcam:  # batch_size >= 1p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), self.dataset.countelse:p, s, im0, frame = path, '', im0s.copy(), getattr(self.dataset, 'frame', 0)p = Path(p)  # to Pathtxt_path = str(self.save_path + "/" + 'labels' + "/" + p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')  # img.txts += '%gx%g ' % img.shape[2:]  # print stringgn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhimc = im0.copy() if self.save_crop else im0  # for save_cropannotator = Annotator(im0, line_width=self.line_thickness, example=str(self.names))if len(det):# Rescale boxes from img_size to im0 sizedet[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()# Print resultsfor c in det[:, -1].unique():n = (det[:, -1] == c).sum()  # detections per classs += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "  # add to string# Write resultsfor *xyxy, conf, cls in reversed(det):c = int(cls)label = self.names[c]# if label == "person":if label:  # 根据对应标签做处理# annotator.box_label(xyxy, label, color=colors(c, True)) # 画框t = int(time.time())img_path = f"{self.save_path}/{self.func_device}_{label}_{t}.jpg"crop = save_one_box(xyxy, imc, img_path, BGR=True)x1, y1, x2, y2 = int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])data = {"device": self.func_device,"value": {"label": label,"time": t,"locate": (x1, y1, x2, y2),"crop": base64_encode_img(crop)}}data = json.dumps(data)  # 打包数据try:self.client.send(data)  # 客户端发送数据passexcept Exception as err:print("发送失败:", err)self.client.connect()self.client.send(data)print("重连成功!")print(data)# if self.save_txt:  # Write to file#     xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(#         -1).tolist()  # normalized xywh#     line = (cls, *xywh, conf) if self.save_conf else (cls, *xywh)  # label format#     with open(txt_path + '.txt', 'a') as f:#         f.write(('%g ' * len(line)).rstrip() % line + '\n')# 画框# if self.save_img or self.save_crop or self.view_img:  # Add bbox to image#     c = int(cls)  # integer class#     label = None if self.hide_labels else (self.names[c] if self.hide_conf else#                                            f'{self.names[c]} {conf:.2f}')#     annotator.box_label(xyxy, label, color=colors(c, True))def run(self):self.client.connect()while True:for path, img, im0s, vid_cap in self.dataset:if self.last_time.__lt__(moment.now()):self.last_time = moment.now().add(seconds=self.check_time_step)try:pred = self.inference(img)self.process(im0s, img, pred, path)              except Exception as err:print(err)if self.save_txt or self.save_img:s = f"\n{len(list(self.save_path.glob('labels/*.txt')))} labels saved to {self.save_path / 'labels'}" if self.save_txt else ''print(f"Results saved to {colorstr('bold', self.save_path)}{s}")if self.update:strip_optimizer(self.weights)  # update model (to fix SourceChangeWarning)if __name__ == "__main__":message_base = MessageBase()wc = WebClient("192.168.6.28", 8000)configs = read_yaml_all("yolo_configs.yaml")config = read_yaml_all("configs.yaml")device_name = config.get("DEVICE_LIST")[0]device_source = config.get("RTSP_URLS").get(device_name)configs["source"] = device_sourceconfigs["func_device"] = device_nameprint(configs)detect = Detect(configs, wc)detect.run()

相关文章:

Yolov5封装detect.py面向对象

主要目标是适应摄像头rtsp流的检测 如果是普通文件夹或者图片,run中的while True去掉即可。 web_client是根据需求创建的客户端,将检测到的数据打包发送给服务器 # YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Run inf…...

入门级深度学习主机组装过程

一 配置 先附上电脑配置图,如下: 利用公司的办公电脑对配置进行升级改造完成。除了显卡和电源,其他硬件都是公司电脑原装。 二 显卡 有钱直接上 RTX4090,也不能复用公司的电脑,其他配置跟不上。 进行深度学习&…...

python爬虫之selenium4使用(万字讲解)

文章目录 一、前言二、selenium的介绍1、优点:2、缺点: 三、selenium环境搭建1、安装python模块2、selenium4新特性3、安装驱动WebDriver驱动选择驱动安装和测试 基础操作1、属性和方法2、单个元素定位通过id定位通过class_name定位一个元素通过xpath定位…...

【ARM 嵌入式 C 头文件系列 22 -- 头文件 stdint.h 介绍】

请阅读【嵌入式开发学习必备专栏 】 文章目录 C 头文件 stdint.h定长整数类型最小宽度整数类型最快最小宽度整数类型整数指针类型最大整数类型 C 头文件 stdint.h 在 C 语言中&#xff0c;头文件 <stdint.h> 是 C99 标准的一部分&#xff0c;旨在提供一组明确的整数类型…...

LabVIEW专栏三、探针和断点

探针和断点是LabVIEW调试的常用手段&#xff0c;该节以上一节的"测试耗时"为例 探针可以打在有线条的任何地方&#xff0c;打上后&#xff0c;经过这条线的所有最后一次的数值都会显示在探针窗口。断点可以打在程序框图的所有G代码对象&#xff0c;包括结构&#xf…...

Transformer模型-softmax的简明介绍

今天介绍transformer模型的softmax softmax的定义和目的&#xff1a; softmax&#xff1a;常用于神经网络的输出层&#xff0c;以将原始的输出值转化为概率分布&#xff0c;从而使得每个类别的概率值在0到1之间&#xff0c;并且所有类别的概率之和为1。这使得Softmax函数特别适…...

记录一下做工厂的打印pdf程序

功能&#xff1a;在网页点击按钮调起本地的打印程序 本人想到的就是直接调起方式&#xff0c;网上大佬们说用注册表的形式来进行。 后面想到一种&#xff0c;在电脑开机时就开启&#xff0c;并在后台运行&#xff0c;等到有人去网页里面进行触发&#xff0c;这时候就有个问题&a…...

Linux网络编程一(协议、TCP协议、UDP、socket编程、TCP服务器端及客户端)

文章目录 协议1、分层模型结构2、网络应用程序设计模式3、ARP协议4、IP协议5、UDP协议6、TCP协议 Socket编程1、网络套接字(socket)2、网络字节序3、IP地址转换4、一系列函数5、TCP通信流程分析 第二次更新&#xff0c;自己再重新梳理一遍… 协议 协议&#xff1a;指一组规则&…...

Python读取Excel根据每行信息生成一个PDF——并自定义添加文本,可用于制作准考证

文章目录 有点小bug的:最终代码(无换行):有换行最终代码无bug根据Excel自动生成PDF,目录结构如上 有点小bug的: # coding=utf-8 import pandas as pd from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.pdfbase import pdf…...

http: server gave HTTP response to HTTPS client 分析一下这个问题如何解决中文告诉我详细的解决方案

这个错误信息表明 Docker 客户端在尝试通过 HTTPS 协议连接到 Docker 仓库时&#xff0c;但是服务器却返回了一个 HTTP 响应。这通常意味着 Docker 仓库没有正确配置为使用 HTTPS&#xff0c;或者客户端没有正确配置以信任仓库的 SSL 证书。以下是几种可能的解决方案&#xff1…...

Flume学习笔记

视频地址:https://www.bilibili.com/video/BV1wf4y1G7EQ/ 定义 Flume是一个高可用的、高可靠的、分布式的海量日志采集、聚合和传输的系统。 Flume高最要的作用就是实时读取服务器本地磁盘的数据,将数据写入HDFS。 官网:https://flume.apache.org/releases/content/1.9.0/…...

数据库系统概论(超详解!!!) 第三节 关系数据库标准语言SQL(Ⅳ)

1.集合查询 集合操作的种类 并操作UNION 交操作INTERSECT 差操作EXCEPT 参加集合操作的各查询结果的列数必须相同;对应项的数据类型也必须相同 查询计算机科学系的学生及年龄不大于19岁的学生。SELECT *FROM StudentWHERE Sdept CSUNIONSELECT *FROM StudentWHERE Sage&l…...

与谷歌“分家”两年后,SandboxAQ推出统一加密管理平台

3月27日&#xff0c;SandboxAQ宣布其AQtive Guard平台现已全面可用&#xff08;GA&#xff09;&#xff0c;适用于所有行业&#xff0c;以防范人工智能驱动和量子攻击的威胁。前者是在两年前3月从谷歌母公司Alphabet分拆出来的初创公司&#xff0c;并在当时获得了“九位数”的融…...

【卫星家族】 | 高分六号卫星影像及获取

1. 卫星简介 高分六号卫星&#xff08;GF-6&#xff09;于2018年6月2日在酒泉卫星发射中心成功发射&#xff0c;是高分专项中的一颗低轨光学遥感卫星&#xff0c;也是我国首颗精准农业观测的高分卫星&#xff0c;具有高分辨率、宽覆盖、高质量成像、高效能成像、国产化率高等特…...

XML与Xpath

XML与Xpath XML是一种具有某种层次结构的文件&#xff0c;Xpath则是解析这种文件的工具 接下来将会解释XML文件的结构和Xpath的基本使用&#xff0c;并且用Java语言进行操作展示。 XML结构 XML&#xff08;可扩展标记语言&#xff09;文件具有一种层次结构&#xff0c;由标签…...

【c++20】CPP-20-STL-Cookbook 学习笔记

Cpp20-STL-Cookbook-src简单的阅读笔记。c++20更好用了,比如STL 包含了一些这样的辅助函数,比如 make_pair() 和make_tuple() 等。 这些代码现在已经过时了,但是为了与旧代码兼容,会保留这些代码。比如 可以声明是一个std的string:Sum s1 {1u, 2.0, 3, 4.0f }?...

Python 之 Flask 框架学习

毕业那会使用过这个轻量级的框架&#xff0c;最近再来回看一下&#xff0c;依赖相关的就不多说了&#xff0c;直接从例子开始。下面示例中的 html 模板&#xff0c;千万记得要放到 templates 目录下。 Flask基础示例 hello world from flask import Flask, jsonify, url_fora…...

精品丨PowerBI负载测试和容量规划

当选择Power BI作为业务报表平台时&#xff0c;如何判断许可证的选择是否符合业务需求&#xff0c;价格占了主导因素。 Power BI的定价是基于SKU和服务器内核决定的&#xff0c;但是很多IT的负责人都不确定自己公司业务具体需要多少。 不幸的是&#xff0c;Power BI的容量和预期…...

【算法-PID】

算法-PID ■ PID■ 闭环原理■ PID 控制流程■ PID 比例环节&#xff08;Proportion&#xff09;■ PID 积分环节&#xff08;Integral&#xff09;■ PID 微分环节&#xff08;Differential&#xff09; ■ 位置式PID&#xff0c;增量式PID介绍■ 位置式 PID 公式■ 增量式 PI…...

ros rosbag使用记录

rosbag: 1. rosbag record -a 记录当前所有消息&#xff08;较少用&#xff09;2. rosbag record -O bag_name.bag /topic 记录指定消息3. rosbag info 查阅bag文件信息4. rosbag play 播放bag文件内容5. python script 查看bag文件内容参考&#xff1a; 1. rosbag record -a 记…...

Java 8 Stream API 入门到实践详解

一、告别 for 循环&#xff01; 传统痛点&#xff1a; Java 8 之前&#xff0c;集合操作离不开冗长的 for 循环和匿名类。例如&#xff0c;过滤列表中的偶数&#xff1a; List<Integer> list Arrays.asList(1, 2, 3, 4, 5); List<Integer> evens new ArrayList…...

从零实现富文本编辑器#5-编辑器选区模型的状态结构表达

先前我们总结了浏览器选区模型的交互策略&#xff0c;并且实现了基本的选区操作&#xff0c;还调研了自绘选区的实现。那么相对的&#xff0c;我们还需要设计编辑器的选区表达&#xff0c;也可以称为模型选区。编辑器中应用变更时的操作范围&#xff0c;就是以模型选区为基准来…...

SCAU期末笔记 - 数据分析与数据挖掘题库解析

这门怎么题库答案不全啊日 来简单学一下子来 一、选择题&#xff08;可多选&#xff09; 将原始数据进行集成、变换、维度规约、数值规约是在以下哪个步骤的任务?(C) A. 频繁模式挖掘 B.分类和预测 C.数据预处理 D.数据流挖掘 A. 频繁模式挖掘&#xff1a;专注于发现数据中…...

汽车生产虚拟实训中的技能提升与生产优化​

在制造业蓬勃发展的大背景下&#xff0c;虚拟教学实训宛如一颗璀璨的新星&#xff0c;正发挥着不可或缺且日益凸显的关键作用&#xff0c;源源不断地为企业的稳健前行与创新发展注入磅礴强大的动力。就以汽车制造企业这一极具代表性的行业主体为例&#xff0c;汽车生产线上各类…...

Java多线程实现之Callable接口深度解析

Java多线程实现之Callable接口深度解析 一、Callable接口概述1.1 接口定义1.2 与Runnable接口的对比1.3 Future接口与FutureTask类 二、Callable接口的基本使用方法2.1 传统方式实现Callable接口2.2 使用Lambda表达式简化Callable实现2.3 使用FutureTask类执行Callable任务 三、…...

【碎碎念】宝可梦 Mesh GO : 基于MESH网络的口袋妖怪 宝可梦GO游戏自组网系统

目录 游戏说明《宝可梦 Mesh GO》 —— 局域宝可梦探索Pokmon GO 类游戏核心理念应用场景Mesh 特性 宝可梦玩法融合设计游戏构想要素1. 地图探索&#xff08;基于物理空间 广播范围&#xff09;2. 野生宝可梦生成与广播3. 对战系统4. 道具与通信5. 延伸玩法 安全性设计 技术选…...

AI病理诊断七剑下天山,医疗未来触手可及

一、病理诊断困局&#xff1a;刀尖上的医学艺术 1.1 金标准背后的隐痛 病理诊断被誉为"诊断的诊断"&#xff0c;医生需通过显微镜观察组织切片&#xff0c;在细胞迷宫中捕捉癌变信号。某省病理质控报告显示&#xff0c;基层医院误诊率达12%-15%&#xff0c;专家会诊…...

【VLNs篇】07:NavRL—在动态环境中学习安全飞行

项目内容论文标题NavRL: 在动态环境中学习安全飞行 (NavRL: Learning Safe Flight in Dynamic Environments)核心问题解决无人机在包含静态和动态障碍物的复杂环境中进行安全、高效自主导航的挑战&#xff0c;克服传统方法和现有强化学习方法的局限性。核心算法基于近端策略优化…...

vulnyx Blogger writeup

信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面&#xff0c;gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress&#xff0c;说明目标所使用的cms是wordpress&#xff0c;访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...

Webpack性能优化:构建速度与体积优化策略

一、构建速度优化 1、​​升级Webpack和Node.js​​ ​​优化效果​​&#xff1a;Webpack 4比Webpack 3构建时间降低60%-98%。​​原因​​&#xff1a; V8引擎优化&#xff08;for of替代forEach、Map/Set替代Object&#xff09;。默认使用更快的md4哈希算法。AST直接从Loa…...