OCR页面上的模糊匹配词

时间:2014-02-07 16:32:41

标签: c# regex ocr levenshtein-distance fuzzy-search

我有一个静态短语,我正在搜索OCR的图像。

string KeywordToFind = "Account Number"

string OcrPageText = "
GEORGIA
POWER

A SOUTHERN COMPANY

AecountNumber

122- 493

Pagel of2

Please Pay By
Jan 29,2014

Total Due
39.11
"

如何使用我的关键字“帐号”找到“AecountNumber”一词?

我尝试使用Levenshtein距离算法HERE的变体,取得了不同的成功。我也试过了正则表达式,但OCR经常以不同的方式转换文本,从而使正则表达式无用。

连连呢?如果链接没有提供足够的信息,我可以提供更多代码。还有,谢谢!

2 个答案:

答案 0 :(得分:0)

为什么不尝试一些大多数任意的东西,比如这个 - 虽然它肯定会比帐号更多地匹配,但是按顺序存在于其他位置的开始和结束字符的可能性非常小。

A.?c.?.?nt ?N.?[mn]b.?r

http://regex101.com/r/zV1yM2

它会匹配以下内容:

Account Number
AccntNumbr
Aecnt Nunber

答案 1 :(得分:0)

使用子字符串回答了我的问题。发布以防其他人遇到相同类型的问题。有点不正统,但它对我很有用。

int TextLengthBuffer = (int)StaticTextLength - 1; //start looking for correct result with one less character than it should have.
int LowestLevenshteinNumber = 999999; //initialize insanely high maximum
decimal PossibleStringLength = (PossibleString.Length); //Length of string to search
decimal StaticTextLength = (StaticText.Length); //Length of text to search for
decimal NumberOfErrorsAllowed = Math.Round((StaticTextLength * (ErrorAllowance / 100)), MidpointRounding.AwayFromZero); //Find number of errors allowed with given ErrorAllowance percentage

    //Look for best match with 1 less character than it should have, then the correct amount of characters.
    //And last, with 1 more character. (This is because one letter can be recognized as 
    //two (W -> VV) and visa versa) 

for (int i = 0; i < 3; i++) 
{
    for (int e = TextLengthBuffer; e <= (int)PossibleStringLength; e++)
    {
        string possibleResult = (PossibleString.Substring((e - TextLengthBuffer), TextLengthBuffer));
        int lAllowance = (int)(Math.Round((possibleResult.Length - StaticTextLength) + (NumberOfErrorsAllowed), MidpointRounding.AwayFromZero));
        int lNumber = LevenshteinAlgorithm(StaticText, possibleResult);

        if (lNumber <= lAllowance && ((lNumber < LowestLevenshteinNumber) || (TextLengthBuffer == StaticText.Length && lNumber <= LowestLevenshteinNumber)))
        {
            PossibleResult = (new StaticTextResult { text = possibleResult, errors = lNumber });
            LowestLevenshteinNumber = lNumber;
        }
    }
    TextLengthBuffer++;
}




public static int LevenshteinAlgorithm(string s, string t) // Levenshtein Algorithm
{
    int n = s.Length;
    int m = t.Length;
    int[,] d = new int[n + 1, m + 1];

    if (n == 0)
    {
        return m;
    }

    if (m == 0)
    {
        return n;
    }

    for (int i = 0; i <= n; d[i, 0] = i++)
    {
    }

    for (int j = 0; j <= m; d[0, j] = j++)
    {
    }

    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

            d[i, j] = Math.Min(
                Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                d[i - 1, j - 1] + cost);
        }
    }
    return d[n, m];
}