ultralytics的YOLOv8改为自用版本_from ultralytics.utils.plotting import annotator, -程序员宅基地

技术标签: YOLO  

由于需要用pyqt给yolov8做一个界面,而ultralytics一层嵌一层,不是很好用,所以对它的这个源码进行精简,具体代码我放到了这里,ultralytics使用的版本是8.0.54。

 具体代码如下,需要根据自己的情况来修改data的配置文件以及权值文件,在代码的49和50行

import torch
import cv2
import numpy as np

from ultralytics.yolo.data.augment import LetterBox
from ultralytics.yolo.engine.results import Results
from ultralytics.yolo.utils import ops
from ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box
from ultralytics.nn.autobackend import AutoBackend


def get_annotator(img):
    return Annotator(img, line_width=3, example=str(model.names))

def preprocess(img):
    img = (img if isinstance(img, torch.Tensor) else torch.from_numpy(img)).to(model.device)
    img = img.float()
    img /= 255  # 0 - 255 to 0.0 - 1.0
    return img

def postprocess(preds, img, orig_imgs):
    preds = ops.non_max_suppression(preds,
                                    conf,
                                    iou,
                                    agnostic=False,
                                    max_det=300,
                                    classes=None)

    results = []
    for i, pred in enumerate(preds):
        orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs # 返回的orig_img变量表示原始图像
        if not isinstance(orig_imgs, torch.Tensor):
            pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
        path = 0
        img_path = path[i] if isinstance(path, list) else path
        results.append(Results(orig_img=orig_img, path=img_path, names=model.names, boxes=pred))
    return results


def save_preds(vid_cap, im0):
    fps = int(vid_cap.get(cv2.CAP_PROP_FPS))  # integer required, floats produce error in MP4 codec
    w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    vid_writer = cv2.VideoWriter('1.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
    im0 = (im0 * 255).astype(np.uint8)  # Convert to byte type
    vid_writer.write(im0)


model = ''
data = ''
imgsz = 640
visualize = False
conf = 0.25
iou = 0.5
model = AutoBackend(model,
                     device=torch.device('cuda:0'),
                     data=data,
                     verbose=True)
device = torch.device('cuda:0')
model.eval()
cam = cv2.VideoCapture(0)

while 1:
    im0 = cam.read()[1]

    im = np.stack([LetterBox(imgsz, True, stride=32)(image=im0)])
    im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW
    im = np.ascontiguousarray(im)  # contiguous
    dt = (ops.Profile(), ops.Profile(), ops.Profile())

    # preprocess
    with dt[0]:
        im = preprocess(im)
        if len(im.shape) == 3:
            im = im[None]  # expand for batch dim

    # inference
    with dt[1]:
        preds = model(im, augment=False, visualize=visualize)

    # postprocess
    with dt[2]:
        results = postprocess(preds, im, im0)

    det = results[0].boxes  # TODO: make boxes inherit from tensors

    # write
    for d in reversed(det):
        cls, conf, id = d.cls.squeeze(), d.conf.squeeze(), None if d.id is None else int(d.id.item())

        c = int(cls)  # integer class
        name = ('' if id is None else f'id:{id} ') + model.names[c]
        label = f'{name} {conf:.2f}'
        p1, p2 = (int(d.xyxy.squeeze()[0]), int(d.xyxy.squeeze()[1])), (int(d.xyxy.squeeze()[2]), int(d.xyxy.squeeze()[3]))
        lw = max(round(sum(im.shape) / 2 * 0.003), 2)
        cv2.rectangle(im0, p1, p2, colors(c, True), thickness=lw, lineType=cv2.LINE_AA)
        if label:
            tf = max(lw - 1, 1)  # font thickness
            w, h = cv2.getTextSize(label, 0, fontScale=lw / 3, thickness=tf)[0]  # text width, height
            outside = p1[1] - h >= 3
            p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3
            # cv2.rectangle(im0, p1, p2, (128, 128, 128), -1, cv2.LINE_AA)  # filled
            cv2.putText(im0,
                        label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),
                        0,
                        lw / 3,
                        (0, 0, 255),
                        thickness=tf,
                        lineType=cv2.LINE_AA)


    cv2.imshow("result", im0)
    # save_preds(cam, im0)
    print('preprocess:{},inference:{},postprocess:{}'.format(dt[0].dt * 1E3 ,dt[1].dt * 1E3 ,dt[2].dt * 1E3 ))
    if cv2.waitKey(1) & 0xff == ord('q'):  # 1 millisecond
        break

cam.release()
cv2.destroyAllWindows()

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/w1036427372/article/details/130784437

智能推荐

人人开源 获取定时任务CronTrigger出现异常-程序员宅基地

文章浏览阅读2.5k次。人人开源 获取定时任务CronTrigger出现异常报错信息:org.springframework.beans.factory.UnsatisfiedDependencyException:Error creating bean with name ‘scheduleJobController’: Unsatisfieddependency expressed through field ‘scheduleJobService’; nestedexception is org.springf

python获取邮件内容_python 接收邮件获取邮件内容-程序员宅基地

文章浏览阅读1.5k次。收取邮件有两种协议,POP3和IMAP,POP3相对于IMAP功能较少无法对邮件进行更深层次的操作,因此本文使用IMAP协议收取邮件。python提供了很多收邮件的模块,本文使用imaplib来接收邮件。前提需要在邮件箱的设置中打开允许IMAP,不同邮件开启全方式不同,具体开启方式自行百度。(本文使用outlook,默认开启)难点获得邮件不难,难点是如何解析邮件的内容,由于邮件内容的编码是不固定的..._python接收邮件內容

