TensorFlow中对图像的处理

日常处理中RGB色彩模式的图片可以看做是一个三维矩阵,矩阵中每个数代表了图像上的额不同位置,不同颜色的亮度。
神经网络中图像的大小不是规整的,因此处理图像以前,需要先把图像的大小统一。
图像大小的调整有两种方法:
1.使用算法进行调整。

tf.image.resize_images(data, shape, method=0,1,2,3)
    data: 图像数据
    shape: 图像的大小,这里指二维图片
    method: 处理方法 0-代表双线性插值法 1-最近邻居法
                    2-双三次插值法  3-面积插值法
# -*- coding: utf-8 -*-
__author__ = 'liudong'
__date__ = '2018/5/1 上午10:48'
import matplotlib.pyplot as plt
import tensorflow as tf
'''
TensorFLow中对图像的处理函数
'''

# 可以用 'rb',才可以达到预期的效果
image_raw_data = tf.gfile.FastGFile("../CNN/cat.jpg", 'rb').read()
with tf.Session() as sess:
    image_data = tf.image.decode_jpeg(image_raw_data)
    print(image_data.eval())

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

    # 将表示一张图像的三维矩阵重新按照jpeg格式编码并存入文件中 可以得到和原始图像一样的图像
    encoded_image = tf.image.encode_jpeg(image_data)
    with tf.gfile.GFile("../CNN/cat.jpeg", "wb") as f:
        f.write(encoded_image.eval())
    # 对原始图像数据进行初始化,数据处理为规范统一的类型
    image_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)
    resized = tf.image.resize_images(image_data, [300, 300], method=3)
    # method  0:双线性插值法 1:最近邻居法 2:双三次插值法 3:面积插值法
    plt.imshow(resized.eval ())
    plt.show()

    # 对图像进行裁剪或者填充 第一个参数是数据源 后边的是图像的裁剪大小
    croped = tf.image.resize_image_with_crop_or_pad(image_data, 1000, 1000)
    padded = tf.image.resize_image_with_crop_or_pad (image_data, 3000, 3000)
    plt.imshow(croped.eval())
    plt.show()
    plt.imshow(padded.eval())
    plt.show()

输出解码后的三维矩阵

[[[162 162 138]
  [161 161 137]
  [160 160 136]
  ...
  [104 140  44]
  [103 139  43]
  [104 141  48]]

 [[162 162 138]
  [163 163 139]
  [162 162 138]
  ...
  [102 138  42]
  [102 137  43]
  [104 139  45]]

 [[163 163 139]
  [163 163 139]
  [164 164 140]
  ...
  [102 136  42]
  [102 136  42]
  [106 140  46]]

 ...

 [[205 200 180]
  [204 199 179]
  [204 199 179]
  ...
  [106  83  49]
  [105  82  48]
  [105  82  50]]

 [[206 201 181]
  [205 200 180]
  [204 199 179]
  ...
  [106  83  49]
  [105  82  48]
  [104  81  49]]

 [[205 200 180]
  [204 199 179]
  [204 199 179]
  ...
  [106  83  49]
  [104  81  47]
  [104  81  49]]]

初始的图片:

初始的图片

优化后的 method=3

这里写图片描述

放大后的(1000, 1000)

这里写图片描述

缩放为(3000,3000)

这里写图片描述

猜你喜欢

转载自blog.csdn.net/xiao2cai3niao/article/details/80155133