Load and preprocess images

简介: This tutorial shows how to load and preprocess an image dataset in three ways. First, you will use high-level Keras preprocessing utilities and layers to read a directory of images on disk. Next, you will write your own input pipeline from scratch using tf.data. Finally, you will download a dataset

This tutorial shows how to load and preprocess an image dataset in three ways. First, you will use high-level Keras preprocessing utilities and layers to read a directory of images on disk. Next, you will write your own input pipeline from scratch using tf.data. Finally, you will download a dataset from the large catalog available in TensorFlow Datasets.

import numpy as np
import os
import PIL
import PIL.Image
import tensorflow as tf
import tensorflow_datasets as tfds

Download the flowers dataset

This tutorial uses a dataset of several thousand photos of flowers. The flowers dataset contains 5 sub-directories, one per class:

flowers_photos/
  daisy/
  dandelion/
  roses/
  sunflowers/
  tulips/
import pathlib
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file(origin=dataset_url, 
                                   fname='flower_photos', 
                                   untar=True)
data_dir = pathlib.Path(data_dir)

# After downloading (218MB), you should now have a copy of the flower photos available. There are 3,670 total images:
image_count = len(list(data_dir.glob('*/*.jpg')))
print(image_count)

Load using tf.keras.preprocessing

Let's load these images off disk using tf.keras.preprocessing.image_dataset_from_directory.

Create a dataset

Define some parameters for the loader:

batch_size = 32
img_height = 180
img_width = 180

It's good practice to use a validation split when developing your model. You will use 80% of the images for training and 20% for validation.

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

You can find the class names in the class_names attribute on these datasets.

class_names = train_ds.class_names
print(class_names)

Standardize the data

The RGB channel values are in the [0, 255] range. This is not ideal for a neural network; in general you should seek to make your input values small. Here, you will standardize values to be in the [0, 1] range by using the tf.keras.layers.experimental.preprocessing.Rescaling layer.

normalization_layer = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)

There are two ways to use this layer. You can apply it to the dataset by calling map:

normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
# Notice the pixels values are now in `[0,1]`.
print(np.min(first_image), np.max(first_image))

Configure the dataset for performance

Let's make sure to use buffered prefetching, so you can yield data from disk without having I/O become blocking. These are two important methods you should use when loading data.

.cache() keeps the images in memory after they're loaded off disk during the first epoch. This will ensure the dataset does not become a bottleneck while training your model. If your dataset is too large to fit into memory, you can also use this method to create a performant on-disk cache.

.prefetch() overlaps data preprocessing and model execution while training.

Interested readers can learn more about both methods, as well as how to cache data to disk in the data performance guide.

AUTOTUNE = tf.data.AUTOTUNEtrain_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

Train a model

For completeness, you will show how to train a simple model using the datasets you have just prepared. This model has not been tuned in any way - the goal is to show you the mechanics using the datasets you just created. To learn more about image classification, visit this tutorial

num_classes = 5model = tf.keras.Sequential([  tf.keras.layers.experimental.preprocessing.Rescaling(1./255),  tf.keras.layers.Conv2D(32, 3, activation='relu'),  tf.keras.layers.MaxPooling2D(),  tf.keras.layers.Conv2D(32, 3, activation='relu'),  tf.keras.layers.MaxPooling2D(),  tf.keras.layers.Conv2D(32, 3, activation='relu'),  tf.keras.layers.MaxPooling2D(),  tf.keras.layers.Flatten(),  tf.keras.layers.Dense(128, activation='relu'),  tf.keras.layers.Dense(num_classes)])
model.compile(  optimizer='adam',  loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),  metrics=['accuracy'])
model.fit(  train_ds,  validation_data=val_ds,  epochs=3)

You may notice the validation accuracy is low compared to the training accuracy, indicating your model is overfitting. You can learn more about overfitting and how to reduce it in this tutorial.

Using tf.data for finer control

The above tf.keras.preprocessing utilities are a convenient way to create a tf.data.Dataset from a directory of images. For finer grain control, you can write your own input pipeline using tf.data. This section shows how to do just that, beginning with the file paths from the TGZ file you downloaded earlier.

