用python调用yolov8
时间: 2024-11-24 20:25:28 浏览: 12
使用python部署yolov9目标检测的onnx源码
5星 · 资源好评率100%
在Python中调用YOLOv8(You Only Look Once version 8)通常需要一些库的支持,如OpenCV、Pillow以及对YOLOv8模型文件的处理。以下是基本步骤:
1. 安装必要的库:
- 首先安装`pip`,然后通过它安装`opencv-python-headless`和`imutils`,这两个库可以帮助处理图像:
```
pip install opencv-python-headless imutils
```
2. 下载YOLOv8模型:YOLOv8官方通常会提供预训练的权重文件(`.weights`),以及配置文件(`.cfg`)。可以从GitHub或其他官方网站获取。
3. 加载模型:
```python
import cv2
from utils.utils import get_classes, plot_one_box
# 加载模型配置文件
config_path = 'path/to/yolov8.cfg'
# 加载权重文件
weight_path = 'path/to/yolov8.weights'
# 获取类别列表
classes_path = 'path/to/coco.names'
class_names = get_classes(classes_path)
model = cv2.dnn.readNetFromDarknet(config_path, weight_path)
model.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
model.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) # 或者DNN_TARGET_OPENCL如果支持GPU加速
```
4. 运行检测:
```python
img = cv2.imread('image.jpg')
height, width, _ = img.shape
blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (416, 416), swapRB=True, crop=False)
# 设置输入并运行前向传播
model.setInput(blob)
layer_names = [layer.name for layer in model.getLayerNames() if 'output' in layer.name]
output_layers = [model.getLayerByName(layer_name).output for layer_name in layer_names]
outputs = model.forward(output_layers)
# 解析检测结果并绘制在图像上
boxes, confidences, class_ids = [], [], []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5: # 可自定义阈值
center_x, center_y = int(detection[0] * width), int(detection[1] * height)
w, h = int(detection[2] * width), int(detection[3] * height)
x, y = center_x - w / 2, center_y - h / 2
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 绘制边界框
plot_one_box(boxes, img, color=(0, 255, 0), label='person', line_thickness=2)
```
5. 显示结果:
```python
cv2.imshow("YOLOv8 Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文