Posted on

使用數據增強加強圖像辨識準確率

數據增強

數據增強(Data Augmentation)是一種在不增加真實數據的情況下,通過對現有數據進行變化來增加數據集大小的方法。
請參見: https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator
常見的數據增強技術包括:

  • 尺度變換: 對圖像進行放大或縮小。
  • 旋轉: 對圖像進行旋轉。
  • 平移: 對圖像進行平移。
  • 剪裁: 對圖像進行剪裁。
  • 翻轉: 對圖像進行水平或垂直翻轉。
  • 調整亮度: 對圖像的亮度進行調整。
  • 調整對比度: 對圖像的對比度進行調整。

通過使用這些技術,可以從現有的數據集中生成新的數據,以增加數據集的大小

使用數據增強的範例 – 使用ImageDataGenerator

以下為一個簡單範例

# 建立模型
model = Sequential()
# 加入多個卷積層和池化層
model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=(img_height,img_width,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=128, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

# 將特徵圖拉平
model.add(Flatten())

# 加入多個全連接層
model.add(Dense(units=256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=128, activation='relu'))
model.add(Dropout(0.5))

# 加入輸出層
model.add(Dense(units=52, activation='softmax'))

# 編譯模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 使用數據增強
datagen = ImageDataGenerator(
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True
)

# 訓練模型
model.fit_generator(
datagen.flow(x_train, y_train, batch_size=32),
steps_per_epoch=len(x_train) / 32,
epochs=10,
validation_data=(x_val, y_val)
)

數據增強範例2 – 載入圖片decode_jpeg後隨機改變圖像

#现在我们的jpg文件进行解码,变成三维矩阵
def load_preprosess_image(path,label):
    #读取路径
    image=tf.io.read_file(path)
    #解码
    image=tf.image.decode_jpeg(image,channels=3)#彩色图像为3个channel
    #将图像改变为同样的大小,利用裁剪或者扭曲,这里应用了扭曲
    image=tf.image.resize(image,[360,360])
    #随机裁剪图像
    image=tf.image.random_crop(image,[256,256,3])
    #随机上下翻转图像
    image=tf.image.random_flip_left_right(image)
    #随机上下翻转
    image=tf.image.random_flip_up_down(image)
    #随机改变图像的亮度
    image=tf.image.random_brightness(image,0.5)
    #随机改变对比度
    image=tf.image.random_contrast(image,0,1)
    #改变数据类型
    image=tf.cast(image,tf.float32)
    #将图像进行归一化
    image=image/255
    #现在还需要对label进行处理,我们现在是列表[1,2,3],
    #需要变成[[1].[2].[3]]
    label=tf.reshape(label,[1])
    return image,label

梗圖分享