上下左右翻转照片以及标注信息扩充数据集

目录

前言:

示例项目数据结构:

源代码:

运行代码后生成的项目结构:

效果:


前言:

使用yolo训练模型时,遇到数据集很小的情况(一两百张),训练出来的模型效果不好,可以选择扩充数据集重新训练,这篇文章提供将照片左右翻转,上下翻转,以及将标注信息进行对应的翻转,这里的标注信息是yolo五列格式的:

分别代表:类别、归一化的中心点的x坐标、归一化的中心点的y坐标、归一化的目标狂的宽、归一化的目标框的高

示例项目数据结构:

源代码:
from PIL import Image
import os

root_dir = 'D:\python\PycharmProjects\photo-deal\\transpose-image\data'
images_dir = "images"
labels_dir = "labels"
for file in os.listdir(os.path.join(root_dir, images_dir)):
    name, ext = os.path.splitext(file)
    image = Image.open(os.path.join(root_dir, images_dir, file))
    # 获取图像的长和宽
    width, height = image.size
    image.transpose(Image.FLIP_TOP_BOTTOM).save(os.path.join(root_dir, images_dir, name + '_tb' + ext))  # 上下翻转
    # 读取对应的txt
    tbtext_list = []
    with open(os.path.join(root_dir, labels_dir, name + '.txt'), "r") as annofile:
        for line in annofile:
            line = line.strip()
            rects = line.split(" ")
            tbtext_list.append(
                rects[0] + " " + rects[1] + " " + "{:.6f}".format((1.0 - float(rects[2]))) + " " + rects[3] + " " +
                rects[4])
    with open(os.path.join(root_dir, labels_dir, name + '_tb.txt'), 'a') as classify_annofile:
        for item in tbtext_list:
            classify_annofile.write(item + "\n")  # 写入内容并换行
    # 翻转图像并保存
    image.transpose(Image.FLIP_LEFT_RIGHT).save(os.path.join(root_dir, images_dir, name + '_lr' + ext))  # 左右翻转
    # 翻转txt文件
    # 读取对应的txt
    text_list = []
    with open(os.path.join(root_dir, labels_dir, name + '.txt'), "r") as annofile:
        for line in annofile:
            line = line.strip()
            rects = line.split(" ")
            text_list.append(
                rects[0] + " " + "{:.6f}".format((1.0 - float(rects[1]))) + " " + rects[2] + " " + rects[3] + " " +
                rects[4])
    with open(os.path.join(root_dir, labels_dir, name + '_lr.txt'), 'a') as classify_annofile:
        for item in text_list:
            classify_annofile.write(item + "\n")  # 写入内容并换行
    print(file + "图像已处理")
运行代码后生成的项目结构:

效果:

原图:

翻转后:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值