今天学到tensorflow图像数据处理,所以写个笔记。
1 首先是导入库
-
import matplotlib.pyplot
as plt
-
import tensorflow
as tf
-
import numpy
as np
2 读取图片
-
image_raw_data = tf.gfile.FastGFile(
'../datasets/cat.jpg',
'rb').read()
-
-
with tf.Session()
as sess:
-
img_data = tf.image.decode_jpeg(image_raw_data)
-
-
# 输出解码之后的三维矩阵。
-
print (img_data.eval())
-
img_data.set_shape([
1797,
2673,
3])
-
print (img_data.get_shape())
用的python3。读的是一个猫的图片其shape是(1797, 2673, 3)。
3 打印图片
-
with tf.Session()
as sess:
-
plt.imshow(img_data.eval())
-
plt.show()
4 调整图像大小
-
with tf.Session()
as sess:
-
resized = tf.image.resize_images(img_data, [
300,
300], method=
0)
-
-
# TensorFlow的函数处理图片后存储的数据是float32格式的,需要转换成uint8才能正确打印图片。
-
print (
"Digital type: ", resized.dtype)
-
cat = np.asarray(resized.eval(), dtype=
'uint8')
-
# tf.image.convert_image_dtype(rgb_image, tf.float32)
-
plt.imshow(cat)
-
plt.show()
其核心是tf.image.resize_images函数。通过上面程序,图片被调整成为300×300的。tf.image.resize_images函数的method参数取值对应不同的图像大小调整算法,如下表
|