对一张图片采用随机色彩失真、随机角度旋转、随机平移、随机扩充、随机裁剪等 图像变换方法进行数据集扩充的python程序
下面是一个示例程序,使用了Python中的PIL库进行图像变换:
from PIL import Image
import os
import random
def random_color_distortion(img):
"""
随机颜色失真
"""
r, g, b = img.split()
r = r.point(lambda i: i + random.randint(-50, 50))
g = g.point(lambda i: i + random.randint(-50, 50))
b = b.point(lambda i: i + random.randint(-50, 50))
img = Image.merge('RGB', (r, g, b))
return img
def random_rotation(img):
"""
随机角度旋转
"""
angle = random.randint(-30, 30)
img = img.rotate(angle, resample=Image.BICUBIC, expand=True)
return img
def random_translation(img):
"""
随机平移
"""
x = random.randint(-50, 50)
y = random.randint(-50, 50)
img = img.transform(img.size, Image.AFFINE, (1, 0, x, 0, 1, y))
return img
def random_expansion(img):
"""
随机扩充
"""
w, h = img.size
expand_w = random.randint(0, w)
expand_h = random.randint(0, h)
img = img.resize((w + expand_w, h + expand_h), resample=Image.BICUBIC)
return img
def random_crop(img):
"""
随机裁剪
"""
w, h = img.size
crop_w = random.randint(0, w)
crop_h = random.randint(0, h)
x1 = random.randint(0, w - crop_w)
y1 = random.randint(0, h - crop_h)
x2 = x1 + crop_w
y2 = y1 + crop_h
img = img.crop((x1, y1, x2, y2))
return img
def augment_image(img_path):
"""
对一张图片进行数据增强
"""
img = Image.open(img_path)
img = random_color_distortion(img)
img = random_rotation(img)
img = random_translation(img)
img = random_expansion(img)
img = random_crop(img)
return img
def augment_dataset(dataset_path, output_path, num_augmentations):
"""
对一个数据集进行数据扩充
"""
if not os.path.exists(output_path):
os.makedirs(output_path)
for root, dirs, files in os.walk(dataset_path):
for file in files:
if file.endswith('.jpg') or file.endswith('.png'):
img_path = os.path.join(root, file)
for i in range(num_augmentations):
img = augment_image(img_path)
output_file = os.path.join(output_path, f'{file[:-4]}_{i}.jpg')
img.save(output_file)
# 使用示例
augment_dataset('dataset/', 'augmented_dataset/', 5)
这个程序可以对一个数据集中的所有图片进行数据扩充,每张图片将会生成指定数量的增强图像。你可以根据需要调整增强方法的参数范围
原文地址: http://www.cveoy.top/t/topic/cJ0a 著作权归作者所有。请勿转载和采集!