python实现图像的随机增强变换

 更新时间:2024年11月12日 15:14:59   作者:Ysn0719  
这篇文章主要为大家介绍了如何利用pythons制作一个小工具工具,可以实现图像的随机增强变换,可用于分类训练数据的增强,有需要的可以参考下

从文件夹中随机选择一定数量的图像,然后对每个选定的图像进行一次随机的数据增强变换。

import os
import random
import cv2
import numpy as np
from PIL import Image, ImageEnhance, ImageOps

# 定义各种数据增强方法
def random_rotate(image, angle_range=(-30, 30)):
    angle = random.uniform(angle_range[0], angle_range[1])
    (h, w) = image.shape[:2]
    center = (w // 2, h // 2)
    M = cv2.getRotationMatrix2D(center, angle, 1.0)
    rotated = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
    return rotated

def random_translate(image, translate_range=(-50, 50)):
    tx = random.randint(translate_range[0], translate_range[1])
    ty = random.randint(translate_range[0], translate_range[1])
    (h, w) = image.shape[:2]
    M = np.float32([[1, 0, tx], [0, 1, ty]])
    translated = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_REFLECT)
    return translated

def random_flip(image):
    flip_code = random.choice([-1, 0, 1])
    flipped = cv2.flip(image, flip_code)
    return flipped

def random_scale(image, scale_range=(0.8, 1.2)):
    scale = random.uniform(scale_range[0], scale_range[1])
    (h, w) = image.shape[:2]
    new_dim = (int(w * scale), int(h * scale))
    scaled = cv2.resize(image, new_dim, interpolation=cv2.INTER_LINEAR)
    return scaled

def random_crop(image, crop_size=(224, 224)):
    (h, w) = image.shape[:2]
    if crop_size[0] > h or crop_size[1] > w:
        # 当裁剪尺寸大于图像尺寸时,抛出异常或调整裁剪尺寸
        raise ValueError("Crop size is larger than image size.")
    top = random.randint(0, h - crop_size[0])
    left = random.randint(0, w - crop_size[1])
    cropped = image[top:top+crop_size[0], left:left+crop_size[1]]
    return cropped

def random_color_jitter(image):
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    color_jitter = ImageEnhance.Color(pil_image).enhance(random.uniform(0.6, 1.4))
    contrast_jitter = ImageEnhance.Contrast(color_jitter).enhance(random.uniform(0.5, 1.5))
    brightness_jitter = ImageEnhance.Brightness(contrast_jitter).enhance(random.uniform(0.6, 1.4))
    sharpness_jitter = ImageEnhance.Sharpness(brightness_jitter).enhance(random.uniform(0.6, 1.4))
    jittered = cv2.cvtColor(np.array(sharpness_jitter), cv2.COLOR_RGB2BGR)
    return jittered

def random_add_noise(image):
    row, col, ch = image.shape
    mean = 0
    var = 0.1
    sigma = var ** 0.5
    gauss = np.random.normal(mean, sigma, (row, col, ch))
    gauss = gauss.reshape(row, col, ch)
    noisy = image + gauss
    return np.clip(noisy, 0, 255).astype(np.uint8)

