上接:https://www.malaoshi.top/show_1EF51UeOXjdv.html
测试模型
- test_ds2执行了
batch(),所以执行take(1),返回的是一批数据,并不是1个数据 - 由于返回一批数据,所以模型执行
predict()返回的是list,list中是这一批数据的结果 - 结果的形状是
(224, 224, 3),因为模型的输出分3类(softmax),所以结果最后一个维度是3,最后一个维度是这3个分类的概率,其和为1 - png图片的形状是(224, 224, 1),要显示成图,需要转成2维
for jpg,png in test_ds2.take(1):
prd=model2.predict(jpg)
# print(len(prd))
# print(prd[0].shape)
# print(prd[0])
for i in range(2):
print("prd[i].shape:",prd[i].shape)
prd_arr=tf.argmax(prd[i],axis=2)
print("prd_arr.shape:",prd_arr.shape)
print("jpg[i].shape:",jpg[i].shape)
print("png[i].shape:",png[i].shape)
plt.imshow(jpg[i].numpy())
plt.show()
plt.imshow(np.squeeze(png[i].numpy()))
# plt.imshow(tf.keras.preprocessing.image.array_to_img(png[i]))
plt.show()
plt.imshow(prd_arr)
plt.show()
执行结果:
prd[i].shape: (224, 224, 3)
prd_arr.shape: (224, 224)
jpg[i].shape: (224, 224, 3)
png[i].shape: (224, 224, 1)
测试其他图片
代码如下
导包
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from collections import Counter
定义常量
img_width=224
img_path="/Users/mym/Desktop/python/fcn32_vgg16/3.jpg"
h5_path="/Users/mym/Desktop/python/fcn32_vgg16/fcn8s_vgg16_me.h5"
定义函数
def read_img(path):
f=tf.io.read_file(path)
img=tf.image.decode_jpeg(f)
img=tf.image.resize(img,(img_width,img_width))
img=img/255
img=tf.expand_dims(img,0)
return img
def show(img):
print(type(img),"----",img.shape)
print(np.min(img),np.max(img))
img=tf.squeeze(img)
img=tf.math.argmax(img,axis=2)
# print(Counter(img.numpy().flatten()))
# img=tf.expand_dims(img,2)
# print(type(img),"----",img.shape,"---",img.dtype)
# img=tf.cast(img,dtype=tf.uint8)
# o_img=img.numpy()
# print(type(img),"----",img.shape)
# img=tf.image.encode_jpeg(img)
# tf.io.write_file(path,img)
# # print(img.numpy())
# print(o_img.dtype,o_img.shape)
# print(o_img)
# print(np.min(o_img),np.max(o_img))
plt.imshow(img)
执行
img=read_img(img_path)
print("img.shape:",img.shape)
model=tf.keras.models.load_model(h5_path)
# print(model.summary())
prd=model.predict(img)
print("prd.shape:",prd.shape)
show(prd)






