用yolov8 onnx模型檢測人
时间: 2023-07-04 21:24:29 浏览: 62
抱歉,目前并不存在 YOLOv8 模型,YOLOv5 是最新的版本。不过,如果你有对应的 YOLOv5 的 ONNX 模型,你可以使用以下代码来进行人体检测:
```python
import cv2
import numpy as np
# 加载 ONNX 模型
model = cv2.dnn.readNetFromONNX('yolov5s.onnx')
# 加载标签信息
with open('coco.names', 'r') as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
img = cv2.imread('test.jpg')
# 获取图像尺寸
height, width, _ = img.shape
# 构建输入图像
blob = cv2.dnn.blobFromImage(img, size=(640, 640), mean=(0, 0, 0), swapRB=True, crop=False)
# 将图像输入模型中进行检测
model.setInput(blob)
outputs = model.forward(model.getUnconnectedOutLayersNames())
# 处理检测结果
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5 and class_id == 0: # 0代表person类别
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
# 显示结果
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在代码中,我们首先加载了 YOLOv5 的 ONNX 模型和标签信息,然后使用 `cv2.dnn.blobFromImage` 方法构建输入图像,将其输入模型中进行检测,最后在图像中标记检测到的人体。你需要将 `yolov5s.onnx` 替换为你自己的 ONNX 模型文件,将 `coco.names` 替换为你自己的标签文件,将 `test.jpg` 替换为你自己的图像文件路径来测试代码。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)