本文用于学习TensorFlow图像处理的基本用法,可用于数据增强!!!
#! -*- coding=UTF-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
# 读取图片
img = tf.gfile.FastGFile("plate.jpg",'rb').read()
# print(img)
# 建立会话
with tf.Session() as sess:
# 解码图像
img_decode = tf.image.decode_jpeg(img)
# print(img_decode.eval())
# # 保存图像,首先编码图像
# img_encode = tf.image.encode_jpeg(img_decode)
# # print(img_encode)
# with tf.gfile.GFile("new_plate.jpg",'wb') as file:
# file.write(img_encode.eval())
# 调整图片大小,首先将图像数据转化为实数类型,即归一化
img_decode_norm = tf.image.convert_image_dtype(img_decode, dtype=tf.float32)
img_resize = tf.image.resize_images(img_decode_norm, [100,200], method=0)
# print("调整后图像的维度:",img_resize.shape)
# 自动裁剪、自动填充图像大小
img_crop = tf.image.resize_image_with_crop_or_pad(img_decode, 100,100)
img_pad = tf.image.resize_image_with_crop_or_pad(img_decode,1000,1000)
# 比例调整图像大小
img_ratio = tf.image.central_crop(img_decode, 0.4)
# 图像翻转 上下、左右、对角线
img_up_down = tf.image.flip_up_down(img_decode)
img_left_right = tf.image.flip_left_right(img_decode)
img_transpose = tf.image.transpose_image(img_decode)
# 随机翻转图像 50概率
img_random_up_down = tf.image.random_flip_up_down(img_decode)
img_random_left_right = tf.image.random_flip_left_right(img_decode)
# 图像亮度调整,调整后为保证像素值在0-1或者0-255的范围内,需要截断操作
img_reduce_brightness = tf.image.adjust_brightness(img_decode_norm, -0.5)
img_add_brightness = tf.image.adjust_brightness(img_decode_norm, 0.5)
img_reduce_brightness = tf.clip_by_value(img_reduce_brightness, 0.0, 1.0)
# 图像对比度调整 按倍数增加或减少
img_reduce_contrast = tf.image.adjust_contrast(img_decode_norm, 0.5)
img_add_contrast = tf.image.adjust_contrast(img_decode_norm, 5)
# 图像色相调整
img_reduce_hue = tf.image.adjust_hue(img_decode_norm, 0.1)
img_add_hue = tf.image.adjust_hue(img_decode_norm, -0.1)
img_reduce_hue = tf.clip_by_value(img_reduce_hue, 0.0, 1.0)
# 图像饱和度调整
img_reduce_saturation = tf.image.adjust_saturation(img_decode_norm, -0.5)
img_add_saturation = tf.image.adjust_saturation(img_decode_norm, 0.5)
img_reduce_saturation = tf.clip_by_value(img_reduce_saturation, 0.0, 1.0)
# 图像标准化 将像素调整为均值为0,方差为1
img_norm = tf.image.per_image_standardization(img_decode_norm)
#可视化图像
plt.imshow(img_reduce_saturation.eval())
plt.show()
参考资料:
1. 《TensorFLow:实战Google深度学习框架》