调用yolov3模型进行目标检测

要调用已经训练好的YOLOv3模型对图片进行检测,需要完成以下几个步骤:

  1. 加载预训练模型:从预训练的权重文件中加载模型。
  2. 准备输入图片:将图片转换为模型所需的格式。
  3. 进行推理:使用模型对图片进行推理,得到检测结果。
  4. 处理输出结果:解析模型的输出,得到检测框、类别和置信度。

以下是一个使用PyTorch和OpenCV的示例代码,展示如何调用已经训练好的YOLOv3模型对图片进行检测:

1. 安装必要的库

确保已经安装了以下库:

bash 复制代码
pip install torch torchvision opencv-python

2. 加载预训练模型

假设已经有一个预训练的YOLOv3模型权重文件 yolov3.weights 和对应的配置文件 yolov3.cfg

python 复制代码
import torch
import cv2
import numpy as np

# 加载预训练模型
model = cv2.dnn.readNetFromDarknet("yolov3.cfg", "yolov3.weights")
model.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
model.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

3. 准备输入图片

读取图片并将其转换为模型所需的格式。

python 复制代码
# 读取图片
image = cv2.imread("test.jpg")
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
model.setInput(blob)

4. 进行推理

使用模型对图片进行推理,得到检测结果。

python 复制代码
# 获取输出层的名称
layer_names = model.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in model.getUnconnectedOutLayers()]

# 进行推理
outputs = model.forward(output_layers)

5. 处理输出结果

解析模型的输出,得到检测框、类别和置信度,并绘制检测结果。

python 复制代码
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4

# 解析输出
for output in outputs:
    for detection in output:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > conf_threshold:
            center_x = int(detection[0] * image.shape[1])
            center_y = int(detection[1] * image.shape[0])
            width = int(detection[2] * image.shape[1])
            height = int(detection[3] * image.shape[0])
            left = int(center_x - width / 2)
            top = int(center_y - height / 2)
            class_ids.append(class_id)
            confidences.append(float(confidence))
            boxes.append([left, top, width, height])

# 非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)

# 绘制检测结果
for i in indices:
    i = i[0]
    box = boxes[i]
    left = box[0]
    top = box[1]
    width = box[2]
    height = box[3]
    cv2.rectangle(image, (left, top), (left + width, top + height), (0, 255, 0), 2)
    label = f"{class_ids[i]} {confidences[i]:.2f}"
    cv2.putText(image, label, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

# 显示结果图片
cv2.imshow("Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

相关推荐
刘大大Leo3 小时前
GPT-5.3-Codex 炸了:第一个「自己造自己」的 AI 编程模型,到底意味着什么?
人工智能·gpt
小镇敲码人3 小时前
剖析CANN框架中Samples仓库:从示例到实战的AI开发指南
c++·人工智能·python·华为·acl·cann
摘星编程3 小时前
CANN ops-nn Pooling算子解读:CNN模型下采样与特征提取的核心
人工智能·神经网络·cnn
程序员清洒3 小时前
CANN模型安全:从对抗防御到隐私保护的全栈安全实战
人工智能·深度学习·安全
island13143 小时前
CANN ops-nn 算子库深度解析:神经网络计算引擎的底层架构、硬件映射与融合优化机制
人工智能·神经网络·架构
小白|3 小时前
CANN与实时音视频AI:构建低延迟智能通信系统的全栈实践
人工智能·实时音视频
Kiyra3 小时前
作为后端开发你不得不知的 AI 知识——Prompt(提示词)
人工智能·prompt
艾莉丝努力练剑3 小时前
实时视频流处理:利用ops-cv构建高性能CV应用
人工智能·cann
程序猿追3 小时前
深度解析CANN ops-nn仓库 神经网络算子的性能优化与实践
人工智能·神经网络·性能优化
User_芊芊君子3 小时前
CANN_PTO_ISA虚拟指令集全解析打造跨平台高性能计算的抽象层
人工智能·深度学习·神经网络