使用ONNX模型进行目标检测的代码实现
{ "title": "使用ONNX模型进行目标检测的代码实现", "description": "这段代码展示了如何使用ONNX模型对图像进行目标检测,并对检测结果进行处理和绘制,最后保存带有检测结果的图像。", "keywords": "目标检测, ONNX模型, 图像处理, 深度学习, OpenCV, Python", "content": "outputs = session.run(outname, inp)[0]\n print('inference time :%.4f' % (time.time() - t1))\n # print(outputs)\n\n ori_images = [img.copy()]\n areas = []\n for i, (batch_id, x0, y0, x1, y1, cls_id, score) in enumerate(outputs):\n image = ori_images[int(batch_id)]\n box = np.array([x0, y0, x1, y1])\n box -= np.array(dwdh * 2)\n box /= ratio\n box = box.round().astype(np.int32).tolist()\n cls_id = int(cls_id)\n score = round(float(score), 3)\n name = names[cls_id]\n color = colors[name]\n name += ' ' + str(score)\n # print(color)\n # print(box)\n areas.append([box[0], box[1], box[2] - box[0], box[3] - box[1], None])\n # cv2.rectangle(image, tuple(box[:2]), tuple(box[2:]), color, 2)\n # cv2.putText(image, name, (box[0], box[1] - 2), cv2.FONT_HERSHEY_SIMPLEX, 0.75, [225, 255, 255], thickness=2)\n # t = int(time.time())\n # cv2.imwrite(image, "process_img/%d.jpg"%t)\n # cv2.imwrite(img2, "process_img/%d_origin.jpg"%t)\n # return areas, gray\n\n cv2.rectangle(image, tuple(box[:2]), tuple(box[2:]), color, 2)\n cv2.putText(image,name,(box[0], box[1] - 2),cv2.FONT_HERSHEY_SIMPLEX,0.75,[225, 255, 255],thickness=2)\n #\n cv2.imwrite('onnx.jpg', ori_images[0])
这段代码实现了对图像进行目标检测的功能。具体步骤如下:
-
使用已加载的模型对输入图像进行推理,得到检测结果。其中,
outname表示输出节点的名称,inp表示输入图像的数据。 -
计算推理时间并打印输出。
-
复制输入图像,并将其存储在
ori_images列表中。 -
遍历检测结果,对每个检测框进行处理。其中,
(batch_id, x0, y0, x1, y1, cls_id, score)表示一个检测框的信息。 -
根据检测框的信息,将其坐标转换为原始图像上的坐标,并将其加入到
areas列表中。 -
给检测框添加矩形框和标签,并在原始图像上绘制。
-
将带有检测结果的图像保存为"onnx.jpg"。
请注意,代码中可能存在一些错误和缺失的部分,所以在运行之前需要进行一些调整和完善。
原文地址: https://www.cveoy.top/t/topic/p777 著作权归作者所有。请勿转载和采集!