如何从Python程序调用YOLOv7的detect检测方法(替代CLI脚本)
在Python程序中直接调用YOLO目标检测方法(替代CLI脚本)
以下针对主流的YOLOv5和YOLOv8框架,给出直接在Python代码中调用检测逻辑、传入指定参数的实现方案:
一、YOLOv5 实现方式
需要基于YOLOv5的源码模块进行调用,确保你已克隆YOLOv5仓库并安装好依赖:
import torch import sys # 如果你的脚本不在YOLOv5根目录,添加路径 sys.path.append("path/to/yolov5") from models.experimental import attempt_load from utils.general import non_max_suppression, scale_coords from utils.datasets import LoadImages # 自定义参数配置 weights = "path/to/your/custom_trained_model.pt" # 自定义训练模型路径 source = "path/to/your/image_or_video_file" # 检测源(图片/视频/摄像头编号如0) conf_thres = 0.5 # 置信度阈值 img_size = 640 # 输入图片尺寸 # 初始化设备与模型 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = attempt_load(weights, map_location=device) # 加载预训练/自定义模型 stride = int(model.stride.max()) # 获取模型步长 # 加载检测数据源 dataset = LoadImages(source, img_size=img_size, stride=stride) # 执行检测循环 for path, img, im0s, vid_cap in dataset: # 预处理输入图片 img = torch.from_numpy(img).to(device) img = img.float() / 255.0 # 归一化至0-1范围 if img.ndimension() == 3: img = img.unsqueeze(0) # 添加batch维度 # 模型推理 pred = model(img, augment=False)[0] # 非极大值抑制(NMS)过滤冗余检测框 pred = non_max_suppression(pred, conf_thres, 0.45, classes=None, agnostic=False) # 处理并输出检测结果 for i, det in enumerate(pred): if len(det): # 将检测框坐标缩放回原图尺寸 det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0s.shape).round() # 遍历每个检测结果 for *xyxy, conf, cls in reversed(det): class_name = model.names[int(cls)] print(f"检测目标: {class_name}, 置信度: {conf:.2f}, 坐标: {xyxy}") # 如需可视化,可调用utils.plots.plot_one_box绘制检测框
二、YOLOv8 实现方式
YOLOv8官方提供了更简洁的API封装,直接通过ultralytics库调用即可:
from ultralytics import YOLO # 自定义参数配置 weights = "path/to/your/custom_trained_model.pt" source = "path/to/your/image_or_video_file" conf_thres = 0.5 img_size = 640 # 加载自定义模型 model = YOLO(weights) # 执行检测并传入参数 results = model.predict( source=source, conf=conf_thres, imgsz=img_size, # 可选参数:save=True(保存检测结果)、show=True(实时显示画面)等 ) # 解析检测结果 for result in results: boxes = result.boxes # 获取所有检测框对象 for box in boxes: cls_idx = int(box.cls[0].item()) confidence = box.conf[0].item() coords = box.xyxy[0].tolist() # 坐标格式:[x1, y1, x2, y2] class_name = result.names[cls_idx] print(f"检测目标: {class_name}, 置信度: {confidence:.2f}, 坐标: {coords}")
注意事项
- 确保环境依赖正确:YOLOv5需克隆仓库并安装
requirements.txt,YOLOv8可直接通过pip install ultralytics安装。 - 路径参数需填写绝对路径或相对于当前脚本的相对路径,避免因路径错误导致加载失败。
- 若使用GPU加速,需确保已安装对应版本的CUDA和PyTorch。
内容的提问来源于stack exchange,提问作者Saumya Gupta
相关产品推荐
相关产品推荐

