怎么让yolov5预测的框进行截取下来保存(附完整detect.py代码,对自己的数据集修改路径即可)

1.修改detect.py的代码

在detect.py中添加剪切代码

if save_crop:
    #未修改代码
    #save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
    if save_crop:
        # Save cropped image
        save_crop_dir = save_dir / "crops" / names[c]
        save_crop_dir.mkdir(parents=True, exist_ok=True)
        save_one_box(xyxy, imc, file=save_crop_dir / f"{p.stem}_{i}.jpg", BGR=True)
        LOGGER.info(f"Saved crop to {save_crop_dir / f'{p.stem}_{i}.jpg'}")

完整的存放结果结果代码图片如下,可以直接进行搜索(ctrl+f)(for *xyxy, conf, cls in reversed(det))然后进行替换这个代码

# Write results
for *xyxy, conf, cls in reversed(det):
    c = int(cls)  # integer class
    label = names[c] if hide_conf else f"{names[c]}"
    confidence = float(conf)
    confidence_str = f"{confidence:.2f}"

    if save_csv:
        write_to_csv(p.name, label, confidence_str)

    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}.jpg", BGR=True)
        if save_crop:
            # Save cropped image
            save_crop_dir = save_dir / "crops" / names[c]
            save_crop_dir.mkdir(parents=True, exist_ok=True)
            save_one_box(xyxy, imc, file=save_crop_dir / f"{p.stem}_{i}.jpg", BGR=True)
            LOGGER.info(f"Saved crop to {save_crop_dir / f'{p.stem}_{i}.jpg'}")

2.在Pycharm的命令端中进行指定运行

(注意:要切换到yolov5-master的路径之下运行)

image-20240607140415438

python detect.py --source ./Maskdata/val/images/ --weights ./runs/train/exp43/weights/best.pt --save-crop

3.展示结果

image-20240607140853679

image-20240607140903949

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值