Python OpenCV数字合并到周围的框中

Python OpenCV数字合并到周围的框中,python,c++,opencv,computer-vision,imagemagick,Python,C++,Opencv,Computer Vision,Imagemagick,我有一大堆日期,我正试图用tesseract进行OCR。 但是,日期中的许多数字与日期框中的行合并,因此: 此外,这里还有一个我可以很好地处理的好形象: 这是我的代码: 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

我有一大堆日期,我正试图用tesseract进行OCR。 但是,日期中的许多数字与日期框中的行合并,因此:



此外,这里还有一个我可以很好地处理的好形象:


这是我的代码:

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
其结果是公平的,但删除的行在一定程度上切断了数字,如下所示:


有没有更好的方法来解决这个问题?我的最终目标是对数字进行细分,因此最终的图像需要非常清晰。

只是一个建议,我从未尝试过

不要试图移除钢筋,而是将其保留并在所有可能的钢筋位置上进行训练。将条修剪到字符限制,以便正确对齐


将其列为
02032018022018
。我想最好是在干净的字符上模拟条形图。

特别是,看看下面的
2018
中的
1
,看看Yves Daoust casus。。。这几乎是一个
“n”
或整数
0
的四分之三,而
8
变成字母
B
2
可以读作倒置的
6
。在某些情况下,
0
也可以被解读为
6
,等等。。如果您将网格保留在适当的位置,甚至有些可能最终会“无法识别”。因此,我的做法是:

  • 去掉冗余网格信息有助于更好地识别内部有直线的整数,如
    0,1,2,4,5
    7
  • 然后使用级联分类器进行字符训练
  • 一旦移除网格并完成训练,一些数字的曲率很容易被检测到。这将减少90-95%的假阴性命中率,使之成为实整数(真阳性)或假整数(真阴性)。然后你只需要担心那5-10%

    可以找到文档和样本代码信息,以及

    图像值
    02032018022018


    以下是一些似乎运行良好的代码。分为两个阶段:

    • 人们可以观察到数字比方框略显粗体。而且整个图像具有很强的横向性。因此,我们可以在水平方向上进行更大的扩张,以消除大部分垂直线
    • 例如,在这一点上,OCR可以检测大多数数字。不幸的是,它有点太好了,并且可以看到其他东西,所以我添加了另一个更复杂的阶段,并且与您的特定上下文非常相关
    以下是第一阶段后的一幅图像结果:

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

    正如你所看到的,它并不完美,8可以被视为B(好吧,即使像我这样的人也把它视为B……但如果你的世界中只有数字,那么它很容易被修复)。还有一个类似“:”的字符(从一条垂直线中删除的遗留字符),我无法摆脱它,也不能太多地调整代码

    C#代码:

    static void Unbox(字符串inputFilePath、字符串outputFilePath)
    {
    使用(var orig=new Mat(inputFilePath))
    {
    使用(var gray=orig.CvtColor(ColorConversionCodes.BGR2GRAY))
    {
    使用(var dst=orig.emptyCyclone())
    {
    //这就是我所说的“水平摇晃”传球。
    //注意,我在这里使用Rect形状,这很重要
    使用(var displate=Cv2.GetStructuringElement(MorphShapes.Rect,新大小(4,1)))
    {
    扩张(灰色,dst,扩张);
    }
    //稍微腐蚀一下,让一些数字恢复生机
    使用(var-crease=Cv2.GetStructuringElement(MorphShapes.Rect,新大小(2,1)))
    {
    侵蚀(dst,dst,侵蚀);
    }
    //此时,好的OCR将看到大多数数字
    //但我们想移除周围的人工制品
    //找伯爵
    使用(var canny=dst.canny(0400))
    {
    var contours=canny.FindContoursArray(RetrievalModes.List,ContourApproximationModes.ApproxSimple);
    //计算不带方框和工件的所有数字的边界矩形
    //这是一个棘手的部分,我们试图丢弃与数字无关的东西
    var boundingRect=Rect.Empty;
    foreach(等高线中的var等高线)
    {
    //丢弃一些小的和破碎的多边形
    var polygon=Cv2.ApproxPolyDP(等高线,4,真);
    如果(多边形长度<3)
    继续;
    //我们只需要数字,盒子大约40像素宽,
    //因此,让我们放弃与长方体相关的多边形(如果有的话)
    //以及其他一些通过先前检查的工件
    //这完全取决于一些上下文知识。。。
    var rect=Cv2.BoundingRect(多边形);
    如果(矩形宽度>40 | |矩形高度<15)
    继续;
    boundingRect=boundingRect.X==0?rect:boundingRect.Union(rect);
    }
    使用(var final=dst.Clone(boundingRect))
    {
    SaveImage(outputFilePath);
    }
    }
    }
    }
    }
    }
    
    预印本上的字符不是用不同的颜色吗?不是,它们都是二进制的。黑色和白色。我会避开泰瑟拉特,选择MNIST。也许效果更好,但MNIST是手写数字。这些是一种字体。Tesseract做得很好。它只需要一个更干净的图像。看起来你的字体是一样的吗?如果是这种情况,tr模板匹配所有10个数字我可能会尝试使用对象检测
    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
    
    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);
                        }
                    }
                }
            }
        }
    }