# 数据增强主函数
def augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image):
    if not os.path.exists(dst_folder):
        os.makedirs(dst_folder)

    # 获取所有图像文件名
    all_filenames = [f for f in os.listdir(src_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg'))]

    # 如果选择的图像数量大于总图像数量,则只处理全部图像
    num_images_to_process = min(num_images_to_select, len(all_filenames))

    # 随机选择图像
    selected_filenames = random.sample(all_filenames, num_images_to_process)

    # 创建一个增强方法列表
    augmentation_methods = [
        random_rotate,
        #random_translate,
        random_flip,
        random_scale,
        #random_crop,
        random_color_jitter,
        random_add_noise
    ]

    for filename in selected_filenames:
        img_path = os.path.join(src_folder, filename)
        image = cv2.imread(img_path)

        for i in range(num_augmentations_per_image):
            # 随机选择一种增强方法
            augmentation_method = random.choice(augmentation_methods)
            
            # 应用选中的增强方法
            augmented_img = augmentation_method(image)

            # 保存增强后的图像
            base_name, ext = os.path.splitext(filename)
            save_path = os.path.join(dst_folder, f"{base_name}_aug_{i}{ext}")
            cv2.imwrite(save_path, augmented_img)

if __name__ == "__main__":
    src_folder = 'path/to/source/folder'  # 替换为你的源文件夹路径
    dst_folder = 'path/to/destination/folder'  # 替换为你要保存增强图像的文件夹路径
    num_images_to_select = 10  # 从源文件夹中随机选择的图像数量
    num_augmentations_per_image = 5  # 每张图像生成的增强图像数量

    augment_random_images(src_folder, dst_folder, num_images_to_select, num_augmentations_per_image)
    print(f"图像增强完成,增强后的图像已保存到 {dst_folder}")

说明

  • 随机选择图像:从源文件夹中随机选择num_images_to_select数量的图像。
  • 随机选择一种增强方法:对于每张选定的图像,随机选择一种数据增强方法。
  • 应用增强方法:对每张选定的图像应用所选的增强方法。
  • 保存增强后的图像:将增强后的图像保存到目标文件夹中。

参数

•src_folder:源文件夹路径。

•dst_folder:目标文件夹路径。

•num_images_to_select:从源文件夹中随机选择的图像数量。

•num_augmentations_per_image:每张选定的图像生成的增强图像数量。

请确保将src_folder和dst_folder变量设置为您实际使用的文件夹路径,并根据需要调整num_images_to_select和num_augmentations_per_image的值。运行这段代码后,将得到从源文件夹中随机选择的图像,并对这些图像进行了随机的数据增强变换。

到此这篇关于python实现图像的随机增强变换的文章就介绍到这了,更多相关python图像随机增强内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 关于Python中异常(Exception)的汇总

    关于Python中异常(Exception)的汇总

    异常是指程序中的例外,违例情况。异常机制是指程序出现错误后,程序的处理方法。当出现错误后,程序的执行流程发生改变,程序的控制权转移到异常处理。下面这篇文章主要汇总了关于Python中异常(Exception)的相关资料,需要的朋友可以参考下。
    2017-01-01
  • python查看微信好友是否删除自己

    python查看微信好友是否删除自己

    这篇文章主要为大家详细介绍了python查看微信好友是否删除自己,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-12-12
  • Python中OTSU算法的原理与实现详解

    Python中OTSU算法的原理与实现详解

    OTSU算法是大津展之提出的阈值分割方法,又叫最大类间方差法,本文主要为大家详细介绍了OTSU算法的原理与Python实现,感兴趣的小伙伴可以了解下
    2023-12-12
  • Python ArcPy实现批量对大量遥感影像相减做差

    Python ArcPy实现批量对大量遥感影像相减做差

    这篇文章主要为大家介绍了如何基于Python中ArcPy模块实现对大量栅格遥感影像文件批量进行相减做差,文中的示例代码讲解详细,感兴趣的可以了解一下
    2023-06-06
  • Python爬取门户论坛评论浅谈Python未来发展方向

    Python爬取门户论坛评论浅谈Python未来发展方向

    这篇文章主要介绍了如何实现Python爬取门户论坛评论,附含图片示例代码,讲解了详细的操作过程,有需要的的朋友可以借鉴参考下,希望可以有所帮助
    2021-09-09
  • Python tuple方法和string常量介绍

    Python tuple方法和string常量介绍

    这篇文章主要介绍了Python tuple方法和string常量,文章基于python的相关资料展开详细内容,对初学python的通知有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • keras回调函数的使用

    keras回调函数的使用

    本文主要介绍了keras回调函数的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-03-03
  • 基于Python实现IP代理池

    基于Python实现IP代理池

    在网络爬虫或数据采集领域,IP代理池是一种常用的工具,本文将详细介绍如何使用Python实现一个简单的IP代理池,有需要的可以参考一下
    2024-11-11
  • Python画图常用命令大全(详解)

    Python画图常用命令大全(详解)

    这篇文章主要介绍了Python画图常用命令大全,内容包括,matplotlib库默认英文字体,读取exal方法,论文图片的类型和格式,柱状图扩展等知识,需要的朋友可以参考下
    2021-09-09
  • 详解python函数的闭包问题(内部函数与外部函数详述)

    详解python函数的闭包问题(内部函数与外部函数详述)

    这篇文章主要介绍了python函数的闭包问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05

最新评论