You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

YOLOv8检测目标裁剪保存无结果问题排查及修复

YOLOv8目标裁剪无输出问题修复

问题概述

使用自行训练的YOLOv8模型在Google Colab中检测并裁剪目标,代码无报错但未生成裁剪图像。

核心问题分析及修复方案

  1. 路径重复错误
    原代码中root_dir路径存在重复:/content/drive/My Drive/content/drive/MyDrive/Data/out_test,这会导致无法正确读取图像文件。Colab中Google Drive的挂载路径统一为/content/drive/MyDrive/,需修正路径。

  2. 未设置检测置信度阈值
    YOLOv8默认置信度阈值为0.25,但如果模型输出的置信度低于该值,会导致无检测结果,进而不生成裁剪图。显式设置阈值可确保低置信度目标也被检测到。

  3. 未判断检测结果是否为空
    若图像中无检测目标,boxes为空,循环不会执行,也不会输出提示信息,需添加判断逻辑。

修改后的完整代码

from google.colab import drive
drive.mount('/content/drive')

!pip install torch torchvision opencv-python
!pip install ultralytics --quiet

import torch
print(f"CUDA available: {torch.cuda.is_available()}")
import cv2
import numpy as np
import os
from ultralytics import YOLO

# Load your model
model_path = '/content/drive/MyDrive/Data/runs/detect/train7/weights/best.pt' 
model = YOLO(model_path)

# 修正路径:移除重复的挂载路径
root_dir = '/content/drive/MyDrive/Data/out_test'  

# 修正保存路径,统一格式
save_dir = '/content/drive/MyDrive/cropped_images'
os.makedirs(save_dir, exist_ok=True)

def crop_objects(img, results, save_dir, img_name):
    # 获取检测框
    boxes = results[0].boxes.xyxy  
    # 检查是否有检测到目标
    if len(boxes) == 0:
        print(f"No objects detected in {img_name}")
        return []
    
    cropped_images = []
    for i, box in enumerate(boxes):
        x1, y1, x2, y2 = map(int, box[:4])
        # 确保坐标在图像范围内(避免越界)
        x1 = max(0, x1)
        y1 = max(0, y1)
        x2 = min(img.shape[1], x2)
        y2 = min(img.shape[0], y2)
        
        # 裁剪图像
        cropped_img = img[y1:y2, x1:x2]
        cropped_images.append(cropped_img)

        # 保存裁剪后的图像
        output_path = os.path.join(save_dir, f'{img_name}_cropped_{i}.jpg')
        # 检查是否成功保存
        if cv2.imwrite(output_path, cropped_img):
            print(f'Cropped image saved to {output_path}')
        else:
            print(f'Failed to save cropped image to {output_path}')
      
    return cropped_images

# 遍历所有子目录处理图像
for subdir, dirs, files in os.walk(root_dir):
    for file in files:
        img_path = os.path.join(subdir, file)
        if img_path.lower().endswith(('png', 'jpg', 'jpeg')):
            print(f"\nProcessing image: {img_path}")
            img = cv2.imread(img_path)
            if img is None:
                print(f"Could not read image: {img_path}")
                continue
            
            img_name = os.path.splitext(file)[0]
            # 设置置信度阈值,可根据模型调整
            results = model(img, conf=0.25)  
            
            # 调试:打印检测到的目标数量
            print(f"Detected {len(results[0].boxes)} objects in {img_name}")

            crop_objects(img, results, save_dir, img_name)

额外调试建议

  • 运行代码后查看Detected X objects的输出,确认是否有目标被检测到
  • 若仍无输出,可添加results[0].show()查看检测可视化结果,确认模型是否正确识别目标
  • 检查save_dir路径是否正确,可在Colab左侧文件管理器中手动查看该目录

内容的提问来源于stack exchange,提问作者Nguyễn Thành Nam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:21:03