TensorFlow图像处理函数

python学习网 2019-01-21 13:27:04

参考书

《TensorFlow:实战Google深度学习框架》(第2版)

1. 图像编码处理

用TensorFlow对jpeg格式图像进行编码/解码。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# coding=utf-8 

"""
@author: Li Tian
@contact: 694317828@qq.com
@software: pycharm
@file: figure_deal_test1.py
@time: 2019/1/21 10:06
@desc: 用TensorFlow对jpeg格式图像进行编码/解码
"""

# matplotlib.puplot是一个python的画图工具。在这一节中使用这个工具来可视化经过TensorFlow处理的图像。
import matplotlib.pyplot as plt
import tensorflow as tf

# 读取图像的原始数据。
image_raw_data = tf.gfile.FastGFile('C:/Users/Administrator/Desktop/Python3Space/figuredata_deal/krystal.jpg', 'rb').read()

with tf.Session() as sess:
    # 对图像进行jpeg的格式解码从而得到图相对应的三维矩阵。TensorFlow还提供了tf.image.decode_png函数对png格式的图像进行解码。
    # 解码之后的结果为一个张量,在使用它的取值之前需要明确调用运行的过程。
    img_data = tf.image.decode_jpeg(image_raw_data)

    print(img_data.eval())

    # 使用pyplot工具可视化得到的图像。
    plt.imshow(img_data.eval())
    plt.show()

    # 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件中,打开这张图像,可以得到和原始图像一样的图像。
    encoded_image = tf.image.encode_jpeg(img_data)
    with tf.gfile.GFile('C:/Users/Administrator/Desktop/Python3Space/figuredata_deal/output', 'wb') as f:
        f.write(encoded_image.eval())

输出结果:

阅读(2713) 评论(0)