OpenCV数字合并到周围的框中

12
我有一些日期需要使用Tesseract识别。但是,很多日期中的数字与日期框中的线条混合在一起,如下所示:

Digits intersecting boxes Digits intersecting boxes Digits intersecting boxes Digits intersecting boxes


此外,这里有一张我可以成功使用Tesseract识别的好图片:

Good Date Image

这是我的代码:

import os
import cv2
from matplotlib import pyplot as plt
import subprocess
import numpy as np
from PIL import Image

def show(img):
    plt.figure(figsize=(20,20))
    plt.imshow(img,cmap='gray')
    plt.show()

def sort_contours(cnts, method="left-to-right"):
    # initialize the reverse flag and sort index
    reverse = False
    i = 0

    # handle if we need to sort in reverse
    if method == "right-to-left" or method == "bottom-to-top":
        reverse = True

    # handle if we are sorting against the y-coordinate rather than
    # the x-coordinate of the bounding box
    if method == "top-to-bottom" or method == "bottom-to-top":
        i = 1

    # construct the list of bounding boxes and sort them from top to
    # bottom
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]

    cnts, boundingBoxes = zip(*sorted(zip(cnts, boundingBoxes),
        key=lambda b:b[1][i], reverse=reverse))

    # return the list of sorted contours and bounding boxes
    return cnts, boundingBoxes


def tesseract_it(contours,main_img, label,delete_last_contour=False):
    min_limit, max_limit = (1300,1700)
    idx =0 
    roi_list = []
    slist= set()
    for cnt in contours:
        idx += 1
        x,y,w,h = cv2.boundingRect(cnt)
        if label=='boxes':
            roi=main_img[y+2:y+h-2,x+2:x+w-2]
        else:
            roi=main_img[y:y+h,x:x+w]

        if w*h > min_limit and w*h < max_limit and w>10 and w< 50 and h>10 and h<50:
            if (x,y,w,h) not in slist: # Stops from identifying repeted contours

                roi = cv2.resize(roi,dsize=(45,45),fx=0 ,fy=0, interpolation = cv2.INTER_AREA)
                roi_list.append(roi)
                slist.add((x,y,w,h))

    if not delete_last_contour:
        vis = np.concatenate((roi_list),1)
    else:
        roi_list.pop(-1)
        vis = np.concatenate((roi_list),1)

    show(vis)

    # Tesseract the final image here
    # ...


image = 'bad_digit/1.jpg'
# image = 'bad_digit/good.jpg'
specimen_orig = cv2.imread(image,0)


specimen = cv2.fastNlMeansDenoising(specimen_orig)
#     show(specimen)
kernel = np.ones((3,3), np.uint8)

# Now we erode
specimen = cv2.erode(specimen, kernel, iterations = 1)
#     show(specimen)
_, specimen = cv2.threshold(specimen, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
#     show(specimen)
specimen_canny = cv2.Canny(specimen, 0, 0)
#     show(specimen_canny)

specimen_blank_image = np.zeros((specimen.shape[0], specimen.shape[1], 3))
_,specimen_contours, retr = cv2.findContours(specimen_canny.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE )
# print(len(specimen_contours))
cv2.drawContours(specimen_blank_image, specimen_contours, -1, 100, 2)
#     show(specimen_blank_image)
specimen_blank_image = np.zeros((specimen.shape[0], specimen.shape[1], 3))

specimen_sorted_contours, specimen_bounding_box = sort_contours(specimen_contours)

output_string = tesseract_it(specimen_sorted_contours,specimen_orig,label='boxes',)
# return output_string

好的图像输出如下: Good output


然而,对于那些线条与数字融合在一起的情况,我的输出结果看起来像这样: bad1 bad2 bad3 bad4

这些对 Tesseract 来说并不起作用。 我想知道是否有一种方法可以去除线条并仅保留数字。

我也尝试了以下方法: https://docs.opencv.org/3.2.0/d1/dee/tutorial_moprh_lines_detection.html

但似乎在我附加的图像上表现不佳。

我还尝试使用 imagemagick:

convert original.jpg \
\( -clone 0 -threshold 50% -negate -statistic median 200x1 \)  \
-compose lighten -composite                                    \
\( -clone 0 -threshold 50% -negate -statistic median 1x200 \)  \
-composite output.jpg

结果还算公平,但是删除的线有点切断数字,如下所示:

imagemagick1 imagemagick2 imagemagick3 imagemagick4

我能不能用更好的方法解决这个问题?我的最终目标是扫描这些数字,所以最后的图像确实需要很清晰。


1
不,它们都是二进制的。黑白的。 - BoreBoar
我会避免使用tesseract,而选择MNIST。也许它的效果更好。 - lucians
2
看起来你的字体是一样的?如果是这种情况,对所有10个数字进行模板匹配。 - Zaw Lin
这是一个非常好的想法。但是,我仍然需要知道是否可以使用OpenCV甚至Imagemagick来进行此类图像清理工作。 - BoreBoar
好的,没问题 :) - BoreBoar
显示剩余7条评论
3个回答

