python api 使用 yolov8预测
时间: 2023-11-02 08:03:20 浏览: 148
yolov8源码,测试可用
首先,你需要安装`yolov5`库。你可以在终端中执行以下命令来安装:
```
pip install yolov5
```
接下来,你需要下载`yolov5`的预训练模型。你可以在[yolov5官网](https://github.com/ultralytics/yolov5/releases)下载。
下载完成后,你可以使用以下代码加载模型并进行预测:
```python
import torch
import cv2
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
from yolov5.models.experimental import attempt_load
from yolov5.utils.general import non_max_suppression, scale_coords
from yolov5.utils.torch_utils import select_device
def predict(image_path):
# Load the model
weights = 'path/to/weights.pt'
device = select_device('cpu')
model = attempt_load(weights, map_location=device)
# Load the image
img = cv2.imread(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = Image.fromarray(img)
# Make predictions
img_size = 640
img = img.resize((img_size, img_size), resample=Image.BILINEAR)
img = np.array(img).transpose(2, 0, 1)
img = torch.from_numpy(img).unsqueeze(0).float() / 255.0
pred = model(img, size=img_size)[0]
pred = non_max_suppression(pred, conf_thres=0.5, iou_thres=0.5, agnostic=False, classes=None)
# Process the predictions
for det in pred:
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img.shape[2:]).round()
for *xyxy, conf, cls in det:
label = f'{model.names[int(cls)]} {conf:.2f}'
xyxy = [int(x) for x in xyxy]
cv2.rectangle(img, (xyxy[0], xyxy[1]), (xyxy[2], xyxy[3]), (0, 255, 0), 2)
cv2.putText(img, label, (xyxy[0], xyxy[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
# Display the image
plt.imshow(img)
plt.show()
predict('path/to/image.jpg')
```
在上面的代码中,`weights`变量是你下载的预训练模型的路径。`predict`函数接受一个图像的路径作为输入,然后返回一个带有预测结果的图像。你可以通过调整`conf_thres`和`iou_thres`参数来控制预测的精度和召回率。
阅读全文