使用onnxruntime调用yolov5-lite进行目标检测的方法如下:
1. **安装必要的库**:
首先,确保你已经安装了`onnxruntime`和`opencv-python`库。如果没有安装,可以使用以下命令进行安装:
```bash
pip install onnxruntime opencv-python
```
2. **下载yolov5-lite模型**:
从YOLOv5官方仓库下载yolov5-lite的ONNX模型文件。你可以从[YOLOv5官方仓库](https://github.com/ultralytics/yolov5)中找到下载链接。
3. **编写Python代码进行目标检测**:
下面是一个示例代码,展示如何使用onnxruntime调用yolov5-lite模型进行目标检测:
```python
import cv2
import numpy as np
import onnxruntime as ort
# 加载ONNX模型
model_path = 'yolov5-lite.onnx'
session = ort.InferenceSession(model_path)
# 获取模型输入和输出的名称
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
# 图像预处理
def preprocess(image):
input_shape = session.get_inputs()[0].shape
input_height, input_width = input_shape[2], input_shape[3]
image = cv2.resize(image, (input_width, input_height))
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = image.astype(np.float32) / 255.0
image = np.transpose(image, (2, 0, 1))
image = np.expand_dims(image, axis=0)
return image
# 后处理
def postprocess(output, image, conf_threshold=0.5):
output = np.squeeze(output)
output = np.where(output[:, 4] >= conf_threshold)
output = output[0]
boxes = output[:, :4]
confidences = output[:, 4]
class_ids = output[:, 5]
for i in range(len(boxes)):
x, y, w, h = boxes[i]
x1 = int((x - w / 2) * image.shape[1])
y1 = int((y - h / 2) * image.shape[0])
x2 = int((x + w / 2) * image.shape[1])
y2 = int((y + h / 2) * image.shape[0])
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f"{class_ids[i]}: {confidences[i]:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
return image
# 主函数
def main():
image_path = 'image.jpg'
image = cv2.imread(image_path)
input_image = preprocess(image)
outputs = session.run([output_name], {input_name: input_image})
result_image = postprocess(outputs[0], image)
cv2.imshow('Result', result_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
```
4. **运行代码**:
将上述代码保存为一个Python文件(例如`yolov5_lite_onnxruntime.py`),并确保在代码中指定正确的模型路径和图像路径。然后在终端中运行:
```bash
python yolov5_lite_onnxruntime.py
```
这样,你就可以使用onnxruntime调用yolov5-lite模型进行目标检测了。