1. 程式人生 > 程式設計 >TensorFlow2.X使用圖片製作簡單的資料集訓練模型

TensorFlow2.X使用圖片製作簡單的資料集訓練模型

Tensorflow內建了許多資料集,但是實際自己應用的時候還是需要使用自己的資料集,這裡TensorFlow 官網也給介紹文件,官方文件。這裡對整個流程做一個總結(以手勢識別的資料集為例)。

1、 收集手勢圖片

資料集下載

方法多種多樣了。我通過攝像頭自己採集了一些手勢圖片。儲存成如下形式,

在這裡插入圖片描述

以同樣的形式在建立一個測試集,當然也可以不弄,在程式裡處理。

2、構建資料集

匯入相關的包

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets,layers,optimizers,Sequential,metrics
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
import os
import pathlib
import random
import matplotlib.pyplot as plt

讀取檔案

data_root = pathlib.Path('D:\code\PYTHON\gesture_recognition\Dataset')
print(data_root)
for item in data_root.iterdir():
 print(item)

執行結果

讀取圖片路徑到list中

all_image_paths = list(data_root.glob('*/*'))
all_image_paths = [str(path) for path in all_image_paths]
random.shuffle(all_image_paths)
image_count = len(all_image_paths)
print(image_count) ##統計共有多少圖片
for i in range(10):
 print(all_image_paths[i])

在這裡插入圖片描述

label_names = sorted(item.name for item in data_root.glob('*/') if item.is_dir())
print(label_names) #其實就是資料夾的名字
label_to_index = dict((name,index) for index,name in enumerate(label_names))
print(label_to_index)
all_image_labels = [label_to_index[pathlib.Path(path).parent.name]
     for path in all_image_paths]

print("First 10 labels indices: ",all_image_labels[:10])

在這裡插入圖片描述

預處理

def preprocess_image(image):
 image = tf.image.decode_jpeg(image,channels=3)
 image = tf.image.resize(image,[100,100])
 image /= 255.0 # normalize to [0,1] range
 # image = tf.reshape(image,[100*100*3])
 return image

def load_and_preprocess_image(path,label):
 image = tf.io.read_file(path)
 return preprocess_image(image),label

構建一個 tf.data.Dataset

ds = tf.data.Dataset.from_tensor_slices((all_image_paths,all_image_labels))
train_data = ds.map(load_and_preprocess_image).batch(16)

同樣的方式在製作一個測試集,就可以用於模型訓練和測試了。

總結

到此這篇關於TensorFlow2.X使用圖片製作簡單的資料集訓練模型的文章就介紹到這了,更多相關TensorFlow資料集訓練模型內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!