栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[YOLOv5] Python文件中将print的输出内容重定向到变量中

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[YOLOv5] Python文件中将print的输出内容重定向到变量中

使用yolov5的时候它将模型都封装好,输出函数也是results.print(),想要获取他的结果得通过截取输出的方式进行,最终采用以下方法操作:

Python文件中将print的输出内容重定向到变量中

个人修改后的代码为:

import torch

import re # 正则表达式
import sys 
class __Autonomy__(object):
    def __init__(self):
        self._buff = ""
    def write(self, out_stream):
        self._buff += out_stream

# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # or yolov5n - yolov5x6, custom

# Images
img = 'https://ultralytics.com/images/zidane.jpg'  # or file, Path, PIL, OpenCV, numpy, list

# Inference
results = model(img)

# Results
print("This is the result")

current = sys.stdout
a = __Autonomy__()
sys.stdout = a
results.print()
sys.stdout = current
print(a._buff)

pattern = re.compile('([1-9])s([a-z]+)')
m = re.findall(pattern,a._buff)
print(m)

tag = [] # image tagging结果
for i in range(len(m)):
    tag.append(m[i][1])
print(tag)

通过这种方式即可获取tagging,通过YOLOv5做一个image tagging的工作。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890413.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号