推理代码
pred_scrapt.py
from ultralytics import YOLO
from PIL import Image
import cv2
model = YOLO("model.pt")
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels
### CUDA_VISIBLE_DEVICES=1 python3 pred_scrapt.py
###RuntimeError:CUDNN BACKEND TENSOR DESCRIPTOR: Check and Set the CUDNN_ATTR_TENSOR_STRIDES Correctly
###CUDA_VISIBLE_DEVICES=2,3
说明
source (str | int | PIL | np.ndarray):
The output of an object detector is
a set of bounding boxes
that enclose the objects in the image,
along with class labels
and confidence scores for each box.
Each result is composed of torch.Tensor by default
for result in results:
result.boxes.xyxy # box with xyxy format, (N, 4)
result.boxes.xyxyn # box with xyxy format but normalized, (N, 4)
result.boxes.conf # confidence score, (N, 1)
result.boxes.cls # cls, (N, 1)
result = result.numpy()
预测代码结构
1. ultralytics/ultralytics/yolo/utils/ops.py
def xyxy2xywh(x): Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format.
def xywh2xyxy(x)
def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
2.
Check if a string is composed of only ASCII characters.
Verify image size is a multiple of the given stride in each dimension
Check file(s) for acceptable suffix
Check if environment supports image displays
3.ultralytics/ultralytics/yolo/utils/plotting.py
方框的颜色及粗细更改
绘制图像检测框
!/usr/bin/env python3
-- coding: UTF-8 --
import cv2
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
01.use PIL
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
im = Image.open('E:/Images/1d.png')
##返回一个 Image 对象 im.format, im.size, im.mode
PIL (Python Image Library)
python PIL图像处理模块中的ImageDraw类支持各种几何图形的绘制和文本的绘制,如直线、椭圆、弧、弦、多边形以及文字等。
首先,通过ImageDraw类创建一个绘制对象draw; draw = ImageDraw.Draw(im)
draw.rectangle():矩形绘制
draw.text():文字的绘制
##Image 模块中的 save() 函数可以保存图片
##PIL保存图片的时候,图片类型一定要是 ndarray类型,不能是tensor类型,tensor转成ndarray类型保存
##numpy中array默认的数据格式是int64类型,而torch中tensor默认的数据格式是float32类型
#Image 类的 thumbnail() 方法可以用来制作缩略图
02.use cv2
读入一张图片:cv2.imread(filepath,flags)
cv2.rectangle(img=img, pt1=point[0:2], pt2=point[2:4], color=blue, thickness=0)
cv2.putText(img=img, text=category, org=point[0:2], fontFace=mark_font, fontScale=0.5, color=(0, 0, 255))
cv2.imwrite(filename=output, img=img)
03. import matplotlib.pyplot as plt
plt.subplots plt.close() fig.savefig
plt.savefig()放在plt.show()之前,又或者是使用plt.gcf()固定图片,再保存
Tidelift是一家为软件开发团队提供开源项目管理工具的公司
###参考 https://simplecv.readthedocs.io/en/latest/
https://pillow.readthedocs.io/en/stable/ https://github.com/python-pillow/Pillow
部署:
选择合适的模型,要明确自己项目的要求和标准,
精度和速度一般是最重要的两个指标,但还有模型参数量、FLOPs计算量等也
mAP这一个指标,也可能需要关注AP50、AP75、Recall等指标。
AI模型端到端的推理速度,也需要考虑到AI模型快速产业落地的速
一、将训练好的模型转换格式为ONNX格式
torch.onnx.export(model, input, output_name)
ONNX, Open Neural Network Exchage,所有其他框架产生的模型包 (.pth, .pb) 都可以转换成这个标准格式,转换成这个标准格式后,
就可以使用统一的 ONNX Runtime等工具进行统一部署。
ONNX定义的数据类包括了我们常用的数据类型,用来定义模型中的输出输出格式
ONNX中定义了很多我们常用的节点,比如 Conv,ReLU,BN, maxpool等等约124种
二、安装onnxruntime --ONNX生态系统的工具
onnxruntime-gpu版本在0.4以上时需要CUDA 10
pip install onnxruntime
pip install onnxruntime-gpu
三、onnxruntime使用方法 生态推理引擎
加载图片
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
tensor = transforms.ToTensor()(img)
tensor = tensor.unsqueeze_(0)
#加载模型
session = onnxruntime.InferenceSession("./dmnet.onnx")
#执行推理
result = session.run([], {"input": tensor.cpu().numpy()}) ##推理:注意:这里的"input"是和转onnx格式时的名字对应
参考
https://onnx.ai/index.html
onnxruntime模型部署流程 https://shelleyhlx.blog.csdn.net/article/details/111504758
浙公网安备 33010602011771号