如何使用Keras OCR示例推断新图像?

问题描述 投票:0回答:1

我正在尝试通过Keras实施OCR项目。所以我尝试向Keras OCR example学习。我使用自己的列车数据来训练新模型并获得.H5模式。现在我想测试一个新图像以查看我的模型性能,所以我编写了一个test.py,如下所示:

from keras.models import Model
import cv2
from keras.preprocessing.image import img_to_array
import numpy as np
from keras.models import load_model
from keras import backend as K
from allNumList import alphabet

def labels_to_text(labels):
    ret = []
    for c in labels:
        if c == len(alphabet):  # CTC Blank
            ret.append("")
        else:
            ret.append(alphabet[c])
    return "".join(ret)

def decode_predict_ctc(out, top_paths = 1):
    results = []
    beam_width = 5
    if beam_width < top_paths:
      beam_width = top_paths
    for i in range(top_paths):
      lables = K.get_value(K.ctc_decode(out, input_length=np.ones(out.shape[0])*out.shape[1],
                           greedy=False, beam_width=beam_width, top_paths=top_paths)[0][i])[0]
      text = labels_to_text(lables)
      results.append(text)
    return results

def test(modelPath,testPicTest):
    img=cv2.imread(testPicTest)
    img=cv2.resize(img,(128,64))
    img=img_to_array(img)
    img=np.array(img,dtype='float')/255.0
    img=np.expand_dims(img, axis=0)
    img=img.swapaxes(1,2)   

    model=load_model(modelPath,custom_objects = {'<lambda>': lambda y_true, y_pred: y_pred})
    net_out_value = model.predict(img)
    top_pred_texts = decode_predict_ctc(net_out_value)
    return top_pred_texts

result=test(r'D:\code\testAndExperiment\py\KerasOcr\weights.h5',r'D:\code\testAndExperiment\py\KerasOcr\test\avo.jpg') 
print(result)  

但我收到这样的错误:

Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 4 array(s), but instead got the following list of 1 arrays: [array([[[[1., 1., 1.],          [1., 1., 1.],          [1., 1., 1.],          ...,          [1., 1., 1.],          [1., 1., 1.],          [1., 1., 1.]],          [[1., 1., 1.],          [1., 1., 1.],...

我参考了一些材料: https://stackoverflow.com/a/49537697/10689350 https://www.dlology.com/blog/how-to-train-a-keras-model-to-recognize-variable-length-text/ How to predict the results for OCR using keras image_ocr example?

一些答案显示我们应该在训练中使用4个输入[input_data, labels, input_length, label_length],但除了input_data之外,其他所有信息仅用于计算损失,因此在测试中可能使用input_data就足够了。所以我只使用没有labels, input_length, label_length的图片。但是我得到了上面的错误。

我很困惑,如果模型需要4个输入或1个测试? 在测试过程中需要4个输入似乎不合理。现在我有model.h5,我接下来该怎么办? 提前致谢。

我的代码在这里:https://github.com/hqabcxyxz/KerasOCR/tree/master

python tensorflow keras ocr rnn
1个回答
0
投票

也许我知道为什么。因为在OCR示例中,我们制作一个lambda层来计算CTC损失。这个层需要4个输入!正确的测试方法是在推理过程中创建一个没有这个lambda层的模型。然后按名称加载模型权重进行推理。得到推理结果后,只需使用CTC解码即可!我稍后会在github中更新我的代码.....

© www.soinside.com 2019 - 2024. All rights reserved.