我是机器学习的新手,我有(可能是个愚蠢的)问题。当我在Keras中创建一个图像分类模型时
train = ImageDataGenerator().flow_from_directory(train_path, target_size = (128,128))test = ImageDataGenerator().flow_from_directory(test_path, target_size = (128,128))
model = Sequential()
num_classes = 131
model.add(Convolution2D(32, (3,3), activation = 'relu', padding='same', use_bias=False, input_shape=(128,128,3)))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Convolution2D(32, (3,3), activation = 'relu', padding='same', use_bias=False))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Convolution2D(64, (3,3), activation = 'relu', padding='same', use_bias=False))
model.add(MaxPool2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes,activation = 'softmax'))
model.summary()并将其转换为tflite
import tensorflow as tf
saved_model_dir = '~/'
tf.saved_model.save(model, saved_model_dir)
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()
with open('Fruits360ModelByKaggle.tflite', 'wb') as f:
f.write(tflite_model)
labels = '\n'.join(sorted(train.class_indices.keys()))
with open('labels.txt', 'w') as f:
f.write(labels)Android告诉我,模型所期望的输入是一个TensorBuffer。我使用了这些人的示例项目(Google Codelabs ),它识别花,它们的模型期望输入一个TensorImage。因此,我尝试在这个项目中使用自己的模型,并将位图转换为TensorBuffer,但失败了。
val tfImage = toBitmap(imageProxy)
val byteBuffer: ByteBuffer = ByteBuffer.allocate(224*224*3)
byteBuffer.rewind()
if (tfImage != null) {
tfImage.copyPixelsToBuffer(byteBuffer)
}
val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 224, 224, 3), DataType.FLOAT32)
inputFeature0.loadBuffer(byteBuffer)
results
val outputs = myModel.process(inputFeature0)是否有一种方法可以在Keras中创建一个模型,该模型接受TensorImage作为输入,并且有人可以帮助我这样做。我会很感激的。非常感谢!
发布于 2020-12-17 20:08:40
是否有一种方法可以在Keras中创建一个模型,该模型接受TensorImage作为输入,并且有人可以帮助我这样做。
不你不能但你也不需要。TFLite是经过优化的模型转换,可以与桌面/服务器以外的HW一起工作,并且它有一些特定的方法,可以通过字节缓冲区来使用延迟较低的数据。TensorImage和TensorBuffer是轻石支撑库的包装器,可以为您提供简单的后处理工具,以实现更简单的数据输入。
您提供的代码将数据从摄像机转换为所需大小的TensorImage。为了考虑您的模型输入大小(128,128,3),您的代码应该以下一种方式进行编辑:
val tfImage = toBitmap(imageProxy)
val byteBuffer: ByteBuffer = ByteBuffer.allocate(128*128*3)
byteBuffer.rewind()
if (tfImage != null) {
tfImage.copyPixelsToBuffer(byteBuffer)
}
val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 128, 128, 3), DataType.FLOAT32)
inputFeature0.loadBuffer(byteBuffer)
results
val outputs = myModel.process(inputFeature0)还要检查输出是如何处理的。
UPD:分类模型以输入图像为输入,并返回猜测类(和分数)。这些数据需要使用其他类型的容器和TensorBuffer。查看myModel内部并检查process方法返回的内容。它有可能返回TensorBuffer,您需要读取/后置处理它,或者只是类/得分/其他东西。
https://stackoverflow.com/questions/65342105
复制相似问题