如果你需要一个更复杂的解决方案来进行图像数据增强,那么你可以考虑使用imgaug
(Image Augmentation)库。imgaug
是一个强大且灵活的图像增强库,它提供了大量的预定义增强方法,并且允许你自定义自己的增强策略。
以下是一个使用imgaug
进行图像数据增强的Python代码示例:
import os
import requests
from PIL import Image
import imgaug as ia
from imgaug import augmenters as iaa# 下载图像的函数
def download_image(url, save_path):response = requests.get(url, stream=True)if response.status_code == 200:with open(save_path, 'wb') as f:for chunk in response:f.write(chunk)else:print(f"Failed to download image from {url}")# 定义数据增强序列
def create_augmentation_seq():seq = iaa.Sequential([iaa.Fliplr(0.5), # 水平翻转,50%的概率iaa.Flipud(0.5), # 垂直翻转,50%的概率iaa.Affine(rotate=(-20, 20), # 随机旋转,范围在-20到20度之间scale=(0.8, 1.2), # 随机缩放,范围在0.8到1.2倍之间translate_percent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)}, # 随机平移,范围在-10%到10%之间mode="constant", # 使用常数填充新的像素cval=(0, 255) # 填充像素的值范围),iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5), # 添加高斯噪声iaa.ContrastNormalization((0.7, 1.3)), # 对比度归一化], random_order=True) # 每次应用增强时的顺序是随机的return seq# 主程序
def main():# 读取face.txt文件中的URLwith open('face.txt', 'r') as f:urls = f.read().splitlines()# 下载图像的目录download_dir = 'downloaded_images'# 增强后图像的目录augmented_dir = 'augmented_images'# 创建目录if not os.path.exists(download_dir):os.makedirs(download_dir)if not os.path.exists(augmented_dir):os.makedirs(augmented_dir)# 创建数据增强序列seq = create_augmentation_seq()# 下载并增强图像for idx, url in enumerate(urls):image_path = os.path.join(download_dir, f"face_{idx}.jpg")download_image(url, image_path)# 读取图像image = Image.open(image_path)# 将PIL图像转换为numpy数组image_array = np.array(image)# 应用数据增强augmented_images = seq(images=[image_array])# 保存增强后的图像for i, aug_image in enumerate(augmented_images):aug_image_path = os.path.join(augmented_dir, f"face_{idx}_aug_{i}.jpg")Image.fromarray(aug_image).save(aug_image_path)print("数据增强完成,增强后的图像已保存在", augmented_dir)# 运行主程序
if __name__ == "__main__":main()
这个脚本首先定义了一个download_image
函数来下载图像,并定义了一个create_augmentation_seq
函数来创建一个包含多种增强方法的序列。然后,主程序main
读取URL列表,下载图像,并使用定义的增强序列对每个图像进行增强。增强后的图像被保存在一个单独的目录中。
请注意,这个脚本假设所有的URL都指向JPEG格式的图像,并且所有的图像都可以被正确下载。在实际应用中,你可能需要添加额外的错误处理和验证逻辑。此外,这个脚本使用的是随机增强,每次运行时都会得到不同的增强结果。
最后,确保你已经安装了imgaug
库和它的依赖项。你可以使用pip来安装它: