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

YOLOv5检测后提取xyxy坐标裁剪图像但无法保存,求错误排查

YOLOv5裁剪图像无法保存的问题排查

你代码里有几个关键错误导致无法正常保存裁剪后的图像,逐一说明:

错误点分析

  • 归一化坐标未转换:result.xyxyn返回的是0-1之间的归一化坐标,直接转成int会得到0或1,裁剪出来的图像要么是空数组,要么只有1x1像素,根本无法正常保存。必须乘以图像的实际宽高才能得到正确的像素坐标。
  • 保存参数错误:cv2.imwrite要求传入单张图像的numpy数组,但你传的是cropped_images这个列表,而且每次循环都写同一个文件名,不仅参数类型不对,还会导致多次覆盖。
  • 冗余的图像类型转换:cv2.imread读取的图像本身就是uint8类型,循环里每次执行image2 = image.astype(np.uint8)完全没必要,属于多余操作。

修正后的代码

import cv2
import numpy as np
import torch
import os

# Load the trained model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='C:/Users/ASUS/Desktop/yolov5-fastapi-main/model/best.pt', force_reload=True) 

def detect_logo(image):
    result = model(image)
    # 获取图像宽高,用于转换归一化坐标
    img_h, img_w = image.shape[:2]
    labels, cord_thres = result.xyxyn[0][:, -1].numpy(), result.xyxyn[0][:, :-1].numpy()
    cropped_images = []
    
    for i, box in enumerate(cord_thres):
        # 将归一化坐标转换为实际像素坐标
        x_min = int(box[0] * img_w)
        y_min = int(box[1] * img_h)
        x_max = int(box[2] * img_w)
        y_max = int(box[3] * img_h)
        
        # 裁剪图像(确保坐标不越界,可选但建议加上)
        x_min = max(0, x_min)
        y_min = max(0, y_min)
        x_max = min(img_w, x_max)
        y_max = min(img_h, y_max)
        
        cropped_image = image[y_min:y_max, x_min:x_max]
        cropped_images.append(cropped_image)
        
        # 保存单张裁剪图,用索引区分文件名避免覆盖
        cv2.imwrite(f"cropped_image_{i}.jpg", cropped_image) 

    return cropped_images

# Read the image
image = cv2.imread("C:/Users/ASUS/Desktop/yolov5-fastapi-main/aetna_003.png")
# 检查图像是否成功读取
if image is None:
    print("Error: 无法读取图像,请检查路径是否正确")
else:
    cropped_images = detect_logo(image)

额外说明

  • 加入了坐标越界检查,避免因归一化计算误差导致裁剪区域超出图像范围的问题。
  • 用循环索引i命名保存的文件,避免多张裁剪图互相覆盖。
  • 增加了图像读取失败的判断,方便排查路径错误。

内容的提问来源于stack exchange,提问作者Sefa Kocaman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:35:34