我是正文
今天也是“白白”的一天,“抄写代码”的时候发现 tf.image.decode_jpeg()。
反手一个搜索,结果发现了惊天大秘密!
原来我们日常双击打开的图片是被记录的压缩编码之后的结果,解码之后的三维矩阵才是图像本身。喵~和我认知刚好相反捏?
import matplotlib.pyplot as plt
import tensorflow as tf
image_raw_data = tf.io.gfile.GFile('./test.png', 'rb').read()
with tf.compat.v1.Session() as sess:
image_data = tf.image.decode_jpeg(image_raw_data)
# Decode a JPEG-encoded image to a uint8 tensor 所以这里的 image_data 已经是一个tsnsor
#print(image_data.eval())
print(image_data.eval().shape)
plt.imshow(image_data.eval())
plt.show()
img_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)
# 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件中。打开这张图像就可以得到和原始图像一样的图像
encoded_image = tf.image.encode_jpeg(image_data)
with tf.io.gfile.GFile('./image_arr.jpg', 'wb') as f:
f.write(encoded_image.eval())
输出如下:
对的这个小可爱其实是个矩阵,平时保存的.png.ipg.jpeg 都是编码之后的。
突然有种万物皆数字的感觉,代码里的世界才是真实的,而现实世界是程序员们构造的梦境hhh~
下面康康读取图像的几种方法:
前两种:
import matplotlib.pyplot as plt
import tensorflow as tf
with tf.compat.v1.Session() as sess:
# x = tf.io.gfile.GFile('./test.png', 'rb').read() # bytes
# x = tf.image.decode_png(x) # tensor
# plt.imshow(x.eval()) # numpy.ndarray
# plt.show()
x=tf.io.read_file('./test.png') # tensor
x=tf.image.decode_png(x) # tensor
plt.imshow(x.eval())
plt.show()
第三种:
import matplotlib.pyplot as plt
import cv2
x = cv2.imread('./test.png') # numpy.ndarray
x = cv2.cvtColor(x,cv2.COLOR_BGR2RGB) # numpy.ndarray
plt.imshow(x)
plt.show()
tf.io.gfile.GFile 读出来的是 bytes;
tf.io.read_file 读出来的是 tensor;
cv2.imread 读出来的是 numpy.ndarray;
发现有趣的再来,未完待续。。。