用训练好的模型在Yolov8上进行推理演示python代码,含图像检测,视频推理,实时摄像头检测。

一,图像检测

用已经训练好的模型进行图像推理检测,运行时注意修改图像和模型路径。

# 引入opencv
import cv2

# 引入YOLO模型
from ultralytics import YOLO

# 打开图像
img_path = "./img.jpg"  # 这里修改你图像保存路径

# 打开图像
img = cv2.imread(filename=img_path)

# 加载模型
model = YOLO(model="yolov8n.pt") # 这里修改你图像保存路径

# 正向推理
res = model(img)

# 绘制推理结果
annotated_img = res[0].plot()

# 显示图像
cv2.imshow(winname="YOLOV8", mat=annotated_img)

# 等待时间
cv2.waitKey(delay=10000)

# 绘制推理结果
cv2.imwrite(filename="jieguo.jpeg", img=annotated_img) 

二, 视频检测

用已经训练好的模型进行视频推理检测,运行时注意修改图像和模型路径。

import cv2

from ultralytics import YOLO

# 加载模型
model = YOLO(model="yolov8x.pt")

# 视频文件
video_path = "nanwangjinxiao.mp4"

# 打开视频
cap = cv2.VideoCapture(video_path)

while cap.isOpened():
    # 获取图像
    res, frame = cap.read()
    # 如果读取成功
    if res:
        # 正向推理
        results = model(frame)

        # 绘制结果
        annotated_frame = results[0].plot()

        # 显示图像
        cv2.imshow(winname="YOLOV8", mat=annotated_frame)

        # 按ESC退出
        if cv2.waitKey(1) == 27:
            break

    else:
        break

# 释放链接
cap.release()
# 销毁所有窗口
cv2.destroyAllWindows() 

三,实时摄像头检测

这里默认打开的是你电脑本地摄像头(编号0)

import cv2

from ultralytics import YOLO

# 加载模型
model = YOLO(model="yolov8n.pt")

# 摄像头编号
camera_no = 0

# 打开摄像头
cap = cv2.VideoCapture(camera_no)

while cap.isOpened():
    # 获取图像
    res, frame = cap.read()
    # 如果读取成功
    if res:
        # 正向推理
        results = model(frame)

        # 绘制结果
        annotated_frame = results[0].plot()

        # 显示图像
        CV2.imshow(winname="YOLOV8", mat=annotated_frame)

        # 按ESC退出
        if CV2.waitKey(1) == 27:
            break

    else:
        break

# 释放链接
cap.release()
# 销毁所有窗口
cv2.destroyAllWindows() 
  • 10
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 你好,以下是 YOLOv8 实时检测推理 Python 代码的示例: ``` import cv2 import numpy as np # Load YOLOv8 model net = cv2.dnn.readNet("yolov8.weights", "yolov8.cfg") # Load input image img = cv2.imread("input.jpg") # Resize image to input size of the model img = cv2.resize(img, (416, 416)) # Create a blob from the image blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False) # Feed the blob to the model net.setInput(blob) # Get the output layer names of the model layer_names = net.getLayerNames() layer_names = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] # Perform forward pass to get detections detections = net.forward(layer_names) # Get the detections from the output detections = np.squeeze(detections) # Get the class IDs and confidences for each detection class_ids, confidences, boxes = [], [], [] for detection in detections: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: center_x, center_y, w, h = (detection[0:4] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])).astype('int') x, y = int(center_x - w / 2), int(center_y - h / 2) boxes.append([x, y, int(w), int(h)]) confidences.append(float(confidence)) class_ids.append(class_id) # Perform non-maximum suppression to get the final detections indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Draw the detections on the image for i in indices: i = i[0] box = boxes[i] x, y, w, h = box[0], box[1], box[2], box[3] cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # Display the image cv2.imshow("detections", img) cv2.waitKey() cv2.destroyAllWindows() ``` 希望这对你有帮助。 ### 回答2: YOLOv8是一个实时目标检测算法,它是YOLO(You Only Look Once)系列的最新版本。下面是一个示例的Python代码,用于进行YOLOv8实时检测推理: ```python import cv2 import torch from torchvision import transforms 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 # 加载模型 weights = 'yolov5s.pt' # 替换为YOLOv8的权重文件路径 device = select_device('') model = attempt_load(weights, map_location=device) stride = int(model.stride.max()) # 计算特征提取步长 # 准备图像 img_size = 640 # 设置输入图像的大小 transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 设置阈值和类别 conf_thres = 0.3 # 检测置信度阈值 iou_thres = 0.5 # 非最大值抑制的IOU阈值 names = model.module.names if hasattr(model, 'module') else model.names # 开启实时摄像头 cap = cv2.VideoCapture(0) while cap.isOpened(): success, frame = cap.read() if not success: break # 图像预处理 img = transform(frame).unsqueeze(0).to(device) img /= 255.0 # 像素值归一化到[0, 1] if img.ndimension() == 3: img = img.unsqueeze(0) # 检测推理 pred = model(img)[0] pred = non_max_suppression(pred, conf_thres, iou_thres)[0] pred = scale_coords(img_size, pred[:, :4], frame.shape).round() # 绘制边界框和标签 for x1, y1, x2, y2, conf, cls in pred: cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2) cv2.putText(frame, f'{names[int(cls)]} {conf:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2) # 展示结果 cv2.imshow('YOLOv8 - Real-time Object Detection', frame) if cv2.waitKey(1) == 27: break # 释放资源 cap.release() cv2.destroyAllWindows() ``` 这段代码使用了OpenCV和PyTorch,首先加载YOLOv8模型的权重文件,然后设置输入图像的大小和预处理方式。接下来,通过调用摄像头获取实时图像,并将其进行预处理。然后通过模型进行推理,获得目标检测结果。最后,将检测结果绘制在原始图像上,并实时展示在窗口中。用户可以按下ESC键停止检测。 注意,这段代码仅提供了一个基本的框架,可能需要根据具体情况进行适当的调整和优化。 ### 回答3: YOLOv8是一种实时目标检测算法,它在Python中有相应的推理代码YOLOv8推理代码可以用来将模型训练所得的权重文件加载到内存中,并使用这些权重来进行实时目标检测。 在Python中,我们首先需要安装相应的库和依赖项,如PyTorch、OpenCV等。安装完成后,我们可以编写推理代码推理代码的第一步是加载YOLOv8模型权重文件。通过调用PyTorch提供的相关函数,我们可以将预训练好的权重文件加载到内存中。 接下来,我们需要定义模型的输入和输出。对于YOLOv8,输入是一张图像,输出是检测到的目标的边界框和类别信息。 在推理过程中,我们将输入图像传递给模型模型将返回一组预测框。然后,我们可以根据预测框的置信度和类别信息进行筛选和筛除,以得到最终的检测结果。 为了实现实时检测,我们可以将推理过程放入一个循环中。在每一次循环中,我们读取一帧图像,并将其传递给模型进行检测。然后,我们可以将检测结果可视化或保存下来。 需要注意的是,YOLOv8推理代码需要在具备足够计算资源的机器上运行,因为它需要高性能的GPU来实现实时检测。 总之,YOLOv8实时检测推理Python代码包括加载权重文件、定义输入输出、进行推理过程,以及在循环中实现实时检测。这些代码可以帮助我们实现基于YOLOv8的目标检测应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TUSTer_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值