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()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/788601.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux基础概念

Linux Linux 和 UNIX 中的文件系统是一个以 / 为根的树状式文件结构,/ 是 Linux 和 UNIX 中的根目录,同样它也是文件系统的起点。所有的文件和目录都位于 / 路径下,包括经常听到的 /usr、/etc、/bin、/home 等。在早期的 UNIX 系统中&#x…

论文阅读RangeDet: In Defense of Range View for LiDAR-based 3D Object Detection

文章目录 RangeDet: In Defense of Range View for LiDAR-based 3D Object Detection问题笛卡尔坐标结构图Meta-Kernel Convolution RangeDet: In Defense of Range View for LiDAR-based 3D Object Detection 论文:https://arxiv.org/pdf/2103.10039.pdf 代码&…

数据结构初阶:顺序表和链表

线性表 线性表 ( linear list ) 是 n 个具有相同特性的数据元素的有限序列。 线性表是一种在实际中广泛使 用的数据结构,常见的线性表:顺序表、链表、栈、队列、字符串 ... 线性表在逻辑上是线性结构,也就说是连续的一条直线。但是在物理结构上并不一定是连续的, 线性…

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…

linux通过进程pid查询容器docker

我遇到的问题是在docker中启动了进行,占用显卡,如下nvidis-smi查看: 现在要查询pid16325属于哪个容器ID,指令: ps -e -o pid,cmd,comm,cgroup | grep 16325查到如下结果,其中12:cpuset:/docker/ 后面的 8…

js实现websocket断线重连功能

在项目开发中我们可能经常要使用websocket技术,当连接发生断线后,如果不进行页面刷新将不能正常接收来自服务端的推送消息。为了有效避免这种问题,我们需要在客户端做断线重连处理。当网络或服务出现问题后,客户端会不断检测网络状…

玩转ChatGPT:Kimi测评(科研写作)

一、写在前面 ChatGPT作为一款领先的语言模型,其强大的语言理解和生成能力,让无数用户惊叹不已。然而,使用的高门槛往往让国内普通用户望而却步。 最近,一款由月之暗面科技有限公司开发的智能助手——Kimi,很火爆哦。…

Linux基础篇:VMware centos7虚拟机网络配置——桥接模式

VMware centos7虚拟机网络配置——桥接模式 1 搞清楚什么是桥接模式 桥接模式允许虚拟机直接连接到物理网络,就像它是物理网络中的一个独立设备一样。在这种模式下,虚拟机将具有与宿主机相同网络中的其他设备相同的网络访问权限。虚拟机将获得一个独立…

Navicat for MySQL 15免费注册方法

一、效果图如下: 注:此方法仅用于非商业用途,请勿传播,否则后果自负。 二、下载安装 下载安装包,分为32位和6位,下载文件名:Navicat for MySQL 15.zip(https://download.csdn.net/…

Flutter 开发学习笔记(4):widget布局容器学习

文章目录 前言相关链接Widget 有状态和无状态Flutter 代码风格去掉烦人的括号后缀提示代码缩进 Flutter 布局最简单的布局widgets和Material widgets Dark语法习惯Flutter 布局默认布局Center居中Padding 填充Align对齐默认居中顶部底部右上角 通用 WidgetContainer处于性能原因…

K8S Pod 的生命周期

本文会介绍 1个 POD 从启动到被关闭删除, 有什么事情发生, 和有什么组件被参与进来 容器环境初始化阶段 apiserver 接受到创建容器的指令时, 在构建容器之前会有一些环境的设置阶段, 例如node 选择, image 镜像下载等…

FPGA在深度学习领域的应用的优势

FPGA(Field-Programmable Gate Array)是一种可编程逻辑芯片,可以根据需要重新配置其内部的逻辑电路和功能。在深度学习领域,FPGA被广泛用于加速模型训练和推理任务。 首先,FPGA可以提供高度定制化的计算架构&#xff…

路由和远程访问是什么?

路由和远程访问在现代互联网时代中,扮演着至关重要的角色。它们为我们提供了便捷的信息传递途径,让不同地区的电脑、设备以及人们之间能够轻松进行通信和交流。 对于路由来说,它是连接互联网上的各个网络的核心设备。一台路由器可以将来自不同…

机器学习模型之支持向量机

支持向量机(Support Vector Machine,SVM)是一种监督学习算法,用于分类和回归分析。它是由Cortes和Vapnik于1995年提出的。SVM在解决小样本、非线性及高维模式识别中表现出许多特有的优势,并能够推广应用到函数拟合等其…

Chatgpt润色论文

使用ChatGPT进行论文润色时的指令 1.英语学术润色 模板:Below is a paragraph from an academic paper. Polish the writing to meet the academic style,improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite th…

【Qt】使用Qt实现Web服务器(九):EventSource+JSON实现工业界面数据刷新

1、效果 效果如下,实时刷新温度、湿度 2、源码 2.1 index.html <html><body> <!-- 页面布局,本人对HTML标签不熟悉,凑合看吧 --> <div><label for

前后端开发之——文章分类管理

原文地址&#xff1a;前后端开发之——文章分类管理 - Pleasure的博客 下面是正文内容&#xff1a; 前言 上回书说到 文章管理系统之添加文章分类。就是通过点击“新建文章分类”按钮从而在服务端数据库中增加一个文章分类。 对于文章分类这个对象&#xff0c;增删改查属于配…

PyQt ui2py 使用PowerShell将ui文件转为py文件并且将导入模块PyQt或PySide转换为qtpy模块开箱即用

前言 由于需要使用不同的qt环境&#xff08;PySide&#xff0c;PyQt&#xff09;所以写了这个脚本&#xff0c;使用找到的随便一个uic命令去转换ui文件&#xff0c;然后将导入模块换成qtpy这个通用库(支持pyside2-6&#xff0c;pyqt5-6)&#xff0c;老版本的是Qt.py(支持pysid…

Appium无线自动化实用教程

文章目录 简介核心特点工作原理使用Appium进行自动化测试的一般步骤 环境设置安装和启动Appium Server使用Node.js和npm安装Appium Server&#xff1a;启动Appium Server:命令行启动使用Appium Desktop安装和启动Appium Server&#xff1a;使用代码启动appium server 编写测试代…

Linux|centos7|postgresql数据库主从复制之异步还是同步的问题

前言&#xff1a; postgresql数据库是一个比较先进的中型关系型数据库&#xff0c;原本以为repmgr和基于repmgr的主从复制是挺简单的一个事情&#xff0c;但现实很快就给我教育了&#xff0c;原来postgresql和MySQL一样的&#xff0c;也是有异步或者同步的复制区别的 Postgre…