图像存储--tf.image.decode_jpeg()//读取图像

我是正文

今天也是“白白”的一天,“抄写代码”的时候发现 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;

在这里插入图片描述

发现有趣的再来,未完待续。。。

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值