在过去的几个小时里,我在互联网上寻找答案,了解如何将单个 jpeg 图像传递到我的预训练模型(保存和加载)并接收字符串格式的预测。
我正在使用此来源的验证码 OCR - https://keras.io/examples/vision/captcha_ocr/
下面这两种方法让我走得最远(我认为),但它们仍然不起作用:
方法 1:
model = load_model('trained_models/my_trained_model.h5', custom_objects={'CTCLayer': CTCLayer})
img_path = '/test/my_image.jpeg'
img = image.load_img(img_path, target_size=(200, 50))
img_array = image.img_to_array(img)
img_batch = np.expand_dims(img_array, axis=0)
img_preprocessed = preprocess_input(img_batch)
prediction = model.predict(img_preprocessed)
通过这种方法,我没有将图像转换为灰度,但在它造成任何麻烦之前,我收到了此错误:
ValueError: Layer ocr_model_v1 expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 200, 50, 3) dtype=float32>]
方法 2: 这种方法几乎是从 OCR 模型的数据预处理中复制而来的:
img = tf.io.read_file(img_path)
img = tf.io.decode_jpeg(img, channels=1)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, [200, 50])
img_preprocessed = tf.transpose(img, perm=[1, 0, 2])
prediction = model.predict(img_preprocessed)
它给了我几乎同样的错误:
ValueError: Layer ocr_model_v1 expects 2 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 200, 1) dtype=float32>]
但是这次看起来图像也变形了。
我认为这个错误是由 OCR 中的这一行引起的:
# Define the model
model = keras.models.Model(
inputs=[input_img, labels], outputs=output, name="ocr_model_v1"
)
由于模型需要两个值(在训练时,我们传递带有图像和图像名称的字典(验证码的答案))。但现在,我希望这个模型能够实际预测图像,所以我无法传递答案/标签。
几个小时后,我能够将其推进到这一刻,但现在我已经没有想法了。
有人可以指出我正确的方向吗?
/// ---------- /// 编辑 /// ---------- ///
嗨!我想编辑我的问题。与此同时,我能够将 jpeg 传递到这个模型中,但方式不太干净。我基本上复制了本教程最低部分的所有代码 - https://keras.io/examples/vision/captcha_ocr/
感谢我没有收到任何错误,但确实有很多代码看起来多余,但我无法有效地重构它。
更改此代码后:
prediction_model = keras.models.Model(
trained_model.get_layer(name="image").input, trained_model.get_layer(name="dense2").output
)
现在我收到有关错误形状等的错误。是否可以以某种方式重构本教程“推理”部分中的代码?
从最后一个代码片段开始,“由于模型需要两个值(在训练时,我们传递带有图像和图像名称的字典(验证码的答案))。但是现在,我希望这个模型能够实际预测图像,所以我无法传递答案/标签。”您已发表的声明。
您正在尝试训练一个输出验证码图像标签的模型。因此,您的模型必须是多类分类模型(如果图像标签数量有限)或图像相似性搜索字典学习方法(如果类别数量非常多)。但是,在这两种模型架构下,您的数据集格式必须采用 {X :验证码图像,y :相关图像标签}。
model = keras.model.fit(inputs=input_img, outputs=labels)
model = keras.model.fit(data=img_preprocessed)
提取层直到输出层得到预测模型:
`prediction_model = keras.models.Model( model.input[0], model.get_layer(name="dense2").output )
prediction_model.save(“model.keras”)
`