目录
- 简介
- 安装
- Overview
- 特效
- Project 结构
- 程序
- 参考的源代码(来源于网络)
- 简易变换 试效果
- 使用 模糊光雨雪雾
- else
- 重命名00001.jpg
- 重命名1.jpg
- 效果图
简介
imgaug:机器学习实验中的图像增强库,特别是卷积神经网络。支持以多种不同方式增强图像、关键点/地标、边界框、热图和分割图。
安装
在anaconda prompt里进行
pip install imgaug
看了几篇文章,出错的话可以先安装依赖库shapely
Overview
特效
Project 结构
程序
图片放入input
参考的源代码(来源于网络)
main.py
# ###################源代码####################
# !usr/bin/python
# -*- coding: utf- -*-
import cv
from imgaug import augmenters as iaa
import os
# Sometimes(.5, ...) 所有情况的 50% 中应用给定的增强器
# e.g. Sometimes(.5, GaussianBlur(0.3)) would blur roughly every second image.
sometimes = lambda aug: iaa.Sometimes(.5, aug)
# 定义一组变换方法.
seq = iaa.Sequential([
# 选择到5种方法做变换
iaa.SomeOf((, 5),
[
iaa.Fliplr(.5), # 对50%的图片进行水平镜像翻转
iaa.Flipud(.5), # 对50%的图片进行垂直镜像翻转
# superpixel representation 将一些图像转换为它们的超像素表示,每张图像采样 到 200 个超像素,但不要用它们的平均值替换所有超像素,只替换其中的一些(p_replace)。
sometimes(
iaa.Superpixels(
p_replace=(, 1.0),
n_segments=(, 200)
)
),
# Blur each image with varying strength using
# gaussian blur (sigma between and 3.0),
# average/uniform blur (kernel size betweenx2 and 7x7)
# median blur (kernel size betweenx3 and 11x11).
iaa.OneOf([
iaa.GaussianBlur((, 3.0)),
iaa.AverageBlur(k=(, 7)),
iaa.MedianBlur(k=(, 11)),
]),
# Sharpen each image, overlay the result with the original
# image using an alpha between (no sharpening) and 1
# (full sharpening effect).
iaa.Sharpen(alpha=(, 1.0), lightness=(0.75, 1.5)),
# Same as sharpen, but for an embossing effect.
iaa.Emboss(alpha=(, 1.0), strength=(0, 2.0)),
# Add gaussian noise to some images.
# In% of these cases, the noise is randomly sampled per
# channel and pixel.
# In the other% of all cases it is sampled once per
# pixel (i.e. brightness change).
iaa.AdditiveGaussianNoise(
loc=, scale=(0.0, 0.05 * 255)
),
# Invert each image's chanell with% probability.
# This sets each pixel value v to-v.
iaa.Invert(.05, per_channel=True), # invert color channels
# Add a value of - to 10 to each pixel.
iaa.Add((-, 10), per_channel=0.5),
# Add random values between - and 40 to images, with each value being sampled per pixel:
iaa.AddElementwise((-, 40)),
# Change brightness of images (-150% of original value).
iaa.Multiply((.5, 1.5)),
# Multiply each pixel with a random value between.5 and 1.5.
iaa.MultiplyElementwise((.5, 1.5)),
# Improve or worsen the contrast of images.
iaa.ContrastNormalization((.5, 2.0)),
iaa.imgcorruptlike.Saturate(severity=),
],
# do all of the above augmentations in random order
random_order=True
)
], random_order=True) # apply augmenters in random order
# 图片文件相关路径
path = './input/'
savedpath = './output/'
imglist = []
filelist = os.listdir(path)
# 遍历要增强的文件夹,把所有的图片保存在imglist中
for item in filelist:
img = cv.imread(path + item)
# print('item is ',item)
# print('img is ',img)
# images = load_batch(batch_idx)
imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')
# 对文件夹中的图片进行增强操作,循环次
for count in range():
images_aug = seq.augment_images(imglist)
for index in range(len(images_aug)):
filename = str(count) + str(index) + '.jpg'
# 保存图片
cv.imwrite(savedpath + filename, images_aug[index])
print('image of count%s index%s has been writen' % (count, index))
简易变换 试效果
test01.py
# ##############简易变换#################
# https://imgaug.readthedocs.io/en/latest/source/overview_of_augmenters.html
import cv
from imgaug import augmenters as iaa
import os
# Sometimes(.5, ...) applies the given augmenter in 50% of all cases,
# e.g. Sometimes(.5, GaussianBlur(0.3)) would blur roughly every second image.
# sometimes = lambda aug: iaa.Sometimes(.5, aug)
# 定义一组变换方法.
seq = iaa.Sequential([
iaa.MotionBlur(k=), # 运动模糊
# iaa.Clouds(), # 云雾
# iaa.imgcorruptlike.Fog(severity=), # 多雾/霜
# iaa.imgcorruptlike.Snow(severity=), # 下雨、大雪
# iaa.Rain(drop_size=(.10, 0.20), speed=(0.2, 0.3)), # 雨
# iaa.Rain(speed=(.3, 0.5)), # 雨
# iaa.Snowflakes(flake_size=(.6, 0.7), speed=(0.02, 0.03)), # 雪点
# iaa.imgcorruptlike.Spatter(severity=), # 溅 123水滴、45泥
# iaa.contrast.LinearContrast((.5, 2.0), per_channel=0.5),# 对比度变为原来的一半或者二倍
# iaa.imgcorruptlike.Brightness(severity=), # 亮度增加
# iaa.imgcorruptlike.Saturate(severity=), # 色彩饱和度
# iaa.FastSnowyLandscape(lightness_threshold=(, 255),lightness_multiplier=(1.5, 2.0)), # 雪地 亮度阈值是从 uniform(100, 255)(每张图像)和来自 uniform(1.5, 2.0)(每张图像)的乘数采样的。
# iaa.Cartoon(blur_ksize=, segmentation_size=1.0, saturation=2.0, edge_prevalence=1.0), # 卡通
])
# 图片文件相关路径
path = './input/'
savedpath = './output_show/'
imglist = []
filelist = os.listdir(path)
# 遍历要增强的文件夹,把所有的图片保存在imglist中
for item in filelist:
img = cv.imread(path + item)
# print('item is ',item)
# print('img is ',img)
# images = load_batch(batch_idx)
imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')
# 对文件夹中的图片进行增强操作,循环次
for count in range():
images_aug = seq.augment_images(imglist)
for index in range(len(images_aug)):
# filename = str(count) + str(index) + '.jpg'
# 保存图片
filename = str(filelist[index])
cv.imwrite(savedpath + filename, images_aug[index])
print('image of count%s index%s has been writen' % (count, index))
使用 模糊光雨雪雾
运动模糊+雨雪雾天气 2-3种
&
对比度 亮度 饱和度 选其一
my_augmentation.py
import cv
from imgaug import augmenters as iaa
import os
# sometimes = lambda aug: iaa.Sometimes(.5, aug) # 所有情况的 50% 中应用给定的增强器
seq = iaa.Sequential([
# 选择到3种方法做变换
iaa.SomeOf((, 3),
[
iaa.imgcorruptlike.MotionBlur(severity=(, 2)), # 运动模糊
# iaa.Clouds(), # 云雾
iaa.imgcorruptlike.Fog(severity=), # 多雾/霜
# iaa.imgcorruptlike.Snow(severity=), # 下雨、大雪
iaa.Rain(drop_size=(.10, 0.15), speed=(0.1, 0.2)), # 雨
iaa.Snowflakes(flake_size=(.1, 0.4), speed=(0.01, 0.03)), # 雪点
# iaa.FastSnowyLandscape(lightness_threshold=(, 255),lightness_multiplier=(1.5, 2.0)), # 雪地 亮度阈值是从 uniform(100, 255)(每张图像)和来自 uniform(1.5, 2.0)(每张图像)的乘数采样的。 这似乎产生了良好而多样的结果。
# iaa.imgcorruptlike.Spatter(severity=), # 溅 123水滴、45泥
# 对比度 亮度 饱和度 选其一
iaa.SomeOf((, 1),
[
iaa.imgaug.augmenters.contrast.LinearContrast((.5, 2.0), per_channel=0.5), # 对比度变为原来的一半或者二倍
iaa.imgcorruptlike.Brightness(severity=(, 2)), # 亮度增加
iaa.imgcorruptlike.Saturate(severity=(, 3)), # 色彩饱和度
]
)
],
# 随机顺序运行augmentations
random_order=True
)
], random_order=True) # 随机运行augmenters数量
# 图片文件相关路径
path = './input/'
savedpath = './output/'
imglist = []
filelist = os.listdir(path)
# 遍历要增强的文件夹,把所有的图片保存在imglist中
for item in filelist:
img = cv.imread(path + item)
# print('item is ',item)
# print('img is ',img)
# images = load_batch(batch_idx)
imglist.append(img)
# print('imglist is ' ,imglist)
print('all the picture have been appent to imglist')
for count in range():
images_aug = seq.augment_images(imglist)
for index in range(len(images_aug)):
# 保存图片 文件名和源文件相同
filename = str(filelist[index])
cv.imwrite(savedpath + filename, images_aug[index])
print('image of count%s index%s has been writen' % (count, index))
else
对input里的原图像重命名:00001.jpg或者1.jpg
重命名00001.jpg
Rename0001.py
# ###################文件重命名#################
import os
import re
import sys
path = r"./input"
filelist = os.listdir(path)
filetype = '.jpg'
for file in filelist:
print(file)
for file in filelist:
Olddir = os.path.join(path, file)
print(Olddir)
if os.path.isdir(Olddir):
continue
# os.path.splitext("path"):分离文件名与扩展名
filename = os.path.splitext(file)[]
filetype = os.path.splitext(file)[]
# zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充
Newdir = os.path.join(path, filename.zfill() + filetype) # 数字5是定义为5位数,可随意修改需要的
os.rename(Olddir, Newdir)
重命名1.jpg
Rename1.py
# ###################文件重命名################
import os
class BatchRename():
def __init__(self):
self.path = './input/' # 图片的路径
def rename(self):
filelist = os.listdir(self.path)
filelist.sort()
total_num = len(filelist) # 获取文件中有多少图片
i = # 文件命名从哪里开始(即命名从哪里开始)
for item in filelist:
if item.endswith('.png'):
src = os.path.join(self.path, item)
dst = os.path.join(os.path.abspath(self.path), str(i) + '.png')
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
i = i +
except Exception as e:
print(e)
print('rename dir fail\r\n')
print('total %d to rename & converted %d jpgs' % (total_num, i))
if __name__ == '__main__':
demo = BatchRename() # 创建对象
demo.rename() # 调用对象的方法
效果图
input示例 00001.jpg
output示例 00001.jpg
input示例 00005.jpg
output示例 00005.jpg