list_ds = tf.data.Dataset.list_files(str(data_dir/'*/*'), shuffle=False)list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)
class_names = np.array(sorted([item.name for item in data_dir.glob('*') if item.name != "LICENSE.txt"]))print(class_names)

Split the dataset into train and validation:

val_size = int(image_count * 0.2)train_ds = list_ds.skip(val_size)val_ds = list_ds.take(val_size)

You can see the length of each dataset as follows:

print(tf.data.experimental.cardinality(train_ds).numpy())print(tf.data.experimental.cardinality(val_ds).numpy())

Write a short function that converts a file path to an (img, label) pair:

def get_label(file_path):  # convert the path to a list of path components  parts = tf.strings.split(file_path, os.path.sep)  # The second to last is the class-directory  one_hot = parts[-2] == class_names  # Integer encode the label  return tf.argmax(one_hot)
def decode_img(img):  # convert the compressed string to a 3D uint8 tensor  img = tf.io.decode_jpeg(img, channels=3)  # resize the image to the desired size  return tf.image.resize(img, [img_height, img_width])
def process_path(file_path):  label = get_label(file_path)  # load the raw data from the file as a string  img = tf.io.read_file(file_path)  img = decode_img(img)  return img, label

Use Dataset.map to create a dataset of image, label pairs:

# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)
for image, label in train_ds.take(1):  print("Image shape: ", image.numpy().shape)  print("Label: ", label.numpy())

Configure dataset for performance

To train a model with this dataset you will want the data:

  • To be well shuffled.
  • To be batched.
  • Batches to be available as soon as possible.

These features can be added using the tf.data API. For more details, see the Input Pipeline Performance guide.

def configure_for_performance(ds):  ds = ds.cache()  ds = ds.shuffle(buffer_size=1000)  ds = ds.batch(batch_size)  ds = ds.prefetch(buffer_size=AUTOTUNE)  return dstrain_ds = configure_for_performance(train_ds)val_ds = configure_for_performance(val_ds)

Continue training the model

You have now manually built a similar tf.data.Dataset to the one created by the keras.preprocessing above. You can continue training the model with it. As before, you will train for just a few epochs to keep the running time short

model.fit(  train_ds,  validation_data=val_ds,  epochs=3)

Using TensorFlow Datasets

So far, this tutorial has focused on loading data off disk. You can also find a dataset to use by exploring the large catalog of easy-to-download datasets at TensorFlow Datasets. As you have previously loaded the Flowers dataset off disk, let's see how to import it with TensorFlow Datasets.

(train_ds, val_ds, test_ds), metadata = tfds.load(    'tf_flowers',    split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],    with_info=True,    as_supervised=True,)

The flowers dataset has five classes.

num_classes = metadata.features['label'].num_classesprint(num_classes)

As before, remember to batch, shuffle, and configure each dataset for performance.

train_ds = configure_for_performance(train_ds)val_ds = configure_for_performance(val_ds)test_ds = configure_for_performance(test_ds)

You can find a complete example of working with the flowers dataset and TensorFlow Datasets by visiting the Data augmentation tutorial.

Next steps

This tutorial showed two ways of loading images off disk. First, you learned how to load and preprocess an image dataset using Keras preprocessing layers and utilities. Next, you learned how to write an input pipeline from scratch using tf.data. Finally, you learned how to download a dataset from TensorFlow Datasets. As a next step, you can learn how to add data augmentation by visiting this tutorial. To learn more about tf.data, you can visit the tf.data: Build TensorFlow input pipelines guide.

代码链接: https://codechina.csdn.net/csdn_codechina/enterprise_technology/-/blob/master/load_preprocess_images.ipynb

