如何加载自定义 yolo v-7 训练模型

pav*_*van 4 python object-detection yolo yolov5 yolov4

如何加载自定义 yolo v-7 模型。

这就是我知道如何加载 yolo v-5 模型的方法:

model = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5/runs/train/exp15/weights/last.pt', force_reload=True)
Run Code Online (Sandbox Code Playgroud)

我在网上看到视频,他们建议使用这个:

!python detect.py --weights runs/train/yolov7x-custom/weights/best.pt --conf 0.5 --img-size 640 --source final_test_v1.mp4 
Run Code Online (Sandbox Code Playgroud)

但我希望它像普通模型一样加载,并给我它找到对象的边界框坐标。

这就是我在 yolo v-5 中的做法:

from models.experimental import attempt_load
yolov5_weight_file = r'weights/rider_helmet_number_medium.pt' # ... may need full path
model = attempt_load(yolov5_weight_file, map_location=device)

def object_detection(frame):
    img = torch.from_numpy(frame)
    img = img.permute(2, 0, 1).float().to(device)  #convert to required shape based on index
    img /= 255.0  
    if img.ndimension() == 3:
        img = img.unsqueeze(0)

    pred = model(img, augment=False)[0]
    pred = non_max_suppression(pred, conf_set, 0.20) # prediction, conf, iou
    # print(pred)
    detection_result = []
    for i, det in enumerate(pred):
        if len(det): 
            for d in det: # d = (x1, y1, x2, y2, conf, cls)
                x1 = int(d[0].item())
                y1 = int(d[1].item())
                x2 = int(d[2].item())
                y2 = int(d[3].item())
                conf = round(d[4].item(), 2)
                c = int(d[5].item())
                
                detected_name = names[c]

                # print(f'Detected: {detected_name} conf: {conf}  bbox: x1:{x1}    y1:{y1}    x2:{x2}    y2:{y2}')
                detection_result.append([x1, y1, x2, y2, conf, c])
                
                frame = cv2.rectangle(frame, (x1, y1), (x2, y2), (255,0,0), 1) # box
                if c!=1: # if it is not head bbox, then write use putText
                    frame = cv2.putText(frame, f'{names[c]} {str(conf)}', (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255), 1, cv2.LINE_AA)

    return (frame, detection_result)
Run Code Online (Sandbox Code Playgroud)

Tla*_*-ES 5

您可以通过以下方式做到这一点:

import torch

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
path = '/path/to/your/file.pt'
model = torch.hub.load("WongKinYiu/yolov7","custom",f"{path}",trust_repo=True)
Run Code Online (Sandbox Code Playgroud)

要获得结果,您可以运行

results = model("/path/to/your/photo")
Run Code Online (Sandbox Code Playgroud)

要获取 bbox,您可以使用:

results.pandas().xyxy
Run Code Online (Sandbox Code Playgroud)

编辑

我使用 python 包创建了一个存储库,以便轻松实现此目的

https://github.com/Tlaloc-Es/aipose