為深度學習模型加載自定義圖像數據集:第1部分


作者|Renu Khandelwal
編譯|VK
來源|Towards Data Science

在本文中,你將學習如何加載自定義數據和創建圖像序列和測試數據集,作為深度學習模型的輸入。

  • Open CV2
  • PIL

這里使用的數據集是來自Kaggle的Intel圖像分類。

數據集鏈接:https://www.kaggle.com/puneet6060/intel-image-classification/version/2

“Intel圖像分類”數據集已分為train、test和Val,我們將僅使用訓練數據集學習如何使用不同的庫加載數據集。

為深度學習模型加載自定義數據集的典型步驟

  1. 打開圖像文件。文件的格式可以是JPEG、PNG、BMP等。

  2. 調整圖像大小以匹配深度學習模型的輸入層的輸入大小。

  3. 將圖像像素轉換為浮點數據類型。

  4. 將圖像標准化,使像素值在0到1之間。

  5. 深度學習模型的圖像數據應該是一個numpy數組或一個張量對象。

自定義圖像數據的文件夾結構

每個類都是一個文件夾,其中包含該特定類的圖像。

使用CV2加載圖像數據

導入所需的庫

import pandas as pd
import numpy as np
import os
import tensorflow as tf
import cv2
from tensorflow import keras
from tensorflow.keras import layers, Dense, Input, InputLayer, Flatten
from tensorflow.keras.models import Sequential, Model
from  matplotlib import pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline

從其中一個文件夾中隨機輸出五張圖像

plt.figure(figsize=(20,20))
test_folder=r'CV\Intel_Images\seg_train\seg_train\forest'
for i in range(5):
    file = random.choice(os.listdir(img_folder))
    image_path= os.path.join(img_folder, file)
    img=mpimg.imread(image_path)
    ax=plt.subplot(1,5,i+1)
    ax.title.set_text(file)
    plt.imshow(img)

設置用於加載數據集的圖像維度和源文件夾

IMG_WIDTH=200
IMG_HEIGHT=200
img_folder=r'CV\Intel_Images\seg_train\seg_train\'

從文件夾中的圖像創建圖像數據和標簽

在下面的函數中

  • source文件夾是包含不同類的圖像的輸入參數。

  • 從文件夾中讀取圖像文件並將其轉換為正確的顏色格式。

  • 根據模型所需的輸入尺寸調整圖像大小

  • 將圖像轉換為數據類型為float32的Numpy數組

  • 將圖像數組標准化,使值在0和1之間,這有助於更快地收斂。

def create_dataset(img_folder):
   
    img_data_array=[]
    class_name=[]
   
    for dir1 in os.listdir(img_folder):
        for file in os.listdir(os.path.join(img_folder, dir1)):
       
            image_path= os.path.join(img_folder, dir1,  file)
            image= cv2.imread( image_path, cv2.COLOR_BGR2RGB)
            image=cv2.resize(image, (IMG_HEIGHT, IMG_WIDTH),interpolation = cv2.INTER_AREA)
            image=np.array(image)
            image = image.astype('float32')
            image /= 255 
            img_data_array.append(image)
            class_name.append(dir1)
    return img_data_array, class_name
# extract the image array and class name
img_data, class_name =create_dataset(r'CV\Intel_Images\seg_train\seg_train')

將文本標簽轉換為數字編碼

為類的所有唯一值創建字典

target_dict={k: v for v, k in enumerate(np.unique(class_name))}
target_dict

根據字典將類名稱轉換為各自的數值

target_val=  [target_dict[class_name[i]] for i in range(len(class_name))]

創建一個簡單的深度學習模型並編譯它

model=tf.keras.Sequential(
        [
            tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)),
            tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'),
            tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(6)
        ])

encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

我們最終調整數據集來訓練模型。我們可以使用Numpy數組作為輸入

history = model.fit(x=np.array(img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)

我們還可以使用tf.cast()將輸入數據轉換為張量來訓練模型。

history = model.fit(x=tf.cast(np.array(img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)

我們使用不同的庫加載圖像數據集但是我們使用相同的模型來進行進一步的訓練

用PIL加載圖像數據

添加附加庫以使用PIL加載圖像數據集

from PIL import Image

使用PIL從文件夾中的圖像創建圖像數據和標簽

在下面的函數中

  • source文件夾是包含不同類的圖像的輸入參數。

  • 使用PIL從文件夾中打開圖像文件。

  • 根據模型所需的輸入尺寸調整圖像大小

  • 將圖像轉換為數據類型為float32的Numpy數組

  • 標准化圖像數組以加快收斂。

def create_dataset_PIL(img_folder):
    
    img_data_array=[]
    class_name=[]
    for dir1 in os.listdir(img_folder):
        for file in os.listdir(os.path.join(img_folder, dir1)):
       
            image_path= os.path.join(img_folder, dir1,  file)
            image= np.array(Image.open(image_path))
            image= np.resize(image,(IMG_HEIGHT,IMG_WIDTH,3))
            image = image.astype('float32')
            image /= 255  
            img_data_array.append(image)
            class_name.append(dir1)
    return img_data_array , class_name
PIL_img_data, class_name=create_dataset_PIL(img_folder)

將文本標簽轉換為數字編碼

下面是我們在CV2中使用的代碼

target_dict={k: v for v, k in enumerate(np.unique(class_name))}
target_val=  [target_dict[class_name[i]] for i in range(len(class_name))]

創建和編譯一個簡單的深度學習模型

model=tf.keras.Sequential(
        [
            tf.keras.layers.InputLayer(input_shape=(IMG_HEIGHT,IMG_WIDTH, 3)),
            tf.keras.layers.Conv2D(filters=32, kernel_size=3, strides=(2, 2), activation='relu'),
            tf.keras.layers.Conv2D(filters=64, kernel_size=3, strides=(2, 2), activation='relu'),
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(6)
        ])

encoder.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

我們最終調整數據集來訓練模型。我們可以使用Numpy數組作為輸入

history = model.fit(x=np.array(PIL_img_data, np.float32), y=np.array(list(map(int,target_val)), np.float32), epochs=5)

我們還可以使用tf.cast()將輸入數據轉換為張量來訓練模型。

history = model.fit(x=tf.cast(np.array(PIL_img_data), tf.float64), y=tf.cast(list(map(int,target_val)),tf.int32), epochs=5)

除了幾個步驟外,使用CV2和PIL加載數據集的過程是相同的。

現在這將幫助你使用CV2和PIL庫加載數據集。

這里提供了使用CV2和PIL加載數據集的代碼:https://github.com/arshren/Load_Dataset

在下一篇文章中,我們將使用以下的庫來加載數據集。

  • Keras
  • tf.data

原文鏈接:https://towardsdatascience.com/loading-custom-image-dataset-for-deep-learning-models-part-1-d64fa7aaeca6

歡迎關注磐創AI博客站:
http://panchuang.net/

sklearn機器學習中文官方文檔:
http://sklearn123.com/

歡迎關注磐創博客資源匯總站:
http://docs.panchuang.net/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM