YOLO v11的学习记录(六) 把标注好的大图切割成小图

有一个工程,从相机获取到训练图的尺寸是4096*3072像素,图上有很多密集的小目标,用anylabeling进行标注后,送进YOLO训练时出了问题,由于电脑显存不大,如果用原图尺寸训练,即使很小的batch_size,也会显存溢出,如果用YOLO默认的imgsz=640,则由于缩小倍数过大,小目标被过度压缩,造成学习效果不佳。解决问题的办法是将大图裁切成小图(640*640)后再训练,下面的脚本实现了这个目的,并且在裁切图片的同时将已经标注好的数据随图片裁切。

python 复制代码
import copy
import json

import cv2
import os
from pathlib import Path


# 将图像尺寸调整为640的倍数
def split_image_into_blocks(image_path, output_dir, block_width=640, block_height=640):
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    # 读取图片
    image = cv2.imread(image_path)
    if image is None:
        raise ValueError(f"无法读取图片: {image_path}")
    # 调整图片尺寸
    height, width = image.shape[:2]
    _, b = divmod(width, block_width)
    w_out = width + block_width - b  # 调整为640的倍数
    _, b = divmod(height, block_height)
    h_out = height + block_height - b   # 调整为640的倍数
    img = cv2.resize(image, (w_out, h_out), interpolation=cv2.INTER_CUBIC)
    # 放大比例
    w_scale = w_out / width
    h_scale = h_out / height


    # 获取同名json文件
    file_name = Path(image_path).stem
    with open(file_name + '.json', encoding="utf-8") as f:
        json_data = json.load(f)  # 同名图片文件的json数据

    # 获取图片尺寸
    height, width = img.shape[:2]
    print(f"调整后的大图片尺寸: 宽{width} x 高{height}")
    print(f"分割块尺寸: 宽{block_width} x 高{block_height}")

    # 计算可以分割的块数(按完整块计算)
    num_blocks_width = width // block_width
    num_blocks_height = height // block_height

    print(f"将分割为 {num_blocks_width}x{num_blocks_height} 个图片块")

    # 分割并保存块
    block_count = 0
    for i in range(num_blocks_height):
        for j in range(num_blocks_width):
            # 计算当前块的坐标(左上角开始)
            start_x = j * block_width
            start_y = i * block_height
            end_x = start_x + block_width
            end_y = start_y + block_height

            # 提取图片块
            block = img[start_y:end_y, start_x:end_x]

            # 保存图片块(文件名包含行列信息)
            block_filename = os.path.join(
                output_dir,
                f"{file_name}_row{i}_col{j}_index{block_count}.jpg"
            )
            json_filename = os.path.join(
                output_dir,
                f"{file_name}_row{i}_col{j}_index{block_count}.json"
            )

            cv2.imwrite(block_filename, block)
            # 更新json文件
            data= copy.deepcopy(json_data)
            for shape in data['shapes']:
                points  = []
                for point in shape['points']:
                    w = round(point[0] * w_scale, 0) - start_x  # 坐标按照小块的0点重新定位
                    h = round(point[1] * h_scale, 0) - start_y
                    if 0 <= w <= block_width and 0 <= h <= block_height:  # 如果坐标在小块内,则添加到points中
                        points.append([w, h])
                # 如果points的长度大于20,则保留,否则删除
                if len(points) > 20:
                    shape['points'] = points
                else:
                    shape['points'] = []

            data['shapes'] = [item for item in data['shapes'] if item['points'] != []]   # 删除points为空的形状
            data['imagePath'] = f"{file_name}_row{i}_col{j}_index{block_count}.jpg"   # 更新图片路径
            data['imageHeight'] = block_height   # 更新图片高度
            data['imageWidth'] = block_width    # 更新图片宽度
            # 更新json文件
            with open(json_filename, 'w', encoding="utf-8") as f:
                json.dump(data, f)
            block_count += 1

    print(f"分割完成,共生成 {block_count} 个块")



if __name__ == "__main__":
    # 替换为你的图片路径
    input_image_path = "img00002.jpg"

    split_image_into_blocks(
        image_path=input_image_path, output_dir='custom_blocks')

标注好的大图(4096*3072像素):

裁切得到的其中一张小图(640*640像素):

相关推荐
汗流浃背了吧,老弟!5 小时前
BPE 词表构建与编解码(英雄联盟-托儿索语料)
人工智能·深度学习
小瑞瑞acd6 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
学习3人组6 小时前
YOLO模型集成到Label Studio的MODEL服务
yolo
芷栀夏6 小时前
CANN ops-math:揭秘异构计算架构下数学算子的低延迟高吞吐优化逻辑
人工智能·深度学习·神经网络·cann
孤狼warrior6 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
机器学习之心7 小时前
TCN-Transformer-BiGRU组合模型回归+SHAP分析+新数据预测+多输出!深度学习可解释分析
深度学习·回归·transformer·shap分析
野犬寒鸦7 小时前
从零起步学习并发编程 || 第七章:ThreadLocal深层解析及常见问题解决方案
java·服务器·开发语言·jvm·后端·学习
LLWZAI7 小时前
让朱雀AI检测无法判断的AI公众号文章,当创作者开始与算法「躲猫猫」
大数据·人工智能·深度学习
陈桴浮海7 小时前
【Linux&Ansible】学习笔记合集二
linux·学习·ansible
xhbaitxl7 小时前
算法学习day39-动态规划
学习·算法·动态规划