12

这里有一些看起来相当不错的代码,包括两个阶段:

  • 我们可以观察到数字比方框略微粗体,并且整个图像具有较强的水平性。因此,我们可以在水平上应用更强的膨胀来消除大部分竖直线。
  • 此时,OCR(例如谷歌的)可以检测出大多数数字。不幸的是,它有点太好了,会看到其他东西,因此我添加了另一个与您特定上下文相关的更复杂的阶段。

以下是第一阶段后一个图像的结果:

输入图像描述

以下是第二阶段所有结果:

输入图像描述

正如您所看到的,这并不完美,8可能被视为B(嗯,即使像我这样的人也会将其视为B...但如果您的世界中只有数字,则可以轻松解决)。还有一个“:”字符(从已删除的竖直线中遗留下来),我也无法摆脱它,除非大幅调整代码...

C#代码:

static void Unbox(string inputFilePath, string outputFilePath)
{
    using (var orig = new Mat(inputFilePath))
    {
        using (var gray = orig.CvtColor(ColorConversionCodes.BGR2GRAY))
        {
            using (var dst = orig.EmptyClone())
            {
                // this is what I call the "horizontal shake" pass.
                // note I use the Rect shape here, this is important
                using (var dilate = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(4, 1)))
                {
                    Cv2.Dilate(gray, dst, dilate);
                }

                // erode just a bit to get back some numbers to life
                using (var erode = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(2, 1)))
                {
                    Cv2.Erode(dst, dst, erode);
                }

                // at this point, good OCR will see most numbers
                // but we want to remove surrounding artifacts

                // find countours
                using (var canny = dst.Canny(0, 400))
                {
                    var contours = canny.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);

                    // compute a bounding rect for all numbers w/o boxes and artifacts
                    // this is the tricky part where we try to discard what's not related exclusively to numbers
                    var boundingRect = Rect.Empty;
                    foreach (var contour in contours)
                    {
                        // discard some small and broken polygons
                        var polygon = Cv2.ApproxPolyDP(contour, 4, true);
                        if (polygon.Length < 3)
                            continue;

                        // we want only numbers, and boxes are approx 40px wide,
                        // so let's discard box-related polygons, if any
                        // and some other artifacts that passed previous checks
                        // this quite depends on some context knowledge...
                        var rect = Cv2.BoundingRect(polygon);
                        if (rect.Width > 40 || rect.Height < 15)
                            continue;

                        boundingRect = boundingRect.X == 0 ? rect : boundingRect.Union(rect);
                    }

                    using (var final = dst.Clone(boundingRect))
                    {
                        final.SaveImage(outputFilePath);
                    }
                }
            }
        }
    }
}

太棒了!非常感谢! :) 另外,您能告诉我如何提取位于顶部或底部水平线上的数字吗?例如在此类图片中:https://www.dropbox.com/s/o4swx5821v5qea7/4K1CDD61780143.jpg?dl=0 - BoreBoar
1
@MetalloyD - 嗯...这个情况比较难,即使对于人类来说也是如此。数字可能恰好匹配水平线。如果没有找到任何内容(例如最终边界矩形区域太小),您可以将40宽度检查更改为更大的值,例如100。这将带给您稍微好一点的结果。Google OCR 几乎可以找到它。 - Simon Mourier

2

仅是一个建议,我没有尝试过。

不要尝试移除这些条,保留它们并训练所有可能出现的条位置。将条修剪到字符限制以进行正确对齐。

输入图像描述 输入图像描述

将它们作为02032018022018进行训练。我猜最好在干净的字符上模拟这些条。


我可能稍后会考虑采用目标检测路线。我只是想知道是否可以使用OpenCV清理这种图像,因为我有很多这样的图像。这只是一个特定的用例 :) - BoreBoar

0
特别是在Yves Daoust案例中,看看你在2018年下面的1...那几乎是一个"n"或者三分之二的整数0,而8变成了字母B。2可以被读作倒置的6。在某些情况下,0也可以被读作6等等。如果您保留网格,则有些可能最终变得“无法识别”。因此,我的方法是:
  1. 去除冗余的网格信息有助于更好地识别具有直线的整数,如0、1、2、4、5和7。
  2. 接着使用级联分类器进行字符训练。
一旦去除了网格并完成了训练,一些数字中的曲率很容易被检测出来。这将把90-95%的假阴性命中降低到真实整数(真阳性)或伪装目标(真阴性)。然后您只需要担心那5-10%的情况。

文档和示例代码信息可以在OpenCV这里Code-Robin这里github这里找到。

图像值02032018022018

values 02032018022018


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接