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的路径之下运行)
python detect.py --source ./Maskdata/val/images/ --weights ./runs/train/exp43/weights/best.pt --save-crop