บทนำ
สร้าง function process_path(file_path) ที่แปลง path string → (image tensor, label int) ประกอบด้วย 3 sub-functions
โค้ดตัวอย่าง
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ผลลัพธ์
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: split path ด้วย os.path.sep → 取 parts[-2] (parent folder name = class) → compare กับ class_names → one-hot → argmax → class index
- decode_img:
tf.io.read_fileอ่าน raw bytes →decode_jpeg→ tensor (H,W,3) →resize→ (img_height, img_width, 3) - process_path: เรียก get_label + decode_img → return (img, label)
โครงสร้างโฟลเดอร์ที่คาดหวัง
data_dir/
daisy/
img1.jpg
img2.jpg
dandelion/
...
roses/
sunflowers/
tulips/class_names = sorted folder names (exclude LICENSE.txt)