【深度学习标注数据处理】imgaug 图像增强库的学习记录

话不多说,先奉上imgaug官网:imgaug — imgaug 0.4.0 documentation

官网的目录,从中可以知道它能够做到的增强范围:

一、imgaug安装

安装依赖库

pip install six numpy scipy matplotlib scikit-image opencv-python imageio

然后,直接在终端进行安装,用anaconda的可以在Prompt进行安装:

pip install imgaug

这里如果不幸,会在一切看似顺利的安装过程中,突然出现一连串的红色错误,如下

G:\python\Pyhton36\Scripts>pip install imgaug
Collecting imgaug
  Downloading https://files.pythonhosted.org/packages/af/fc/c56a7da8c23122b7c5325b941850013880a7a93c21dc95e2b1ecd4750108/imgaug-0.2.7-py3-none-any.whl (644kB)
    100% |████████████████████████████████| 645kB 73kB/s
Requirement already satisfied: scikit-image>=0.11.0 in g:\python\pyhton36\lib\site-packages (from imgaug) (0.14.1)
Collecting imageio (from imgaug)
  Downloading https://files.pythonhosted.org/packages/28/b4/cbb592964dfd71a9de6a5b08f882fd334fb99ae09ddc82081dbb2f718c81/imageio-2.4.1.tar.gz (3.3MB)
    100% |████████████████████████████████| 3.3MB 438kB/s
Collecting Shapely (from imgaug)
  Downloading https://files.pythonhosted.org/packages/a2/fb/7a7af9ef7a35d16fa23b127abee272cfc483ca89029b73e92e93cdf36e6b/Shapely-1.6.4.post2.tar.gz (225kB)
    100% |████████████████████████████████| 235kB 181kB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\34905\AppData\Local\Temp\pip-install-43zide7u\Shapely\setup.py", line 80, in <module>
        from shapely._buildcfg import geos_version_string, geos_version, \
      File "C:\Users\34905\AppData\Local\Temp\pip-install-43zide7u\Shapely\shapely\_buildcfg.py", line 200, in <module>
        lgeos = CDLL("geos_c.dll")
      File "g:\python\pyhton36\lib\ctypes\__init__.py", line 348, in __init__
        self._handle = _dlopen(self._name, mode)
    OSError: [WinError 126] 找不到指定的模块。
 
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\34905\AppData\Local\Temp\pip-install-43zide7u\Shapely\

查阅了网上前辈的资料,需要先安装shapely

通过这个网址 https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely (这是一个非常好的扩展包非正式网址,里面有许多的工具可供使用) 中找到适合自己python版本的shapely下载到指定路径

我是windows,64位操作系统,python3.5,我选择下面这个

然后通过如下命令进行安装:

G:\python\Pyhton36\Scripts>python -m pip install Shapely‑1.6.4.post2‑cp35‑cp35m‑win_amd64.whl

最后再重复之前安装imgaug的命令:

pip install imgaug

搞定,收工,安装完成

参考:Windows10在cmd中用pip安装imgaug的时候报错_LebronChen666的博客-CSDN博客


二、github原代码遇见问题,批量的BoundingBox带XML文件的增强

github原作者地址:GitHub - xinyu-ch/Data-Augment: imgaug--Bounding Boxes augment

存在一丢丢的错误,这里进行了修改,往下看(第三节),已调试,可用,这里讲下遇见的一些小问题

1.如果不幸的遇见了下面的问题,这是一个常见问题,解决方式较为统一:解决UnicodeDecodeError: 'gbk' codec can't decode byte 0xb9 in position x: illegal multibyte sequence_强殖装甲凯普的博客-CSDN博客

解决方式如下:

第一种解决方法,增加encoding=‘UTF-8’

FILE_OBJECT= open( 'train.txt','r', encoding='UTF-8' )

第二种方法,二进制读取

FILE_OBJECT= open( 'train.txt', 'rb' )

之后,就可以看第三节,是对上文作者github部分做了修改后的,调试可用


三、调试后批量的BoundingBox带XML文件的增强(可直接用)

  1. 创建要保存增强后的图像和xml文件的文件夹
  2. 提前设定好采用什么方式进行图像的增强,是旋转,还是加噪声,是提升亮度,还是平移补充
  3. 然后读进来一张图片,和该图像对应的xml内标签的坐标信息
  4. 对图像和矩形框进行变换
  5. 最后保存增强后的图片和xml文件
import xml.etree.ElementTree as ET
import pickle
import os
from os import getcwd
import numpy as np
from PIL import Image
import shutil
import matplotlib.pyplot as plt

import imgaug as ia
from imgaug import augmenters as iaa

ia.seed(1)

def read_xml_annotation(root, image_id):
    in_file = open(os.path.join(root, image_id), encoding='UTF-8')
    tree = ET.parse(in_file)
    root = tree.getroot()
    bndboxlist = []

    for object in root.findall('object'):  # 找到root节点下的所有country节点
        bndbox = object.find('bndbox')  # 子节点下节点rank的值

        xmin = int(bndbox.find('xmin').text)
        xmax = int(bndbox.find('xmax').text)
        ymin = int(bndbox.find('ymin').text)
        ymax = int(bndbox.find('ymax').text)
        # print(xmin,ymin,xmax,ymax)
        bndboxlist.append([xmin, ymin, xmax, ymax])
        # print(bndboxlist)

    # ndbox = root.find('object').find('bndbox')
    return bndboxlist


# (506.0000, 330.0000, 528.0000, 348.0000) -> (520.4747, 381.5080, 540.5596, 398.6603)
def change_xml_annotation(root, image_id, new_target):
    new_xmin = new_target[0]
    new_ymin = new_target[1]
    new_xmax = new_target[2]
    new_ymax = new_target[3]

    in_file = open(os.path.join(root, str(image_id) + '.xml'), encoding='UTF-8' )  # 这里root分别由两个意思
    tree = ET.parse(in_file)
    xmlroot = tree.getroot()
    object = xmlroot.find('object')
    bndbox = object.find('bndbox')
    xmin = bndbox.find('xmin')
    xmin.text = str(new_xmin)
    ymin = bndbox.find('ymin')
    ymin.text = str(new_ymin)
    xmax = bndbox.find('xmax')
    xmax.text = str(new_xmax)
    ymax = bndbox.find('ymax')
    ymax.text = str(new_ymax)
    tree.write(os.path.join(root, str("%06d" % (str(id) + '.xml'))))


def change_xml_list_annotation(root, image_id, new_target, saveroot, id):
    in_file = open(os.path.join(root, str(image_id) + '.xml'), encoding='UTF-8' )  # 这里root分别由两个意思
    tree = ET.parse(in_file)
    elem = tree.find('filename')
    elem.text = (str("%06d" % int(id)) + '.png')
    xmlroot = tree.getroot()
    index = 0

    for object in xmlroot.findall('object'):  # 找到root节点下的所有country节点
        bndbox = object.find('bndbox')  # 子节点下节点rank的值

        # xmin = int(bndbox.find('xmin').text)
        # xmax = int(bndbox.find('xmax').text)
        # ymin = int(bndbox.find('ymin').text)
        # ymax = int(bndbox.find('ymax').text)

        new_xmin = new_target[index][0]
        new_ymin = new_target[index][1]
        new_xmax = new_target[index][2]
        new_ymax = new_target[index][3]

        xmin = bndbox.find('xmin')
        xmin.text = str(new_xmin)
        ymin = bndbox.find('ymin')
        ymin.text = str(new_ymin)
        xmax = bndbox.find('xmax')
        xmax.text = str(new_xmax)
        ymax = bndbox.find('ymax')
        ymax.text = str(new_ymax)

        index += 1

        print("index=",index)


    tree.write(os.path.join(saveroot, str("%06d" % int(id)) + '.xml'))


def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path + ' 目录已存在')
        return False