监控zabbix面试题-程序员宅基地

文章浏览阅读1.3w次,点赞25次,收藏396次。目录我们可以用zabbix监控哪些zabbix的主动监控与被动监控配置zabbix自定义监控流程安全组是什么,限制了3306的入规则,客户端还能访问吗Nagio监控?服务器一般需要监控哪些项目? 凭借这些项目如何判断服务器的瓶颈?zabbix监控mysql的io情况是否正常的流程监控MySQL主从同步是否异常,如果异常,则发送短信或者邮件给管理员。zabbix如何修改其中监控的一台服务器中内存阈值信息,比如正常内存使用到了 80%报**警,我想修改为 60%报警...

理解 asyncio 来构建高性能 Python 网络程序 - Ricequant米筐量化_asyncio网络-程序员宅基地

文章浏览阅读325次。Python 是一门上手快、优雅简洁的编程语言,其多范式、丰富的标准库和第三方库能够让编程人员把精力集中在逻辑和思维方法上,而不用去担心复杂语法、类型系统等外在因素,从而高效地达成自己的编程目标。Python 抽象层次非常高,这帮助我们更好更快地完成编程,但也屏蔽了很多细节,程序员也无法精确控制计算机底层的资源,代码性能优化就变得比较复杂。很多资深的程序员可能会觉得 Python 性能不够好,无法编写高性能的程序,其实这句话也不全对。对于计算密集型的程序,Python 可以通过扩展的形式使得核心计算直接调用_asyncio网络

Java框架--Spring(轻量级容器框架)(声明式事务)_spring容器事务-程序员宅基地

文章浏览阅读2.1k次,点赞2次,收藏2次。笔记型博客之spring-声明式事务_spring容器事务

1444-DYN04-01RA AB 控制器传感器_1444-dyn04-01ra手册-程序员宅基地

文章浏览阅读861次,点赞15次,收藏19次。总之,1444-DYN04-01RA AB 控制器传感器是一款功能强大、可靠稳定的传感器,适用于各种旋转和往复机械的监测和控制。它的应用可以提高机械的运行效率和安全性,为工业生产和能源领域的发展提供有力支持。此外,1444-DYN04-01RA AB 控制器传感器还具有友好的人机界面,可以方便地进行操作和维护。1444-DYN04-01RA AB 控制器传感器是一款用于监测旋转和往复机械的传感器,可以测量振动和压力等动态输入以及轴位移、偏心和活塞杆沉降等静态输入。_1444-dyn04-01ra手册

随便推点

Ubuntu之apt-get--安装gcc--方法/教程_apt-get gcc-程序员宅基地

文章浏览阅读8.2k次,点赞38次,收藏18次。本文介绍Ubuntu如何安装gcc。_apt-get gcc

如何在 React 中使用 Sass_react 使用sass-程序员宅基地

文章浏览阅读9.2k次。Sass 是 CSS 的改进版本,您现在就可以在 React 项目中使用它。_react 使用sass

flutter打包的app有多大_Flutter原生混合开发-程序员宅基地

文章浏览阅读211次。使用 Flutter 从头开始写一个 App是一件轻松惬意的事情。但是对于成熟产品来说,完全摒弃原有 App 的历史沉淀,全面转向 Flutter 并不现实。用 Flutter 去统一 iOS/Android 技术栈,把它作为已有原生 App 的扩展,然后通过逐步试验有序推进从而提升终端开发效率,可能才是现阶段 Flutter 最有效的集成方式。那么,Flutter 工程与原生工程该如何组织管理?..._flutter 打包ios 是原生app吗

2021安洵杯Misc writeup_chr(ord(tmp)+26)-程序员宅基地

文章浏览阅读1.1k次。忘了发了,来迟了Misc应该算是签到来得早不如来的巧CyzCC_loves_LOL小脑洞+老考点,理解一下其实是放进百度翻译然后一下看出来了s = 'D0g3isthepAssword'flag = ''for i in range(len(s)): tmp = ord(s[i])-3 if(tmp<65): flag += chr(tmp+26) else: flag += chr(tmp)print(flag)密码_chr(ord(tmp)+26)

Pytorch中,将label变成one hot编码的两种方式_label变为onehot-程序员宅基地

文章浏览阅读7.3w次,点赞90次,收藏216次。由于Pytorch不像TensorFlow有谷歌巨头做维护,很多功能并没有很高级的封装,比如说没有tf.one_hot函数。本篇介绍将一个mini batch的label向量变成形状为[batch size, class numbers]的one hot编码的两种方法,涉及到tensor.scatter_tensor.index_select使用scatter_获得one hot 编码..._label变为onehot

影视级调色lut预设包 Triune Color Cinematic LUTs V2-程序员宅基地

文章浏览阅读3.7k次。与大家分享一套影视级调色预设 Triune Color Cinematic LUTs V2。兼容ps,fcpx,pr,ae,lr等后期视频和图像处理软件,帮助大家轻松实现电影级调色,让作品获得更震撼、更高级的色彩表现。原文及下载地址:https://www.mac69.com/cj/1287.html影视级调色预设 Triune Color Cinematic LUTs V2 官方介绍..._triune color cinematic luts