数据集太少怎么办?数据集扩充方法

我学习深度学习写代码的时候,数据集图像太少只有1406张还分4个类别,一个类别只有300来张,再分为train、valid和test,图像就更少了,训练的图像少,深度学习的准确度就会不高。
这里是我找到的扩充数据集的方法,对图像进行亮度增强、对比度增强、水平翻转和随机方向旋转,我的1406张图扩充到了7030张。

  • 变换程序
from PIL import ImageEnhance
import os
import numpy as np
from PIL import Image

def brightnessEnhancement(root_path,img_name):#亮度增强
    image = Image.open(os.path.join(root_path, img_name))
    enh_bri = ImageEnhance.Brightness(image)
    # brightness = 1.1+0.4*np.random.random()#取值范围1.1-1.5
    brightness = 1.5
    image_brightened = enh_bri.enhance(brightness)
    return image_brightened


def contrastEnhancement(root_path, img_name):  # 对比度增强
    image = Image.open(os.path.join(root_path, img_name))
    enh_con = ImageEnhance.Contrast(image)
    # contrast = 1.1+0.4*np.random.random()#取值范围1.1-1.5
    contrast = 1.5
    image_contrasted = enh_con.enhance(contrast)
    return image_contrasted

def rotation(root_path, img_name):
    img = Image.open(os.path.join(root_path, img_name))
    random_angle = np.random.randint(-2, 2)*90
    if random_angle==0:
     rotation_img = img.rotate(-90) #旋转角度
    else:
        rotation_img = img.rotate( random_angle)  # 旋转角度
    # rotation_img.save(os.path.join(root_path,img_name.split('.')[0] + '_rotation.jpg'))
    return rotation_img

def flip(root_path,img_name):   #翻转图像
    img = Image.open(os.path.join(root_path, img_name))
    filp_img = img.transpose(Image.FLIP_LEFT_RIGHT)
    # filp_img.save(os.path.join(root_path,img_name.split('.')[0] + '_flip.jpg'))
    return filp_img


def createImage(imageDir,saveDir):
   i=0
   for name in os.listdir(imageDir):
      i=i+1
      saveName="cesun"+str(i)+".jpg"
      saveImage=contrastEnhancement(imageDir,name)
      saveImage.save(os.path.join(saveDir,saveName))
      saveName1 = "flip" + str(i) + ".jpg"
      saveImage1 = flip(imageDir,name)
      saveImage1.save(os.path.join(saveDir, saveName1))
      saveName2 = "brightnessE" + str(i) + ".jpg"
      saveImage2 = brightnessEnhancement(imageDir, name)
      saveImage2.save(os.path.join(saveDir, saveName2))
      saveName3 = "rotate" + str(i) + ".jpg"
      saveImage = rotation(imageDir, name)
      saveImage.save(os.path.join(saveDir, saveName3))
  • 调用程序
from test3 import createImage

imageDir="C:/Users/lenovo/Desktop/maize/3" #要改变的图片的路径文件夹
saveDir="C:/Users/lenovo/Desktop/maize/3"   #数据增强生成图片的路径文件夹
createImage(imageDir,saveDir)

这里的test3就是上一段程序(变换程序)的文件名,你的变换程序取什么名字就用什么名。createImage就是变换程序中的最后一个函数,只需要调用这个就行了,这里生成的图你可以和原图放在一起,也可以放到别的文件夹里。

希望对你有帮助!

参考博客

你可能感兴趣的:(pytorch,笔记)