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

  • 图像编码处理
    将图像转为一个三维矩阵,并使用三维矩阵形成一个图像:
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)
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值