【TensorFlow】图片预处理函数

Python版本:3.6
TensorFlow版本:1.12.0
Matplotlib版本:3.1.1

tf.gfile.FastGFile() 读取图像
tf.image.resize_images()图像大小调整
tf.image.resize_image_with_crop_or_pad()图像裁剪或填充
tf.image.central_crop()按比例调整图像
flipped = tf.image.flip_up_down(img_data):图像上下翻转
flipped = tf.image.flip_left_right(img_data):图像左右翻转
flipped = tf.image.transpose_image(img_data):图像对角翻转

1、tf.gfile.FastGFile()

功能:读取图片
tf.gfile.FastGFile(path,decodestyle)
path:图片所在路径(如:E:/album/corgi.jpeg)
decodestyle:图片的解码方式。(‘r’:UTF-8编码; ‘rb’:非UTF-8编码)
代码1

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    plt.imshow(img_data.eval())
    plt.show

读取的图片类型为jpeg,如果读取的图片类型为png,可以使用img_data = tf.image.decode_png(img_raw_data)进行解码。

如果代码1无法显示图像,请尝试使用代码2。

代码2
matplotlib还提供了一个名为pylab的模块,其中包括了许多NumPypyplot模块中常用的函数,方便用户快速进行计算和绘图。

通过import pylab导入,并将代码1的plt.show()换成pylab.show()

import tensorflow as tf
import matplotlib.pyplot as plt
import pylab

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    plt.imshow(img_data.eval())
    pylab.show()

效果
在这里插入图片描述

2、tf.image.resize_images()

功能:调整图像大小
img_data_resize1 = tf.image.resize_images(img_data, [x, y], method=0)
img_data:原始图像(像素值在0.0-1.0范围内)
[x, y]:目标图像的大小
method=0:调整图像大小的算法

Mehod取值图像大小调整算法
0双线性插值法(Bilinear interpolation)
1最近邻居法(Nearest neighbor interpolation)
2双三次插值法(Bicubic interpolation)
3面积插值法(Area interpolation)

代码

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    plt.imshow(img_data.eval())
    plt.show()

    # 将0-255的像素值转化为0.0-1.0范围内的实数。
    img_data_float = tf.image.convert_image_dtype(img_data, dtype=tf.float32)
    img_data_resize = tf.image.resize_images(img_data_float, [300, 300], method=0)

    plt.imshow(img_data_resize.eval())
    plt.show()

效果
在这里插入图片描述

3、tf.resize_image_with_crop_or_pad()

功能:裁剪或填充图像,
tf.image.resize_image_with_crop_or_pad(img_data, x, y)
img_data:原始图像。
xy:目标图像的大小。

如果原始图像尺寸大于目标图像,那么函数会自动截取原始图像居中的部分;如果原始图像尺寸小于目标图像,那么函数会自动在原始图像的四周填充0背景。

代码

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    plt.imshow(img_data.eval())
    plt.show()

    croped = tf.image.resize_image_with_crop_or_pad(img_data, 300, 300)
    padded = tf.image.resize_image_with_crop_or_pad(img_data, 2000, 2000)

    plt.imshow(croped.eval())
    plt.show()
    plt.imshow(padded.eval())
    plt.show()

效果
在这里插入图片描述

4、tf.image.central_crop()

功能:按比例调整图像(基准点为图像中心)
central_cropped = tf.image.central_crop(img_data, alpha)
img_data:原始图像。
alpha:比例系数,取值范围 ( 0 , 1 ] (0,1] (0,1]

代码

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    central_cropped = tf.image.central_crop(img_data, 0.5)
    plt.imshow(central_cropped.eval())
    plt.show()

效果在这里插入图片描述

5、图像翻转

功能:图像翻转
flipped = tf.image.flip_up_down(img_data):图像上下翻转
flipped = tf.image.flip_left_right(img_data):图像左右翻转
flipped = tf.image.transpose_image(img_data):图像对角翻转

