import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
img_path = r'C:\Users\Nolan\Desktop\py\TF2_0\Dogs\test\chihuahua\n02085620_9357.jpg'
# 读入图片
img = tf.io.read_file(img_path)
# 解码为tensor格式
img = tf.image.decode_jpeg(img)
print('shape:', img.shape, 'dtype:', img.dtype)
# 将图片转换问灰度图片,即最后一维只有1
img = tf.image.rgb_to_grayscale(img)
# 剪裁图片, 高度和宽度
img = tf.image.resize_with_crop_or_pad(img, 250, 151)
# 编码tensor
img = tf.image.encode_jpeg(img, quality= 100)
# 写入./221.jpg这个文件里面
with tf.io.gfile.GFile('./221.jpg', 'wb') as file:
file.write(img.numpy())
处理后的图片
原图