Mathematica 中的以下原型查找文本块的坐标并在每个块内执行 OCR。您可能需要调整参数值以适合实际图像的尺寸。我不讨论问题的机器学习部分;也许您甚至不需要此应用程序。
导入图片,为打印部分创建二进制蒙版,并使用水平闭合(膨胀和腐蚀)放大这些部分。
查询每个斑点的方向,对方向进行聚类,并通过对最大聚类的方向进行平均来确定整体旋转。
使用之前的角度来拉直图像。此时 OCR 是可能的,但您会丢失文本块的空间信息,这将使后处理比需要的困难得多。相反,通过水平闭合来查找文本块。
对于每个连接的组件,查询边界框位置和质心位置。使用边界框位置提取相应的图像块并对块执行 OCR。
此时,您已经有了字符串及其空间位置的列表。这还不是 XML,但听起来像是一个很好的起点,可以直接根据您的需求进行定制。
这是代码。同样,形态函数的参数(结构元素)可能需要根据实际图像的比例进行更改;此外,如果发票太倾斜,您可能需要大致“旋转”结构元素,以便仍然实现良好的“不倾斜”。
img = ColorConvert[Import@"http://www.team-bhp.com/forum/attachments/test-drives-initial-ownership-reports/490952d1296308008-laura-tsi-initial-ownership-experience-img023.jpg", "Grayscale"];
b = ColorNegate@Binarize[img];
mask = Closing[b, BoxMatrix[{2, 20}]]
orientations = ComponentMeasurements[mask, "Orientation"];
angles = FindClusters@orientations[[All, 2]]
\[Theta] = Mean[angles[[1]]]
straight = ColorNegate@Binarize[ImageRotate[img, \[Pi] - \[Theta], Background -> 1]]
TextRecognize[straight]
boxes = Closing[straight, BoxMatrix[{1, 20}]]
comp = MorphologicalComponents[boxes];
measurements = ComponentMeasurements[{comp, straight}, {"BoundingBox", "Centroid"}];
texts = TextRecognize@ImageTrim[straight, #] & /@ measurements[[All, 2, 1]];
Cases[Thread[measurements[[All, 2, 2]] -> texts], (_ -> t_) /; StringLength[t] > 0] // TableForm