How can I use the Keras OCR example? How can I use the Keras OCR example? python python

How can I use the Keras OCR example?


Well, I will try to answer everything you asked here:

As commented in the OCR code, Keras doesn't support losses with multiple parameters, so it calculated the NN loss in a lambda layer. What does this mean in this case?

The neural network may look confusing because it is using 4 inputs ([input_data, labels, input_length, label_length]) and loss_out as output. Besides input_data, everything else is information used only for calculating the loss, it means it is only used for training. We desire something like in line 468 of the original code:

Model(inputs=input_data, outputs=y_pred).summary()

which means "I have an image as input, please tell me what is written here". So how to achieve it?

1) Keep the original training code as it is, do the training normally;

2) After training, save this model Model(inputs=input_data, outputs=y_pred)in a .h5 file to be loaded wherever you want;

3) Do the prediction: if you take a look at the code, the input image is inverted and translated, so you can use this code to make it easy:

from scipy.misc import imread, imresize#use width and height from your neural network here.def load_for_nn(img_file):    image = imread(img_file, flatten=True)    image = imresize(image,(height, width))    image = image.T    images = np.ones((1,width,height)) #change 1 to any number of images you want to predict, here I just want to predict one    images[0] = image    images = images[:,:,:,np.newaxis]    images /= 255    return images

With the image loaded, let's do the prediction:

def predict_image(image_path): #insert the path of your image     image = load_for_nn(image_path) #load from the snippet code    raw_word = model.predict(image) #do the prediction with the neural network    final_word = decode_output(raw_word)[0] #the output of our neural network is only numbers. Use decode_output from image_ocr.py to get the desirable string.    return final_word

This should be enough. From my experience, the images used in the training are not good enough to make good predictions, I will release a code using other datasets that improved my results later if necessary.

Answering related questions:

It is a technique used to improve sequence classification. The original paper proves it improves results on discovering what is said in audio. In this case it is a sequence of characters. The explanation is a bit trick but you can find a good one here.

  • Are there algorithms which reliably detect the rotation of a document?

I am not sure but you could take a look at Attention mechanism in neural networks. I don't have any good link now but I know it could be the case.

  • Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

OpenCV implements Maximally Stable Extremal Regions (known as MSER). I really like the results of this algorithm, it is fast and was good enough for me when I needed.

As I said before, I will release a code soon. I will edit the question with the repository when I do, but I believe the information here is enough to get the example running.


Here, you created a model that needs 4 inputs:

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

Your predict attempt, on the other hand, is loading just an image.
Hence the message: The model expects 4 arrays, but only received one array

From your code, the necessary inputs are:

input_data = Input(name='the_input', shape=input_shape, dtype='float32')labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len],dtype='float32')input_length = Input(name='input_length', shape=[1], dtype='int64')label_length = Input(name='label_length', shape=[1], dtype='int64')

The original code and your training work because they're using the TextImageGenerator. This generator cares to give you the four necessary inputs for the model.

So, what you have to do is to predict using the generator. As you have the fit_generator() method for training with the generator, you also have the predict_generator() method for predicting with the generator.


Now, for a complete answer and solution, I'd have to study your generator and see how it works (which would take me some time). But now you know what is to be done, you can probably figure it out.

You can either use the generator as it is, and predict probably a huge lot of data, or you can try to replicate a generator that will yield just one or a few images with the necessary labels, length and label length.

Or maybe, if possible, just create the 3 remaining arrays manually, but making sure they have the same shapes (except for the first, which is the batch size) as the generator outputs.

The one thing you must assert, though, is: have 4 arrays with the same shapes as the generator outputs, except for the first dimension.


Now I have a model.h5. What's next?

First I should comment that the model.h5 contains the weights of your network, if you wish to save the architecture of your network as well you should save it as a json like this example:

model_json = model_json = model.to_json()with open("model_arch.json", "w") as json_file:    json_file.write(model_json)

Now, once you have your model and its weights you can load them on demand by doing the following:

json_file = open('model_arch.json', 'r')loaded_model_json = json_file.read()json_file.close()loaded_model = model_from_json(loaded_model_json)# load weights into new model# if you already have a loaded model and dont need to save start from hereloaded_model.load_weights("model.h5")    # compile loaded model with certain specificationssgd = SGD(lr=0.01)loaded_model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"])

Then, with that loaded_module you can proceed to predict the classification of certain input like this:

prediction = loaded_model.predict(some_input, batch_size=20, verbose=0)

Which will return the classification of that input.

About the Side Questions:

  1. CTC seems to be a term they are defining in the paper you refered, extracting from it says:

In what follows, we refer to the task of labelling un- segmented data sequences as temporal classification (Kadous, 2002), and to our use of RNNs for this pur- pose as connectionist temporal classification (CTC).

  1. To compensate the rotation of a document, images, or similar you could either generate more data from your current one by applying such transformations (take a look at this blog post that explains a way to do that ), or you could use a Convolutional Neural Network approach, which also is actually what that Keras example you are using does, as we can see from that git:

This example uses a convolutional stack followed by a recurrent stack and a CTC logloss function to perform optical character recognition of generated text images.

You can check this tutorial that is related to what you are doing and where they also explain more about Convolutional Neural Networks.

  1. Well this one is a broad question but to detect lines you could use the Hough Line Transform, or also Canny Edge Detection could be good options.

Edit: The error you are getting is because it is expected more parameters instead of 1, from the keras docs we can see:

predict(self, x, batch_size=32, verbose=0)

Raises ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.