验证onnx格式的YOLO

  • 相关参数改成自己的
  • 注意输出的shape,onnx有时候会合并输出,目前不知道什么原因
import onnxruntime   
import cv2, torch
import numpy as np

anchors=[[22, 55,  38, 44,  32, 88,  70, 56], [22, 22,  17, 35,  37, 24,  27, 34]]
ans=len(anchors[0])//2
cls_num=1
conf_th=0.25
nms_th=0.45
model_w=
model_h=

def get_boxes(output, anchors):
	h=output.size(2)
	w=output.size(3)
	output=output.view(ans,int(cls_num+5),h,w).permute(0,2,3,1).contiguous()
	# conf
	conf = torch.sigmoid(output[..., 4])
	cl = torch.sigmoid(output[..., 5:])
	#conf = output[..., 4]
	#cl = output[..., 5:]
	clv, cli = torch.max(cl, -1)
	#print(conf[conf>0.5])
	conf = conf * clv
	#print(conf[conf>0.15])
	mask = conf > conf_th
	conf = conf[mask].unsqueeze(-1)
	cli = cli[mask].unsqueeze(-1)
	# grid
	FloatTensor = torch.cuda.FloatTensor if conf.is_cuda else torch.FloatTensor
	grid_h, grid_w = torch.meshgrid(torch.arange(h), torch.arange(w))
	grid_h = grid_h.repeat(ans,1,1).type(FloatTensor)
	grid_w = grid_w.repeat(ans,1,1).type(FloatTensor)
	tx = (torch.sigmoid(output[..., 0]) + grid_w) / w
	ty = (torch.sigmoid(output[..., 1]) + grid_h) / h
	tx = tx[mask].unsqueeze(-1)
	ty = ty[mask].unsqueeze(-1)
	# anchor
	aw = torch.Tensor(anchors[0::2]).view(ans,1).repeat(1,h*w).view(ans,h,w).type(FloatTensor)
	ah = torch.Tensor(anchors[1::2]).view(ans,1).repeat(1,h*w).view(ans,h,w).type(FloatTensor)
	tw = torch.exp(output[..., 2]) * aw
	th = torch.exp(output[..., 3]) * ah
	tw = tw[mask].unsqueeze(-1)
	th = th[mask].unsqueeze(-1)
	return torch.cat([tx, ty, tw, th, cli, conf], -1)
	
def iou(a,b):
	A=len(a)
	B=len(b)
	area1=a[:,2]*a[:,3]
	area1=area1.unsqueeze(1).expand(A,B)
	area2=b[:,2]*b[:,3]
	area2=area2.unsqueeze(0).expand(A,B)
	ba=torch.zeros(a.shape).cuda()
	bb=torch.zeros(b.shape).cuda()
	ba[:,0:2]=a[:,0:2]-a[:,2:]/2.0
	ba[:,2:]=ba[:,0:2]+a[:,2:]
	bb[:,0:2]=b[:,0:2]-b[:,2:]/2.0
	bb[:,2:]=bb[:,0:2]+b[:,2:]
	ba=ba.unsqueeze(1).expand(A,B,4)
	bb=bb.unsqueeze(0).expand(A,B,4)
	lt=torch.max(ba[:,:,0:2], bb[:,:,0:2])
	rb=torch.min(ba[:,:,2:], bb[:,:,2:])
	inter=torch.clamp((rb-lt),min=0)
	inter=inter[:,:,0]*inter[:,:,1]
	return inter/(area1+area2-inter)

def nms(box):
	box = box[torch.argsort(box[:,-1])]
	result=[]
	while len(box) > 0:
		result.append(box[0])
		if len(box) == 1: break
		ious=iou(box[0:1, 0:4], box[1:, 0:4])
		#print(ious)
		box=box[1:][ious.squeeze(0) < nms_th]
	return torch.stack(result)

def deal(boxes):
	labels = boxes[:, -2].unique()
	result=[]
	for l in labels:
		box = boxes[boxes[:, -2]==l]
		box = nms(box)
		for b in box: 
			result.append(b)
	return torch.stack(result)

session = onnxruntime.InferenceSession('.onnx', None)
input_name = session.get_inputs()[0].name
for node in session.get_outputs():
	print(node.name)
for line in open("jpg.txt"):
	line=line.strip()
	print(line)
	raw=cv2.imread(line)
	ih, iw, _ = raw.shape
	im=cv2.resize(raw, (model_w, model_h))
	im=im[..., ::-1]
	im=im.astype('float32')/255.0
	image = np.expand_dims(np.transpose(im, (2, 0, 1)), 0)
	outputs = session.run(None, {input_name: image})
	print(type(outputs))
	thld_boxes=[]
	for i,output in enumerate(outputs):
		output=torch.from_numpy(output).cuda()
		print(output.shape)
		boxes = get_boxes(output, anchors[i])
		if len(boxes) == 0: continue
		boxes[:,0] = boxes[:,0] * iw
		boxes[:,1] = boxes[:,1] * ih
		boxes[:,2] = boxes[:,2] / model_w * iw
		boxes[:,3] = boxes[:,3] / model_h * ih
		for b in boxes: thld_boxes.append(b)
	if len(thld_boxes) != 0: 
		boxes=deal(torch.stack(thld_boxes))
		print(len(boxes))
		for b in boxes:
			cx = b[0]
			cy = b[1]
			w = b[2]
			h = b[3]
			cv2.rectangle(raw, (int(cx-w/2), int(cy-h/2)), (int(cx+w/2), int(cy+h/2)), (0,0,255))
	cv2.imwrite("result/"+line.split('/')[-1], raw)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
YOLO v7是目前最流行的物体检测模型之一,它能够非常准确地识别各种物体并提供丰富的语义信息。PT是PyTorch的缩写,它是一种非常灵活和强大的深度学习框架,可以用来训练各种模型。而ONNX是另一种非常流行的深度学习格式,它可以将模型转换成一种通用的格式,以便在各种硬件上进行加速。 那么为什么要将YOLO v7的PT转换成ONNX呢?首先,ONNX具有非常高的跨平台兼容性,可以在各种设备上运行,这包括CPU、GPU、FPGA等等。这非常有益于将训练好的模型应用到实际场景中,因为不同设备的性能和架构可能有所不同。 其次,ONNX有一些非常先进的优化技术,可以显著提高模型的性能和效率。例如,ONNX可以使用精度修剪、通道剪枝等技术来减少模型的参数数量,从而加快模型的训练和推理速度。此外,ONNX还可以通过模型量化、压缩等技术来减小模型大小,从而节省存储空间和传输带宽。 最后,在实际应用中,将PT模型转换成ONNX格式还有助于提高模型的可靠性和稳定性。因为在转换的过程中,会对模型进行一系列的检查和验证,以确保模型的正确性和可用性。这可以大大减少在实际应用中遇到的问题和故障。 总之,将YOLO v7的PT模型转换成ONNX格式是非常有必要的。它可以使模型更加灵活、高效、可靠,从而更好地应用于实际场景中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刀么克瑟拉莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值