图片数据预处理

目录

图片数据处理的基本手段

实际应用


图片数据处理的基本手段

在实际使用中,图片数据通常需要进行预处理,以确保数据的质量和可重复性。常用的预处理步骤包括:

  • 缩放:将图片的大小调整为网络输入层的大小。
  • 归一化:将图片的像素值归一化到一定的范围内,通常是0 ~ 1之间。
  • 翻转:将图片左右或上下翻转。
  • 旋转:将图片旋转一定的角度。
  • 剪切:将图片裁剪为网络输入层的大小。
  • 扩充:在图片周围填充额外的像素。
  • 灰度化:将彩色图片转换为灰度图片。

这些预处理步骤可以通过PIL库,opencv库等图片处理库来实现。

此外, Tensorflow 也提供了一些预处理函数,例如:

  • tf.image.resize_images : 对图像进行缩放
  • tf.image.per_image_standardization : 对图像进行归一化
  • tf.image.random_flip_left_right : 对图像进行随机左右翻转
  • tf.image.random_rotation : 对图像进行随机旋转
  • tf.image.random_crop : 对图像进行随机剪切
  • tf.image.random_brightness : 对图像进行随机亮度调整

这些预处理函数可以帮助你更方便地处理图片数据,同时还能防止过拟合。

实际应用

对于大量的图片数据,我们可以使用 TensorFlow 的数据读取函数,如tf.data.Dataset,tf.keras.preprocessing.image_dataset_from_directory 来读取并预处理图片数据.

例如,我们可以使用tf.data.Dataset函数读取图片数据,并使用map函数进行预处理,例如:

import tensorflow as tf
# Create a dataset from the images
ds = tf.data.Dataset.from_tensor_slices(image_filenames)

# Define a function to preprocess the images
def preprocess_image(image):
    # Load the image and resize it
    image = tf.image.decode_jpeg(tf.read_file(image), channels=3)
    image = tf.image.resize_images(image, [256, 256])

    # Normalize the image
    image /= 255.0

    return image

# Apply the preprocessing function to the dataset
ds = ds.map(preprocess_image)

在上面的代码中,我们使用tf.data.Dataset.from_tensor_slices函数读取了图片文件名,并使用map函数将预处理函数应用到每一张图片上。

或者我们可以使用tf.keras.preprocessing.image_dataset_from_directory函数读取图片数据并进行预处理,例如:

# Create a dataset from the images
ds = tf.keras.preprocessing.image_dataset_from_directory(
    "path/to/images",
    image_size=(256, 256),
    batch_size=32,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_data_format="channels_last",
    label_mode="categorical"
)

在上面的代码中,我们使用tf.keras.preprocessing.image_dataset_from_directory读取了一个文件夹中的图片。

猜你喜欢

转载自blog.csdn.net/weixin_42043935/article/details/128719085