if __name__ == "__main__":

    IMG_DIR = "F:\\image\\raw_xml"
    XML_DIR = "F:\\image\\xml"

    AUG_XML_DIR = "./Annotations"  # 存储增强后的XML文件夹路径
    try:
        shutil.rmtree(AUG_XML_DIR)
    except FileNotFoundError as e:
        a = 1
    mkdir(AUG_XML_DIR)

    AUG_IMG_DIR = "./JPEGImages"  # 存储增强后的影像文件夹路径
    try:
        shutil.rmtree(AUG_IMG_DIR)
    except FileNotFoundError as e:
        a = 1
    mkdir(AUG_IMG_DIR)

    AUGLOOP = 2  # 每张影像增强的数量

    boxes_img_aug_list = []
    new_bndbox = []
    new_bndbox_list = []

    # 影像增强
    seq = iaa.Sequential([
        iaa.Flipud(0.5),  # vertically flip 20% of all images
        iaa.Fliplr(0.5),  # 镜像
        iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),
        iaa.Crop(px=(0, 16)),
        iaa.Add((-10, 10), per_channel=0.5),
        iaa.Multiply((1.2, 1.5)),  # change brightness, doesn't affect BBs
        iaa.Affine(
            translate_px={"x": 15, "y": 15},
            scale=(0.8, 0.95)
            #rotate=(-30, 30)
        )  # translate by 40/60px on x/y axis, and scale to 50-70%, affects BBs
    ])

    for root, sub_folders, files in os.walk(XML_DIR):

        for name in files:

            bndbox = read_xml_annotation(XML_DIR, name)
            shutil.copy(os.path.join(XML_DIR, name), AUG_XML_DIR)
            shutil.copy(os.path.join(IMG_DIR, name[:-4] + '.png'), AUG_IMG_DIR)
            print(os.path.join(IMG_DIR, name[:-4] + '.png'))

            for epoch in range(AUGLOOP):
                seq_det = seq.to_deterministic()  # 保持坐标和图像同步改变,而不是随机
                # 读取图片
                img = Image.open(os.path.join(IMG_DIR, name[:-4] + '.png'))
                # sp = img.size
                img = np.asarray(img)
                # bndbox 坐标增强
                for i in range(len(bndbox)):
                    bbs = ia.BoundingBoxesOnImage([
                        ia.BoundingBox(x1=bndbox[i][0], y1=bndbox[i][1], x2=bndbox[i][2], y2=bndbox[i][3]),
                    ], shape=img.shape)

                    bbs_aug = seq_det.augment_bounding_boxes([bbs])[0]
                    boxes_img_aug_list.append(bbs_aug)

                    # new_bndbox_list:[[x1,y1,x2,y2],...[],[]]
                    n_x1 = int(max(1, min(img.shape[1], bbs_aug.bounding_boxes[0].x1)))
                    n_y1 = int(max(1, min(img.shape[0], bbs_aug.bounding_boxes[0].y1)))
                    n_x2 = int(max(1, min(img.shape[1], bbs_aug.bounding_boxes[0].x2)))
                    n_y2 = int(max(1, min(img.shape[0], bbs_aug.bounding_boxes[0].y2)))
                    if n_x1 == 1 and n_x1 == n_x2:
                        n_x2 += 1
                    if n_y1 == 1 and n_y2 == n_y1:
                        n_y2 += 1
                    if n_x1 >= n_x2 or n_y1 >= n_y2:
                        print('error', name)
                    new_bndbox_list.append([n_x1, n_y1, n_x2, n_y2])

                    # 存储变化后的图片
                    image_aug = seq_det.augment_images([img])[0]
                    path = os.path.join(AUG_IMG_DIR,str("%06d" % (len(files) + int(name[:-4]) + epoch * 250)) + '.png')

                    image_auged = bbs.draw_on_image(image_aug, thickness=0)####################################

                    Image.fromarray(image_auged).save(path)

                # 存储变化后的XML
                change_xml_list_annotation(XML_DIR, name[:-4], new_bndbox_list, AUG_XML_DIR,len(files) + int(name[:-4]) + epoch * 250)
                print(str("%06d" % (len(files) + int(name[:-4]) + epoch * 250)) + '.png')
                new_bndbox_list = []

 代码中写死了对数据的读取方式:elem.text = (str("%06d" % int(id)) + '.png')

如果没必要,就按下面这种形式进行命名

增强后,用labelImg查看的结果如下:

详细部分参考这里:使用imgaug--python图像数据增强库进行Bounding Boxes影像增强_MagicMicky的博客-CSDN博客使用imgaug图像数据增强库进行Bounding Boxes影像增强简介imgaug安装Bounding Boxes实现读取原影像bounding boxes坐标生成变换后的bounding boxe坐标文件生成变换序列bounding box 变化后坐标计算使用示例数据准备设置文件路径设置增强次数设置增强参数输出简介相较于Augmentor,imgaug具有更多的功能,比如对影像增强的同时...https://blog.csdn.net/coooo0l/article/details/84492916#commentsedit

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钱多多先森

你的鼓励,是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值