目录
相关文章
|
4月前
|
存储 Shell API
拆解 dsh 系列:从源码和版本变化看 DeepSeek Harness 的设计取舍
DeepSeek Harness(dsh)发布仅两周,实则历经两个月内部打磨。本文基于Git历史与npm发布数据,梳理其从0.0.1-rc.1到0.1.1-rc.2的演进:命名重构、定位升维(Coding Agent→Agent Harness)、核心与扩展边界持续厘清,展现一个开源智能体运行时如何审慎定义自身能力疆界。
535 1
拆解 dsh 系列:从源码和版本变化看 DeepSeek Harness 的设计取舍
|
10月前
|
传感器 人工智能 监控
过负荷监控系统:守护电力安全的全方位智能卫士,沃思智能
炎炎夏日变压器起火、精密仪器因过载损毁……这些风险能否提前预警?现代过负荷监控系统正是电力系统的“智能守护者”:融合高精度传感、AI动态分析与柔性应急决策,实现毫秒级响应、92%预测准确率,已应用于电网、医院、消防及光伏等领域,为城市用电安全保驾护航。(239字)
405 1
|
4月前
|
存储 安全 算法
PACS 系统核心功能详解:读懂医学影像的数字化全流程
PACS(影像归档与通信系统)是医院数字化影像管理核心,基于DICOM标准,实现CT、MR等设备影像的采集、存储、传输、处理与调阅;支持无胶片化阅片、结构化报告、RIS/HIS集成及多学科协同,全面提升诊疗效率与质量。
690 0
|
6月前
|
Java API PHP
阿里千问大模型API多语言对接完全指南:PHP、Java、Python、Go、.NET全栈实战
本文提供了一份完整的阿里千问大模型API多语言对接指南。千问API支持DashScope SDK和OpenAI兼容两种接入方式,覆盖PHP、Java、Python、Go、.NET五种主流开发语言。文章从开通服务、获取API Key开始,逐步讲解每种语言的SDK安装、环境配置、基础调用、流式输出、错误处理等核心环节。PHP因无官方SDK需直连REST API,Java和Python可通过DashScope官方SDK快速集成,Go和.NET则可通过OpenAI兼容模式调用。同时深入介绍了模型选型策略、参数调优、安全实践和成本优化建议,帮助开发者在不同技术栈下高效集成千问大模型能力。全文附带完整的可
|
12月前
|
敏捷开发 Dubbo Java
需求开发人日评估
本文介绍敏捷开发中工时评估的关键方法——人日估算。涵盖开发、自测、联调、测试及发布各阶段的时间分配,并提供常见需求如Excel导入导出、单表增删改查、跨服务调用等的参考人日,助力团队科学规划迭代周期。(238字)
 需求开发人日评估
|
传感器 人工智能 监控
【免费开源】基于STM32的智能宠物喂食系统设计与实现(全流程技术详解)附源码
本项目基于STM32F103C8T6设计实现智能宠物喂食系统,支持定时喂食、远程控制、余粮检测、语音提示等功能,结合传感器与物联网技术,提升宠物喂养智能化水平,适用于家庭及嵌入式课程实践。源码开源,具备良好扩展性。
【免费开源】基于STM32的智能宠物喂食系统设计与实现(全流程技术详解)附源码
|
存储 Kubernetes 异构计算
Qwen3 大模型在阿里云容器服务上的极简部署教程
通义千问 Qwen3 是 Qwen 系列最新推出的首个混合推理模型,其在代码、数学、通用能力等基准测试中,与 DeepSeek-R1、o1、o3-mini、Grok-3 和 Gemini-2.5-Pro 等顶级模型相比,表现出极具竞争力的结果。
|
小程序 前端开发 Java
200道微信小程序毕业设计最新题目(持续更新,附源码和说明文档)
200道微信小程序毕业设计最新题目(持续更新,附源码和说明文档)
|
12月前
|
人工智能 数据可视化 安全
通过阿里云 Chat App 合规接入 WhatsApp Business API:WABA 注册指南
本文将详解如何通过阿里云 Chat App 消息服务完成WABA 账号注册。
2390 0
|
数据可视化 项目管理
项目计划与进度跟踪:甘特图的强大功能解析
甘特图是现代项目管理中不可或缺的工具,通过时间线和任务条直观展示项目进度,支持任务分解、依赖关系管理和进度跟踪。结合板栗看板,可实现任务可视化与实时协作,提升团队效率。定期更新甘特图并灵活应对变化,确保项目顺利推进。