如何使用TensorFlow和檔案路徑建立花卉資料集的影像-標籤對?
建立影像-標籤對的方法是:首先將檔案路徑轉換為路徑元件列表。然後,將倒數第二個值新增到目錄中。然後,將標籤編碼為整數格式。壓縮後的字串被轉換為張量,然後被重塑為所需的大小。
閱讀更多: 什麼是 TensorFlow 以及 Keras 如何與 TensorFlow 協同工作來建立神經網路?
我們將使用花卉資料集,其中包含數千張花的影像。它包含 5 個子目錄,每個類別都有一個子目錄。
我們使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 幫助在瀏覽器上執行 Python 程式碼,無需任何配置,並可免費訪問 GPU(圖形處理器)。Colaboratory 基於 Jupyter Notebook 構建。
print("Function to convert file path to (image,label) pair")
print("First, path is converted to list of path components")
print("Then, the second to last value is added to class directory")
print("The label is integer encoded")
def get_label(file_path):
parts = tf.strings.split(file_path, os.path.sep)
one_hot = parts[-2] == class_names
return tf.argmax(one_hot)
print("The compressed string is converted to a 3 dimensional int tensor")
print("The image is resized to the required size")
def decode_img(img):
img = tf.image.decode_jpeg(img, channels=3)
return tf.image.resize(img, [img_height, img_width])
print("The raw data is loaded from the file as a string value")
def process_path(file_path):
label = get_label(file_path)
img = tf.io.read_file(file_path)
img = decode_img(img)
return img, label程式碼來源:https://www.tensorflow.org/tutorials/load_data/images
輸出
Function to convert file path to (image,label) pair First, path is converted to list of path components Then, the second to last value is added to class directory The label is integer encoded The compressed string is converted to a 3 dimensional int tensor The image is resized to the required size The raw data is loaded from the file as a string value
解釋
- 定義了一個名為 `get_label` 的函式,它將檔案路徑轉換為影像-標籤對。
- 檔案路徑被轉換為路徑元件列表。
- 將倒數第二個值新增到類別目錄中。
- 接下來,標籤被編碼為整數。
- 另一個名為 `decode_img` 的函式用於調整影像大小並返回它。
- 首先將壓縮後的字串轉換為三維整數張量,然後調整大小。
- 定義了另一個名為 `process_path` 的函式,它將檔案中的原始資料載入為字串值。
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP