#665·yolov9

detect.py crops only 1 objects per class from 1 image

Author: KazuhideMimuraCreated Apr 13, 2026Updated Apr 13, 2026

Hi, it seems that save_crop option can only save image of 1 object from 1 image, because savename is not unique. I'd recommend a correction like bellow.

https://github.com/WongKinYiu/yolov9/blob/main/detect.py#L123

if len(det):
    # Rescale boxes from img_size to im0 size
    det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

    # Print results
    for c in det[:, 5].unique():
        n = (det[:, 5] == c).sum()  # detections per class
        s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

    # Write results

    cnt_object = 0 # <-- added
    
    for *xyxy, conf, cls in reversed(det):
        if save_txt:  # Write to file
            xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
            with open(f'{txt_path}.txt', 'a') as f:
                f.write(('%g ' * len(line)).rstrip() % line + '\n')

        if save_img or save_crop or view_img:  # Add bbox to image
            c = int(cls)  # integer class
            label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
            annotator.box_label(xyxy, label, color=colors(c, True))
        if save_crop:
            
            save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}_{cnt_object:0=4}.jpg', BGR=True) # <-- modified
            cnt_object += 1 # <-- added