我不明白为什么下面的代码会给出不同的结果。我正在打印预测数组的前3个组件以比较结果。my_features
和feat
的结果完全不同,但在模型和数据相同的情况下,它们应该是相同的。加载和图像预处理应该有问题,但我找不到。任何帮助都将不胜感激。
import tensorflow as tf
import os
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications import MobileNetV3Small
from tensorflow.keras.applications.imagenet_utils import preprocess_input
model= MobileNetV3Small(weights='imagenet', include_top=False, pooling='avg')
DatasetPath= "DB"
imagePathList= sorted(os.listdir(DatasetPath))
imagePathList= [os.path.join(DatasetPath, imagePath) for imagePath in imagePathList]
def read_image(filename):
image_string = tf.io.read_file(filename)
image = tf.image.decode_jpeg(image_string, channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)
image = tf.image.resize(image, [224,224])
image = tf.keras.applications.mobilenet_v3.preprocess_input(image)
return image
ds_imagePathList= tf.data.Dataset.from_tensor_slices(imagePathList)
dataset = ds_imagePathList.map(read_image, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.batch(32, drop_remainder=False)
dataset = dataset.prefetch(tf.data.AUTOTUNE)
my_features = model.predict(dataset)
my_features[0][:3]
第二段
def loadProcessedImage(path):
#img = image.load_img(path, target_size=model.input_shape[1:3])
img = image.load_img(path, target_size= (224,224,3))
imgP = image.img_to_array(img)
imgP = np.expand_dims(imgP, axis=0)
imgP = preprocess_input(imgP)
return img, imgP
img, x = loadProcessedImage(imagePathList[0])
feat = model.predict(x)
feat = feat.flatten()
feat[:3]
问题与图像大小调整有关。在第二个片段中,有一个对load_img
的调用,它在内部使用pillow
来加载图像并调整图像大小。问题是tf.image.resize
不正确,看这里,即使这是一篇2018年的博客文章,问题仍然存在