代码

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取图片
img_raw_data = tf.gfile.FastGFile("E:/album/corgi.jpeg", 'rb').read()

with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(img_raw_data)      # 图像解码
    print(img_data.eval())  # 打印解码后的图像,三维矩阵

    flipped_1 = tf.image.flip_up_down(img_data)  # 上下翻转
    flipped_2 = tf.image.flip_left_right(img_data)  # 左右翻转
    flipped_3 = tf.image.transpose_image(img_data)  # 对角线翻转

    fig = plt.figure()

    img = fig.add_subplot(221)
    plt.imshow(img_data.eval())

    img = fig.add_subplot(222)
    plt.imshow(flipped_1.eval())

    img = fig.add_subplot(223)
    plt.imshow(flipped_2.eval())

    img = fig.add_subplot(224)
    plt.imshow(flipped_3.eval())

    plt.show()

效果
在这里插入图片描述

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
TensorFlow提供了一个名为tf.Transform的库,用于数据预处理。tf.Transform允许用户使用TensorFlow来转换数据,结合各种数据处理框架,例如Apache Beam等。tf.Transform的主要目的是使数据预处理与模型训练分离,从而使数据预处理更加可重复和可扩展。 tf.Transform的工作流程如下: 1. 定义预处理函数:定义一个Python函数来执行数据预处理操作。 2. 将预处理函数转换为TensorFlow图:使用beam.Map将预处理函数转换为TensorFlow图。 3. 运行转换后的图:使用Apache Beam运行转换后的图,以生成预处理后的数据集。 以下是一个简单的示例,演示如何使用tf.Transform对数据进行预处理: ```python import tensorflow as tf import tensorflow_transform as tft import apache_beam as beam # 定义预处理函数 def preprocessing_fn(inputs): x = inputs['x'] y = inputs['y'] s = inputs['s'] x_centered = x - tft.mean(x) y_normalized = tft.scale_to_0_1(y) s_integerized = tft.compute_and_apply_vocabulary(s) return { 'x_centered': x_centered, 'y_normalized': y_normalized, 's_integerized': s_integerized } # 加载数据集 raw_data = [ {'x': 1, 'y': 2, 's': 'hello'}, {'x': 2, 'y': 3, 's': 'world'}, {'x': 3, 'y': 4, 's': 'hello'} ] raw_data_metadata = tft.tf_metadata.dataset_metadata.DatasetMetadata( tft.tf_metadata.schema_utils.schema_from_feature_spec({ 's': tf.io.FixedLenFeature([], tf.string), 'y': tf.io.FixedLenFeature([], tf.float32), 'x': tf.io.FixedLenFeature([], tf.float32), })) raw_data_metadata = tft.tf_metadata.dataset_metadata.DatasetMetadata( tft.tf_metadata.schema_utils.schema_from_feature_spec({ 's': tf.io.FixedLenFeature([], tf.string), 'y': tf.io.FixedLenFeature([], tf.float32), 'x': tf.io.FixedLenFeature([], tf.float32), })) # 将预处理函数转换为TensorFlow图 with beam.Pipeline() as pipeline: with tft_beam.Context(temp_dir=tempfile.mkdtemp()): coder = tft.coders.ExampleProtoCoder(raw_data_metadata.schema) examples = pipeline | 'CreateExamples' >> beam.Create(raw_data) | 'ToTFExample' >> beam.Map(coder.encode) # 使用tft_beam.AnalyzeAndTransformDataset将预处理函数转换为TensorFlow图 transformed_dataset, transform_fn = ( (examples, raw_data_metadata) | tft_beam.AnalyzeAndTransformDataset(preprocessing_fn)) transformed_data, transformed_metadata = transformed_dataset # 运行转换后的图 transformed_data | 'WriteData' >> beam.io.WriteToTFRecord(output_path) transform_fn | 'WriteTransformFn' >> tft_beam.WriteTransformFn(output_path) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

望天边星宿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值