您的位置:首页 > 其它

使用TensorFlow进行常用的图像处理-图像转为矩阵以及图像大小调整

2018-02-06 17:09 483 查看
图像编码处理

将图像转为一个三维矩阵,并使用三维矩阵形成一个图像:

import tensorflow as tf
import matplotlib.pyplot as plt

# 读取原始图像数据
image_raw_data = tf.gfile.FastGFile("/tensorflow_google/cat.jpg", 'rb').read()

with tf.Session() as sess:
# 将jpg图像转化为三维矩阵,若为png格式,可使用tf.image.decode_png
img_data = tf.image.decode_jpeg(image_raw_data)
# 输出解码之后的三维矩阵
# print(img_data.eval())
# 使用plt显示图像
# plt.imshow(img_data.eval())
# plt.show()

# 将数据的类型转化为实处方便处理
img_data = tf.image.convert_image_dtype(img_data, dtype=tf.uint8)

# 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件
encoded_image = tf.image.encode_jpeg(img_data)
with tf.gfile.GFile("/tensorflow_google/encoded.jpeg", 'wb') as f:
f.write(encoded_image.eval())


图像大小调整

将图像的大小统一,TensorFlow使用了四种不同的方法,并将它们封装到tf.image.resize_images函数中:

1)method = 0,使用双线性插值法

2)method = 1, 使用最近邻法

3)method = 2, 使用双三次插值法

4)method = 3, 使用面积插值法

以下为使用代码:

import tensorflow as tf

# 读取原始图像数据
image_raw_data = tf.gfile.FastGFile("/tensorflow_google/cat.jpg", 'rb').read()

with tf.Session() as sess:
# 将jpg图像转化为三维矩阵,若为png格式,可使用tf.image.decode_png
img_data = tf.image.decode_jpeg(image_raw_data)
img_data = tf.image.convert_image_dtype(img_data, dtype=tf.float32)
# 通过tf.image.resize_images调整图像大小,size中为调整后的格式,method为调整图像大小的算法
resized = tf.image.resize_images(img_data, size=[300, 300], method=0)

# 输出调整后图像的大小,深度没有设置,所以是?
print(resized.get_shape())

>>(300, 300, ?)


注意:若出现以下错误

TypeError: resize_images() got multiple values for argument ‘method’

则是因为使用了旧版resize_images函数,如下:

resized = tf.image.resize_images(img_data, 300, 300, method=0)


新版resize_images函数改为:

resized = tf.image.resize_images(img_data, size=[300, 300], method=0)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: