Python调用yolo模型

文章讲述了作者在PyCharm环境下成功运行了调用YOLOv5模型进行图像识别的代码,但在JupyterNotebook中遇到了错误。代码中使用`torch.hub.load`加载了本地自定义模型,并指定了权重文件路径。问题可能在于路径处理或环境配置差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python调用yolo模型

本文在pycharm实验没问题,在juypter notebook会报错。

导入依赖

#导入依赖
import torch

载入本地模型

C:/Users/Qingchen/yolov5为克隆的yolov5的路径,C:/Users/Qingchen/yolov5/best_0523.pt是自己训练模型的weights的路径,可以替换成官方给的weights测试

#载入本地模型
model = torch.hub.load('C:/Users/Qingchen/yolov5', 'custom', 'C:/Users/Qingchen/yolov5/best_0523.pt', source
### 如何在Python中加载并使用YOLO模型进行目标检测 为了实现这一功能,需先安装必要的库,如`opencv-python`和`numpy`。可以通过pip命令完成安装: ```bash pip install opencv-python numpy ``` 加载预训练的YOLO模型涉及几个关键步骤。首先定义模型路径,包括权重文件(weights)和配置文件(cfg)。通过OpenCV的DNN模块读取这些文件来初始化神经网络。 ```python import cv2 # 定义模型路径 weights_path = "yolov3.weights" config_path = "yolov3.cfg" # 使用 OpenCV 的 DNN 模块加载 YOLOv3 模型 net = cv2.dnn.readNetFromDarknet(config_path, weights_path) # 获取未连接层的名字列表 layer_names = net.getLayerNames() output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()] ``` 准备图像数据作为输入给YOLO模型之前,应该调整其大小到适合模型处理的形式,并转换成blob格式以便于传递至网络中。这一步骤对于确保良好的性能至关重要[^1]。 ```python image = cv2.imread('example.jpg') # 替换为实际图片路径 height, width, channels = image.shape # 将图像转化为 blob 形式供后续处理 blob = cv2.dnn.blobFromImage(image, scalefactor=1/255.0, size=(416, 416), swapRB=True, crop=False) net.setInput(blob) outs = net.forward(output_layers) ``` 最后,在获得预测结果后,解析输出以识别物体边界框及其类别标签。此过程可能涉及到非极大值抑制(NMS)算法去除冗余重叠区域提案,从而提高最终检测效果的质量。 ```python class_ids = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # 设置置信度阈值过滤弱检测 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) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indices = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold=0.5, nms_threshold=0.4) if len(indices) > 0: for i in indices.flatten(): (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) color = [int(c) for c in colors[class_ids[i]]] cv2.rectangle(image, (x, y), (x + w, y + h), color, thickness=2) text = f"{classes[class_ids[i]]}: {confidences[i]:.2f}" cv2.putText(image, text, (x, y - 5), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=color, thickness=2) ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一傲

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

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

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

打赏作者

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

抵扣说明:

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

余额充值