tensorflow读取图片、灰度化、显示图片

读取图片

import tensorflow as tf

#读取图片
img = tf.io.read_file("如何使用vscode.png")
#解码
img_data = tf.io.decode_jpeg(img, channels=3)


# 显示图片
from PIL import Image
Image.fromarray(img_data.numpy())

灰度化

import tensorflow as tf

#读取图片
img = tf.io.read_file("a.png")
#解码
img_data = tf.io.decode_jpeg(img, channels=3)

# 灰度化
img_data_gray = tf.image.rgb_to_grayscale(img_data) 
# 将(h,w,1)降维到(h,w)
img_data_gray=tf.squeeze(img_data_gray)

# 显示图片
from PIL import Image
Image.fromarray(img_data_gray.numpy())