import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# 使用'r'会出错,无法解码,只能以2进制形式读取
# img_raw = tf.gfile.FastGFile('E:\\myresource\\moutance.jpg','rb').read()
img_raw = open('E:\\myresource\\moutance.jpg','rb').read()

# 把二进制文件解码为uint8
img_0 = tf.image.decode_png(img_raw)
# 可以用np直接转换了
# img_1 = tf.image.convert_image_dtype(img_0,dtype=tf.uint8)

sess = tf.Session()
print(sess.run(img_0).shape)
plt.imshow(sess.run(img_0))
plt.show()

def show_pho(img,sess=sess):
    '''
    TF处理过的图片自动转换了类型,需要调整回uint8才能正常显示
    :param sess: 
    :param img: 
    :return: 
    '''
    moutance = np.asarray(sess.run(img),dtype='uint8')
    print(moutance.shape)
    plt.imshow(moutance)
    plt.show()

'''调整图像大小'''
# 插值尽量保存原图信息
img_1 = tf.image.resize_images(img_0,[500,500],method=3)
show_pho(img_1)

# 裁剪或填充
# 自动中央截取
img_2 = tf.image.resize_image_with_crop_or_pad(img_0,500,500)
show_pho(img_2)

# 比例中央裁剪
img_4 = tf.image.central_crop(img_0,0.5)
show_pho(img_4)