【发布时间】:2017-12-04 11:19:42
【问题描述】:
我发现examples/image_ocr.py 似乎适用于 OCR。因此,应该可以给模型一个图像并接收文本。但是,我不知道该怎么做。如何为模型提供新图像?需要哪种预处理?
我做了什么
安装依赖:
- 安装
cairocffi:sudo apt-get install python-cairocffi - 安装
editdistance:sudo -H pip install editdistance - 更改
train以返回模型并保存训练好的模型。 - 运行脚本来训练模型。
现在我有一个model.h5。下一步是什么?
请参阅https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras 了解我当前的代码。我知道如何加载模型(见下文),这似乎有效。问题是我不知道如何将带有文本的新图像扫描提供给模型。
相关问题
- 什么是 CTC? Connectionist Temporal Classification?
- 是否有可靠检测文档旋转的算法?
- 是否有算法可以可靠地检测行/文本块/表格/图像(从而进行合理的分割)?我猜边缘检测与平滑和逐行直方图的效果已经相当不错了?
我尝试了什么
#!/usr/bin/env python
from keras import backend as K
import keras
from keras.models import load_model
import os
from image_ocr import ctc_lambda_func, create_model, TextImageGenerator
from keras.layers import Lambda
from keras.utils.data_utils import get_file
import scipy.ndimage
import numpy
img_h = 64
img_w = 512
pool_size = 2
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))
if K.image_data_format() == 'channels_first':
input_shape = (1, img_w, img_h)
else:
input_shape = (img_w, img_h, 1)
fdir = os.path.dirname(get_file('wordlists.tgz',
origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))
img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
minibatch_size=32,
img_w=img_w,
img_h=img_h,
downsample_factor=(pool_size ** 2),
val_split=words_per_epoch - val_words
)
print("Input shape: {}".format(input_shape))
model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)
model.load_weights("my_model.h5")
x = scipy.ndimage.imread('example.png', mode='L').transpose()
x = x.reshape(x.shape + (1,))
# Does not work
print(model.predict(x))
这给了
2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
File "eval_example.py", line 45, in <module>
print(model.predict(x))
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict
check_batch_axis=False)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data
'Found: array with shape ' + str(data.shape))
ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1)
【问题讨论】:
-
使用第478行定义的函数怎么样?您可以将其用作
prediction = test_func(input_data)。让我知道它是否有帮助,我可以添加一个正式的答案来创建它。您也可以使用model.predict,因为它仅用于此目的。 -
我看到你刚刚编辑了这个问题。我将发布我目前正在写的一篇,我们可以在之后发表评论
-
@MartinThoma 好的,我发布了一个答案,详细解释了您可以做什么。还有如何正确获取输入的分类
-
@MartinThoma 编辑了有关您遇到的异常的问题...我想知道为什么要投反对票,因为它是一个彻底的答案
-
@devilinthedetail 不错!我认为这可能是要走的路。至少我从后面得到了一个形状为
(1, 128, 28)的矩阵。开放的问题仍然是(1)图像可以有多大的尺寸? (2) 如果我有一份扫描文件(例如 2000 像素 x 1000 像素),如何应用? (3) 模型给我的每个维度到底代表什么?我如何从中得到最可能的图像内容假设?