code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#!/usr/bin/env python """ tesshelper.py -- Utility operations to compare, report stats, and copy public headers for tesseract 3.0x VS2008 Project $RCSfile: tesshelper.py,v $ $Revision: 7ca575b377aa $ $Date: 2012/03/07 17:26:31 $ """ r""" Requires: python 2.7 or greater: activestate.com http://www.activestate.com/activepython/downloads because using the new argparse module and new literal set syntax (s={1, 2}) . General Notes: -------------- Format for a .vcproj file entry: <File RelativePath="..\src\allheaders.h" > </File> """ epilogStr = r""" Examples: Assume that tesshelper.py is in c:\buildfolder\tesseract-3.02\vs2008, which is also the current directory. Then, python tesshelper .. compare will compare c:\buildfolder\tesseract-3.02 "library" directories to the libtesseract Project (c:\buildfolder\tesseract-3.02\vs2008\libtesseract\libtesseract.vcproj). python tesshelper .. report will display summary stats for c:\buildfolder\tesseract-3.02 "library" directories and the libtesseract Project. python tesshelper .. copy ..\..\include will copy all "public" libtesseract header files to c:\buildfolder\include. python tesshelper .. clean will clean the vs2008 folder of all build directories, and .user, .suo, .ncb, and other temp files. """ # imports of python standard library modules # See Python Documentation | Library Reference for details import collections import glob import argparse import os import re import shutil import sys # ==================================================================== VERSION = "1.0 %s" % "$Date: 2012/03/07 17:26:31 $".split()[1] PROJ_SUBDIR = r"vs2008\libtesseract" PROJFILE = "libtesseract.vcproj" NEWHEADERS_FILENAME = "newheaders.txt" NEWSOURCES_FILENAME = "newsources.txt" fileNodeTemplate = \ ''' <File RelativePath="..\..\%s" > </File> ''' # ==================================================================== def getProjectfiles(libTessDir, libProjectFile, nTrimChars): """Return sets of all, c, h, and resources files in libtesseract Project""" #extract filenames of header & source files from the .vcproj projectCFiles = set() projectHFiles = set() projectRFiles = set() projectFilesSet = set() f = open(libProjectFile, "r") data = f.read() f.close() projectFiles = re.findall(r'(?i)RelativePath="(\.[^"]+)"', data) for projectFile in projectFiles: root, ext = os.path.splitext(projectFile.lower()) if ext == ".c" or ext == ".cpp": projectCFiles.add(projectFile) elif ext == ".h": projectHFiles.add(projectFile) elif ext == ".rc": projectRFiles.add(projectFile) else: print "unknown file type: %s" % projectFile relativePath = os.path.join(libTessDir, projectFile) relativePath = os.path.abspath(relativePath) relativePath = relativePath[nTrimChars:].lower() projectFilesSet.add(relativePath) return projectFilesSet, projectHFiles, projectCFiles, projectRFiles def getTessLibFiles(tessDir, nTrimChars): """Return set of all libtesseract files in tessDir""" libDirs = [ "api", "ccmain", "ccstruct", "ccutil", "classify", "cube", "cutil", "dict", r"neural_networks\runtime", "opencl", "textord", "viewer", "wordrec", #"training", r"vs2008\port", r"vs2008\libtesseract", ] #create list of all .h, .c, .cpp files in "library" directories tessFiles = set() for curDir in libDirs: baseDir = os.path.join(tessDir, curDir) for filetype in ["*.c", "*.cpp", "*.h", "*.rc"]: pattern = os.path.join(baseDir, filetype) fileList = glob.glob(pattern) for curFile in fileList: curFile = os.path.abspath(curFile) relativePath = curFile[nTrimChars:].lower() tessFiles.add(relativePath) return tessFiles # ==================================================================== def tessCompare(tessDir): '''Compare libtesseract Project files and actual "sub-library" files.''' vs2008Dir = os.path.join(tessDir, "vs2008") libTessDir = os.path.join(vs2008Dir, "libtesseract") libProjectFile = os.path.join(libTessDir,"libtesseract.vcproj") tessAbsDir = os.path.abspath(tessDir) nTrimChars = len(tessAbsDir)+1 print 'Comparing VS2008 Project "%s" with\n "%s"' % (libProjectFile, tessAbsDir) projectFilesSet, projectHFiles, projectCFiles, projectRFiles = \ getProjectfiles(libTessDir, libProjectFile, nTrimChars) tessFiles = getTessLibFiles(tessDir, nTrimChars) extraFiles = tessFiles - projectFilesSet print "%2d Extra files (in %s but not in Project)" % (len(extraFiles), tessAbsDir) headerFiles = [] sourceFiles = [] sortedList = list(extraFiles) sortedList.sort() for filename in sortedList: root, ext = os.path.splitext(filename.lower()) if ext == ".h": headerFiles.append(filename) else: sourceFiles.append(filename) print " %s " % filename print print "%2d new header file items written to %s" % (len(headerFiles), NEWHEADERS_FILENAME) headerFiles.sort() with open(NEWHEADERS_FILENAME, "w") as f: for filename in headerFiles: f.write(fileNodeTemplate % filename) print "%2d new source file items written to %s" % (len(sourceFiles), NEWSOURCES_FILENAME) sourceFiles.sort() with open(NEWSOURCES_FILENAME, "w") as f: for filename in sourceFiles: f.write(fileNodeTemplate % filename) print deadFiles = projectFilesSet - tessFiles print "%2d Dead files (in Project but not in %s" % (len(deadFiles), tessAbsDir) sortedList = list(deadFiles) sortedList.sort() for filename in sortedList: print " %s " % filename # ==================================================================== def tessReport(tessDir): """Report summary stats on "sub-library" files and libtesseract Project file.""" vs2008Dir = os.path.join(tessDir, "vs2008") libTessDir = os.path.join(vs2008Dir, "libtesseract") libProjectFile = os.path.join(libTessDir,"libtesseract.vcproj") tessAbsDir = os.path.abspath(tessDir) nTrimChars = len(tessAbsDir)+1 projectFilesSet, projectHFiles, projectCFiles, projectRFiles = \ getProjectfiles(libTessDir, libProjectFile, nTrimChars) tessFiles = getTessLibFiles(tessDir, nTrimChars) print 'Summary stats for "%s" library directories' % tessAbsDir folderCounters = {} for tessFile in tessFiles: tessFile = tessFile.lower() folder, head = os.path.split(tessFile) file, ext = os.path.splitext(head) typeCounter = folderCounters.setdefault(folder, collections.Counter()) typeCounter[ext[1:]] += 1 folders = folderCounters.keys() folders.sort() totalFiles = 0 totalH = 0 totalCPP = 0 totalOther = 0 print print " total h cpp" print " ----- --- ---" for folder in folders: counters = folderCounters[folder] nHFiles = counters['h'] nCPPFiles = counters['cpp'] total = nHFiles + nCPPFiles totalFiles += total totalH += nHFiles totalCPP += nCPPFiles print " %5d %3d %3d %s" % (total, nHFiles, nCPPFiles, folder) print " ----- --- ---" print " %5d %3d %3d" % (totalFiles, totalH, totalCPP) print print 'Summary stats for VS2008 Project "%s"' % libProjectFile print " %5d %s" %(len(projectHFiles), "Header files") print " %5d %s" % (len(projectCFiles), "Source files") print " %5d %s" % (len(projectRFiles), "Resource files") print " -----" print " %5d" % (len(projectHFiles) + len(projectCFiles) + len(projectRFiles), ) # ==================================================================== def copyIncludes(fileSet, description, tessDir, includeDir): """Copy set of files to specified include dir.""" print print 'Copying libtesseract "%s" headers to %s' % (description, includeDir) print sortedList = list(fileSet) sortedList.sort() count = 0 errList = [] for includeFile in sortedList: filepath = os.path.join(tessDir, includeFile) if os.path.isfile(filepath): shutil.copy2(filepath, includeDir) print "Copied: %s" % includeFile count += 1 else: print '***Error: "%s" doesn\'t exist"' % filepath errList.append(filepath) print '%d header files successfully copied to "%s"' % (count, includeDir) if len(errList): print "The following %d files were not copied:" for filepath in errList: print " %s" % filepath def tessCopy(tessDir, includeDir): '''Copy all "public" libtesseract Project header files to include directory. Preserves directory hierarchy.''' baseIncludeSet = { r"api\baseapi.h", r"api\capi.h", r"api\apitypes.h", r"ccstruct\publictypes.h", r"ccmain\thresholder.h", r"ccutil\host.h", r"ccutil\basedir.h", r"ccutil\tesscallback.h", r"ccutil\unichar.h", r"ccutil\platform.h", } strngIncludeSet = { r"ccutil\strngs.h", r"ccutil\memry.h", r"ccutil\host.h", r"ccutil\serialis.h", r"ccutil\errcode.h", r"ccutil\fileerr.h", #r"ccutil\genericvector.h", } resultIteratorIncludeSet = { r"ccmain\ltrresultiterator.h", r"ccmain\pageiterator.h", r"ccmain\resultiterator.h", r"ccutil\genericvector.h", r"ccutil\tesscallback.h", r"ccutil\errcode.h", r"ccutil\host.h", r"ccutil\helpers.h", r"ccutil\ndminx.h", r"ccutil\params.h", r"ccutil\unicharmap.h", r"ccutil\unicharset.h", } genericVectorIncludeSet = { r"ccutil\genericvector.h", r"ccutil\tesscallback.h", r"ccutil\errcode.h", r"ccutil\host.h", r"ccutil\helpers.h", r"ccutil\ndminx.h", } blobsIncludeSet = { r"ccstruct\blobs.h", r"ccstruct\rect.h", r"ccstruct\points.h", r"ccstruct\ipoints.h", r"ccutil\elst.h", r"ccutil\host.h", r"ccutil\serialis.h", r"ccutil\lsterr.h", r"ccutil\ndminx.h", r"ccutil\tprintf.h", r"ccutil\params.h", r"viewer\scrollview.h", r"ccstruct\vecfuncs.h", } extraFilesSet = { #r"vs2008\include\stdint.h", r"vs2008\include\leptonica_versionnumbers.vsprops", r"vs2008\include\tesseract_versionnumbers.vsprops", } tessIncludeDir = os.path.join(includeDir, "tesseract") if os.path.isfile(tessIncludeDir): print 'Aborting: "%s" is a file not a directory.' % tessIncludeDir return if not os.path.exists(tessIncludeDir): os.mkdir(tessIncludeDir) #fileSet = baseIncludeSet | strngIncludeSet | genericVectorIncludeSet | blobsIncludeSet fileSet = baseIncludeSet | strngIncludeSet | resultIteratorIncludeSet copyIncludes(fileSet, "public", tessDir, tessIncludeDir) copyIncludes(extraFilesSet, "extra", tessDir, includeDir) # ==================================================================== def tessClean(tessDir): '''Clean vs2008 folder of all build directories and certain temp files.''' vs2008Dir = os.path.join(tessDir, "vs2008") vs2008AbsDir = os.path.abspath(vs2008Dir) answer = raw_input( 'Are you sure you want to clean the\n "%s" folder (Yes/No) [No]? ' % vs2008AbsDir) if answer.lower() not in ("yes",): return answer = raw_input('Only list the items to be deleted (Yes/No) [Yes]? ') answer = answer.strip() listOnly = answer.lower() not in ("no",) for rootDir, dirs, files in os.walk(vs2008AbsDir): for buildDir in ("LIB_Release", "LIB_Debug", "DLL_Release", "DLL_Debug"): if buildDir in dirs: dirs.remove(buildDir) absBuildDir = os.path.join(rootDir, buildDir) if listOnly: print "Would remove: %s" % absBuildDir else: print "Removing: %s" % absBuildDir shutil.rmtree(absBuildDir) if rootDir == vs2008AbsDir: for file in files: if file.lower() not in ("tesseract.sln", "tesshelper.py", "readme.txt"): absPath = os.path.join(rootDir, file) if listOnly: print "Would remove: %s" % absPath else: print "Removing: %s" % absPath os.remove(absPath) else: for file in files: root, ext = os.path.splitext(file) if ext.lower() in (".suo", ".ncb", ".user", ) or ( len(ext)>0 and ext[-1] == "~"): absPath = os.path.join(rootDir, file) if listOnly: print "Would remove: %s" % absPath else: print "Removing: %s" % absPath os.remove(absPath) # ==================================================================== def validateTessDir(tessDir): """Check that tessDir is a valid tesseract directory.""" if not os.path.isdir(tessDir): raise argparse.ArgumentTypeError('Directory "%s" doesn\'t exist.' % tessDir) projFile = os.path.join(tessDir, PROJ_SUBDIR, PROJFILE) if not os.path.isfile(projFile): raise argparse.ArgumentTypeError('Project file "%s" doesn\'t exist.' % projFile) return tessDir def validateDir(dir): """Check that dir is a valid directory named include.""" if not os.path.isdir(dir): raise argparse.ArgumentTypeError('Directory "%s" doesn\'t exist.' % dir) dirpath = os.path.abspath(dir) head, tail = os.path.split(dirpath) if tail.lower() != "include": raise argparse.ArgumentTypeError('Include directory "%s" must be named "include".' % tail) return dir def main (): parser = argparse.ArgumentParser( epilog=epilogStr, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--version", action="version", version="%(prog)s " + VERSION) parser.add_argument('tessDir', type=validateTessDir, help="tesseract installation directory") subparsers = parser.add_subparsers( dest="subparser_name", title="Commands") parser_changes = subparsers.add_parser('compare', help="compare libtesseract Project with tessDir") parser_changes.set_defaults(func=tessCompare) parser_report = subparsers.add_parser('report', help="report libtesseract summary stats") parser_report.set_defaults(func=tessReport) parser_copy = subparsers.add_parser('copy', help="copy public libtesseract header files to includeDir") parser_copy.add_argument('includeDir', type=validateDir, help="Directory to copy header files to.") parser_copy.set_defaults(func=tessCopy) parser_clean = subparsers.add_parser('clean', help="clean vs2008 folder of build folders and .user files") parser_clean.set_defaults(func=tessClean) #kludge because argparse has no ability to set default subparser if (len(sys.argv) == 2): sys.argv.append("compare") args = parser.parse_args() #handle commands if args.func == tessCopy: args.func(args.tessDir, args.includeDir) else: args.func(args.tessDir) if __name__ == '__main__' : main()
1080228-arabicocr11
vs2008/tesshelper.py
Python
asf20
17,177
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by tesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2008/shapeclustering/resource.h
C
asf20
403
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by tesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2008/tesseract/resource.h
C
asf20
403
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by tesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2008/dawg2wordlist/resource.h
C
asf20
403
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by tesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2008/combine_tessdata/resource.h
C
asf20
403
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2012 Zdenko Podobný # Author: Zdenko Podobný # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Simple python demo script of tesseract-ocr 3.02 c-api """ import os import sys import ctypes # Demo variables lang = "eng" filename = "../phototest.tif" libpath = "/usr/local/lib64/" libpath_w = "../vs2008/DLL_Release/" TESSDATA_PREFIX = os.environ.get('TESSDATA_PREFIX') if not TESSDATA_PREFIX: TESSDATA_PREFIX = "../" if sys.platform == "win32": libname = libpath_w + "libtesseract302.dll" libname_alt = "libtesseract302.dll" os.environ["PATH"] += os.pathsep + libpath_w else: libname = libpath + "libtesseract.so.3.0.2" libname_alt = "libtesseract.so.3" try: tesseract = ctypes.cdll.LoadLibrary(libname) except: try: tesseract = ctypes.cdll.LoadLibrary(libname_alt) except WindowsError, err: print("Trying to load '%s'..." % libname) print("Trying to load '%s'..." % libname_alt) print(err) exit(1) tesseract.TessVersion.restype = ctypes.c_char_p tesseract_version = tesseract.TessVersion()[:4] # We need to check library version because libtesseract.so.3 is symlink # and can point to other version than 3.02 if float(tesseract_version) < 3.02: print("Found tesseract-ocr library version %s." % tesseract_version) print("C-API is present only in version 3.02!") exit(2) api = tesseract.TessBaseAPICreate() rc = tesseract.TessBaseAPIInit3(api, TESSDATA_PREFIX, lang); if (rc): tesseract.TessBaseAPIDelete(api) print("Could not initialize tesseract.\n") exit(3) text_out = tesseract.TessBaseAPIProcessPages(api, filename, None , 0); result_text = ctypes.string_at(text_out) print result_text
1080228-arabicocr11
contrib/tesseract-c_api-demo.py
Python
asf20
2,184
#-*- mode: shell-script;-*- # # bash completion support for tesseract # # Copyright (C) 2009 Neskie A. Manuel <neskiem@gmail.com> # Distributed under the Apache License, Version 2.0. # _tesseract_languages() { local TESSDATA="/usr/share/tesseract-ocr/tessdata/" local langs="$(ls $TESSDATA | grep traineddata | cut -d \. -f 1)" COMPREPLY=(${COMPREPLY[@]:-} $(compgen -W "$langs" -- "$cur") ) } _tesseract() { local cur prev COMPREPLY=() cur="$2" prev="$3" case "$prev" in tesseract) COMPREPLY=($(compgen -f -X "!*.+(tif)" -- "$cur") ) ;; *.tif) COMPREPLY=($(compgen -W "$(basename $prev .tif)" ) ) ;; -l) _tesseract_languages ;; *) COMPREPLY=($(compgen -W "-l" ) ) ;; esac } complete -F _tesseract -o nospace tesseract
1080228-arabicocr11
contrib/tesseract.completion
Shell
asf20
789
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by libtesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2010/libtesseract/resource.h
C
asf20
406
/////////////////////////////////////////////////////////////////////// // File: gettimeofday.h // Description: Header file for gettimeofday.cpp // Author: tomp2010, zdenop // Created: Tue Feb 21 21:38:00 CET 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef VS2008_PORT_GETTIMEOFDAY_H_ #define VS2008_PORT_GETTIMEOFDAY_H_ #ifdef _WIN32 #include <winsock.h> // timeval is defined in here. #endif typedef struct timezone tz; int gettimeofday(struct timeval * tp, struct timezone * tzp); #endif // VS2008_PORT_GETTIMEOFDAY_H_
1080228-arabicocr11
vs2010/port/gettimeofday.h
C
asf20
1,181
/* * Copyright (c) 1995, 1996, 1997 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // source: https://github.com/heimdal/heimdal/blob/master/lib/roken/strtok_r.c #include <string.h> char *strtok_r(char *s1, const char *s2, char **lasts) { char *ret; if (s1 == NULL) s1 = *lasts; while (*s1 && strchr(s2, *s1)) ++s1; if (*s1 == '\0') return NULL; ret = s1; while (*s1 && !strchr(s2, *s1)) ++s1; if (*s1) *s1++ = '\0'; *lasts = s1; return ret; }
1080228-arabicocr11
vs2010/port/strtok_r.cpp
C++
asf20
2,054
/////////////////////////////////////////////////////////////////////// // File: mathfix.h // Description: Implement missing math functions // Author: zdenop // Created: Fri Feb 03 06:45:06 CET 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef VS2008_INCLUDE_MATHFIX_H_ #define VS2008_INCLUDE_MATHFIXT_H_ #ifndef _MSC_VER #error "Use this header only with Microsoft Visual C++ compilers!" #endif #include <math.h> #include <float.h> // for _isnan(), _finite() on VC++ #if _MSC_VER < 1800 #define isnan(x) _isnan(x) #define isinf(x) (!_finite(x)) #define fmax max //VC++ does not implement all the provisions of C99 Standard #define round(x) roundf(x) inline float roundf(float num) { return num > 0 ? floorf(num + 0.5f) : ceilf(num - 0.5f); } #endif #endif // VS2008_INCLUDE_MATHFIXT_H_
1080228-arabicocr11
vs2010/port/mathfix.h
C
asf20
1,431
/* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies of the Software and its Copyright notices. In addition publicly documented acknowledgment must be given that this software has been used if no source code of this software is made available publicly. Making the source available publicly means including the source for this software with the distribution, or a method to get this software via some reasonable mechanism (electronic transfer via a network or media) as well as making an offer to supply the source on request. This Copyright notice serves as an offer to supply the source on on request as well. Instead of this, supplying acknowledgments of use of this software in either Copyright notices, Manuals, Publicity and Marketing documents or any documentation provided with any product containing this software. This License does not apply to any software that links to the libraries provided by this software (statically or dynamically), but only to the software provided. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Source: Evil 1.7.4 The Evil library tried to port some convenient Unix functions to the Windows (XP or CE) platform. They are planned to be used http://git.enlightenment.org/legacy/evil.git/tree/src/lib/evil_string.h?id=eeaddf80d0d547d4c216974038c0599b34359695 */ #ifndef VS2010_PORT_STRCASESTR_H_ #define VS2010_PORT_STRCASESTR_H_ /** * @brief Locatea substring into a string, ignoring case. * * @param haystack The string to search in. * @param needle The substring to find. * @return * * This function locates the string @p needle into the string @p haystack, * ignoring the case of the characters. It returns apointer to the * beginning of the substring, or NULL if the substring is not found. * If @p haystack or @p needle are @c NULL, this function returns @c NULL. * * Conformity: Non applicable. * * Supported OS: Windows XP, Windows CE */ char *strcasestr(const char *haystack, const char *needle); #endif /* VS2010_PORT_STRCASESTR_H_ */
1080228-arabicocr11
vs2010/port/strcasestr.h
C
asf20
2,864
/////////////////////////////////////////////////////////////////////// // File: gettimeofday.cpp // Description: Implementation of gettimeofday based on leptonica // Author: tomp2010, zdenop // Created: Tue Feb 21 21:38:00 CET 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include <allheaders.h> #include "gettimeofday.h" int gettimeofday(struct timeval *tp, struct timezone *tzp) { l_int32 sec, usec; if (tp == NULL) return -1; l_getCurrentTime(&sec, &usec); tp->tv_sec = sec; tp->tv_usec = usec; return 0; }
1080228-arabicocr11
vs2010/port/gettimeofday.cpp
C++
asf20
1,164
/* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies of the Software and its Copyright notices. In addition publicly documented acknowledgment must be given that this software has been used if no source code of this software is made available publicly. Making the source available publicly means including the source for this software with the distribution, or a method to get this software via some reasonable mechanism (electronic transfer via a network or media) as well as making an offer to supply the source on request. This Copyright notice serves as an offer to supply the source on on request as well. Instead of this, supplying acknowledgments of use of this software in either Copyright notices, Manuals, Publicity and Marketing documents or any documentation provided with any product containing this software. This License does not apply to any software that links to the libraries provided by this software (statically or dynamically), but only to the software provided. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Source: Evil 1.7.4 The Evil library tried to port some convenient Unix functions to the Windows (XP or CE) platform. They are planned to be used http://git.enlightenment.org/legacy/evil.git/tree/src/lib/evil_string.c?id=eeaddf80d0d547d4c216974038c0599b34359695 */ #include <stdlib.h> #include <string.h> #include <ctype.h> char *strcasestr(const char *haystack, const char *needle) { size_t length_needle; size_t length_haystack; size_t i; if (!haystack || !needle) return NULL; length_needle = strlen(needle); length_haystack = strlen(haystack) - length_needle + 1; for (i = 0; i < length_haystack; i++) { size_t j; for (j = 0; j < length_needle; j++) { unsigned char c1; unsigned char c2; c1 = haystack[i+j]; c2 = needle[j]; if (toupper(c1) != toupper(c2)) goto next; } return (char *) haystack + i; next: ; } return NULL; }
1080228-arabicocr11
vs2010/port/strcasestr.cpp
C++
asf20
2,903
/////////////////////////////////////////////////////////////////////// // File: strtok_r.h // Description: Header file for strtok_r.cpp // source: https://github.com/heimdal/heimdal/blob/master/lib/roken/ // strtok_r.c // Author: zdenop // Created: Fri Aug 12 23:55:06 CET 2011 // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef VS2010_PORT_STRTOK_R_H_ #define VS2010_PORT_STRTOK_R_H_ char *strtok_r(char *s1, const char *s2, char **lasts); #endif // VS2010_PORT_STRCASESTR_H_
1080228-arabicocr11
vs2010/port/strtok_r.h
C
asf20
1,126
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by tesseract.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
1080228-arabicocr11
vs2010/tesseract/resource.h
C
asf20
403
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // neuron.cpp: The implementation of a class for an object // that represents a single neuron in a neural network #include "neuron.h" #include "input_file_buffer.h" namespace tesseract { // Instantiate all supported templates template bool Neuron::ReadBinary(InputFileBuffer *input_buffer); // default and only constructor Neuron::Neuron() { Init(); } // virtual destructor Neuron::~Neuron() { } // Initializer void Neuron::Init() { id_ = -1; frwd_dirty_ = false; fan_in_.clear(); fan_in_weights_.clear(); activation_ = 0.0f; output_ = 0.0f; bias_ = 0.0f; node_type_ = Unknown; } // Computes the activation and output of the neuron if not fresh // by pulling the outputs of all fan-in neurons void Neuron::FeedForward() { if (!frwd_dirty_ ) { return; } // nothing to do for input nodes: just pass the input to the o/p // otherwise, pull the output of all fan-in neurons if (node_type_ != Input) { int fan_in_cnt = fan_in_.size(); // sum out the activation activation_ = -bias_; for (int in = 0; in < fan_in_cnt; in++) { if (fan_in_[in]->frwd_dirty_) { fan_in_[in]->FeedForward(); } activation_ += ((*(fan_in_weights_[in])) * fan_in_[in]->output_); } // sigmoid it output_ = Sigmoid(activation_); } frwd_dirty_ = false; } // set the type of the neuron void Neuron::set_node_type(NeuronTypes Type) { node_type_ = Type; } // Adds new connections *to* this neuron *From* // a target neuron using specfied params // Note that what is actually copied in this function are pointers to the // specified Neurons and weights and not the actualt values. This is by // design to centralize the alloction of neurons and weights and so // increase the locality of reference and improve cache-hits resulting // in a faster net. This technique resulted in a 2X-10X speedup // (depending on network size and processor) void Neuron::AddFromConnection(Neuron *neurons, float *wts_offset, int from_cnt) { for (int in = 0; in < from_cnt; in++) { fan_in_.push_back(neurons + in); fan_in_weights_.push_back(wts_offset + in); } } // fast computation of sigmoid function using a lookup table // defined in sigmoid_table.cpp float Neuron::Sigmoid(float activation) { if (activation <= -10.0f) { return 0.0f; } else if (activation >= 10.0f) { return 1.0f; } else { return kSigmoidTable[static_cast<int>(100 * (activation + 10.0))]; } } }
1080228-arabicocr11
neural_networks/runtime/neuron.cpp
C++
asf20
2,613
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // neural_net.h: Declarations of a class for an object that // represents an arbitrary network of neurons // #ifndef NEURAL_NET_H #define NEURAL_NET_H #include <string> #include <vector> #include "neuron.h" #include "input_file_buffer.h" namespace tesseract { // Minimum input range below which we set the input weight to zero static const float kMinInputRange = 1e-6f; class NeuralNet { public: NeuralNet(); virtual ~NeuralNet(); // create a net object from a file. Uses stdio static NeuralNet *FromFile(const string file_name); // create a net object from an input buffer static NeuralNet *FromInputBuffer(InputFileBuffer *ib); // Different flavors of feed forward function template <typename Type> bool FeedForward(const Type *inputs, Type *outputs); // Compute the output of a specific output node. // This function is useful for application that are interested in a single // output of the net and do not want to waste time on the rest template <typename Type> bool GetNetOutput(const Type *inputs, int output_id, Type *output); // Accessor functions int in_cnt() const { return in_cnt_; } int out_cnt() const { return out_cnt_; } protected: struct Node; // A node-weight pair struct WeightedNode { Node *input_node; float input_weight; }; // node struct used for fast feedforward in // Read only nets struct Node { float out; float bias; int fan_in_cnt; WeightedNode *inputs; }; // Read-Only flag (no training: On by default) // will presumeably be set to false by // the inherting TrainableNeuralNet class bool read_only_; // input count int in_cnt_; // output count int out_cnt_; // Total neuron count (including inputs) int neuron_cnt_; // count of unique weights int wts_cnt_; // Neuron vector Neuron *neurons_; // size of allocated weight chunk (in weights) // This is basically the size of the biggest network // that I have trained. However, the class will allow // a bigger sized net if desired static const int kWgtChunkSize = 0x10000; // Magic number expected at the beginning of the NN // binary file static const unsigned int kNetSignature = 0xFEFEABD0; // count of allocated wgts in the last chunk int alloc_wgt_cnt_; // vector of weights buffers vector<vector<float> *>wts_vec_; // Is the net an auto-encoder type bool auto_encoder_; // vector of input max values vector<float> inputs_max_; // vector of input min values vector<float> inputs_min_; // vector of input mean values vector<float> inputs_mean_; // vector of input standard deviation values vector<float> inputs_std_dev_; // vector of input offsets used by fast read-only // feedforward function vector<Node> fast_nodes_; // Network Initialization function void Init(); // Clears all neurons void Clear() { for (int node = 0; node < neuron_cnt_; node++) { neurons_[node].Clear(); } } // Reads the net from an input buffer template<class ReadBuffType> bool ReadBinary(ReadBuffType *input_buff) { // Init vars Init(); // is this an autoencoder unsigned int read_val; unsigned int auto_encode; // read and verify signature if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } if (read_val != kNetSignature) { return false; } if (input_buff->Read(&auto_encode, sizeof(auto_encode)) != sizeof(auto_encode)) { return false; } auto_encoder_ = auto_encode; // read and validate total # of nodes if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } neuron_cnt_ = read_val; if (neuron_cnt_ <= 0) { return false; } // set the size of the neurons vector neurons_ = new Neuron[neuron_cnt_]; if (neurons_ == NULL) { return false; } // read & validate inputs if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } in_cnt_ = read_val; if (in_cnt_ <= 0) { return false; } // read outputs if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } out_cnt_ = read_val; if (out_cnt_ <= 0) { return false; } // set neuron ids and types for (int idx = 0; idx < neuron_cnt_; idx++) { neurons_[idx].set_id(idx); // input type if (idx < in_cnt_) { neurons_[idx].set_node_type(Neuron::Input); } else if (idx >= (neuron_cnt_ - out_cnt_)) { neurons_[idx].set_node_type(Neuron::Output); } else { neurons_[idx].set_node_type(Neuron::Hidden); } } // read the connections for (int node_idx = 0; node_idx < neuron_cnt_; node_idx++) { // read fanout if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } // read the neuron's info int fan_out_cnt = read_val; for (int fan_out_idx = 0; fan_out_idx < fan_out_cnt; fan_out_idx++) { // read the neuron id if (input_buff->Read(&read_val, sizeof(read_val)) != sizeof(read_val)) { return false; } // create the connection if (!SetConnection(node_idx, read_val)) { return false; } } } // read all the neurons' fan-in connections for (int node_idx = 0; node_idx < neuron_cnt_; node_idx++) { // read if (!neurons_[node_idx].ReadBinary(input_buff)) { return false; } } // size input stats vector to expected input size inputs_mean_.resize(in_cnt_); inputs_std_dev_.resize(in_cnt_); inputs_min_.resize(in_cnt_); inputs_max_.resize(in_cnt_); // read stats if (input_buff->Read(&(inputs_mean_.front()), sizeof(inputs_mean_[0]) * in_cnt_) != sizeof(inputs_mean_[0]) * in_cnt_) { return false; } if (input_buff->Read(&(inputs_std_dev_.front()), sizeof(inputs_std_dev_[0]) * in_cnt_) != sizeof(inputs_std_dev_[0]) * in_cnt_) { return false; } if (input_buff->Read(&(inputs_min_.front()), sizeof(inputs_min_[0]) * in_cnt_) != sizeof(inputs_min_[0]) * in_cnt_) { return false; } if (input_buff->Read(&(inputs_max_.front()), sizeof(inputs_max_[0]) * in_cnt_) != sizeof(inputs_max_[0]) * in_cnt_) { return false; } // create a readonly version for fast feedforward if (read_only_) { return CreateFastNet(); } return true; } // creates a connection between two nodes bool SetConnection(int from, int to); // Create a read only version of the net that // has faster feedforward performance bool CreateFastNet(); // internal function to allocate a new set of weights // Centralized weight allocation attempts to increase // weights locality of reference making it more cache friendly float *AllocWgt(int wgt_cnt); // different flavors read-only feedforward function template <typename Type> bool FastFeedForward(const Type *inputs, Type *outputs); // Compute the output of a specific output node. // This function is useful for application that are interested in a single // output of the net and do not want to waste time on the rest // This is the fast-read-only version of this function template <typename Type> bool FastGetNetOutput(const Type *inputs, int output_id, Type *output); }; } #endif // NEURAL_NET_H__
1080228-arabicocr11
neural_networks/runtime/neural_net.h
C++
asf20
8,317
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // neural_net.cpp: Declarations of a class for an object that // represents an arbitrary network of neurons // #include <vector> #include <string> #include "neural_net.h" #include "input_file_buffer.h" namespace tesseract { NeuralNet::NeuralNet() { Init(); } NeuralNet::~NeuralNet() { // clean up the wts chunks vector for (int vec = 0; vec < static_cast<int>(wts_vec_.size()); vec++) { delete wts_vec_[vec]; } // clean up neurons delete []neurons_; // clean up nodes for (int node_idx = 0; node_idx < neuron_cnt_; node_idx++) { delete []fast_nodes_[node_idx].inputs; } } // Initiaization function void NeuralNet::Init() { read_only_ = true; auto_encoder_ = false; alloc_wgt_cnt_ = 0; wts_cnt_ = 0; neuron_cnt_ = 0; in_cnt_ = 0; out_cnt_ = 0; wts_vec_.clear(); neurons_ = NULL; inputs_mean_.clear(); inputs_std_dev_.clear(); inputs_min_.clear(); inputs_max_.clear(); } // Does a fast feedforward for read_only nets // Templatized for float and double Types template <typename Type> bool NeuralNet::FastFeedForward(const Type *inputs, Type *outputs) { int node_idx = 0; Node *node = &fast_nodes_[0]; // feed inputs in and offset them by the pre-computed bias for (node_idx = 0; node_idx < in_cnt_; node_idx++, node++) { node->out = inputs[node_idx] - node->bias; } // compute nodes activations and outputs for (;node_idx < neuron_cnt_; node_idx++, node++) { double activation = -node->bias; for (int fan_in_idx = 0; fan_in_idx < node->fan_in_cnt; fan_in_idx++) { activation += (node->inputs[fan_in_idx].input_weight * node->inputs[fan_in_idx].input_node->out); } node->out = Neuron::Sigmoid(activation); } // copy the outputs to the output buffers node = &fast_nodes_[neuron_cnt_ - out_cnt_]; for (node_idx = 0; node_idx < out_cnt_; node_idx++, node++) { outputs[node_idx] = node->out; } return true; } // Performs a feedforward for general nets. Used mainly in training mode // Templatized for float and double Types template <typename Type> bool NeuralNet::FeedForward(const Type *inputs, Type *outputs) { // call the fast version in case of readonly nets if (read_only_) { return FastFeedForward(inputs, outputs); } // clear all neurons Clear(); // for auto encoders, apply no input normalization if (auto_encoder_) { for (int in = 0; in < in_cnt_; in++) { neurons_[in].set_output(inputs[in]); } } else { // Input normalization : subtract mean and divide by stddev for (int in = 0; in < in_cnt_; in++) { neurons_[in].set_output((inputs[in] - inputs_min_[in]) / (inputs_max_[in] - inputs_min_[in])); neurons_[in].set_output((neurons_[in].output() - inputs_mean_[in]) / inputs_std_dev_[in]); } } // compute the net outputs: follow a pull model each output pulls the // outputs of its input nodes and so on for (int out = neuron_cnt_ - out_cnt_; out < neuron_cnt_; out++) { neurons_[out].FeedForward(); // copy the values to the output buffer outputs[out] = neurons_[out].output(); } return true; } // Sets a connection between two neurons bool NeuralNet::SetConnection(int from, int to) { // allocate the wgt float *wts = AllocWgt(1); if (wts == NULL) { return false; } // register the connection neurons_[to].AddFromConnection(neurons_ + from, wts, 1); return true; } // Create a fast readonly version of the net bool NeuralNet::CreateFastNet() { fast_nodes_.resize(neuron_cnt_); // build the node structures int wts_cnt = 0; for (int node_idx = 0; node_idx < neuron_cnt_; node_idx++) { Node *node = &fast_nodes_[node_idx]; if (neurons_[node_idx].node_type() == Neuron::Input) { // Input neurons have no fan-in node->fan_in_cnt = 0; node->inputs = NULL; // Input bias is the normalization offset computed from // training input stats if (fabs(inputs_max_[node_idx] - inputs_min_[node_idx]) < kMinInputRange) { // if the range approaches zero, the stdev is not defined, // this indicates that this input does not change. // Set the bias to zero node->bias = 0.0f; } else { node->bias = inputs_min_[node_idx] + (inputs_mean_[node_idx] * (inputs_max_[node_idx] - inputs_min_[node_idx])); } } else { node->bias = neurons_[node_idx].bias(); node->fan_in_cnt = neurons_[node_idx].fan_in_cnt(); // allocate memory for fan-in nodes node->inputs = new WeightedNode[node->fan_in_cnt]; if (node->inputs == NULL) { return false; } for (int fan_in = 0; fan_in < node->fan_in_cnt; fan_in++) { // identify fan-in neuron const int id = neurons_[node_idx].fan_in(fan_in)->id(); // Feedback connections are not allowed and should never happen if (id >= node_idx) { return false; } // add the the fan-in neuron and its wgt node->inputs[fan_in].input_node = &fast_nodes_[id]; float wgt_val = neurons_[node_idx].fan_in_wts(fan_in); // for input neurons normalize the wgt by the input scaling // values to save time during feedforward if (neurons_[node_idx].fan_in(fan_in)->node_type() == Neuron::Input) { // if the range approaches zero, the stdev is not defined, // this indicates that this input does not change. // Set the weight to zero if (fabs(inputs_max_[id] - inputs_min_[id]) < kMinInputRange) { wgt_val = 0.0f; } else { wgt_val /= ((inputs_max_[id] - inputs_min_[id]) * inputs_std_dev_[id]); } } node->inputs[fan_in].input_weight = wgt_val; } // incr wgt count to validate against at the end wts_cnt += node->fan_in_cnt; } } // sanity check return wts_cnt_ == wts_cnt; } // returns a pointer to the requested set of weights // Allocates in chunks float * NeuralNet::AllocWgt(int wgt_cnt) { // see if need to allocate a new chunk of wts if (wts_vec_.size() == 0 || (alloc_wgt_cnt_ + wgt_cnt) > kWgtChunkSize) { // add the new chunck to the wts_chunks vector wts_vec_.push_back(new vector<float> (kWgtChunkSize)); alloc_wgt_cnt_ = 0; } float *ret_ptr = &((*wts_vec_.back())[alloc_wgt_cnt_]); // incr usage counts alloc_wgt_cnt_ += wgt_cnt; wts_cnt_ += wgt_cnt; return ret_ptr; } // create a new net object using an input file as a source NeuralNet *NeuralNet::FromFile(const string file_name) { // open the file InputFileBuffer input_buff(file_name); // create a new net object using input buffer NeuralNet *net_obj = FromInputBuffer(&input_buff); return net_obj; } // create a net object from an input buffer NeuralNet *NeuralNet::FromInputBuffer(InputFileBuffer *ib) { // create a new net object NeuralNet *net_obj = new NeuralNet(); if (net_obj == NULL) { return NULL; } // load the net if (!net_obj->ReadBinary(ib)) { delete net_obj; net_obj = NULL; } return net_obj; } // Compute the output of a specific output node. // This function is useful for application that are interested in a single // output of the net and do not want to waste time on the rest // This is the fast-read-only version of this function template <typename Type> bool NeuralNet::FastGetNetOutput(const Type *inputs, int output_id, Type *output) { // feed inputs in and offset them by the pre-computed bias int node_idx = 0; Node *node = &fast_nodes_[0]; for (node_idx = 0; node_idx < in_cnt_; node_idx++, node++) { node->out = inputs[node_idx] - node->bias; } // compute nodes' activations and outputs for hidden nodes if any int hidden_node_cnt = neuron_cnt_ - out_cnt_; for (;node_idx < hidden_node_cnt; node_idx++, node++) { double activation = -node->bias; for (int fan_in_idx = 0; fan_in_idx < node->fan_in_cnt; fan_in_idx++) { activation += (node->inputs[fan_in_idx].input_weight * node->inputs[fan_in_idx].input_node->out); } node->out = Neuron::Sigmoid(activation); } // compute the output of the required output node node += output_id; double activation = -node->bias; for (int fan_in_idx = 0; fan_in_idx < node->fan_in_cnt; fan_in_idx++) { activation += (node->inputs[fan_in_idx].input_weight * node->inputs[fan_in_idx].input_node->out); } (*output) = Neuron::Sigmoid(activation); return true; } // Performs a feedforward for general nets. Used mainly in training mode // Templatized for float and double Types template <typename Type> bool NeuralNet::GetNetOutput(const Type *inputs, int output_id, Type *output) { // validate output id if (output_id < 0 || output_id >= out_cnt_) { return false; } // call the fast version in case of readonly nets if (read_only_) { return FastGetNetOutput(inputs, output_id, output); } // For the slow version, we'll just call FeedForward and return the // appropriate output vector<Type> outputs(out_cnt_); if (!FeedForward(inputs, &outputs[0])) { return false; } (*output) = outputs[output_id]; return true; } // Instantiate all supported templates now that the functions have been defined. template bool NeuralNet::FeedForward(const float *inputs, float *outputs); template bool NeuralNet::FeedForward(const double *inputs, double *outputs); template bool NeuralNet::FastFeedForward(const float *inputs, float *outputs); template bool NeuralNet::FastFeedForward(const double *inputs, double *outputs); template bool NeuralNet::GetNetOutput(const float *inputs, int output_id, float *output); template bool NeuralNet::GetNetOutput(const double *inputs, int output_id, double *output); template bool NeuralNet::FastGetNetOutput(const float *inputs, int output_id, float *output); template bool NeuralNet::FastGetNetOutput(const double *inputs, int output_id, double *output); template bool NeuralNet::ReadBinary(InputFileBuffer *input_buffer); }
1080228-arabicocr11
neural_networks/runtime/neural_net.cpp
C++
asf20
10,750
AM_CPPFLAGS += \ -DUSE_STD_NAMESPACE \ -I$(top_srcdir)/cutil -I$(top_srcdir)/ccutil \ -I$(top_srcdir)/ccstruct -I$(top_srcdir)/dict \ -I$(top_srcdir)/image -I$(top_srcdir)/viewer if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS \ -fvisibility=hidden -fvisibility-inlines-hidden endif noinst_HEADERS = \ input_file_buffer.h neural_net.h neuron.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_neural.la else lib_LTLIBRARIES = libtesseract_neural.la libtesseract_neural_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) endif libtesseract_neural_la_SOURCES = \ input_file_buffer.cpp neural_net.cpp neuron.cpp sigmoid_table.cpp
1080228-arabicocr11
neural_networks/runtime/Makefile.am
Makefile
asf20
668
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // input_file_buffer.h: Declarations of a class for an object that // represents an input file buffer. // #ifndef INPUT_FILE_BUFFER_H #define INPUT_FILE_BUFFER_H #include <stdio.h> #include <string> #ifdef USE_STD_NAMESPACE using std::string; #endif namespace tesseract { class InputFileBuffer { public: explicit InputFileBuffer(const string &file_name); virtual ~InputFileBuffer(); int Read(void *buffer, int bytes_to_read); protected: string file_name_; FILE *fp_; }; } #endif // INPUT_FILE_BUFFER_H__
1080228-arabicocr11
neural_networks/runtime/input_file_buffer.h
C++
asf20
640
// Copyright 2007 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // sigmoid_table.cpp: Sigmoid function lookup table #include "neuron.h" namespace tesseract { const float Neuron::kSigmoidTable[] = { 4.53979E-05f, 4.58541E-05f, 4.63149E-05f, 4.67804E-05f, 4.72505E-05f, 4.77254E-05f, 4.8205E-05f, 4.86894E-05f, 4.91787E-05f, 4.9673E-05f, 5.01722E-05f, 5.06764E-05f, 5.11857E-05f, 5.17001E-05f, 5.22196E-05f, 5.27444E-05f, 5.32745E-05f, 5.38099E-05f, 5.43506E-05f, 5.48968E-05f, 5.54485E-05f, 5.60058E-05f, 5.65686E-05f, 5.71371E-05f, 5.77113E-05f, 5.82913E-05f, 5.88771E-05f, 5.94688E-05f, 6.00664E-05f, 6.067E-05f, 6.12797E-05f, 6.18956E-05f, 6.25176E-05f, 6.31459E-05f, 6.37805E-05f, 6.44214E-05f, 6.50688E-05f, 6.57227E-05f, 6.63832E-05f, 6.70503E-05f, 6.77241E-05f, 6.84047E-05f, 6.90922E-05f, 6.97865E-05f, 7.04878E-05f, 7.11962E-05f, 7.19117E-05f, 7.26343E-05f, 7.33643E-05f, 7.41016E-05f, 7.48462E-05f, 7.55984E-05f, 7.63581E-05f, 7.71255E-05f, 7.79005E-05f, 7.86834E-05f, 7.94741E-05f, 8.02728E-05f, 8.10794E-05f, 8.18942E-05f, 8.27172E-05f, 8.35485E-05f, 8.43881E-05f, 8.52361E-05f, 8.60927E-05f, 8.69579E-05f, 8.78317E-05f, 8.87144E-05f, 8.96059E-05f, 9.05064E-05f, 9.14159E-05f, 9.23345E-05f, 9.32624E-05f, 9.41996E-05f, 9.51463E-05f, 9.61024E-05f, 9.70682E-05f, 9.80436E-05f, 9.90289E-05f, 0.000100024f, 0.000101029f, 0.000102044f, 0.00010307f, 0.000104106f, 0.000105152f, 0.000106209f, 0.000107276f, 0.000108354f, 0.000109443f, 0.000110542f, 0.000111653f, 0.000112775f, 0.000113909f, 0.000115053f, 0.000116209f, 0.000117377f, 0.000118557f, 0.000119748f, 0.000120951f, 0.000122167f, 0.000123395f, 0.000124635f, 0.000125887f, 0.000127152f, 0.00012843f, 0.00012972f, 0.000131024f, 0.000132341f, 0.00013367f, 0.000135014f, 0.00013637f, 0.000137741f, 0.000139125f, 0.000140523f, 0.000141935f, 0.000143361f, 0.000144802f, 0.000146257f, 0.000147727f, 0.000149211f, 0.00015071f, 0.000152225f, 0.000153754f, 0.000155299f, 0.00015686f, 0.000158436f, 0.000160028f, 0.000161636f, 0.000163261f, 0.000164901f, 0.000166558f, 0.000168232f, 0.000169922f, 0.00017163f, 0.000173354f, 0.000175096f, 0.000176856f, 0.000178633f, 0.000180428f, 0.000182241f, 0.000184072f, 0.000185922f, 0.00018779f, 0.000189677f, 0.000191583f, 0.000193508f, 0.000195452f, 0.000197416f, 0.0001994f, 0.000201403f, 0.000203427f, 0.000205471f, 0.000207536f, 0.000209621f, 0.000211727f, 0.000213855f, 0.000216003f, 0.000218174f, 0.000220366f, 0.00022258f, 0.000224817f, 0.000227076f, 0.000229357f, 0.000231662f, 0.00023399f, 0.000236341f, 0.000238715f, 0.000241114f, 0.000243537f, 0.000245984f, 0.000248455f, 0.000250951f, 0.000253473f, 0.00025602f, 0.000258592f, 0.00026119f, 0.000263815f, 0.000266465f, 0.000269143f, 0.000271847f, 0.000274578f, 0.000277337f, 0.000280123f, 0.000282938f, 0.000285781f, 0.000288652f, 0.000291552f, 0.000294481f, 0.00029744f, 0.000300429f, 0.000303447f, 0.000306496f, 0.000309575f, 0.000312685f, 0.000315827f, 0.000319f, 0.000322205f, 0.000325442f, 0.000328712f, 0.000332014f, 0.00033535f, 0.000338719f, 0.000342122f, 0.00034556f, 0.000349031f, 0.000352538f, 0.00035608f, 0.000359657f, 0.00036327f, 0.00036692f, 0.000370606f, 0.000374329f, 0.00037809f, 0.000381888f, 0.000385725f, 0.0003896f, 0.000393514f, 0.000397467f, 0.00040146f, 0.000405494f, 0.000409567f, 0.000413682f, 0.000417838f, 0.000422035f, 0.000426275f, 0.000430557f, 0.000434882f, 0.000439251f, 0.000443664f, 0.000448121f, 0.000452622f, 0.000457169f, 0.000461762f, 0.0004664f, 0.000471085f, 0.000475818f, 0.000480597f, 0.000485425f, 0.000490301f, 0.000495226f, 0.000500201f, 0.000505226f, 0.000510301f, 0.000515427f, 0.000520604f, 0.000525833f, 0.000531115f, 0.00053645f, 0.000541839f, 0.000547281f, 0.000552779f, 0.000558331f, 0.000563939f, 0.000569604f, 0.000575325f, 0.000581104f, 0.00058694f, 0.000592836f, 0.00059879f, 0.000604805f, 0.000610879f, 0.000617015f, 0.000623212f, 0.000629472f, 0.000635794f, 0.00064218f, 0.00064863f, 0.000655144f, 0.000661724f, 0.00066837f, 0.000675083f, 0.000681863f, 0.000688711f, 0.000695628f, 0.000702614f, 0.00070967f, 0.000716798f, 0.000723996f, 0.000731267f, 0.000738611f, 0.000746029f, 0.000753521f, 0.000761088f, 0.000768731f, 0.000776451f, 0.000784249f, 0.000792124f, 0.000800079f, 0.000808113f, 0.000816228f, 0.000824425f, 0.000832703f, 0.000841065f, 0.000849511f, 0.000858041f, 0.000866657f, 0.00087536f, 0.000884149f, 0.000893027f, 0.000901994f, 0.000911051f, 0.000920199f, 0.000929439f, 0.000938771f, 0.000948197f, 0.000957717f, 0.000967333f, 0.000977045f, 0.000986855f, 0.000996763f, 0.001006771f, 0.001016879f, 0.001027088f, 0.0010374f, 0.001047815f, 0.001058334f, 0.00106896f, 0.001079691f, 0.00109053f, 0.001101478f, 0.001112536f, 0.001123705f, 0.001134985f, 0.001146379f, 0.001157887f, 0.00116951f, 0.00118125f, 0.001193108f, 0.001205084f, 0.001217181f, 0.001229399f, 0.001241739f, 0.001254203f, 0.001266792f, 0.001279507f, 0.00129235f, 0.001305321f, 0.001318423f, 0.001331655f, 0.001345021f, 0.00135852f, 0.001372155f, 0.001385926f, 0.001399835f, 0.001413884f, 0.001428073f, 0.001442405f, 0.00145688f, 0.001471501f, 0.001486267f, 0.001501182f, 0.001516247f, 0.001531462f, 0.001546829f, 0.001562351f, 0.001578028f, 0.001593862f, 0.001609855f, 0.001626008f, 0.001642323f, 0.001658801f, 0.001675444f, 0.001692254f, 0.001709233f, 0.001726381f, 0.001743701f, 0.001761195f, 0.001778864f, 0.00179671f, 0.001814734f, 0.001832939f, 0.001851326f, 0.001869898f, 0.001888655f, 0.0019076f, 0.001926735f, 0.001946061f, 0.001965581f, 0.001985296f, 0.002005209f, 0.00202532f, 0.002045634f, 0.00206615f, 0.002086872f, 0.002107801f, 0.00212894f, 0.00215029f, 0.002171854f, 0.002193633f, 0.002215631f, 0.002237849f, 0.002260288f, 0.002282953f, 0.002305844f, 0.002328964f, 0.002352316f, 0.002375901f, 0.002399721f, 0.002423781f, 0.00244808f, 0.002472623f, 0.002497411f, 0.002522447f, 0.002547734f, 0.002573273f, 0.002599068f, 0.00262512f, 0.002651433f, 0.002678009f, 0.002704851f, 0.002731961f, 0.002759342f, 0.002786996f, 0.002814927f, 0.002843137f, 0.002871629f, 0.002900406f, 0.00292947f, 0.002958825f, 0.002988472f, 0.003018416f, 0.003048659f, 0.003079205f, 0.003110055f, 0.003141213f, 0.003172683f, 0.003204467f, 0.003236568f, 0.00326899f, 0.003301735f, 0.003334807f, 0.00336821f, 0.003401946f, 0.003436018f, 0.003470431f, 0.003505187f, 0.00354029f, 0.003575744f, 0.003611551f, 0.003647715f, 0.00368424f, 0.003721129f, 0.003758387f, 0.003796016f, 0.00383402f, 0.003872403f, 0.00391117f, 0.003950322f, 0.003989865f, 0.004029802f, 0.004070138f, 0.004110875f, 0.004152019f, 0.004193572f, 0.00423554f, 0.004277925f, 0.004320734f, 0.004363968f, 0.004407633f, 0.004451734f, 0.004496273f, 0.004541256f, 0.004586687f, 0.004632571f, 0.004678911f, 0.004725713f, 0.00477298f, 0.004820718f, 0.004868931f, 0.004917624f, 0.004966802f, 0.005016468f, 0.005066629f, 0.005117289f, 0.005168453f, 0.005220126f, 0.005272312f, 0.005325018f, 0.005378247f, 0.005432006f, 0.005486299f, 0.005541132f, 0.005596509f, 0.005652437f, 0.005708921f, 0.005765966f, 0.005823577f, 0.005881761f, 0.005940522f, 0.005999867f, 0.006059801f, 0.006120331f, 0.006181461f, 0.006243198f, 0.006305547f, 0.006368516f, 0.006432108f, 0.006496332f, 0.006561193f, 0.006626697f, 0.006692851f, 0.006759661f, 0.006827132f, 0.006895273f, 0.006964089f, 0.007033587f, 0.007103774f, 0.007174656f, 0.00724624f, 0.007318533f, 0.007391541f, 0.007465273f, 0.007539735f, 0.007614933f, 0.007690876f, 0.00776757f, 0.007845023f, 0.007923242f, 0.008002235f, 0.008082009f, 0.008162571f, 0.00824393f, 0.008326093f, 0.008409068f, 0.008492863f, 0.008577485f, 0.008662944f, 0.008749246f, 0.0088364f, 0.008924415f, 0.009013299f, 0.009103059f, 0.009193705f, 0.009285246f, 0.009377689f, 0.009471044f, 0.009565319f, 0.009660523f, 0.009756666f, 0.009853756f, 0.009951802f, 0.010050814f, 0.010150801f, 0.010251772f, 0.010353738f, 0.010456706f, 0.010560688f, 0.010665693f, 0.01077173f, 0.01087881f, 0.010986943f, 0.011096138f, 0.011206406f, 0.011317758f, 0.011430203f, 0.011543752f, 0.011658417f, 0.011774206f, 0.011891132f, 0.012009204f, 0.012128435f, 0.012248835f, 0.012370415f, 0.012493186f, 0.012617161f, 0.012742349f, 0.012868764f, 0.012996417f, 0.013125318f, 0.013255481f, 0.013386918f, 0.01351964f, 0.013653659f, 0.013788989f, 0.01392564f, 0.014063627f, 0.014202961f, 0.014343656f, 0.014485724f, 0.014629178f, 0.014774032f, 0.014920298f, 0.01506799f, 0.015217121f, 0.015367706f, 0.015519757f, 0.015673288f, 0.015828314f, 0.015984848f, 0.016142905f, 0.016302499f, 0.016463645f, 0.016626356f, 0.016790648f, 0.016956536f, 0.017124033f, 0.017293157f, 0.01746392f, 0.01763634f, 0.017810432f, 0.01798621f, 0.018163691f, 0.018342891f, 0.018523825f, 0.01870651f, 0.018890962f, 0.019077197f, 0.019265233f, 0.019455085f, 0.01964677f, 0.019840306f, 0.020035709f, 0.020232997f, 0.020432187f, 0.020633297f, 0.020836345f, 0.021041347f, 0.021248323f, 0.02145729f, 0.021668266f, 0.021881271f, 0.022096322f, 0.022313439f, 0.022532639f, 0.022753943f, 0.02297737f, 0.023202938f, 0.023430668f, 0.023660578f, 0.023892689f, 0.024127021f, 0.024363594f, 0.024602428f, 0.024843544f, 0.025086962f, 0.025332703f, 0.025580788f, 0.025831239f, 0.026084075f, 0.02633932f, 0.026596994f, 0.026857119f, 0.027119717f, 0.027384811f, 0.027652422f, 0.027922574f, 0.028195288f, 0.028470588f, 0.028748496f, 0.029029036f, 0.029312231f, 0.029598104f, 0.02988668f, 0.030177981f, 0.030472033f, 0.030768859f, 0.031068484f, 0.031370932f, 0.031676228f, 0.031984397f, 0.032295465f, 0.032609455f, 0.032926395f, 0.033246309f, 0.033569223f, 0.033895164f, 0.034224158f, 0.03455623f, 0.034891409f, 0.035229719f, 0.035571189f, 0.035915846f, 0.036263716f, 0.036614828f, 0.036969209f, 0.037326887f, 0.037687891f, 0.038052247f, 0.038419986f, 0.038791134f, 0.039165723f, 0.03954378f, 0.039925334f, 0.040310415f, 0.040699054f, 0.041091278f, 0.041487119f, 0.041886607f, 0.042289772f, 0.042696644f, 0.043107255f, 0.043521635f, 0.043939815f, 0.044361828f, 0.044787703f, 0.045217473f, 0.045651171f, 0.046088827f, 0.046530475f, 0.046976146f, 0.047425873f, 0.04787969f, 0.048337629f, 0.048799723f, 0.049266006f, 0.049736512f, 0.050211273f, 0.050690325f, 0.051173701f, 0.051661435f, 0.052153563f, 0.052650118f, 0.053151136f, 0.053656652f, 0.0541667f, 0.054681317f, 0.055200538f, 0.055724398f, 0.056252934f, 0.056786181f, 0.057324176f, 0.057866955f, 0.058414556f, 0.058967013f, 0.059524366f, 0.06008665f, 0.060653903f, 0.061226163f, 0.061803466f, 0.062385851f, 0.062973356f, 0.063566018f, 0.064163876f, 0.064766969f, 0.065375333f, 0.065989009f, 0.066608036f, 0.067232451f, 0.067862294f, 0.068497604f, 0.06913842f, 0.069784783f, 0.070436731f, 0.071094304f, 0.071757542f, 0.072426485f, 0.073101173f, 0.073781647f, 0.074467945f, 0.075160109f, 0.07585818f, 0.076562197f, 0.077272202f, 0.077988235f, 0.078710337f, 0.079438549f, 0.080172912f, 0.080913467f, 0.081660255f, 0.082413318f, 0.083172696f, 0.083938432f, 0.084710566f, 0.085489139f, 0.086274194f, 0.087065772f, 0.087863915f, 0.088668663f, 0.089480059f, 0.090298145f, 0.091122961f, 0.09195455f, 0.092792953f, 0.093638212f, 0.094490369f, 0.095349465f, 0.096215542f, 0.097088641f, 0.097968804f, 0.098856073f, 0.099750489f, 0.100652094f, 0.101560928f, 0.102477033f, 0.103400451f, 0.104331223f, 0.10526939f, 0.106214992f, 0.10716807f, 0.108128667f, 0.109096821f, 0.110072574f, 0.111055967f, 0.112047039f, 0.11304583f, 0.114052381f, 0.115066732f, 0.116088922f, 0.117118991f, 0.118156978f, 0.119202922f, 0.120256862f, 0.121318838f, 0.122388887f, 0.123467048f, 0.124553358f, 0.125647857f, 0.12675058f, 0.127861566f, 0.128980852f, 0.130108474f, 0.131244469f, 0.132388874f, 0.133541723f, 0.134703052f, 0.135872897f, 0.137051293f, 0.138238273f, 0.139433873f, 0.140638126f, 0.141851065f, 0.143072723f, 0.144303134f, 0.145542329f, 0.14679034f, 0.148047198f, 0.149312935f, 0.15058758f, 0.151871164f, 0.153163716f, 0.154465265f, 0.15577584f, 0.157095469f, 0.158424179f, 0.159761997f, 0.16110895f, 0.162465063f, 0.163830361f, 0.16520487f, 0.166588614f, 0.167981615f, 0.169383897f, 0.170795482f, 0.172216392f, 0.173646647f, 0.175086268f, 0.176535275f, 0.177993686f, 0.179461519f, 0.180938793f, 0.182425524f, 0.183921727f, 0.185427419f, 0.186942614f, 0.188467325f, 0.190001566f, 0.191545349f, 0.193098684f, 0.194661584f, 0.196234056f, 0.197816111f, 0.199407757f, 0.201009f, 0.202619846f, 0.204240302f, 0.205870372f, 0.207510059f, 0.209159365f, 0.210818293f, 0.212486844f, 0.214165017f, 0.215852811f, 0.217550224f, 0.219257252f, 0.220973892f, 0.222700139f, 0.224435986f, 0.226181426f, 0.227936451f, 0.229701051f, 0.231475217f, 0.233258936f, 0.235052196f, 0.236854984f, 0.238667285f, 0.240489083f, 0.242320361f, 0.244161101f, 0.246011284f, 0.247870889f, 0.249739894f, 0.251618278f, 0.253506017f, 0.255403084f, 0.257309455f, 0.259225101f, 0.261149994f, 0.263084104f, 0.265027401f, 0.266979851f, 0.268941421f, 0.270912078f, 0.272891784f, 0.274880502f, 0.276878195f, 0.278884822f, 0.280900343f, 0.282924715f, 0.284957894f, 0.286999837f, 0.289050497f, 0.291109827f, 0.293177779f, 0.295254302f, 0.297339346f, 0.299432858f, 0.301534784f, 0.30364507f, 0.30576366f, 0.307890496f, 0.310025519f, 0.312168669f, 0.314319886f, 0.316479106f, 0.318646266f, 0.320821301f, 0.323004144f, 0.325194727f, 0.327392983f, 0.32959884f, 0.331812228f, 0.334033073f, 0.336261303f, 0.338496841f, 0.340739612f, 0.342989537f, 0.345246539f, 0.347510538f, 0.349781451f, 0.352059198f, 0.354343694f, 0.356634854f, 0.358932594f, 0.361236825f, 0.36354746f, 0.365864409f, 0.368187582f, 0.370516888f, 0.372852234f, 0.375193526f, 0.377540669f, 0.379893568f, 0.382252125f, 0.384616244f, 0.386985824f, 0.389360766f, 0.391740969f, 0.394126332f, 0.39651675f, 0.398912121f, 0.40131234f, 0.403717301f, 0.406126897f, 0.408541022f, 0.410959566f, 0.413382421f, 0.415809477f, 0.418240623f, 0.420675748f, 0.423114739f, 0.425557483f, 0.428003867f, 0.430453776f, 0.432907095f, 0.435363708f, 0.437823499f, 0.440286351f, 0.442752145f, 0.445220765f, 0.44769209f, 0.450166003f, 0.452642382f, 0.455121108f, 0.457602059f, 0.460085115f, 0.462570155f, 0.465057055f, 0.467545694f, 0.470035948f, 0.472527696f, 0.475020813f, 0.477515175f, 0.48001066f, 0.482507142f, 0.485004498f, 0.487502604f, 0.490001333f, 0.492500562f, 0.495000167f, 0.497500021f, 0.5f, 0.502499979f, 0.504999833f, 0.507499438f, 0.509998667f, 0.512497396f, 0.514995502f, 0.517492858f, 0.51998934f, 0.522484825f, 0.524979187f, 0.527472304f, 0.529964052f, 0.532454306f, 0.534942945f, 0.537429845f, 0.539914885f, 0.542397941f, 0.544878892f, 0.547357618f, 0.549833997f, 0.55230791f, 0.554779235f, 0.557247855f, 0.559713649f, 0.562176501f, 0.564636292f, 0.567092905f, 0.569546224f, 0.571996133f, 0.574442517f, 0.576885261f, 0.579324252f, 0.581759377f, 0.584190523f, 0.586617579f, 0.589040434f, 0.591458978f, 0.593873103f, 0.596282699f, 0.59868766f, 0.601087879f, 0.60348325f, 0.605873668f, 0.608259031f, 0.610639234f, 0.613014176f, 0.615383756f, 0.617747875f, 0.620106432f, 0.622459331f, 0.624806474f, 0.627147766f, 0.629483112f, 0.631812418f, 0.634135591f, 0.63645254f, 0.638763175f, 0.641067406f, 0.643365146f, 0.645656306f, 0.647940802f, 0.650218549f, 0.652489462f, 0.654753461f, 0.657010463f, 0.659260388f, 0.661503159f, 0.663738697f, 0.665966927f, 0.668187772f, 0.67040116f, 0.672607017f, 0.674805273f, 0.676995856f, 0.679178699f, 0.681353734f, 0.683520894f, 0.685680114f, 0.687831331f, 0.689974481f, 0.692109504f, 0.69423634f, 0.69635493f, 0.698465216f, 0.700567142f, 0.702660654f, 0.704745698f, 0.706822221f, 0.708890173f, 0.710949503f, 0.713000163f, 0.715042106f, 0.717075285f, 0.719099657f, 0.721115178f, 0.723121805f, 0.725119498f, 0.727108216f, 0.729087922f, 0.731058579f, 0.733020149f, 0.734972599f, 0.736915896f, 0.738850006f, 0.740774899f, 0.742690545f, 0.744596916f, 0.746493983f, 0.748381722f, 0.750260106f, 0.752129111f, 0.753988716f, 0.755838899f, 0.757679639f, 0.759510917f, 0.761332715f, 0.763145016f, 0.764947804f, 0.766741064f, 0.768524783f, 0.770298949f, 0.772063549f, 0.773818574f, 0.775564014f, 0.777299861f, 0.779026108f, 0.780742748f, 0.782449776f, 0.784147189f, 0.785834983f, 0.787513156f, 0.789181707f, 0.790840635f, 0.792489941f, 0.794129628f, 0.795759698f, 0.797380154f, 0.798991f, 0.800592243f, 0.802183889f, 0.803765944f, 0.805338416f, 0.806901316f, 0.808454651f, 0.809998434f, 0.811532675f, 0.813057386f, 0.814572581f, 0.816078273f, 0.817574476f, 0.819061207f, 0.820538481f, 0.822006314f, 0.823464725f, 0.824913732f, 0.826353353f, 0.827783608f, 0.829204518f, 0.830616103f, 0.832018385f, 0.833411386f, 0.83479513f, 0.836169639f, 0.837534937f, 0.83889105f, 0.840238003f, 0.841575821f, 0.842904531f, 0.84422416f, 0.845534735f, 0.846836284f, 0.848128836f, 0.84941242f, 0.850687065f, 0.851952802f, 0.85320966f, 0.854457671f, 0.855696866f, 0.856927277f, 0.858148935f, 0.859361874f, 0.860566127f, 0.861761727f, 0.862948707f, 0.864127103f, 0.865296948f, 0.866458277f, 0.867611126f, 0.868755531f, 0.869891526f, 0.871019148f, 0.872138434f, 0.87324942f, 0.874352143f, 0.875446642f, 0.876532952f, 0.877611113f, 0.878681162f, 0.879743138f, 0.880797078f, 0.881843022f, 0.882881009f, 0.883911078f, 0.884933268f, 0.885947619f, 0.88695417f, 0.887952961f, 0.888944033f, 0.889927426f, 0.890903179f, 0.891871333f, 0.89283193f, 0.893785008f, 0.89473061f, 0.895668777f, 0.896599549f, 0.897522967f, 0.898439072f, 0.899347906f, 0.900249511f, 0.901143927f, 0.902031196f, 0.902911359f, 0.903784458f, 0.904650535f, 0.905509631f, 0.906361788f, 0.907207047f, 0.90804545f, 0.908877039f, 0.909701855f, 0.910519941f, 0.911331337f, 0.912136085f, 0.912934228f, 0.913725806f, 0.914510861f, 0.915289434f, 0.916061568f, 0.916827304f, 0.917586682f, 0.918339745f, 0.919086533f, 0.919827088f, 0.920561451f, 0.921289663f, 0.922011765f, 0.922727798f, 0.923437803f, 0.92414182f, 0.924839891f, 0.925532055f, 0.926218353f, 0.926898827f, 0.927573515f, 0.928242458f, 0.928905696f, 0.929563269f, 0.930215217f, 0.93086158f, 0.931502396f, 0.932137706f, 0.932767549f, 0.933391964f, 0.934010991f, 0.934624667f, 0.935233031f, 0.935836124f, 0.936433982f, 0.937026644f, 0.937614149f, 0.938196534f, 0.938773837f, 0.939346097f, 0.93991335f, 0.940475634f, 0.941032987f, 0.941585444f, 0.942133045f, 0.942675824f, 0.943213819f, 0.943747066f, 0.944275602f, 0.944799462f, 0.945318683f, 0.9458333f, 0.946343348f, 0.946848864f, 0.947349882f, 0.947846437f, 0.948338565f, 0.948826299f, 0.949309675f, 0.949788727f, 0.950263488f, 0.950733994f, 0.951200277f, 0.951662371f, 0.95212031f, 0.952574127f, 0.953023854f, 0.953469525f, 0.953911173f, 0.954348829f, 0.954782527f, 0.955212297f, 0.955638172f, 0.956060185f, 0.956478365f, 0.956892745f, 0.957303356f, 0.957710228f, 0.958113393f, 0.958512881f, 0.958908722f, 0.959300946f, 0.959689585f, 0.960074666f, 0.96045622f, 0.960834277f, 0.961208866f, 0.961580014f, 0.961947753f, 0.962312109f, 0.962673113f, 0.963030791f, 0.963385172f, 0.963736284f, 0.964084154f, 0.964428811f, 0.964770281f, 0.965108591f, 0.96544377f, 0.965775842f, 0.966104836f, 0.966430777f, 0.966753691f, 0.967073605f, 0.967390545f, 0.967704535f, 0.968015603f, 0.968323772f, 0.968629068f, 0.968931516f, 0.969231141f, 0.969527967f, 0.969822019f, 0.97011332f, 0.970401896f, 0.970687769f, 0.970970964f, 0.971251504f, 0.971529412f, 0.971804712f, 0.972077426f, 0.972347578f, 0.972615189f, 0.972880283f, 0.973142881f, 0.973403006f, 0.97366068f, 0.973915925f, 0.974168761f, 0.974419212f, 0.974667297f, 0.974913038f, 0.975156456f, 0.975397572f, 0.975636406f, 0.975872979f, 0.976107311f, 0.976339422f, 0.976569332f, 0.976797062f, 0.97702263f, 0.977246057f, 0.977467361f, 0.977686561f, 0.977903678f, 0.978118729f, 0.978331734f, 0.97854271f, 0.978751677f, 0.978958653f, 0.979163655f, 0.979366703f, 0.979567813f, 0.979767003f, 0.979964291f, 0.980159694f, 0.98035323f, 0.980544915f, 0.980734767f, 0.980922803f, 0.981109038f, 0.98129349f, 0.981476175f, 0.981657109f, 0.981836309f, 0.98201379f, 0.982189568f, 0.98236366f, 0.98253608f, 0.982706843f, 0.982875967f, 0.983043464f, 0.983209352f, 0.983373644f, 0.983536355f, 0.983697501f, 0.983857095f, 0.984015152f, 0.984171686f, 0.984326712f, 0.984480243f, 0.984632294f, 0.984782879f, 0.98493201f, 0.985079702f, 0.985225968f, 0.985370822f, 0.985514276f, 0.985656344f, 0.985797039f, 0.985936373f, 0.98607436f, 0.986211011f, 0.986346341f, 0.98648036f, 0.986613082f, 0.986744519f, 0.986874682f, 0.987003583f, 0.987131236f, 0.987257651f, 0.987382839f, 0.987506814f, 0.987629585f, 0.987751165f, 0.987871565f, 0.987990796f, 0.988108868f, 0.988225794f, 0.988341583f, 0.988456248f, 0.988569797f, 0.988682242f, 0.988793594f, 0.988903862f, 0.989013057f, 0.98912119f, 0.98922827f, 0.989334307f, 0.989439312f, 0.989543294f, 0.989646262f, 0.989748228f, 0.989849199f, 0.989949186f, 0.990048198f, 0.990146244f, 0.990243334f, 0.990339477f, 0.990434681f, 0.990528956f, 0.990622311f, 0.990714754f, 0.990806295f, 0.990896941f, 0.990986701f, 0.991075585f, 0.9911636f, 0.991250754f, 0.991337056f, 0.991422515f, 0.991507137f, 0.991590932f, 0.991673907f, 0.99175607f, 0.991837429f, 0.991917991f, 0.991997765f, 0.992076758f, 0.992154977f, 0.99223243f, 0.992309124f, 0.992385067f, 0.992460265f, 0.992534727f, 0.992608459f, 0.992681467f, 0.99275376f, 0.992825344f, 0.992896226f, 0.992966413f, 0.993035911f, 0.993104727f, 0.993172868f, 0.993240339f, 0.993307149f, 0.993373303f, 0.993438807f, 0.993503668f, 0.993567892f, 0.993631484f, 0.993694453f, 0.993756802f, 0.993818539f, 0.993879669f, 0.993940199f, 0.994000133f, 0.994059478f, 0.994118239f, 0.994176423f, 0.994234034f, 0.994291079f, 0.994347563f, 0.994403491f, 0.994458868f, 0.994513701f, 0.994567994f, 0.994621753f, 0.994674982f, 0.994727688f, 0.994779874f, 0.994831547f, 0.994882711f, 0.994933371f, 0.994983532f, 0.995033198f, 0.995082376f, 0.995131069f, 0.995179282f, 0.99522702f, 0.995274287f, 0.995321089f, 0.995367429f, 0.995413313f, 0.995458744f, 0.995503727f, 0.995548266f, 0.995592367f, 0.995636032f, 0.995679266f, 0.995722075f, 0.99576446f, 0.995806428f, 0.995847981f, 0.995889125f, 0.995929862f, 0.995970198f, 0.996010135f, 0.996049678f, 0.99608883f, 0.996127597f, 0.99616598f, 0.996203984f, 0.996241613f, 0.996278871f, 0.99631576f, 0.996352285f, 0.996388449f, 0.996424256f, 0.99645971f, 0.996494813f, 0.996529569f, 0.996563982f, 0.996598054f, 0.99663179f, 0.996665193f, 0.996698265f, 0.99673101f, 0.996763432f, 0.996795533f, 0.996827317f, 0.996858787f, 0.996889945f, 0.996920795f, 0.996951341f, 0.996981584f, 0.997011528f, 0.997041175f, 0.99707053f, 0.997099594f, 0.997128371f, 0.997156863f, 0.997185073f, 0.997213004f, 0.997240658f, 0.997268039f, 0.997295149f, 0.997321991f, 0.997348567f, 0.99737488f, 0.997400932f, 0.997426727f, 0.997452266f, 0.997477553f, 0.997502589f, 0.997527377f, 0.99755192f, 0.997576219f, 0.997600279f, 0.997624099f, 0.997647684f, 0.997671036f, 0.997694156f, 0.997717047f, 0.997739712f, 0.997762151f, 0.997784369f, 0.997806367f, 0.997828146f, 0.99784971f, 0.99787106f, 0.997892199f, 0.997913128f, 0.99793385f, 0.997954366f, 0.99797468f, 0.997994791f, 0.998014704f, 0.998034419f, 0.998053939f, 0.998073265f, 0.9980924f, 0.998111345f, 0.998130102f, 0.998148674f, 0.998167061f, 0.998185266f, 0.99820329f, 0.998221136f, 0.998238805f, 0.998256299f, 0.998273619f, 0.998290767f, 0.998307746f, 0.998324556f, 0.998341199f, 0.998357677f, 0.998373992f, 0.998390145f, 0.998406138f, 0.998421972f, 0.998437649f, 0.998453171f, 0.998468538f, 0.998483753f, 0.998498818f, 0.998513733f, 0.998528499f, 0.99854312f, 0.998557595f, 0.998571927f, 0.998586116f, 0.998600165f, 0.998614074f, 0.998627845f, 0.99864148f, 0.998654979f, 0.998668345f, 0.998681577f, 0.998694679f, 0.99870765f, 0.998720493f, 0.998733208f, 0.998745797f, 0.998758261f, 0.998770601f, 0.998782819f, 0.998794916f, 0.998806892f, 0.99881875f, 0.99883049f, 0.998842113f, 0.998853621f, 0.998865015f, 0.998876295f, 0.998887464f, 0.998898522f, 0.99890947f, 0.998920309f, 0.99893104f, 0.998941666f, 0.998952185f, 0.9989626f, 0.998972912f, 0.998983121f, 0.998993229f, 0.999003237f, 0.999013145f, 0.999022955f, 0.999032667f, 0.999042283f, 0.999051803f, 0.999061229f, 0.999070561f, 0.999079801f, 0.999088949f, 0.999098006f, 0.999106973f, 0.999115851f, 0.99912464f, 0.999133343f, 0.999141959f, 0.999150489f, 0.999158935f, 0.999167297f, 0.999175575f, 0.999183772f, 0.999191887f, 0.999199921f, 0.999207876f, 0.999215751f, 0.999223549f, 0.999231269f, 0.999238912f, 0.999246479f, 0.999253971f, 0.999261389f, 0.999268733f, 0.999276004f, 0.999283202f, 0.99929033f, 0.999297386f, 0.999304372f, 0.999311289f, 0.999318137f, 0.999324917f, 0.99933163f, 0.999338276f, 0.999344856f, 0.99935137f, 0.99935782f, 0.999364206f, 0.999370528f, 0.999376788f, 0.999382985f, 0.999389121f, 0.999395195f, 0.99940121f, 0.999407164f, 0.99941306f, 0.999418896f, 0.999424675f, 0.999430396f, 0.999436061f, 0.999441669f, 0.999447221f, 0.999452719f, 0.999458161f, 0.99946355f, 0.999468885f, 0.999474167f, 0.999479396f, 0.999484573f, 0.999489699f, 0.999494774f, 0.999499799f, 0.999504774f, 0.999509699f, 0.999514575f, 0.999519403f, 0.999524182f, 0.999528915f, 0.9995336f, 0.999538238f, 0.999542831f, 0.999547378f, 0.999551879f, 0.999556336f, 0.999560749f, 0.999565118f, 0.999569443f, 0.999573725f, 0.999577965f, 0.999582162f, 0.999586318f, 0.999590433f, 0.999594506f, 0.99959854f, 0.999602533f, 0.999606486f, 0.9996104f, 0.999614275f, 0.999618112f, 0.99962191f, 0.999625671f, 0.999629394f, 0.99963308f, 0.99963673f, 0.999640343f, 0.99964392f, 0.999647462f, 0.999650969f, 0.99965444f, 0.999657878f, 0.999661281f, 0.99966465f, 0.999667986f, 0.999671288f, 0.999674558f, 0.999677795f, 0.999681f, 0.999684173f, 0.999687315f, 0.999690425f, 0.999693504f, 0.999696553f, 0.999699571f, 0.99970256f, 0.999705519f, 0.999708448f, 0.999711348f, 0.999714219f, 0.999717062f, 0.999719877f, 0.999722663f, 0.999725422f, 0.999728153f, 0.999730857f, 0.999733535f, 0.999736185f, 0.99973881f, 0.999741408f, 0.99974398f, 0.999746527f, 0.999749049f, 0.999751545f, 0.999754016f, 0.999756463f, 0.999758886f, 0.999761285f, 0.999763659f, 0.99976601f, 0.999768338f, 0.999770643f, 0.999772924f, 0.999775183f, 0.99977742f, 0.999779634f, 0.999781826f, 0.999783997f, 0.999786145f, 0.999788273f, 0.999790379f, 0.999792464f, 0.999794529f, 0.999796573f, 0.999798597f, 0.9998006f, 0.999802584f, 0.999804548f, 0.999806492f, 0.999808417f, 0.999810323f, 0.99981221f, 0.999814078f, 0.999815928f, 0.999817759f, 0.999819572f, 0.999821367f, 0.999823144f, 0.999824904f, 0.999826646f, 0.99982837f, 0.999830078f, 0.999831768f, 0.999833442f, 0.999835099f, 0.999836739f, 0.999838364f, 0.999839972f, 0.999841564f, 0.99984314f, 0.999844701f, 0.999846246f, 0.999847775f, 0.99984929f, 0.999850789f, 0.999852273f, 0.999853743f, 0.999855198f, 0.999856639f, 0.999858065f, 0.999859477f, 0.999860875f, 0.999862259f, 0.99986363f, 0.999864986f, 0.99986633f, 0.999867659f, 0.999868976f, 0.99987028f, 0.99987157f, 0.999872848f, 0.999874113f, 0.999875365f, 0.999876605f, 0.999877833f, 0.999879049f, 0.999880252f, 0.999881443f, 0.999882623f, 0.999883791f, 0.999884947f, 0.999886091f, 0.999887225f, 0.999888347f, 0.999889458f, 0.999890557f, 0.999891646f, 0.999892724f, 0.999893791f, 0.999894848f, 0.999895894f, 0.99989693f, 0.999897956f, 0.999898971f, 0.999899976f, 0.999900971f, 0.999901956f, 0.999902932f, 0.999903898f, 0.999904854f, 0.9999058f, 0.999906738f, 0.999907665f, 0.999908584f, 0.999909494f, 0.999910394f, 0.999911286f, 0.999912168f, 0.999913042f, 0.999913907f, 0.999914764f, 0.999915612f, 0.999916452f, 0.999917283f, 0.999918106f, 0.999918921f, 0.999919727f, 0.999920526f, 0.999921317f, 0.999922099f, 0.999922875f, 0.999923642f, 0.999924402f, 0.999925154f, 0.999925898f, 0.999926636f, 0.999927366f, 0.999928088f, 0.999928804f, 0.999929512f, 0.999930213f, 0.999930908f, 0.999931595f, 0.999932276f, 0.99993295f, 0.999933617f, 0.999934277f, 0.999934931f, 0.999935579f, 0.99993622f, 0.999936854f, 0.999937482f, 0.999938104f, 0.99993872f, 0.99993933f, 0.999939934f, 0.999940531f, 0.999941123f, 0.999941709f, 0.999942289f, 0.999942863f, 0.999943431f, 0.999943994f, 0.999944551f, 0.999945103f, 0.999945649f, 0.99994619f, 0.999946726f, 0.999947256f, 0.99994778f, 0.9999483f, 0.999948814f, 0.999949324f, 0.999949828f, 0.999950327f, 0.999950821f, 0.999951311f, 0.999951795f, 0.999952275f, 0.999952749f, 0.99995322f, 0.999953685f, 0.999954146f, 0.999954602f }; } // namespace tesseract
1080228-arabicocr11
neural_networks/runtime/sigmoid_table.cpp
C++
asf20
29,038
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // neuron.h: Declarations of a class for an object that // represents a single neuron in a neural network // #ifndef NEURON_H #define NEURON_H #include <math.h> #include <vector> #ifdef USE_STD_NAMESPACE using std::vector; #endif namespace tesseract { // Input Node bias values static const float kInputNodeBias = 0.0f; class Neuron { public: // Types of nodes enum NeuronTypes { Unknown = 0, Input, Hidden, Output }; Neuron(); ~Neuron(); // set the forward dirty flag indicating that the // activation of the net is not fresh void Clear() { frwd_dirty_ = true; } // Read a binary representation of the neuron info from // an input buffer. template <class BuffType> bool ReadBinary(BuffType *input_buff) { float val; if (input_buff->Read(&val, sizeof(val)) != sizeof(val)) { return false; } // input nodes should have no biases if (node_type_ == Input) { bias_ = kInputNodeBias; } else { bias_ = val; } // read fanin count int fan_in_cnt; if (input_buff->Read(&fan_in_cnt, sizeof(fan_in_cnt)) != sizeof(fan_in_cnt)) { return false; } // validate fan-in cnt if (fan_in_cnt != fan_in_.size()) { return false; } // read the weights for (int in = 0; in < fan_in_cnt; in++) { if (input_buff->Read(&val, sizeof(val)) != sizeof(val)) { return false; } *(fan_in_weights_[in]) = val; } return true; } // Add a new connection from this neuron *From* // a target neuron using specfied params // Note that what is actually copied in this function are pointers to the // specified Neurons and weights and not the actualt values. This is by // design to centralize the alloction of neurons and weights and so // increase the locality of reference and improve cache-hits resulting // in a faster net. This technique resulted in a 2X-10X speedup // (depending on network size and processor) void AddFromConnection(Neuron *neuron_vec, float *wts_offset, int from_cnt); // Set the type of a neuron void set_node_type(NeuronTypes type); // Computes the output of the node by // "pulling" the output of the fan-in nodes void FeedForward(); // fast computation of sigmoid function using a lookup table // defined in sigmoid_table.cpp static float Sigmoid(float activation); // Accessor functions float output() const { return output_; } void set_output(float out_val) { output_ = out_val; } int id() const { return id_; } int fan_in_cnt() const { return fan_in_.size(); } Neuron * fan_in(int idx) const { return fan_in_[idx]; } float fan_in_wts(int idx) const { return *(fan_in_weights_[idx]); } void set_id(int id) { id_ = id; } float bias() const { return bias_; } Neuron::NeuronTypes node_type() const { return node_type_; } protected: // Type of Neuron NeuronTypes node_type_; // unqique id of the neuron int id_; // node bias float bias_; // node net activation float activation_; // node output float output_; // pointers to fanin nodes vector<Neuron *> fan_in_; // pointers to fanin weights vector<float *> fan_in_weights_; // Sigmoid function lookup table used for fast computation // of sigmoid function static const float kSigmoidTable[]; // flag determining if the activation of the node // is fresh or not (dirty) bool frwd_dirty_; // Initializer void Init(); }; } #endif // NEURON_H__
1080228-arabicocr11
neural_networks/runtime/neuron.h
C++
asf20
3,913
// Copyright 2008 Google Inc. // All Rights Reserved. // Author: ahmadab@google.com (Ahmad Abdulkader) // // input_file_buffer.h: Declarations of a class for an object that // represents an input file buffer. #include <string> #include "input_file_buffer.h" namespace tesseract { // default and only contsructor InputFileBuffer::InputFileBuffer(const string &file_name) : file_name_(file_name) { fp_ = NULL; } // virtual destructor InputFileBuffer::~InputFileBuffer() { if (fp_ != NULL) { fclose(fp_); } } // Read the specified number of bytes to the specified input buffer int InputFileBuffer::Read(void *buffer, int bytes_to_read) { // open the file if necessary if (fp_ == NULL) { fp_ = fopen(file_name_.c_str(), "rb"); if (fp_ == NULL) { return 0; } } return fread(buffer, 1, bytes_to_read, fp_); } }
1080228-arabicocr11
neural_networks/runtime/input_file_buffer.cpp
C++
asf20
847
/* -*-C-*- ******************************************************************************** * * File: blobs.c (Formerly blobs.c) * Description: Blob definition * Author: Mark Seaman, OCR Technology * Created: Fri Oct 27 15:39:52 1989 * Modified: Thu Mar 28 15:33:26 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1989, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "blobs.h" #include "ccstruct.h" #include "clst.h" #include "cutil.h" #include "emalloc.h" #include "helpers.h" #include "linlsq.h" #include "ndminx.h" #include "normalis.h" #include "ocrblock.h" #include "ocrrow.h" #include "points.h" #include "polyaprx.h" #include "structures.h" #include "werd.h" using tesseract::CCStruct; // A Vector representing the "vertical" direction when measuring the // divisiblity of blobs into multiple blobs just by separating outlines. // See divisible_blob below for the use. const TPOINT kDivisibleVerticalUpright(0, 1); // A vector representing the "vertical" direction for italic text for use // when separating outlines. Using it actually deteriorates final accuracy, // so it is only used for ApplyBoxes chopping to get a better segmentation. const TPOINT kDivisibleVerticalItalic(1, 5); /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ CLISTIZE(EDGEPT); // Consume the circular list of EDGEPTs to make a TESSLINE. TESSLINE* TESSLINE::BuildFromOutlineList(EDGEPT* outline) { TESSLINE* result = new TESSLINE; result->loop = outline; if (outline->src_outline != NULL) { // ASSUMPTION: This function is only ever called from ApproximateOutline // and therefore either all points have a src_outline or all do not. // Just as SetupFromPos sets the vectors from the vertices, setup the // step_count members to indicate the (positive) number of original // C_OUTLINE steps to the next vertex. EDGEPT* pt = outline; do { pt->step_count = pt->next->start_step - pt->start_step; if (pt->step_count < 0) pt->step_count += pt->src_outline->pathlength(); pt = pt->next; } while (pt != outline); } result->SetupFromPos(); return result; } // Copies the data and the outline, but leaves next untouched. void TESSLINE::CopyFrom(const TESSLINE& src) { Clear(); topleft = src.topleft; botright = src.botright; start = src.start; is_hole = src.is_hole; if (src.loop != NULL) { EDGEPT* prevpt = NULL; EDGEPT* newpt = NULL; EDGEPT* srcpt = src.loop; do { newpt = new EDGEPT(*srcpt); if (prevpt == NULL) { loop = newpt; } else { newpt->prev = prevpt; prevpt->next = newpt; } prevpt = newpt; srcpt = srcpt->next; } while (srcpt != src.loop); loop->prev = newpt; newpt->next = loop; } } // Deletes owned data. void TESSLINE::Clear() { if (loop == NULL) return; EDGEPT* this_edge = loop; do { EDGEPT* next_edge = this_edge->next; delete this_edge; this_edge = next_edge; } while (this_edge != loop); loop = NULL; } // Normalize in-place using the DENORM. void TESSLINE::Normalize(const DENORM& denorm) { EDGEPT* pt = loop; do { denorm.LocalNormTransform(pt->pos, &pt->pos); pt = pt->next; } while (pt != loop); SetupFromPos(); } // Rotates by the given rotation in place. void TESSLINE::Rotate(const FCOORD rot) { EDGEPT* pt = loop; do { int tmp = static_cast<int>(floor(pt->pos.x * rot.x() - pt->pos.y * rot.y() + 0.5)); pt->pos.y = static_cast<int>(floor(pt->pos.y * rot.x() + pt->pos.x * rot.y() + 0.5)); pt->pos.x = tmp; pt = pt->next; } while (pt != loop); SetupFromPos(); } // Moves by the given vec in place. void TESSLINE::Move(const ICOORD vec) { EDGEPT* pt = loop; do { pt->pos.x += vec.x(); pt->pos.y += vec.y(); pt = pt->next; } while (pt != loop); SetupFromPos(); } // Scales by the given factor in place. void TESSLINE::Scale(float factor) { EDGEPT* pt = loop; do { pt->pos.x = static_cast<int>(floor(pt->pos.x * factor + 0.5)); pt->pos.y = static_cast<int>(floor(pt->pos.y * factor + 0.5)); pt = pt->next; } while (pt != loop); SetupFromPos(); } // Sets up the start and vec members of the loop from the pos members. void TESSLINE::SetupFromPos() { EDGEPT* pt = loop; do { pt->vec.x = pt->next->pos.x - pt->pos.x; pt->vec.y = pt->next->pos.y - pt->pos.y; pt = pt->next; } while (pt != loop); start = pt->pos; ComputeBoundingBox(); } // Recomputes the bounding box from the points in the loop. void TESSLINE::ComputeBoundingBox() { int minx = MAX_INT32; int miny = MAX_INT32; int maxx = -MAX_INT32; int maxy = -MAX_INT32; // Find boundaries. start = loop->pos; EDGEPT* this_edge = loop; do { if (!this_edge->IsHidden() || !this_edge->prev->IsHidden()) { if (this_edge->pos.x < minx) minx = this_edge->pos.x; if (this_edge->pos.y < miny) miny = this_edge->pos.y; if (this_edge->pos.x > maxx) maxx = this_edge->pos.x; if (this_edge->pos.y > maxy) maxy = this_edge->pos.y; } this_edge = this_edge->next; } while (this_edge != loop); // Reset bounds. topleft.x = minx; topleft.y = maxy; botright.x = maxx; botright.y = miny; } // Computes the min and max cross product of the outline points with the // given vec and returns the results in min_xp and max_xp. Geometrically // this is the left and right edge of the outline perpendicular to the // given direction, but to get the distance units correct, you would // have to divide by the modulus of vec. void TESSLINE::MinMaxCrossProduct(const TPOINT vec, int* min_xp, int* max_xp) const { *min_xp = MAX_INT32; *max_xp = MIN_INT32; EDGEPT* this_edge = loop; do { if (!this_edge->IsHidden() || !this_edge->prev->IsHidden()) { int product = CROSS(this_edge->pos, vec); UpdateRange(product, min_xp, max_xp); } this_edge = this_edge->next; } while (this_edge != loop); } TBOX TESSLINE::bounding_box() const { return TBOX(topleft.x, botright.y, botright.x, topleft.y); } #ifndef GRAPHICS_DISABLED void TESSLINE::plot(ScrollView* window, ScrollView::Color color, ScrollView::Color child_color) { if (is_hole) window->Pen(child_color); else window->Pen(color); window->SetCursor(start.x, start.y); EDGEPT* pt = loop; do { bool prev_hidden = pt->IsHidden(); pt = pt->next; if (prev_hidden) window->SetCursor(pt->pos.x, pt->pos.y); else window->DrawTo(pt->pos.x, pt->pos.y); } while (pt != loop); } #endif // GRAPHICS_DISABLED // Returns the first non-hidden EDGEPT that has a different src_outline to // its predecessor, or, if all the same, the lowest indexed point. EDGEPT* TESSLINE::FindBestStartPt() const { EDGEPT* best_start = loop; int best_step = loop->start_step; // Iterate the polygon. EDGEPT* pt = loop; do { if (pt->IsHidden()) continue; if (pt->prev->IsHidden() || pt->prev->src_outline != pt->src_outline) return pt; // Qualifies as the best. if (pt->start_step < best_step) { best_step = pt->start_step; best_start = pt; } } while ((pt = pt->next) != loop); return best_start; } // Iterate the given list of outlines, converting to TESSLINE by polygonal // approximation and recursively any children, returning the current tail // of the resulting list of TESSLINEs. static TESSLINE** ApproximateOutlineList(bool allow_detailed_fx, C_OUTLINE_LIST* outlines, bool children, TESSLINE** tail) { C_OUTLINE_IT ol_it(outlines); for (ol_it.mark_cycle_pt(); !ol_it.cycled_list(); ol_it.forward()) { C_OUTLINE* outline = ol_it.data(); if (outline->pathlength() > 0) { TESSLINE* tessline = ApproximateOutline(allow_detailed_fx, outline); tessline->is_hole = children; *tail = tessline; tail = &tessline->next; } if (!outline->child()->empty()) { tail = ApproximateOutlineList(allow_detailed_fx, outline->child(), true, tail); } } return tail; } // Factory to build a TBLOB from a C_BLOB with polygonal approximation along // the way. If allow_detailed_fx is true, the EDGEPTs in the returned TBLOB // contain pointers to the input C_OUTLINEs that enable higher-resolution // feature extraction that does not use the polygonal approximation. TBLOB* TBLOB::PolygonalCopy(bool allow_detailed_fx, C_BLOB* src) { TBLOB* tblob = new TBLOB; ApproximateOutlineList(allow_detailed_fx, src->out_list(), false, &tblob->outlines); return tblob; } // Factory builds a blob with no outlines, but copies the other member data. TBLOB* TBLOB::ShallowCopy(const TBLOB& src) { TBLOB* blob = new TBLOB; blob->denorm_ = src.denorm_; return blob; } // Normalizes the blob for classification only if needed. // (Normally this means a non-zero classify rotation.) // If no Normalization is needed, then NULL is returned, and the input blob // can be used directly. Otherwise a new TBLOB is returned which must be // deleted after use. TBLOB* TBLOB::ClassifyNormalizeIfNeeded() const { TBLOB* rotated_blob = NULL; // If necessary, copy the blob and rotate it. The rotation is always // +/- 90 degrees, as 180 was already taken care of. if (denorm_.block() != NULL && denorm_.block()->classify_rotation().y() != 0.0) { TBOX box = bounding_box(); int x_middle = (box.left() + box.right()) / 2; int y_middle = (box.top() + box.bottom()) / 2; rotated_blob = new TBLOB(*this); const FCOORD& rotation = denorm_.block()->classify_rotation(); // Move the rotated blob back to the same y-position so that we // can still distinguish similar glyphs with differeny y-position. float target_y = kBlnBaselineOffset + (rotation.y() > 0 ? x_middle - box.left() : box.right() - x_middle); rotated_blob->Normalize(NULL, &rotation, &denorm_, x_middle, y_middle, 1.0f, 1.0f, 0.0f, target_y, denorm_.inverse(), denorm_.pix()); } return rotated_blob; } // Copies the data and the outline, but leaves next untouched. void TBLOB::CopyFrom(const TBLOB& src) { Clear(); TESSLINE* prev_outline = NULL; for (TESSLINE* srcline = src.outlines; srcline != NULL; srcline = srcline->next) { TESSLINE* new_outline = new TESSLINE(*srcline); if (outlines == NULL) outlines = new_outline; else prev_outline->next = new_outline; prev_outline = new_outline; } denorm_ = src.denorm_; } // Deletes owned data. void TBLOB::Clear() { for (TESSLINE* next_outline = NULL; outlines != NULL; outlines = next_outline) { next_outline = outlines->next; delete outlines; } } // Sets up the built-in DENORM and normalizes the blob in-place. // For parameters see DENORM::SetupNormalization, plus the inverse flag for // this blob and the Pix for the full image. void TBLOB::Normalize(const BLOCK* block, const FCOORD* rotation, const DENORM* predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift, bool inverse, Pix* pix) { denorm_.SetupNormalization(block, rotation, predecessor, x_origin, y_origin, x_scale, y_scale, final_xshift, final_yshift); denorm_.set_inverse(inverse); denorm_.set_pix(pix); // TODO(rays) outline->Normalize is more accurate, but breaks tests due // the changes it makes. Reinstate this code with a retraining. // The reason this change is troublesome is that it normalizes for the // baseline value computed independently at each x-coord. If the baseline // is not horizontal, this introduces shear into the normalized blob, which // is useful on the rare occasions that the baseline is really curved, but // the baselines need to be stabilized the rest of the time. #if 0 for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) { outline->Normalize(denorm_); } #else denorm_.LocalNormBlob(this); #endif } // Rotates by the given rotation in place. void TBLOB::Rotate(const FCOORD rotation) { for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) { outline->Rotate(rotation); } } // Moves by the given vec in place. void TBLOB::Move(const ICOORD vec) { for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) { outline->Move(vec); } } // Scales by the given factor in place. void TBLOB::Scale(float factor) { for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) { outline->Scale(factor); } } // Recomputes the bounding boxes of the outlines. void TBLOB::ComputeBoundingBoxes() { for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) { outline->ComputeBoundingBox(); } } // Returns the number of outlines. int TBLOB::NumOutlines() const { int result = 0; for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) ++result; return result; } /********************************************************************** * TBLOB::bounding_box() * * Compute the bounding_box of a compound blob, defined to be the * bounding box of the union of all top-level outlines in the blob. **********************************************************************/ TBOX TBLOB::bounding_box() const { if (outlines == NULL) return TBOX(0, 0, 0, 0); TESSLINE *outline = outlines; TBOX box = outline->bounding_box(); for (outline = outline->next; outline != NULL; outline = outline->next) { box += outline->bounding_box(); } return box; } #ifndef GRAPHICS_DISABLED void TBLOB::plot(ScrollView* window, ScrollView::Color color, ScrollView::Color child_color) { for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) outline->plot(window, color, child_color); } #endif // GRAPHICS_DISABLED // Computes the center of mass and second moments for the old baseline and // 2nd moment normalizations. Returns the outline length. // The input denorm should be the normalizations that have been applied from // the image to the current state of this TBLOB. int TBLOB::ComputeMoments(FCOORD* center, FCOORD* second_moments) const { // Compute 1st and 2nd moments of the original outline. LLSQ accumulator; TBOX box = bounding_box(); // Iterate the outlines, accumulating edges relative the box.botleft(). CollectEdges(box, NULL, &accumulator, NULL, NULL); *center = accumulator.mean_point() + box.botleft(); // The 2nd moments are just the standard deviation of the point positions. double x2nd = sqrt(accumulator.x_variance()); double y2nd = sqrt(accumulator.y_variance()); if (x2nd < 1.0) x2nd = 1.0; if (y2nd < 1.0) y2nd = 1.0; second_moments->set_x(x2nd); second_moments->set_y(y2nd); return accumulator.count(); } // Computes the precise bounding box of the coords that are generated by // GetEdgeCoords. This may be different from the bounding box of the polygon. void TBLOB::GetPreciseBoundingBox(TBOX* precise_box) const { TBOX box = bounding_box(); *precise_box = TBOX(); CollectEdges(box, precise_box, NULL, NULL, NULL); precise_box->move(box.botleft()); } // Adds edges to the given vectors. // For all the edge steps in all the outlines, or polygonal approximation // where there are no edge steps, collects the steps into x_coords/y_coords. // x_coords is a collection of the x-coords of vertical edges for each // y-coord starting at box.bottom(). // y_coords is a collection of the y-coords of horizontal edges for each // x-coord starting at box.left(). // Eg x_coords[0] is a collection of the x-coords of edges at y=bottom. // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1. void TBLOB::GetEdgeCoords(const TBOX& box, GenericVector<GenericVector<int> >* x_coords, GenericVector<GenericVector<int> >* y_coords) const { GenericVector<int> empty; x_coords->init_to_size(box.height(), empty); y_coords->init_to_size(box.width(), empty); CollectEdges(box, NULL, NULL, x_coords, y_coords); // Sort the output vectors. for (int i = 0; i < x_coords->size(); ++i) (*x_coords)[i].sort(); for (int i = 0; i < y_coords->size(); ++i) (*y_coords)[i].sort(); } // Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over // the integer coordinate grid to properly weight long vectors. static void SegmentLLSQ(const FCOORD& pt1, const FCOORD& pt2, LLSQ* accumulator) { FCOORD step(pt2); step -= pt1; int xstart = IntCastRounded(MIN(pt1.x(), pt2.x())); int xend = IntCastRounded(MAX(pt1.x(), pt2.x())); int ystart = IntCastRounded(MIN(pt1.y(), pt2.y())); int yend = IntCastRounded(MAX(pt1.y(), pt2.y())); if (xstart == xend && ystart == yend) return; // Nothing to do. double weight = step.length() / (xend - xstart + yend - ystart); // Compute and save the y-position at the middle of each x-step. for (int x = xstart; x < xend; ++x) { double y = pt1.y() + step.y() * (x + 0.5 - pt1.x()) / step.x(); accumulator->add(x + 0.5, y, weight); } // Compute and save the x-position at the middle of each y-step. for (int y = ystart; y < yend; ++y) { double x = pt1.x() + step.x() * (y + 0.5 - pt1.y()) / step.y(); accumulator->add(x, y + 0.5, weight); } } // Adds any edges from a single segment of outline between pt1 and pt2 to // the x_coords, y_coords vectors. pt1 and pt2 should be relative to the // bottom-left of the bounding box, hence indices to x_coords, y_coords // are clipped to ([0,x_limit], [0,y_limit]). // See GetEdgeCoords above for a description of x_coords, y_coords. static void SegmentCoords(const FCOORD& pt1, const FCOORD& pt2, int x_limit, int y_limit, GenericVector<GenericVector<int> >* x_coords, GenericVector<GenericVector<int> >* y_coords) { FCOORD step(pt2); step -= pt1; int start = ClipToRange(IntCastRounded(MIN(pt1.x(), pt2.x())), 0, x_limit); int end = ClipToRange(IntCastRounded(MAX(pt1.x(), pt2.x())), 0, x_limit); for (int x = start; x < end; ++x) { int y = IntCastRounded(pt1.y() + step.y() * (x + 0.5 - pt1.x()) / step.x()); (*y_coords)[x].push_back(y); } start = ClipToRange(IntCastRounded(MIN(pt1.y(), pt2.y())), 0, y_limit); end = ClipToRange(IntCastRounded(MAX(pt1.y(), pt2.y())), 0, y_limit); for (int y = start; y < end; ++y) { int x = IntCastRounded(pt1.x() + step.x() * (y + 0.5 - pt1.y()) / step.y()); (*x_coords)[y].push_back(x); } } // Adds any edges from a single segment of outline between pt1 and pt2 to // the bbox such that it guarantees to contain anything produced by // SegmentCoords. static void SegmentBBox(const FCOORD& pt1, const FCOORD& pt2, TBOX* bbox) { FCOORD step(pt2); step -= pt1; int x1 = IntCastRounded(MIN(pt1.x(), pt2.x())); int x2 = IntCastRounded(MAX(pt1.x(), pt2.x())); if (x2 > x1) { int y1 = IntCastRounded(pt1.y() + step.y() * (x1 + 0.5 - pt1.x()) / step.x()); int y2 = IntCastRounded(pt1.y() + step.y() * (x2 - 0.5 - pt1.x()) / step.x()); TBOX point(x1, MIN(y1, y2), x2, MAX(y1, y2)); *bbox += point; } int y1 = IntCastRounded(MIN(pt1.y(), pt2.y())); int y2 = IntCastRounded(MAX(pt1.y(), pt2.y())); if (y2 > y1) { int x1 = IntCastRounded(pt1.x() + step.x() * (y1 + 0.5 - pt1.y()) / step.y()); int x2 = IntCastRounded(pt1.x() + step.x() * (y2 - 0.5 - pt1.y()) / step.y()); TBOX point(MIN(x1, x2), y1, MAX(x1, x2), y2); *bbox += point; } } // Collects edges into the given bounding box, LLSQ accumulator and/or x_coords, // y_coords vectors. // For a description of x_coords/y_coords, see GetEdgeCoords above. // Startpt to lastpt, inclusive, MUST have the same src_outline member, // which may be NULL. The vector from lastpt to its next is included in // the accumulation. Hidden edges should be excluded by the caller. // The input denorm should be the normalizations that have been applied from // the image to the current state of the TBLOB from which startpt, lastpt come. // box is the bounding box of the blob from which the EDGEPTs are taken and // indices into x_coords, y_coords are offset by box.botleft(). static void CollectEdgesOfRun(const EDGEPT* startpt, const EDGEPT* lastpt, const DENORM& denorm, const TBOX& box, TBOX* bounding_box, LLSQ* accumulator, GenericVector<GenericVector<int> > *x_coords, GenericVector<GenericVector<int> > *y_coords) { const C_OUTLINE* outline = startpt->src_outline; int x_limit = box.width() - 1; int y_limit = box.height() - 1; if (outline != NULL) { // Use higher-resolution edge points stored on the outline. // The outline coordinates may not match the binary image because of the // rotation for vertical text lines, but the root_denorm IS the matching // start of the DENORM chain. const DENORM* root_denorm = denorm.RootDenorm(); int step_length = outline->pathlength(); int start_index = startpt->start_step; // Note that if this run straddles the wrap-around point of the outline, // that lastpt->start_step may have a lower index than startpt->start_step, // and we want to use an end_index that allows us to use a positive // increment, so we add step_length if necessary, but that may be beyond the // bounds of the outline steps/ due to wrap-around, so we use % step_length // everywhere, except for start_index. int end_index = lastpt->start_step + lastpt->step_count; if (end_index <= start_index) end_index += step_length; // pos is the integer coordinates of the binary image steps. ICOORD pos = outline->position_at_index(start_index); FCOORD origin(box.left(), box.bottom()); // f_pos is a floating-point version of pos that offers improved edge // positioning using greyscale information or smoothing of edge steps. FCOORD f_pos = outline->sub_pixel_pos_at_index(pos, start_index); // pos_normed is f_pos after the appropriate normalization, and relative // to origin. // prev_normed is the previous value of pos_normed. FCOORD prev_normed; denorm.NormTransform(root_denorm, f_pos, &prev_normed); prev_normed -= origin; for (int index = start_index; index < end_index; ++index) { ICOORD step = outline->step(index % step_length); // Only use the point if its edge strength is positive. This excludes // points that don't provide useful information, eg // ___________ // |___________ // The vertical step provides only noisy, damaging information, as even // with a greyscale image, the positioning of the edge there may be a // fictitious extrapolation, so previous processing has eliminated it. if (outline->edge_strength_at_index(index % step_length) > 0) { FCOORD f_pos = outline->sub_pixel_pos_at_index(pos, index % step_length); FCOORD pos_normed; denorm.NormTransform(root_denorm, f_pos, &pos_normed); pos_normed -= origin; // Accumulate the information that is selected by the caller. if (bounding_box != NULL) { SegmentBBox(pos_normed, prev_normed, bounding_box); } if (accumulator != NULL) { SegmentLLSQ(pos_normed, prev_normed, accumulator); } if (x_coords != NULL && y_coords != NULL) { SegmentCoords(pos_normed, prev_normed, x_limit, y_limit, x_coords, y_coords); } prev_normed = pos_normed; } pos += step; } } else { // There is no outline, so we are forced to use the polygonal approximation. const EDGEPT* endpt = lastpt->next; const EDGEPT* pt = startpt; do { FCOORD next_pos(pt->next->pos.x - box.left(), pt->next->pos.y - box.bottom()); FCOORD pos(pt->pos.x - box.left(), pt->pos.y - box.bottom()); if (bounding_box != NULL) { SegmentBBox(next_pos, pos, bounding_box); } if (accumulator != NULL) { SegmentLLSQ(next_pos, pos, accumulator); } if (x_coords != NULL && y_coords != NULL) { SegmentCoords(next_pos, pos, x_limit, y_limit, x_coords, y_coords); } } while ((pt = pt->next) != endpt); } } // For all the edge steps in all the outlines, or polygonal approximation // where there are no edge steps, collects the steps into the bounding_box, // llsq and/or the x_coords/y_coords. Both are used in different kinds of // normalization. // For a description of x_coords, y_coords, see GetEdgeCoords above. void TBLOB::CollectEdges(const TBOX& box, TBOX* bounding_box, LLSQ* llsq, GenericVector<GenericVector<int> >* x_coords, GenericVector<GenericVector<int> >* y_coords) const { // Iterate the outlines. for (const TESSLINE* ol = outlines; ol != NULL; ol = ol->next) { // Iterate the polygon. EDGEPT* loop_pt = ol->FindBestStartPt(); EDGEPT* pt = loop_pt; if (pt == NULL) continue; do { if (pt->IsHidden()) continue; // Find a run of equal src_outline. EDGEPT* last_pt = pt; do { last_pt = last_pt->next; } while (last_pt != loop_pt && !last_pt->IsHidden() && last_pt->src_outline == pt->src_outline); last_pt = last_pt->prev; CollectEdgesOfRun(pt, last_pt, denorm_, box, bounding_box, llsq, x_coords, y_coords); pt = last_pt; } while ((pt = pt->next) != loop_pt); } } // Factory to build a TWERD from a (C_BLOB) WERD, with polygonal // approximation along the way. TWERD* TWERD::PolygonalCopy(bool allow_detailed_fx, WERD* src) { TWERD* tessword = new TWERD; tessword->latin_script = src->flag(W_SCRIPT_IS_LATIN); C_BLOB_IT b_it(src->cblob_list()); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { C_BLOB* blob = b_it.data(); TBLOB* tblob = TBLOB::PolygonalCopy(allow_detailed_fx, blob); tessword->blobs.push_back(tblob); } return tessword; } // Baseline normalizes the blobs in-place, recording the normalization in the // DENORMs in the blobs. void TWERD::BLNormalize(const BLOCK* block, const ROW* row, Pix* pix, bool inverse, float x_height, bool numeric_mode, tesseract::OcrEngineMode hint, const TBOX* norm_box, DENORM* word_denorm) { TBOX word_box = bounding_box(); if (norm_box != NULL) word_box = *norm_box; float word_middle = (word_box.left() + word_box.right()) / 2.0f; float input_y_offset = 0.0f; float final_y_offset = static_cast<float>(kBlnBaselineOffset); float scale = kBlnXHeight / x_height; if (hint == tesseract::OEM_CUBE_ONLY || row == NULL) { word_middle = word_box.left(); input_y_offset = word_box.bottom(); final_y_offset = 0.0f; if (hint == tesseract::OEM_CUBE_ONLY) scale = 1.0f; } else { input_y_offset = row->base_line(word_middle); } for (int b = 0; b < blobs.size(); ++b) { TBLOB* blob = blobs[b]; TBOX blob_box = blob->bounding_box(); float mid_x = (blob_box.left() + blob_box.right()) / 2.0f; float baseline = input_y_offset; float blob_scale = scale; if (numeric_mode) { baseline = blob_box.bottom(); blob_scale = ClipToRange(kBlnXHeight * 4.0f / (3 * blob_box.height()), scale, scale * 1.5f); } else if (row != NULL && hint != tesseract::OEM_CUBE_ONLY) { baseline = row->base_line(mid_x); } // The image will be 8-bit grey if the input was grey or color. Note that in // a grey image 0 is black and 255 is white. If the input was binary, then // the pix will be binary and 0 is white, with 1 being black. // To tell the difference pixGetDepth() will return 8 or 1. // The inverse flag will be true iff the word has been determined to be // white on black, and is independent of whether the pix is 8 bit or 1 bit. blob->Normalize(block, NULL, NULL, word_middle, baseline, blob_scale, blob_scale, 0.0f, final_y_offset, inverse, pix); } if (word_denorm != NULL) { word_denorm->SetupNormalization(block, NULL, NULL, word_middle, input_y_offset, scale, scale, 0.0f, final_y_offset); word_denorm->set_inverse(inverse); word_denorm->set_pix(pix); } } // Copies the data and the blobs, but leaves next untouched. void TWERD::CopyFrom(const TWERD& src) { Clear(); latin_script = src.latin_script; for (int b = 0; b < src.blobs.size(); ++b) { TBLOB* new_blob = new TBLOB(*src.blobs[b]); blobs.push_back(new_blob); } } // Deletes owned data. void TWERD::Clear() { blobs.delete_data_pointers(); blobs.clear(); } // Recomputes the bounding boxes of the blobs. void TWERD::ComputeBoundingBoxes() { for (int b = 0; b < blobs.size(); ++b) { blobs[b]->ComputeBoundingBoxes(); } } TBOX TWERD::bounding_box() const { TBOX result; for (int b = 0; b < blobs.size(); ++b) { TBOX box = blobs[b]->bounding_box(); result += box; } return result; } // Merges the blobs from start to end, not including end, and deletes // the blobs between start and end. void TWERD::MergeBlobs(int start, int end) { if (start >= blobs.size() - 1) return; // Nothing to do. TESSLINE* outline = blobs[start]->outlines; for (int i = start + 1; i < end && i < blobs.size(); ++i) { TBLOB* next_blob = blobs[i]; // Take the outlines from the next blob. if (outline == NULL) { blobs[start]->outlines = next_blob->outlines; outline = blobs[start]->outlines; } else { while (outline->next != NULL) outline = outline->next; outline->next = next_blob->outlines; next_blob->outlines = NULL; } // Delete the next blob and move on. delete next_blob; blobs[i] = NULL; } // Remove dead blobs from the vector. for (int i = start + 1; i < end && start + 1 < blobs.size(); ++i) { blobs.remove(start + 1); } } #ifndef GRAPHICS_DISABLED void TWERD::plot(ScrollView* window) { ScrollView::Color color = WERD::NextColor(ScrollView::BLACK); for (int b = 0; b < blobs.size(); ++b) { blobs[b]->plot(window, color, ScrollView::BROWN); color = WERD::NextColor(color); } } #endif // GRAPHICS_DISABLED /********************************************************************** * blob_origin * * Compute the origin of a compound blob, define to be the centre * of the bounding box. **********************************************************************/ void blob_origin(TBLOB *blob, /*blob to compute on */ TPOINT *origin) { /*return value */ TBOX bbox = blob->bounding_box(); *origin = (bbox.topleft() + bbox.botright()) / 2; } /********************************************************************** * divisible_blob * * Returns true if the blob contains multiple outlines than can be * separated using divide_blobs. Sets the location to be used in the * call to divide_blobs. **********************************************************************/ bool divisible_blob(TBLOB *blob, bool italic_blob, TPOINT* location) { if (blob->outlines == NULL || blob->outlines->next == NULL) return false; // Need at least 2 outlines for it to be possible. int max_gap = 0; TPOINT vertical = italic_blob ? kDivisibleVerticalItalic : kDivisibleVerticalUpright; for (TESSLINE* outline1 = blob->outlines; outline1 != NULL; outline1 = outline1->next) { if (outline1->is_hole) continue; // Holes do not count as separable. TPOINT mid_pt1( static_cast<inT16>((outline1->topleft.x + outline1->botright.x) / 2), static_cast<inT16>((outline1->topleft.y + outline1->botright.y) / 2)); int mid_prod1 = CROSS(mid_pt1, vertical); int min_prod1, max_prod1; outline1->MinMaxCrossProduct(vertical, &min_prod1, &max_prod1); for (TESSLINE* outline2 = outline1->next; outline2 != NULL; outline2 = outline2->next) { if (outline2->is_hole) continue; // Holes do not count as separable. TPOINT mid_pt2( static_cast<inT16>((outline2->topleft.x + outline2->botright.x) / 2), static_cast<inT16>((outline2->topleft.y + outline2->botright.y) / 2)); int mid_prod2 = CROSS(mid_pt2, vertical); int min_prod2, max_prod2; outline2->MinMaxCrossProduct(vertical, &min_prod2, &max_prod2); int mid_gap = abs(mid_prod2 - mid_prod1); int overlap = MIN(max_prod1, max_prod2) - MAX(min_prod1, min_prod2); if (mid_gap - overlap / 4 > max_gap) { max_gap = mid_gap - overlap / 4; *location = mid_pt1; *location += mid_pt2; *location /= 2; } } } // Use the y component of the vertical vector as an approximation to its // length. return max_gap > vertical.y; } /********************************************************************** * divide_blobs * * Create two blobs by grouping the outlines in the appropriate blob. * The outlines that are beyond the location point are moved to the * other blob. The ones whose x location is less than that point are * retained in the original blob. **********************************************************************/ void divide_blobs(TBLOB *blob, TBLOB *other_blob, bool italic_blob, const TPOINT& location) { TPOINT vertical = italic_blob ? kDivisibleVerticalItalic : kDivisibleVerticalUpright; TESSLINE *outline1 = NULL; TESSLINE *outline2 = NULL; TESSLINE *outline = blob->outlines; blob->outlines = NULL; int location_prod = CROSS(location, vertical); while (outline != NULL) { TPOINT mid_pt( static_cast<inT16>((outline->topleft.x + outline->botright.x) / 2), static_cast<inT16>((outline->topleft.y + outline->botright.y) / 2)); int mid_prod = CROSS(mid_pt, vertical); if (mid_prod < location_prod) { // Outline is in left blob. if (outline1) outline1->next = outline; else blob->outlines = outline; outline1 = outline; } else { // Outline is in right blob. if (outline2) outline2->next = outline; else other_blob->outlines = outline; outline2 = outline; } outline = outline->next; } if (outline1) outline1->next = NULL; if (outline2) outline2->next = NULL; }
1080228-arabicocr11
ccstruct/blobs.cpp
C
asf20
36,440
/********************************************************************** * File: blread.cpp (Formerly pdread.c) * Description: Friend function of BLOCK to read the uscan pd file. * Author: Ray Smith * Created: Mon Mar 18 14:39:00 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdlib.h> #ifdef __UNIX__ #include <assert.h> #endif #include "scanutils.h" #include "fileerr.h" #include "blread.h" #define UNLV_EXT ".uzn" // unlv zone file /********************************************************************** * read_unlv_file * * Read a whole unlv zone file to make a list of blocks. **********************************************************************/ bool read_unlv_file( //print list of sides STRING name, //basename of file inT32 xsize, //image size inT32 ysize, //image size BLOCK_LIST *blocks //output list ) { FILE *pdfp; //file pointer BLOCK *block; //current block int x; //current top-down coords int y; int width; //of current block int height; BLOCK_IT block_it = blocks; //block iterator name += UNLV_EXT; //add extension if ((pdfp = fopen (name.string (), "rb")) == NULL) { return false; //didn't read one } else { while (tfscanf(pdfp, "%d %d %d %d %*s", &x, &y, &width, &height) >= 4) { //make rect block block = new BLOCK (name.string (), TRUE, 0, 0, (inT16) x, (inT16) (ysize - y - height), (inT16) (x + width), (inT16) (ysize - y)); //on end of list block_it.add_to_end (block); } fclose(pdfp); } return true; } void FullPageBlock(int width, int height, BLOCK_LIST *blocks) { BLOCK_IT block_it(blocks); BLOCK* block = new BLOCK("", TRUE, 0, 0, 0, 0, width, height); block_it.add_to_end(block); }
1080228-arabicocr11
ccstruct/blread.cpp
C++
asf20
2,765
/////////////////////////////////////////////////////////////////////// // File: publictypes.h // Description: Types used in both the API and internally // Author: Ray Smith // Created: Wed Mar 03 09:22:53 PST 2010 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCSTRUCT_PUBLICTYPES_H__ #define TESSERACT_CCSTRUCT_PUBLICTYPES_H__ // This file contains types that are used both by the API and internally // to Tesseract. In order to decouple the API from Tesseract and prevent cyclic // dependencies, THIS FILE SHOULD NOT DEPEND ON ANY OTHER PART OF TESSERACT. // Restated: It is OK for low-level Tesseract files to include publictypes.h, // but not for the low-level tesseract code to include top-level API code. // This file should not use other Tesseract types, as that would drag // their includes into the API-level. // API-level code should include apitypes.h in preference to this file. /** Number of printers' points in an inch. The unit of the pointsize return. */ const int kPointsPerInch = 72; /** * Possible types for a POLY_BLOCK or ColPartition. * Must be kept in sync with kPBColors in polyblk.cpp and PTIs*Type functions * below, as well as kPolyBlockNames in publictypes.cpp. * Used extensively by ColPartition, and POLY_BLOCK. */ enum PolyBlockType { PT_UNKNOWN, // Type is not yet known. Keep as the first element. PT_FLOWING_TEXT, // Text that lives inside a column. PT_HEADING_TEXT, // Text that spans more than one column. PT_PULLOUT_TEXT, // Text that is in a cross-column pull-out region. PT_EQUATION, // Partition belonging to an equation region. PT_INLINE_EQUATION, // Partition has inline equation. PT_TABLE, // Partition belonging to a table region. PT_VERTICAL_TEXT, // Text-line runs vertically. PT_CAPTION_TEXT, // Text that belongs to an image. PT_FLOWING_IMAGE, // Image that lives inside a column. PT_HEADING_IMAGE, // Image that spans more than one column. PT_PULLOUT_IMAGE, // Image that is in a cross-column pull-out region. PT_HORZ_LINE, // Horizontal Line. PT_VERT_LINE, // Vertical Line. PT_NOISE, // Lies outside of any column. PT_COUNT }; /** Returns true if PolyBlockType is of horizontal line type */ inline bool PTIsLineType(PolyBlockType type) { return type == PT_HORZ_LINE || type == PT_VERT_LINE; } /** Returns true if PolyBlockType is of image type */ inline bool PTIsImageType(PolyBlockType type) { return type == PT_FLOWING_IMAGE || type == PT_HEADING_IMAGE || type == PT_PULLOUT_IMAGE; } /** Returns true if PolyBlockType is of text type */ inline bool PTIsTextType(PolyBlockType type) { return type == PT_FLOWING_TEXT || type == PT_HEADING_TEXT || type == PT_PULLOUT_TEXT || type == PT_TABLE || type == PT_VERTICAL_TEXT || type == PT_CAPTION_TEXT || type == PT_INLINE_EQUATION; } // Returns true if PolyBlockType is of pullout(inter-column) type inline bool PTIsPulloutType(PolyBlockType type) { return type == PT_PULLOUT_IMAGE || type == PT_PULLOUT_TEXT; } /** String name for each block type. Keep in sync with PolyBlockType. */ extern const char* kPolyBlockNames[]; namespace tesseract { /** * +------------------+ Orientation Example: * | 1 Aaaa Aaaa Aaaa | ==================== * | Aaa aa aaa aa | To left is a diagram of some (1) English and * | aaaaaa A aa aaa. | (2) Chinese text and a (3) photo credit. * | 2 | * | ####### c c C | Upright Latin characters are represented as A and a. * | ####### c c c | '<' represents a latin character rotated * | < ####### c c c | anti-clockwise 90 degrees. * | < ####### c c | * | < ####### . c | Upright Chinese characters are represented C and c. * | 3 ####### c | * +------------------+ NOTA BENE: enum values here should match goodoc.proto * If you orient your head so that "up" aligns with Orientation, * then the characters will appear "right side up" and readable. * * In the example above, both the English and Chinese paragraphs are oriented * so their "up" is the top of the page (page up). The photo credit is read * with one's head turned leftward ("up" is to page left). * * The values of this enum match the convention of Tesseract's osdetect.h */ enum Orientation { ORIENTATION_PAGE_UP = 0, ORIENTATION_PAGE_RIGHT = 1, ORIENTATION_PAGE_DOWN = 2, ORIENTATION_PAGE_LEFT = 3, }; /** * The grapheme clusters within a line of text are laid out logically * in this direction, judged when looking at the text line rotated so that * its Orientation is "page up". * * For English text, the writing direction is left-to-right. For the * Chinese text in the above example, the writing direction is top-to-bottom. */ enum WritingDirection { WRITING_DIRECTION_LEFT_TO_RIGHT = 0, WRITING_DIRECTION_RIGHT_TO_LEFT = 1, WRITING_DIRECTION_TOP_TO_BOTTOM = 2, }; /** * The text lines are read in the given sequence. * * In English, the order is top-to-bottom. * In Chinese, vertical text lines are read right-to-left. Mongolian is * written in vertical columns top to bottom like Chinese, but the lines * order left-to right. * * Note that only some combinations make sense. For example, * WRITING_DIRECTION_LEFT_TO_RIGHT implies TEXTLINE_ORDER_TOP_TO_BOTTOM */ enum TextlineOrder { TEXTLINE_ORDER_LEFT_TO_RIGHT = 0, TEXTLINE_ORDER_RIGHT_TO_LEFT = 1, TEXTLINE_ORDER_TOP_TO_BOTTOM = 2, }; /** * Possible modes for page layout analysis. These *must* be kept in order * of decreasing amount of layout analysis to be done, except for OSD_ONLY, * so that the inequality test macros below work. */ enum PageSegMode { PSM_OSD_ONLY, ///< Orientation and script detection only. PSM_AUTO_OSD, ///< Automatic page segmentation with orientation and ///< script detection. (OSD) PSM_AUTO_ONLY, ///< Automatic page segmentation, but no OSD, or OCR. PSM_AUTO, ///< Fully automatic page segmentation, but no OSD. PSM_SINGLE_COLUMN, ///< Assume a single column of text of variable sizes. PSM_SINGLE_BLOCK_VERT_TEXT, ///< Assume a single uniform block of vertically ///< aligned text. PSM_SINGLE_BLOCK, ///< Assume a single uniform block of text. (Default.) PSM_SINGLE_LINE, ///< Treat the image as a single text line. PSM_SINGLE_WORD, ///< Treat the image as a single word. PSM_CIRCLE_WORD, ///< Treat the image as a single word in a circle. PSM_SINGLE_CHAR, ///< Treat the image as a single character. PSM_SPARSE_TEXT, ///< Find as much text as possible in no particular order. PSM_SPARSE_TEXT_OSD, ///< Sparse text with orientation and script det. PSM_RAW_LINE, ///< Treat the image as a single text line, bypassing ///< hacks that are Tesseract-specific. PSM_COUNT ///< Number of enum entries. }; /** * Inline functions that act on a PageSegMode to determine whether components of * layout analysis are enabled. * *Depend critically on the order of elements of PageSegMode.* * NOTE that arg is an int for compatibility with INT_PARAM. */ inline bool PSM_OSD_ENABLED(int pageseg_mode) { return pageseg_mode <= PSM_AUTO_OSD || pageseg_mode == PSM_SPARSE_TEXT_OSD; } inline bool PSM_COL_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_AUTO; } inline bool PSM_SPARSE(int pageseg_mode) { return pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD; } inline bool PSM_BLOCK_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_COLUMN; } inline bool PSM_LINE_FIND_ENABLED(int pageseg_mode) { return pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_BLOCK; } inline bool PSM_WORD_FIND_ENABLED(int pageseg_mode) { return (pageseg_mode >= PSM_AUTO_OSD && pageseg_mode <= PSM_SINGLE_LINE) || pageseg_mode == PSM_SPARSE_TEXT || pageseg_mode == PSM_SPARSE_TEXT_OSD; } /** * enum of the elements of the page hierarchy, used in ResultIterator * to provide functions that operate on each level without having to * have 5x as many functions. */ enum PageIteratorLevel { RIL_BLOCK, // Block of text/image/separator line. RIL_PARA, // Paragraph within a block. RIL_TEXTLINE, // Line within a paragraph. RIL_WORD, // Word within a textline. RIL_SYMBOL // Symbol/character within a word. }; /** * JUSTIFICATION_UNKNONW * The alignment is not clearly one of the other options. This could happen * for example if there are only one or two lines of text or the text looks * like source code or poetry. * * NOTA BENE: Fully justified paragraphs (text aligned to both left and right * margins) are marked by Tesseract with JUSTIFICATION_LEFT if their text * is written with a left-to-right script and with JUSTIFICATION_RIGHT if * their text is written in a right-to-left script. * * Interpretation for text read in vertical lines: * "Left" is wherever the starting reading position is. * * JUSTIFICATION_LEFT * Each line, except possibly the first, is flush to the same left tab stop. * * JUSTIFICATION_CENTER * The text lines of the paragraph are centered about a line going * down through their middle of the text lines. * * JUSTIFICATION_RIGHT * Each line, except possibly the first, is flush to the same right tab stop. */ enum ParagraphJustification { JUSTIFICATION_UNKNOWN, JUSTIFICATION_LEFT, JUSTIFICATION_CENTER, JUSTIFICATION_RIGHT, }; /** * When Tesseract/Cube is initialized we can choose to instantiate/load/run * only the Tesseract part, only the Cube part or both along with the combiner. * The preference of which engine to use is stored in tessedit_ocr_engine_mode. * * ATTENTION: When modifying this enum, please make sure to make the * appropriate changes to all the enums mirroring it (e.g. OCREngine in * cityblock/workflow/detection/detection_storage.proto). Such enums will * mention the connection to OcrEngineMode in the comments. */ enum OcrEngineMode { OEM_TESSERACT_ONLY, // Run Tesseract only - fastest OEM_CUBE_ONLY, // Run Cube only - better accuracy, but slower OEM_TESSERACT_CUBE_COMBINED, // Run both and combine results - best accuracy OEM_DEFAULT // Specify this mode when calling init_*(), // to indicate that any of the above modes // should be automatically inferred from the // variables in the language-specific config, // command-line configs, or if not specified // in any of the above should be set to the // default OEM_TESSERACT_ONLY. }; } // namespace tesseract. #endif // TESSERACT_CCSTRUCT_PUBLICTYPES_H__
1080228-arabicocr11
ccstruct/publictypes.h
C++
asf20
11,578
/* -*-C-*- ******************************************************************************** * * File: split.h (Formerly split.h) * Description: * Author: Mark Seaman, SW Productivity * Created: Fri Oct 16 14:37:00 1987 * Modified: Mon May 13 10:49:23 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *****************************************************************************/ #ifndef SPLIT_H #define SPLIT_H /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "blobs.h" #include "oldlist.h" /*---------------------------------------------------------------------- T y p e s ----------------------------------------------------------------------*/ typedef struct split_record { /* SPLIT */ EDGEPT *point1; EDGEPT *point2; } SPLIT; typedef LIST SPLITS; /* SPLITS */ /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ extern BOOL_VAR_H(wordrec_display_splits, 0, "Display splits"); /*---------------------------------------------------------------------- M a c r o s ----------------------------------------------------------------------*/ /********************************************************************** * clone_split * * Create a new split record and set the contents equal to the contents * of this record. **********************************************************************/ #define clone_split(dest,source) \ if (source) \ (dest) = new_split ((source)->point1, (source)->point2); \ else \ (dest) = (SPLIT*) NULL \ /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ void delete_split(SPLIT *split); EDGEPT *make_edgept(int x, int y, EDGEPT *next, EDGEPT *prev); void remove_edgept(EDGEPT *point); SPLIT *new_split(EDGEPT *point1, EDGEPT *point2); void print_split(SPLIT *split); void split_outline(EDGEPT *join_point1, EDGEPT *join_point2); void unsplit_outlines(EDGEPT *p1, EDGEPT *p2); #endif
1080228-arabicocr11
ccstruct/split.h
C
asf20
3,176
/********************************************************************** * File: pdblock.c (Formerly pdblk.c) * Description: PDBLK member functions and iterator functions. * Author: Ray Smith * Created: Fri Mar 15 09:41:28 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdlib.h> #include "allheaders.h" #include "blckerr.h" #include "pdblock.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #define BLOCK_LABEL_HEIGHT 150 //char height of block id CLISTIZE (PDBLK) /********************************************************************** * PDBLK::PDBLK * * Constructor for a simple rectangular block. **********************************************************************/ PDBLK::PDBLK ( //rectangular block inT16 xmin, //bottom left inT16 ymin, inT16 xmax, //top right inT16 ymax): box (ICOORD (xmin, ymin), ICOORD (xmax, ymax)) { //boundaries ICOORDELT_IT left_it = &leftside; ICOORDELT_IT right_it = &rightside; hand_poly = NULL; left_it.set_to_list (&leftside); right_it.set_to_list (&rightside); //make default box left_it.add_to_end (new ICOORDELT (xmin, ymin)); left_it.add_to_end (new ICOORDELT (xmin, ymax)); right_it.add_to_end (new ICOORDELT (xmax, ymin)); right_it.add_to_end (new ICOORDELT (xmax, ymax)); index_ = 0; } /********************************************************************** * PDBLK::set_sides * * Sets left and right vertex lists **********************************************************************/ void PDBLK::set_sides( //set vertex lists ICOORDELT_LIST *left, //left vertices ICOORDELT_LIST *right //right vertices ) { //boundaries ICOORDELT_IT left_it = &leftside; ICOORDELT_IT right_it = &rightside; leftside.clear (); left_it.move_to_first (); left_it.add_list_before (left); rightside.clear (); right_it.move_to_first (); right_it.add_list_before (right); } /********************************************************************** * PDBLK::contains * * Return TRUE if the given point is within the block. **********************************************************************/ BOOL8 PDBLK::contains( //test containment ICOORD pt //point to test ) { BLOCK_RECT_IT it = this; //rectangle iterator ICOORD bleft, tright; //corners of rectangle for (it.start_block (); !it.cycled_rects (); it.forward ()) { //get rectangle it.bounding_box (bleft, tright); //inside rect if (pt.x () >= bleft.x () && pt.x () <= tright.x () && pt.y () >= bleft.y () && pt.y () <= tright.y ()) return TRUE; //is inside } return FALSE; //not inside } /********************************************************************** * PDBLK::move * * Reposition block **********************************************************************/ void PDBLK::move( // reposition block const ICOORD vec // by vector ) { ICOORDELT_IT it(&leftside); for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) *(it.data ()) += vec; it.set_to_list (&rightside); for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) *(it.data ()) += vec; box.move (vec); } // Returns a binary Pix mask with a 1 pixel for every pixel within the // block. Rotates the coordinate system by rerotation prior to rendering. Pix* PDBLK::render_mask(const FCOORD& rerotation) { TBOX rotated_box(box); rotated_box.rotate(rerotation); Pix* pix = pixCreate(rotated_box.width(), rotated_box.height(), 1); if (hand_poly != NULL) { // We are going to rotate, so get a deep copy of the points and // make a new POLY_BLOCK with it. ICOORDELT_LIST polygon; polygon.deep_copy(hand_poly->points(), ICOORDELT::deep_copy); POLY_BLOCK image_block(&polygon, hand_poly->isA()); image_block.rotate(rerotation); // Block outline is a polygon, so use a PB_LINE_IT to get the // rasterized interior. (Runs of interior pixels on a line.) PB_LINE_IT *lines = new PB_LINE_IT(&image_block); for (int y = box.bottom(); y < box.top(); ++y) { ICOORDELT_LIST* segments = lines->get_line(y); if (!segments->empty()) { ICOORDELT_IT s_it(segments); // Each element of segments is a start x and x size of the // run of interior pixels. for (s_it.mark_cycle_pt(); !s_it.cycled_list(); s_it.forward()) { int start = s_it.data()->x(); int xext = s_it.data()->y(); // Set the run of pixels to 1. pixRasterop(pix, start - rotated_box.left(), rotated_box.height() - 1 - (y - rotated_box.bottom()), xext, 1, PIX_SET, NULL, 0, 0); } } delete segments; } delete lines; } else { // Just fill the whole block as there is only a bounding box. pixRasterop(pix, 0, 0, rotated_box.width(), rotated_box.height(), PIX_SET, NULL, 0, 0); } return pix; } /********************************************************************** * PDBLK::plot * * Plot the outline of a block in the given colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED void PDBLK::plot( //draw outline ScrollView* window, //window to draw in inT32 serial, //serial number ScrollView::Color colour //colour to draw in ) { ICOORD startpt; //start of outline ICOORD endpt; //end of outline ICOORD prevpt; //previous point ICOORDELT_IT it = &leftside; //iterator //set the colour window->Pen(colour); window->TextAttributes("Times", BLOCK_LABEL_HEIGHT, false, false, false); if (hand_poly != NULL) { hand_poly->plot(window, serial); } else if (!leftside.empty ()) { startpt = *(it.data ()); //bottom left corner // tprintf("Block %d bottom left is (%d,%d)\n", // serial,startpt.x(),startpt.y()); char temp_buff[34]; #if defined(__UNIX__) || defined(MINGW) sprintf(temp_buff, INT32FORMAT, serial); #else ultoa (serial, temp_buff, 10); #endif window->Text(startpt.x (), startpt.y (), temp_buff); window->SetCursor(startpt.x (), startpt.y ()); do { prevpt = *(it.data ()); //previous point it.forward (); //move to next point //draw round corner window->DrawTo(prevpt.x (), it.data ()->y ()); window->DrawTo(it.data ()->x (), it.data ()->y ()); } while (!it.at_last ()); //until end of list endpt = *(it.data ()); //end point //other side of boundary window->SetCursor(startpt.x (), startpt.y ()); it.set_to_list (&rightside); prevpt = startpt; for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { //draw round corner window->DrawTo(prevpt.x (), it.data ()->y ()); window->DrawTo(it.data ()->x (), it.data ()->y ()); prevpt = *(it.data ()); //previous point } //close boundary window->DrawTo(endpt.x(), endpt.y()); } } #endif /********************************************************************** * PDBLK::operator= * * Assignment - duplicate the block structure, but with an EMPTY row list. **********************************************************************/ PDBLK & PDBLK::operator= ( //assignment const PDBLK & source //from this ) { // this->ELIST_LINK::operator=(source); if (!leftside.empty ()) leftside.clear (); if (!rightside.empty ()) rightside.clear (); leftside.deep_copy(&source.leftside, &ICOORDELT::deep_copy); rightside.deep_copy(&source.rightside, &ICOORDELT::deep_copy); box = source.box; return *this; } /********************************************************************** * BLOCK_RECT_IT::BLOCK_RECT_IT * * Construct a block rectangle iterator. **********************************************************************/ BLOCK_RECT_IT::BLOCK_RECT_IT ( //iterate rectangles PDBLK * blkptr //from block ):left_it (&blkptr->leftside), right_it (&blkptr->rightside) { block = blkptr; //remember block //non empty list if (!blkptr->leftside.empty ()) { start_block(); //ready for iteration } } /********************************************************************** * BLOCK_RECT_IT::set_to_block * * Start a new block. **********************************************************************/ void BLOCK_RECT_IT::set_to_block( //start (new) block PDBLK *blkptr) { //block to start block = blkptr; //remember block //set iterators left_it.set_to_list (&blkptr->leftside); right_it.set_to_list (&blkptr->rightside); if (!blkptr->leftside.empty ()) start_block(); //ready for iteration } /********************************************************************** * BLOCK_RECT_IT::start_block * * Restart a block. **********************************************************************/ void BLOCK_RECT_IT::start_block() { //start (new) block left_it.move_to_first (); right_it.move_to_first (); left_it.mark_cycle_pt (); right_it.mark_cycle_pt (); ymin = left_it.data ()->y (); //bottom of first box ymax = left_it.data_relative (1)->y (); if (right_it.data_relative (1)->y () < ymax) //smallest step ymax = right_it.data_relative (1)->y (); } /********************************************************************** * BLOCK_RECT_IT::forward * * Move to the next rectangle in the block. **********************************************************************/ void BLOCK_RECT_IT::forward() { //next rectangle if (!left_it.empty ()) { //non-empty list if (left_it.data_relative (1)->y () == ymax) left_it.forward (); //move to meet top if (right_it.data_relative (1)->y () == ymax) right_it.forward (); //last is special if (left_it.at_last () || right_it.at_last ()) { left_it.move_to_first (); //restart right_it.move_to_first (); //now at bottom ymin = left_it.data ()->y (); } else { ymin = ymax; //new bottom } //next point ymax = left_it.data_relative (1)->y (); if (right_it.data_relative (1)->y () < ymax) //least step forward ymax = right_it.data_relative (1)->y (); } } /********************************************************************** * BLOCK_LINE_IT::get_line * * Get the the start and width of a line in the block. **********************************************************************/ inT16 BLOCK_LINE_IT::get_line( //get a line inT16 y, //line to get inT16 &xext //output extent ) { ICOORD bleft; //bounding box ICOORD tright; //of block & rect //get block box block->bounding_box (bleft, tright); if (y < bleft.y () || y >= tright.y ()) { // block->print(stderr,FALSE); BADBLOCKLINE.error ("BLOCK_LINE_IT::get_line", ABORT, "Y=%d", y); } //get rectangle box rect_it.bounding_box (bleft, tright); //inside rectangle if (y >= bleft.y () && y < tright.y ()) { //width of line xext = tright.x () - bleft.x (); return bleft.x (); //start of line } for (rect_it.start_block (); !rect_it.cycled_rects (); rect_it.forward ()) { //get rectangle box rect_it.bounding_box (bleft, tright); //inside rectangle if (y >= bleft.y () && y < tright.y ()) { //width of line xext = tright.x () - bleft.x (); return bleft.x (); //start of line } } LOSTBLOCKLINE.error ("BLOCK_LINE_IT::get_line", ABORT, "Y=%d", y); return 0; //dummy to stop warning }
1080228-arabicocr11
ccstruct/pdblock.cpp
C++
asf20
13,583
/********************************************************************** * File: linlsq.h (Formerly llsq.h) * Description: Linear Least squares fitting code. * Author: Ray Smith * Created: Thu Sep 12 08:44:51 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCSTRUCT_LINLSQ_H_ #define TESSERACT_CCSTRUCT_LINLSQ_H_ #include "points.h" #include "params.h" class LLSQ { public: LLSQ() { // constructor clear(); // set to zeros } void clear(); // initialize // Adds an element with a weight of 1. void add(double x, double y); // Adds an element with a specified weight. void add(double x, double y, double weight); // Adds a whole LLSQ. void add(const LLSQ& other); // Deletes an element with a weight of 1. void remove(double x, double y); inT32 count() const { // no of elements return static_cast<int>(total_weight + 0.5); } double m() const; // get gradient double c(double m) const; // get constant double rms(double m, double c) const; // get error double pearson() const; // get correlation coefficient. // Returns the x,y means as an FCOORD. FCOORD mean_point() const; // Returns the average sum of squared perpendicular error from a line // through mean_point() in the direction dir. double rms_orth(const FCOORD &dir) const; // Returns the direction of the fitted line as a unit vector, using the // least mean squared perpendicular distance. The line runs through the // mean_point, i.e. a point p on the line is given by: // p = mean_point() + lambda * vector_fit() for some real number lambda. // Note that the result (0<=x<=1, -1<=y<=-1) is directionally ambiguous // and may be negated without changing its meaning, since a line is only // unique to a range of pi radians. // Modernists prefer to think of this as an Eigenvalue problem, but // Pearson had the simple solution in 1901. // // Note that this is equivalent to returning the Principal Component in PCA, // or the eigenvector corresponding to the largest eigenvalue in the // covariance matrix. FCOORD vector_fit() const; // Returns the covariance. double covariance() const { if (total_weight > 0.0) return (sigxy - sigx * sigy / total_weight) / total_weight; else return 0.0; } double x_variance() const { if (total_weight > 0.0) return (sigxx - sigx * sigx / total_weight) / total_weight; else return 0.0; } double y_variance() const { if (total_weight > 0.0) return (sigyy - sigy * sigy / total_weight) / total_weight; else return 0.0; } private: double total_weight; // no of elements or sum of weights. double sigx; // sum of x double sigy; // sum of y double sigxx; // sum x squared double sigxy; // sum of xy double sigyy; // sum y squared }; // Returns the median value of the vector, given that the values are // circular, with the given modulus. Values may be signed or unsigned, // eg range from -pi to pi (modulus 2pi) or from 0 to 2pi (modulus 2pi). // NOTE that the array is shuffled, but the time taken is linear. // An assumption is made that most of the values are spread over no more than // half the range, but wrap-around is accounted for if the median is near // the wrap-around point. // Cannot be a member of GenericVector, as it makes heavy used of LLSQ. // T must be an integer or float/double type. template<typename T> T MedianOfCircularValues(T modulus, GenericVector<T>* v) { LLSQ stats; T halfrange = static_cast<T>(modulus / 2); int num_elements = v->size(); for (int i = 0; i < num_elements; ++i) { stats.add((*v)[i], (*v)[i] + halfrange); } bool offset_needed = stats.y_variance() < stats.x_variance(); if (offset_needed) { for (int i = 0; i < num_elements; ++i) { (*v)[i] += halfrange; } } int median_index = v->choose_nth_item(num_elements / 2); if (offset_needed) { for (int i = 0; i < num_elements; ++i) { (*v)[i] -= halfrange; } } return (*v)[median_index]; } #endif // TESSERACT_CCSTRUCT_LINLSQ_H_
1080228-arabicocr11
ccstruct/linlsq.h
C++
asf20
4,831
/////////////////////////////////////////////////////////////////////// // File: publictypes.cpp // Description: Types used in both the API and internally // Author: Ray Smith // Created: Wed Mar 03 11:17:09 PST 2010 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "publictypes.h" /** String name for each block type. Keep in sync with PolyBlockType. */ const char* kPolyBlockNames[] = { "Unknown", "Flowing Text", "Heading Text", "Pullout Text", "Equation", "Inline Equation", "Table", "Vertical Text", "Caption Text", "Flowing Image", "Heading Image", "Pullout Image", "Horizontal Line", "Vertical Line", "Noise", "" // End marker for testing that sizes match. };
1080228-arabicocr11
ccstruct/publictypes.cpp
C++
asf20
1,336
/********************************************************************** * File: genblob.h (Formerly gblob.h) * Description: Generic Blob processing routines * Author: Phil Cheatle * Created: Mon Nov 25 10:53:26 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef GENBLOB_H #define GENBLOB_H // Sort function to sort blobs by ascending left edge. int c_blob_comparator(const void *blob1p, // ptr to ptr to blob1 const void *blob2p); #endif
1080228-arabicocr11
ccstruct/genblob.h
C
asf20
1,148
/********************************************************************** * File: blobbox.h (Formerly blobnbox.h) * Description: Code for the textord blob class. * Author: Ray Smith * Created: Thu Jul 30 09:08:51 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef BLOBBOX_H #define BLOBBOX_H #include "clst.h" #include "elst2.h" #include "werd.h" #include "ocrblock.h" #include "statistc.h" enum PITCH_TYPE { PITCH_DUNNO, // insufficient data PITCH_DEF_FIXED, // definitely fixed PITCH_MAYBE_FIXED, // could be PITCH_DEF_PROP, PITCH_MAYBE_PROP, PITCH_CORR_FIXED, PITCH_CORR_PROP }; // The possible tab-stop types of each side of a BLOBNBOX. // The ordering is important, as it is used for deleting dead-ends in the // search. ALIGNED, CONFIRMED and VLINE should remain greater than the // non-aligned, unset, or deleted members. enum TabType { TT_NONE, // Not a tab. TT_DELETED, // Not a tab after detailed analysis. TT_MAYBE_RAGGED, // Initial designation of a tab-stop candidate. TT_MAYBE_ALIGNED, // Initial designation of a tab-stop candidate. TT_CONFIRMED, // Aligned with neighbours. TT_VLINE // Detected as a vertical line. }; // The possible region types of a BLOBNBOX. // Note: keep all the text types > BRT_UNKNOWN and all the image types less. // Keep in sync with kBlobTypes in colpartition.cpp and BoxColor, and the // *Type static functions below. enum BlobRegionType { BRT_NOISE, // Neither text nor image. BRT_HLINE, // Horizontal separator line. BRT_VLINE, // Vertical separator line. BRT_RECTIMAGE, // Rectangular image. BRT_POLYIMAGE, // Non-rectangular image. BRT_UNKNOWN, // Not determined yet. BRT_VERT_TEXT, // Vertical alignment, not necessarily vertically oriented. BRT_TEXT, // Convincing text. BRT_COUNT // Number of possibilities. }; // enum for elements of arrays that refer to neighbours. // NOTE: keep in this order, so ^2 can be used to flip direction. enum BlobNeighbourDir { BND_LEFT, BND_BELOW, BND_RIGHT, BND_ABOVE, BND_COUNT }; // enum for special type of text characters, such as math symbol or italic. enum BlobSpecialTextType { BSTT_NONE, // No special. BSTT_ITALIC, // Italic style. BSTT_DIGIT, // Digit symbols. BSTT_MATH, // Mathmatical symobls (not including digit). BSTT_UNCLEAR, // Characters with low recognition rate. BSTT_SKIP, // Characters that we skip labeling (usually too small). BSTT_COUNT }; inline BlobNeighbourDir DirOtherWay(BlobNeighbourDir dir) { return static_cast<BlobNeighbourDir>(dir ^ 2); } // BlobTextFlowType indicates the quality of neighbouring information // related to a chain of connected components, either horizontally or // vertically. Also used by ColPartition for the collection of blobs // within, which should all have the same value in most cases. enum BlobTextFlowType { BTFT_NONE, // No text flow set yet. BTFT_NONTEXT, // Flow too poor to be likely text. BTFT_NEIGHBOURS, // Neighbours support flow in this direction. BTFT_CHAIN, // There is a weak chain of text in this direction. BTFT_STRONG_CHAIN, // There is a strong chain of text in this direction. BTFT_TEXT_ON_IMAGE, // There is a strong chain of text on an image. BTFT_LEADER, // Leader dots/dashes etc. BTFT_COUNT }; // Returns true if type1 dominates type2 in a merge. Mostly determined by the // ordering of the enum, LEADER is weak and dominates nothing. // The function is anti-symmetric (t1 > t2) === !(t2 > t1), except that // this cannot be true if t1 == t2, so the result is undefined. inline bool DominatesInMerge(BlobTextFlowType type1, BlobTextFlowType type2) { // LEADER always loses. if (type1 == BTFT_LEADER) return false; if (type2 == BTFT_LEADER) return true; // With those out of the way, the ordering of the enum determines the result. return type1 >= type2; } namespace tesseract { class ColPartition; } class BLOBNBOX; ELISTIZEH (BLOBNBOX) class BLOBNBOX:public ELIST_LINK { public: BLOBNBOX() { ConstructionInit(); } explicit BLOBNBOX(C_BLOB *srcblob) { box = srcblob->bounding_box(); ConstructionInit(); cblob_ptr = srcblob; area = static_cast<int>(srcblob->area()); } static BLOBNBOX* RealBlob(C_OUTLINE* outline) { C_BLOB* blob = new C_BLOB(outline); return new BLOBNBOX(blob); } // Rotates the box and the underlying blob. void rotate(FCOORD rotation); // Methods that act on the box without touching the underlying blob. // Reflect the box in the y-axis, leaving the underlying blob untouched. void reflect_box_in_y_axis(); // Rotates the box by the angle given by rotation. // If the blob is a diacritic, then only small rotations for skew // correction can be applied. void rotate_box(FCOORD rotation); // Moves just the box by the given vector. void translate_box(ICOORD v) { if (IsDiacritic()) { box.move(v); base_char_top_ += v.y(); base_char_bottom_ += v.y(); } else { box.move(v); set_diacritic_box(box); } } void merge(BLOBNBOX *nextblob); void really_merge(BLOBNBOX* other); void chop( // fake chop blob BLOBNBOX_IT *start_it, // location of this BLOBNBOX_IT *blob_it, // iterator FCOORD rotation, // for landscape float xheight); // line height void NeighbourGaps(int gaps[BND_COUNT]) const; void MinMaxGapsClipped(int* h_min, int* h_max, int* v_min, int* v_max) const; void CleanNeighbours(); // Returns positive if there is at least one side neighbour that has a // similar stroke width and is not on the other side of a rule line. int GoodTextBlob() const; // Returns the number of side neighbours that are of type BRT_NOISE. int NoisyNeighbours() const; // Returns true if the blob is noise and has no owner. bool DeletableNoise() const { return owner() == NULL && region_type() == BRT_NOISE; } // Returns true, and sets vert_possible/horz_possible if the blob has some // feature that makes it individually appear to flow one way. // eg if it has a high aspect ratio, yet has a complex shape, such as a // joined word in Latin, Arabic, or Hindi, rather than being a -, I, l, 1. bool DefiniteIndividualFlow(); // Returns true if there is no tabstop violation in merging this and other. bool ConfirmNoTabViolation(const BLOBNBOX& other) const; // Returns true if other has a similar stroke width to this. bool MatchingStrokeWidth(const BLOBNBOX& other, double fractional_tolerance, double constant_tolerance) const; // Returns a bounding box of the outline contained within the // given horizontal range. TBOX BoundsWithinLimits(int left, int right); // Estimates and stores the baseline position based on the shape of the // outline. void EstimateBaselinePosition(); // Simple accessors. const TBOX& bounding_box() const { return box; } // Set the bounding box. Use with caution. // Normally use compute_bounding_box instead. void set_bounding_box(const TBOX& new_box) { box = new_box; base_char_top_ = box.top(); base_char_bottom_ = box.bottom(); } void compute_bounding_box() { box = cblob_ptr->bounding_box(); base_char_top_ = box.top(); base_char_bottom_ = box.bottom(); baseline_y_ = box.bottom(); } const TBOX& reduced_box() const { return red_box; } void set_reduced_box(TBOX new_box) { red_box = new_box; reduced = TRUE; } inT32 enclosed_area() const { return area; } bool joined_to_prev() const { return joined != 0; } bool red_box_set() const { return reduced != 0; } int repeated_set() const { return repeated_set_; } void set_repeated_set(int set_id) { repeated_set_ = set_id; } C_BLOB *cblob() const { return cblob_ptr; } TabType left_tab_type() const { return left_tab_type_; } void set_left_tab_type(TabType new_type) { left_tab_type_ = new_type; } TabType right_tab_type() const { return right_tab_type_; } void set_right_tab_type(TabType new_type) { right_tab_type_ = new_type; } BlobRegionType region_type() const { return region_type_; } void set_region_type(BlobRegionType new_type) { region_type_ = new_type; } BlobSpecialTextType special_text_type() const { return spt_type_; } void set_special_text_type(BlobSpecialTextType new_type) { spt_type_ = new_type; } BlobTextFlowType flow() const { return flow_; } void set_flow(BlobTextFlowType value) { flow_ = value; } bool vert_possible() const { return vert_possible_; } void set_vert_possible(bool value) { vert_possible_ = value; } bool horz_possible() const { return horz_possible_; } void set_horz_possible(bool value) { horz_possible_ = value; } int left_rule() const { return left_rule_; } void set_left_rule(int new_left) { left_rule_ = new_left; } int right_rule() const { return right_rule_; } void set_right_rule(int new_right) { right_rule_ = new_right; } int left_crossing_rule() const { return left_crossing_rule_; } void set_left_crossing_rule(int new_left) { left_crossing_rule_ = new_left; } int right_crossing_rule() const { return right_crossing_rule_; } void set_right_crossing_rule(int new_right) { right_crossing_rule_ = new_right; } float horz_stroke_width() const { return horz_stroke_width_; } void set_horz_stroke_width(float width) { horz_stroke_width_ = width; } float vert_stroke_width() const { return vert_stroke_width_; } void set_vert_stroke_width(float width) { vert_stroke_width_ = width; } float area_stroke_width() const { return area_stroke_width_; } tesseract::ColPartition* owner() const { return owner_; } void set_owner(tesseract::ColPartition* new_owner) { owner_ = new_owner; } bool leader_on_left() const { return leader_on_left_; } void set_leader_on_left(bool flag) { leader_on_left_ = flag; } bool leader_on_right() const { return leader_on_right_; } void set_leader_on_right(bool flag) { leader_on_right_ = flag; } BLOBNBOX* neighbour(BlobNeighbourDir n) const { return neighbours_[n]; } bool good_stroke_neighbour(BlobNeighbourDir n) const { return good_stroke_neighbours_[n]; } void set_neighbour(BlobNeighbourDir n, BLOBNBOX* neighbour, bool good) { neighbours_[n] = neighbour; good_stroke_neighbours_[n] = good; } bool IsDiacritic() const { return base_char_top_ != box.top() || base_char_bottom_ != box.bottom(); } int base_char_top() const { return base_char_top_; } int base_char_bottom() const { return base_char_bottom_; } int baseline_position() const { return baseline_y_; } int line_crossings() const { return line_crossings_; } void set_line_crossings(int value) { line_crossings_ = value; } void set_diacritic_box(const TBOX& diacritic_box) { base_char_top_ = diacritic_box.top(); base_char_bottom_ = diacritic_box.bottom(); } BLOBNBOX* base_char_blob() const { return base_char_blob_; } void set_base_char_blob(BLOBNBOX* blob) { base_char_blob_ = blob; } bool UniquelyVertical() const { return vert_possible_ && !horz_possible_; } bool UniquelyHorizontal() const { return horz_possible_ && !vert_possible_; } // Returns true if the region type is text. static bool IsTextType(BlobRegionType type) { return type == BRT_TEXT || type == BRT_VERT_TEXT; } // Returns true if the region type is image. static bool IsImageType(BlobRegionType type) { return type == BRT_RECTIMAGE || type == BRT_POLYIMAGE; } // Returns true if the region type is line. static bool IsLineType(BlobRegionType type) { return type == BRT_HLINE || type == BRT_VLINE; } // Returns true if the region type cannot be merged. static bool UnMergeableType(BlobRegionType type) { return IsLineType(type) || IsImageType(type); } // Helper to call CleanNeighbours on all blobs on the list. static void CleanNeighbours(BLOBNBOX_LIST* blobs); // Helper to delete all the deletable blobs on the list. static void DeleteNoiseBlobs(BLOBNBOX_LIST* blobs); // Helper to compute edge offsets for all the blobs on the list. // See coutln.h for an explanation of edge offsets. static void ComputeEdgeOffsets(Pix* thresholds, Pix* grey, BLOBNBOX_LIST* blobs); #ifndef GRAPHICS_DISABLED // Helper to draw all the blobs on the list in the given body_colour, // with child outlines in the child_colour. static void PlotBlobs(BLOBNBOX_LIST* list, ScrollView::Color body_colour, ScrollView::Color child_colour, ScrollView* win); // Helper to draw only DeletableNoise blobs (unowned, BRT_NOISE) on the // given list in the given body_colour, with child outlines in the // child_colour. static void PlotNoiseBlobs(BLOBNBOX_LIST* list, ScrollView::Color body_colour, ScrollView::Color child_colour, ScrollView* win); static ScrollView::Color TextlineColor(BlobRegionType region_type, BlobTextFlowType flow_type); // Keep in sync with BlobRegionType. ScrollView::Color BoxColor() const; void plot(ScrollView* window, // window to draw in ScrollView::Color blob_colour, // for outer bits ScrollView::Color child_colour); // for holes #endif // Initializes the bulk of the members to default values for use at // construction time. void ConstructionInit() { cblob_ptr = NULL; area = 0; area_stroke_width_ = 0.0f; horz_stroke_width_ = 0.0f; vert_stroke_width_ = 0.0f; ReInit(); } // Initializes members set by StrokeWidth and beyond, without discarding // stored area and strokewidth values, which are expensive to calculate. void ReInit() { joined = false; reduced = false; repeated_set_ = 0; left_tab_type_ = TT_NONE; right_tab_type_ = TT_NONE; region_type_ = BRT_UNKNOWN; flow_ = BTFT_NONE; spt_type_ = BSTT_SKIP; left_rule_ = 0; right_rule_ = 0; left_crossing_rule_ = 0; right_crossing_rule_ = 0; if (area_stroke_width_ == 0.0f && area > 0 && cblob() != NULL) area_stroke_width_ = 2.0f * area / cblob()->perimeter(); owner_ = NULL; base_char_top_ = box.top(); base_char_bottom_ = box.bottom(); baseline_y_ = box.bottom(); line_crossings_ = 0; base_char_blob_ = NULL; horz_possible_ = false; vert_possible_ = false; leader_on_left_ = false; leader_on_right_ = false; ClearNeighbours(); } void ClearNeighbours() { for (int n = 0; n < BND_COUNT; ++n) { neighbours_[n] = NULL; good_stroke_neighbours_[n] = false; } } private: C_BLOB *cblob_ptr; // edgestep blob TBOX box; // bounding box TBOX red_box; // bounding box int area:30; // enclosed area int joined:1; // joined to prev int reduced:1; // reduced box set int repeated_set_; // id of the set of repeated blobs TabType left_tab_type_; // Indicates tab-stop assessment TabType right_tab_type_; // Indicates tab-stop assessment BlobRegionType region_type_; // Type of region this blob belongs to BlobTextFlowType flow_; // Quality of text flow. inT16 left_rule_; // x-coord of nearest but not crossing rule line inT16 right_rule_; // x-coord of nearest but not crossing rule line inT16 left_crossing_rule_; // x-coord of nearest or crossing rule line inT16 right_crossing_rule_; // x-coord of nearest or crossing rule line inT16 base_char_top_; // y-coord of top/bottom of diacritic base, inT16 base_char_bottom_; // if it exists else top/bottom of this blob. inT16 baseline_y_; // Estimate of baseline position. int line_crossings_; // Number of line intersections touched. BLOBNBOX* base_char_blob_; // The blob that was the base char. float horz_stroke_width_; // Median horizontal stroke width float vert_stroke_width_; // Median vertical stroke width float area_stroke_width_; // Stroke width from area/perimeter ratio. tesseract::ColPartition* owner_; // Who will delete me when I am not needed BlobSpecialTextType spt_type_; // Special text type. BLOBNBOX* neighbours_[BND_COUNT]; bool good_stroke_neighbours_[BND_COUNT]; bool horz_possible_; // Could be part of horizontal flow. bool vert_possible_; // Could be part of vertical flow. bool leader_on_left_; // There is a leader to the left. bool leader_on_right_; // There is a leader to the right. }; class TO_ROW: public ELIST2_LINK { public: static const int kErrorWeight = 3; TO_ROW() { clear(); } //empty TO_ROW( //constructor BLOBNBOX *blob, //from first blob float top, //of row //target height float bottom, float row_size); void print() const; float max_y() const { //access function return y_max; } float min_y() const { return y_min; } float mean_y() const { return (y_min + y_max) / 2.0f; } float initial_min_y() const { return initial_y_min; } float line_m() const { //access to line fit return m; } float line_c() const { return c; } float line_error() const { return error; } float parallel_c() const { return para_c; } float parallel_error() const { return para_error; } float believability() const { //baseline goodness return credibility; } float intercept() const { //real parallel_c return y_origin; } void add_blob( //put in row BLOBNBOX *blob, //blob to add float top, //of row //target height float bottom, float row_size); void insert_blob( //put in row in order BLOBNBOX *blob); BLOBNBOX_LIST *blob_list() { //get list return &blobs; } void set_line( //set line spec float new_m, //line to set float new_c, float new_error) { m = new_m; c = new_c; error = new_error; } void set_parallel_line( //set fixed gradient line float gradient, //page gradient float new_c, float new_error) { para_c = new_c; para_error = new_error; credibility = (float) (blobs.length () - kErrorWeight * new_error); y_origin = (float) (new_c / sqrt (1 + gradient * gradient)); //real intercept } void set_limits( //set min,max float new_min, //bottom and float new_max) { //top of row y_min = new_min; y_max = new_max; } void compute_vertical_projection(); //get projection bool rep_chars_marked() const { return num_repeated_sets_ != -1; } void clear_rep_chars_marked() { num_repeated_sets_ = -1; } int num_repeated_sets() const { return num_repeated_sets_; } void set_num_repeated_sets(int num_sets) { num_repeated_sets_ = num_sets; } // true when dead BOOL8 merged; BOOL8 all_caps; // had no ascenders BOOL8 used_dm_model; // in guessing pitch inT16 projection_left; // start of projection inT16 projection_right; // start of projection PITCH_TYPE pitch_decision; // how strong is decision float fixed_pitch; // pitch or 0 float fp_space; // sp if fixed pitch float fp_nonsp; // nonsp if fixed pitch float pr_space; // sp if prop float pr_nonsp; // non sp if prop float spacing; // to "next" row float xheight; // of line int xheight_evidence; // number of blobs of height xheight float ascrise; // ascenders float descdrop; // descenders float body_size; // of CJK characters. Assumed to be // xheight+ascrise for non-CJK text. inT32 min_space; // min size for real space inT32 max_nonspace; // max size of non-space inT32 space_threshold; // space vs nonspace float kern_size; // average non-space float space_size; // average space WERD_LIST rep_words; // repeated chars ICOORDELT_LIST char_cells; // fixed pitch cells QSPLINE baseline; // curved baseline STATS projection; // vertical projection private: void clear(); // clear all values to reasonable defaults BLOBNBOX_LIST blobs; //blobs in row float y_min; //coords float y_max; float initial_y_min; float m, c; //line spec float error; //line error float para_c; //constrained fit float para_error; float y_origin; //rotated para_c; float credibility; //baseline believability int num_repeated_sets_; // number of sets of repeated blobs // set to -1 if we have not searched // for repeated blobs in this row yet }; ELIST2IZEH (TO_ROW) class TO_BLOCK:public ELIST_LINK { public: TO_BLOCK() : pitch_decision(PITCH_DUNNO) { clear(); } //empty TO_BLOCK( //constructor BLOCK *src_block); //real block ~TO_BLOCK(); void clear(); // clear all scalar members. TO_ROW_LIST *get_rows() { //access function return &row_list; } // Rotate all the blobnbox lists and the underlying block. Then update the // median size statistic from the blobs list. void rotate(const FCOORD& rotation) { BLOBNBOX_LIST* blobnbox_list[] = {&blobs, &underlines, &noise_blobs, &small_blobs, &large_blobs, NULL}; for (BLOBNBOX_LIST** list = blobnbox_list; *list != NULL; ++list) { BLOBNBOX_IT it(*list); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { it.data()->rotate(rotation); } } // Rotate the block ASSERT_HOST(block->poly_block() != NULL); block->rotate(rotation); // Update the median size statistic from the blobs list. STATS widths(0, block->bounding_box().width()); STATS heights(0, block->bounding_box().height()); BLOBNBOX_IT blob_it(&blobs); for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) { widths.add(blob_it.data()->bounding_box().width(), 1); heights.add(blob_it.data()->bounding_box().height(), 1); } block->set_median_size(static_cast<int>(widths.median() + 0.5), static_cast<int>(heights.median() + 0.5)); } void print_rows() { //debug info TO_ROW_IT row_it = &row_list; TO_ROW *row; for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { row = row_it.data(); tprintf("Row range (%g,%g), para_c=%g, blobcount=" INT32FORMAT "\n", row->min_y(), row->max_y(), row->parallel_c(), row->blob_list()->length()); } } // Reorganizes the blob lists with a different definition of small, medium // and large, compared to the original definition. // Height is still the primary filter key, but medium width blobs of small // height become medium, and very wide blobs of small height stay small. void ReSetAndReFilterBlobs(); // Deletes noise blobs from all lists where not owned by a ColPartition. void DeleteUnownedNoise(); // Computes and stores the edge offsets on each blob for use in feature // extraction, using greyscale if the supplied grey and thresholds pixes // are 8-bit or otherwise (if NULL or not 8 bit) the original binary // edge step outlines. // Thresholds must either be the same size as grey or an integer down-scale // of grey. // See coutln.h for an explanation of edge offsets. void ComputeEdgeOffsets(Pix* thresholds, Pix* grey); #ifndef GRAPHICS_DISABLED // Draw the noise blobs from all lists in red. void plot_noise_blobs(ScrollView* to_win); // Draw the blobs on on the various lists in the block in different colors. void plot_graded_blobs(ScrollView* to_win); #endif BLOBNBOX_LIST blobs; //medium size BLOBNBOX_LIST underlines; //underline blobs BLOBNBOX_LIST noise_blobs; //very small BLOBNBOX_LIST small_blobs; //fairly small BLOBNBOX_LIST large_blobs; //big blobs BLOCK *block; //real block PITCH_TYPE pitch_decision; //how strong is decision float line_spacing; //estimate // line_size is a lower-bound estimate of the font size in pixels of // the text in the block (with ascenders and descenders), being a small // (1.25) multiple of the median height of filtered blobs. // In most cases the font size will be bigger, but it will be closer // if the text is allcaps, or in a no-x-height script. float line_size; //estimate float max_blob_size; //line assignment limit float baseline_offset; //phase shift float xheight; //median blob size float fixed_pitch; //pitch or 0 float kern_size; //average non-space float space_size; //average space inT32 min_space; //min definite space inT32 max_nonspace; //max definite float fp_space; //sp if fixed pitch float fp_nonsp; //nonsp if fixed pitch float pr_space; //sp if prop float pr_nonsp; //non sp if prop TO_ROW *key_row; //starting row private: TO_ROW_LIST row_list; //temporary rows }; ELISTIZEH (TO_BLOCK) extern double_VAR_H (textord_error_weight, 3, "Weighting for error in believability"); void find_cblob_limits( //get y limits C_BLOB *blob, //blob to search float leftx, //x limits float rightx, FCOORD rotation, //for landscape float &ymin, //output y limits float &ymax); void find_cblob_vlimits( //get y limits C_BLOB *blob, //blob to search float leftx, //x limits float rightx, float &ymin, //output y limits float &ymax); void find_cblob_hlimits( //get x limits C_BLOB *blob, //blob to search float bottomy, //y limits float topy, float &xmin, //output x limits float &xymax); C_BLOB *crotate_cblob( //rotate it C_BLOB *blob, //blob to search FCOORD rotation //for landscape ); TBOX box_next( //get bounding box BLOBNBOX_IT *it //iterator to blobds ); TBOX box_next_pre_chopped( //get bounding box BLOBNBOX_IT *it //iterator to blobds ); void vertical_cblob_projection( //project outlines C_BLOB *blob, //blob to project STATS *stats //output ); void vertical_coutline_projection( //project outlines C_OUTLINE *outline, //outline to project STATS *stats //output ); #ifndef GRAPHICS_DISABLED void plot_blob_list(ScrollView* win, // window to draw in BLOBNBOX_LIST *list, // blob list ScrollView::Color body_colour, // colour to draw ScrollView::Color child_colour); // colour of child #endif // GRAPHICS_DISABLED #endif
1080228-arabicocr11
ccstruct/blobbox.h
C++
asf20
30,507
/********************************************************************** * File: polyblk.h (Formerly poly_block.h) * Description: Polygonal blocks * Author: Sheelagh Lloyd? * Created: * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef POLYBLK_H #define POLYBLK_H #include "publictypes.h" #include "elst.h" #include "points.h" #include "rect.h" #include "scrollview.h" class DLLSYM POLY_BLOCK { public: POLY_BLOCK() { } // Initialize from box coordinates. POLY_BLOCK(const TBOX& box, PolyBlockType type); POLY_BLOCK(ICOORDELT_LIST *points, PolyBlockType type); ~POLY_BLOCK () { } TBOX *bounding_box() { // access function return &box; } ICOORDELT_LIST *points() { // access function return &vertices; } void compute_bb(); PolyBlockType isA() const { return type; } bool IsText() const { return PTIsTextType(type); } // Rotate about the origin by the given rotation. (Analogous to // multiplying by a complex number. void rotate(FCOORD rotation); // Reflect the coords of the polygon in the y-axis. (Flip the sign of x.) void reflect_in_y_axis(); // Move by adding shift to all coordinates. void move(ICOORD shift); void plot(ScrollView* window, inT32 num); #ifndef GRAPHICS_DISABLED void fill(ScrollView* window, ScrollView::Color colour); #endif // GRAPHICS_DISABLED // Returns true if other is inside this. bool contains(POLY_BLOCK *other); // Returns true if the polygons of other and this overlap. bool overlap(POLY_BLOCK *other); // Returns the winding number of this around the test_pt. // Positive for anticlockwise, negative for clockwise, and zero for // test_pt outside this. inT16 winding_number(const ICOORD &test_pt); #ifndef GRAPHICS_DISABLED // Static utility functions to handle the PolyBlockType. // Returns a color to draw the given type. static ScrollView::Color ColorForPolyBlockType(PolyBlockType type); #endif // GRAPHICS_DISABLED private: ICOORDELT_LIST vertices; // vertices TBOX box; // bounding box PolyBlockType type; // Type of this region. }; // Class to iterate the scanlines of a polygon. class DLLSYM PB_LINE_IT { public: PB_LINE_IT(POLY_BLOCK *blkptr) { block = blkptr; } void set_to_block(POLY_BLOCK * blkptr) { block = blkptr; } // Returns a list of runs of pixels for the given y coord. // Each element of the returned list is the start (x) and extent(y) of // a run inside the region. // Delete the returned list after use. ICOORDELT_LIST *get_line(inT16 y); private: POLY_BLOCK * block; }; #endif
1080228-arabicocr11
ccstruct/polyblk.h
C++
asf20
3,297
/////////////////////////////////////////////////////////////////////// // File: imagedata.h // Description: Class to hold information about a single image and its // corresponding boxes or text file. // Author: Ray Smith // Created: Mon Jul 22 14:17:06 PDT 2013 // // (C) Copyright 2013, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_IMAGE_IMAGEDATA_H_ #define TESSERACT_IMAGE_IMAGEDATA_H_ #include "genericvector.h" #include "normalis.h" #include "rect.h" #include "strngs.h" struct Pix; namespace tesseract { // Amount of padding to apply in output pixels in feature mode. const int kFeaturePadding = 2; // Number of pixels to pad around text boxes. const int kImagePadding = 4; // Number of training images to combine into a mini-batch for training. const int kNumPagesPerMiniBatch = 100; class WordFeature { public: WordFeature(); WordFeature(const FCOORD& fcoord, uinT8 dir); // Computes the maximum x and y value in the features. static void ComputeSize(const GenericVector<WordFeature>& features, int* max_x, int* max_y); // Draws the features in the given window. static void Draw(const GenericVector<WordFeature>& features, ScrollView* window); // Accessors. int x() const { return x_; } int y() const { return y_; } int dir() const { return dir_; } // Writes to the given file. Returns false in case of error. bool Serialize(FILE* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp); private: inT16 x_; uinT8 y_; uinT8 dir_; }; // A floating-point version of WordFeature, used as an intermediate during // scaling. struct FloatWordFeature { static void FromWordFeatures(const GenericVector<WordFeature>& word_features, GenericVector<FloatWordFeature>* float_features); // Sort function to sort first by x-bucket, then by y. static int SortByXBucket(const void*, const void*); float x; float y; float dir; int x_bucket; }; // Class to hold information on a single image: // Filename, cached image as a Pix*, character boxes, text transcription. // The text transcription is the ground truth UTF-8 text for the image. // Character boxes are optional and indicate the desired segmentation of // the text into recognition units. class ImageData { public: ImageData(); // Takes ownership of the pix. ImageData(bool vertical, Pix* pix); ~ImageData(); // Builds and returns an ImageData from the basic data. Note that imagedata, // truth_text, and box_text are all the actual file data, NOT filenames. static ImageData* Build(const char* name, int page_number, const char* lang, const char* imagedata, int imagedatasize, const char* truth_text, const char* box_text); // Writes to the given file. Returns false in case of error. bool Serialize(TFile* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, TFile* fp); // Other accessors. const STRING& imagefilename() const { return imagefilename_; } void set_imagefilename(const STRING& name) { imagefilename_ = name; } int page_number() const { return page_number_; } void set_page_number(int num) { page_number_ = num; } const GenericVector<char>& image_data() const { return image_data_; } const STRING& language() const { return language_; } void set_language(const STRING& lang) { language_ = lang; } const STRING& transcription() const { return transcription_; } const GenericVector<TBOX>& boxes() const { return boxes_; } const GenericVector<STRING>& box_texts() const { return box_texts_; } const STRING& box_text(int index) const { return box_texts_[index]; } // Saves the given Pix as a PNG-encoded string and destroys it. void SetPix(Pix* pix); // Returns the Pix image for *this. Must be pixDestroyed after use. Pix* GetPix() const; // Gets anything and everything with a non-NULL pointer, prescaled to a // given target_height (if 0, then the original image height), and aligned. // Also returns (if not NULL) the width and height of the scaled image. // The return value is the scale factor that was applied to the image to // achieve the target_height. float PreScale(int target_height, Pix** pix, int* scaled_width, int* scaled_height, GenericVector<TBOX>* boxes) const; int MemoryUsed() const; // Draws the data in a new window. void Display() const; // Adds the supplied boxes and transcriptions that correspond to the correct // page number. void AddBoxes(const GenericVector<TBOX>& boxes, const GenericVector<STRING>& texts, const GenericVector<int>& box_pages); private: // Saves the given Pix as a PNG-encoded string and destroys it. static void SetPixInternal(Pix* pix, GenericVector<char>* image_data); // Returns the Pix image for the image_data. Must be pixDestroyed after use. static Pix* GetPixInternal(const GenericVector<char>& image_data); // Parses the text string as a box file and adds any discovered boxes that // match the page number. Returns false on error. bool AddBoxes(const char* box_text); private: STRING imagefilename_; // File to read image from. inT32 page_number_; // Page number if multi-page tif or -1. GenericVector<char> image_data_; // PNG file data. STRING language_; // Language code for image. STRING transcription_; // UTF-8 ground truth of image. GenericVector<TBOX> boxes_; // If non-empty boxes of the image. GenericVector<STRING> box_texts_; // String for text in each box. bool vertical_text_; // Image has been rotated from vertical. }; // A collection of ImageData that knows roughly how much memory it is using. class DocumentData { public: explicit DocumentData(const STRING& name); ~DocumentData(); // Reads all the pages in the given lstmf filename to the cache. The reader // is used to read the file. bool LoadDocument(const char* filename, const char* lang, int start_page, inT64 max_memory, FileReader reader); // Writes all the pages to the given filename. Returns false on error. bool SaveDocument(const char* filename, FileWriter writer); bool SaveToBuffer(GenericVector<char>* buffer); // Adds the given page data to this document, counting up memory. void AddPageToDocument(ImageData* page); const STRING& document_name() const { return document_name_; } int NumPages() const { return total_pages_; } inT64 memory_used() const { return memory_used_; } // Returns a pointer to the page with the given index, modulo the total // number of pages, recaching if needed. const ImageData* GetPage(int index); // Takes ownership of the given page index. The page is made NULL in *this. ImageData* TakePage(int index) { ImageData* page = pages_[index]; pages_[index] = NULL; return page; } private: // Loads as many pages can fit in max_memory_ starting at index pages_offset_. bool ReCachePages(); private: // A name for this document. STRING document_name_; // The language of this document. STRING lang_; // A group of pages that corresponds in some loose way to a document. PointerVector<ImageData> pages_; // Page number of the first index in pages_. int pages_offset_; // Total number of pages in document (may exceed size of pages_.) int total_pages_; // Total of all pix sizes in the document. inT64 memory_used_; // Max memory to use at any time. inT64 max_memory_; // Saved reader from LoadDocument to allow re-caching. FileReader reader_; }; // A collection of DocumentData that knows roughly how much memory it is using. class DocumentCache { public: explicit DocumentCache(inT64 max_memory); ~DocumentCache(); // Adds all the documents in the list of filenames, counting memory. // The reader is used to read the files. bool LoadDocuments(const GenericVector<STRING>& filenames, const char* lang, FileReader reader); // Adds document to the cache, throwing out other documents if needed. bool AddToCache(DocumentData* data); // Finds and returns a document by name. DocumentData* FindDocument(const STRING& document_name) const; // Returns a page by serial number, selecting them in a round-robin fashion // from all the documents. const ImageData* GetPageBySerial(int serial); const PointerVector<DocumentData>& documents() const { return documents_; } int total_pages() const { return total_pages_; } private: // A group of pages that corresponds in some loose way to a document. PointerVector<DocumentData> documents_; // Total of all pages. int total_pages_; // Total of all memory used by the cache. inT64 memory_used_; // Max memory allowed in this cache. inT64 max_memory_; }; } // namespace tesseract #endif // TESSERACT_IMAGE_IMAGEDATA_H_
1080228-arabicocr11
ccstruct/imagedata.h
C++
asf20
9,898
/********************************************************************** * File: ipoints.h (Formerly icoords.h) * Description: Inline functions for coords.h. * Author: Ray Smith * Created: Fri Jun 21 15:14:21 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef IPOINTS_H #define IPOINTS_H #include <math.h> /********************************************************************** * operator! * * Rotate an ICOORD 90 degrees anticlockwise. **********************************************************************/ inline ICOORD operator! ( //rotate 90 deg anti const ICOORD & src //thing to rotate ) { ICOORD result; //output result.xcoord = -src.ycoord; result.ycoord = src.xcoord; return result; } /********************************************************************** * operator- * * Unary minus of an ICOORD. **********************************************************************/ inline ICOORD operator- ( //unary minus const ICOORD & src //thing to minus ) { ICOORD result; //output result.xcoord = -src.xcoord; result.ycoord = -src.ycoord; return result; } /********************************************************************** * operator+ * * Add 2 ICOORDS. **********************************************************************/ inline ICOORD operator+ ( //sum vectors const ICOORD & op1, //operands const ICOORD & op2) { ICOORD sum; //result sum.xcoord = op1.xcoord + op2.xcoord; sum.ycoord = op1.ycoord + op2.ycoord; return sum; } /********************************************************************** * operator+= * * Add 2 ICOORDS. **********************************************************************/ inline ICOORD & operator+= ( //sum vectors ICOORD & op1, //operands const ICOORD & op2) { op1.xcoord += op2.xcoord; op1.ycoord += op2.ycoord; return op1; } /********************************************************************** * operator- * * Subtract 2 ICOORDS. **********************************************************************/ inline ICOORD operator- ( //subtract vectors const ICOORD & op1, //operands const ICOORD & op2) { ICOORD sum; //result sum.xcoord = op1.xcoord - op2.xcoord; sum.ycoord = op1.ycoord - op2.ycoord; return sum; } /********************************************************************** * operator-= * * Subtract 2 ICOORDS. **********************************************************************/ inline ICOORD & operator-= ( //sum vectors ICOORD & op1, //operands const ICOORD & op2) { op1.xcoord -= op2.xcoord; op1.ycoord -= op2.ycoord; return op1; } /********************************************************************** * operator% * * Scalar product of 2 ICOORDS. **********************************************************************/ inline inT32 operator% ( //scalar product const ICOORD & op1, //operands const ICOORD & op2) { return op1.xcoord * op2.xcoord + op1.ycoord * op2.ycoord; } /********************************************************************** * operator* * * Cross product of 2 ICOORDS. **********************************************************************/ inline inT32 operator *( //cross product const ICOORD &op1, //operands const ICOORD &op2) { return op1.xcoord * op2.ycoord - op1.ycoord * op2.xcoord; } /********************************************************************** * operator* * * Scalar multiply of an ICOORD. **********************************************************************/ inline ICOORD operator *( //scalar multiply const ICOORD &op1, //operands inT16 scale) { ICOORD result; //output result.xcoord = op1.xcoord * scale; result.ycoord = op1.ycoord * scale; return result; } inline ICOORD operator *( //scalar multiply inT16 scale, const ICOORD &op1 //operands ) { ICOORD result; //output result.xcoord = op1.xcoord * scale; result.ycoord = op1.ycoord * scale; return result; } /********************************************************************** * operator*= * * Scalar multiply of an ICOORD. **********************************************************************/ inline ICOORD & operator*= ( //scalar multiply ICOORD & op1, //operands inT16 scale) { op1.xcoord *= scale; op1.ycoord *= scale; return op1; } /********************************************************************** * operator/ * * Scalar divide of an ICOORD. **********************************************************************/ inline ICOORD operator/ ( //scalar divide const ICOORD & op1, //operands inT16 scale) { ICOORD result; //output result.xcoord = op1.xcoord / scale; result.ycoord = op1.ycoord / scale; return result; } /********************************************************************** * operator/= * * Scalar divide of an ICOORD. **********************************************************************/ inline ICOORD & operator/= ( //scalar divide ICOORD & op1, //operands inT16 scale) { op1.xcoord /= scale; op1.ycoord /= scale; return op1; } /********************************************************************** * ICOORD::rotate * * Rotate an ICOORD by the given (normalized) (cos,sin) vector. **********************************************************************/ inline void ICOORD::rotate( //rotate by vector const FCOORD& vec) { inT16 tmp; tmp = (inT16) floor (xcoord * vec.x () - ycoord * vec.y () + 0.5); ycoord = (inT16) floor (ycoord * vec.x () + xcoord * vec.y () + 0.5); xcoord = tmp; } /********************************************************************** * operator! * * Rotate an FCOORD 90 degrees anticlockwise. **********************************************************************/ inline FCOORD operator! ( //rotate 90 deg anti const FCOORD & src //thing to rotate ) { FCOORD result; //output result.xcoord = -src.ycoord; result.ycoord = src.xcoord; return result; } /********************************************************************** * operator- * * Unary minus of an FCOORD. **********************************************************************/ inline FCOORD operator- ( //unary minus const FCOORD & src //thing to minus ) { FCOORD result; //output result.xcoord = -src.xcoord; result.ycoord = -src.ycoord; return result; } /********************************************************************** * operator+ * * Add 2 FCOORDS. **********************************************************************/ inline FCOORD operator+ ( //sum vectors const FCOORD & op1, //operands const FCOORD & op2) { FCOORD sum; //result sum.xcoord = op1.xcoord + op2.xcoord; sum.ycoord = op1.ycoord + op2.ycoord; return sum; } /********************************************************************** * operator+= * * Add 2 FCOORDS. **********************************************************************/ inline FCOORD & operator+= ( //sum vectors FCOORD & op1, //operands const FCOORD & op2) { op1.xcoord += op2.xcoord; op1.ycoord += op2.ycoord; return op1; } /********************************************************************** * operator- * * Subtract 2 FCOORDS. **********************************************************************/ inline FCOORD operator- ( //subtract vectors const FCOORD & op1, //operands const FCOORD & op2) { FCOORD sum; //result sum.xcoord = op1.xcoord - op2.xcoord; sum.ycoord = op1.ycoord - op2.ycoord; return sum; } /********************************************************************** * operator-= * * Subtract 2 FCOORDS. **********************************************************************/ inline FCOORD & operator-= ( //sum vectors FCOORD & op1, //operands const FCOORD & op2) { op1.xcoord -= op2.xcoord; op1.ycoord -= op2.ycoord; return op1; } /********************************************************************** * operator% * * Scalar product of 2 FCOORDS. **********************************************************************/ inline float operator% ( //scalar product const FCOORD & op1, //operands const FCOORD & op2) { return op1.xcoord * op2.xcoord + op1.ycoord * op2.ycoord; } /********************************************************************** * operator* * * Cross product of 2 FCOORDS. **********************************************************************/ inline float operator *( //cross product const FCOORD &op1, //operands const FCOORD &op2) { return op1.xcoord * op2.ycoord - op1.ycoord * op2.xcoord; } /********************************************************************** * operator* * * Scalar multiply of an FCOORD. **********************************************************************/ inline FCOORD operator *( //scalar multiply const FCOORD &op1, //operands float scale) { FCOORD result; //output result.xcoord = op1.xcoord * scale; result.ycoord = op1.ycoord * scale; return result; } inline FCOORD operator *( //scalar multiply float scale, const FCOORD &op1 //operands ) { FCOORD result; //output result.xcoord = op1.xcoord * scale; result.ycoord = op1.ycoord * scale; return result; } /********************************************************************** * operator*= * * Scalar multiply of an FCOORD. **********************************************************************/ inline FCOORD & operator*= ( //scalar multiply FCOORD & op1, //operands float scale) { op1.xcoord *= scale; op1.ycoord *= scale; return op1; } /********************************************************************** * operator/ * * Scalar divide of an FCOORD. **********************************************************************/ inline FCOORD operator/ ( //scalar divide const FCOORD & op1, //operands float scale) { FCOORD result; //output if (scale != 0) { result.xcoord = op1.xcoord / scale; result.ycoord = op1.ycoord / scale; } return result; } /********************************************************************** * operator/= * * Scalar divide of an FCOORD. **********************************************************************/ inline FCOORD & operator/= ( //scalar divide FCOORD & op1, //operands float scale) { if (scale != 0) { op1.xcoord /= scale; op1.ycoord /= scale; } return op1; } /********************************************************************** * rotate * * Rotate an FCOORD by the given (normalized) (cos,sin) vector. **********************************************************************/ inline void FCOORD::rotate( //rotate by vector const FCOORD vec) { float tmp; tmp = xcoord * vec.x () - ycoord * vec.y (); ycoord = ycoord * vec.x () + xcoord * vec.y (); xcoord = tmp; } inline void FCOORD::unrotate(const FCOORD& vec) { rotate(FCOORD(vec.x(), -vec.y())); } #endif
1080228-arabicocr11
ccstruct/ipoints.h
C
asf20
12,925
/********************************************************************** * File: statistc.h (Formerly stats.h) * Description: Class description for STATS class. * Author: Ray Smith * Created: Mon Feb 04 16:19:07 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCSTRUCT_STATISTC_H_ #define TESSERACT_CCSTRUCT_STATISTC_H_ #include <stdio.h> #include "host.h" #include "kdpair.h" #include "scrollview.h" template <typename T> class GenericVector; // Simple histogram-based statistics for integer values in a known // range, such that the range is small compared to the number of samples. class STATS { public: // The histogram buckets are in the range // [min_bucket_value, max_bucket_value_plus_1 - 1] i.e. // [min_bucket_value, max_bucket_value]. // Any data under min_bucket value is silently mapped to min_bucket_value, // and likewise, any data over max_bucket_value is silently mapped to // max_bucket_value. // In the internal array, min_bucket_value maps to 0 and // max_bucket_value_plus_1 - min_bucket_value to the array size. // TODO(rays) This is ugly. Convert the second argument to // max_bucket_value and all the code that uses it. STATS(inT32 min_bucket_value, inT32 max_bucket_value_plus_1); STATS(); // empty for arrays ~STATS(); // (Re)Sets the range and clears the counts. // See the constructor for info on max and min values. bool set_range(inT32 min_bucket_value, inT32 max_bucket_value_plus_1); void clear(); // empty buckets void add(inT32 value, inT32 count); // "Accessors" return various statistics on the data. inT32 mode() const; // get mode of samples double mean() const; // get mean of samples double sd() const; // standard deviation // Returns the fractile value such that frac fraction (in [0,1]) of samples // has a value less than the return value. double ile(double frac) const; // Returns the minimum used entry in the histogram (ie the minimum of the // data, NOT the minimum of the supplied range, nor is it an index.) // Would normally be called min(), but that is a reserved word in VC++. inT32 min_bucket() const; // Find min // Returns the maximum used entry in the histogram (ie the maximum of the // data, NOT the maximum of the supplied range, nor is it an index.) inT32 max_bucket() const; // Find max // Finds a more useful estimate of median than ile(0.5). // Overcomes a problem with ile() - if the samples are, for example, // 6,6,13,14 ile(0.5) return 7.0 - when a more useful value would be midway // between 6 and 13 = 9.5 double median() const; // get median of samples // Returns the count of the given value. inT32 pile_count(inT32 value ) const { if (value <= rangemin_) return buckets_[0]; if (value >= rangemax_ - 1) return buckets_[rangemax_ - rangemin_ - 1]; return buckets_[value - rangemin_]; } // Returns the total count of all buckets. inT32 get_total() const { return total_count_; // total of all piles } // Returns true if x is a local min. bool local_min(inT32 x) const; // Apply a triangular smoothing filter to the stats. // This makes the modes a bit more useful. // The factor gives the height of the triangle, i.e. the weight of the // centre. void smooth(inT32 factor); // Cluster the samples into max_cluster clusters. // Each call runs one iteration. The array of clusters must be // max_clusters+1 in size as cluster 0 is used to indicate which samples // have been used. // The return value is the current number of clusters. inT32 cluster(float lower, // thresholds float upper, float multiple, // distance threshold inT32 max_clusters, // max no to make STATS *clusters); // array of clusters // Finds (at most) the top max_modes modes, well actually the whole peak around // each mode, returning them in the given modes vector as a <mean of peak, // total count of peak> pair in order of decreasing total count. // Since the mean is the key and the count the data in the pair, a single call // to sort on the output will re-sort by increasing mean of peak if that is // more useful than decreasing total count. // Returns the actual number of modes found. int top_n_modes( int max_modes, GenericVector<tesseract::KDPairInc<float, int> >* modes) const; // Prints a summary and table of the histogram. void print() const; // Prints summary stats only of the histogram. void print_summary() const; #ifndef GRAPHICS_DISABLED // Draws the histogram as a series of rectangles. void plot(ScrollView* window, // window to draw in float xorigin, // origin of histo float yorigin, // gram float xscale, // size of one unit float yscale, // size of one uint ScrollView::Color colour) const; // colour to draw in // Draws a line graph of the histogram. void plotline(ScrollView* window, // window to draw in float xorigin, // origin of histo float yorigin, // gram float xscale, // size of one unit float yscale, // size of one uint ScrollView::Color colour) const; // colour to draw in #endif // GRAPHICS_DISABLED private: inT32 rangemin_; // min of range // rangemax_ is not well named as it is really one past the max. inT32 rangemax_; // max of range inT32 total_count_; // no of samples inT32* buckets_; // array of cells }; // Returns the nth ordered item from the array, as if they were // ordered, but without ordering them, in linear time. // The array does get shuffled! inT32 choose_nth_item(inT32 index, // index to choose float *array, // array of items inT32 count); // no of items // Generic version uses a defined comparator (with qsort semantics). inT32 choose_nth_item(inT32 index, // index to choose void *array, // array of items inT32 count, // no of items size_t size, // element size int (*compar)(const void*, const void*)); // comparator // Swaps 2 entries in an array in-place. void swap_entries(void *array, // array of entries size_t size, // size of entry inT32 index1, // entries to swap inT32 index2); #endif // TESSERACT_CCSTRUCT_STATISTC_H_
1080228-arabicocr11
ccstruct/statistc.h
C++
asf20
7,250
/********************************************************************** * File: coutln.c (Formerly: coutline.c) * Description: Code for the C_OUTLINE class. * Author: Ray Smith * Created: Mon Oct 07 16:01:57 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef COUTLN_H #define COUTLN_H #include "crakedge.h" #include "mod128.h" #include "bits16.h" #include "rect.h" #include "blckerr.h" #include "scrollview.h" class DENORM; #define INTERSECTING MAX_INT16//no winding number //mask to get step #define STEP_MASK 3 enum C_OUTLINE_FLAGS { COUT_INVERSE //White on black blob }; // Simple struct to hold the 3 values needed to compute a more precise edge // position and direction. The offset_numerator is the difference between the // grey threshold and the mean pixel value. pixel_diff is the difference between // the pixels in the edge. Consider the following row of pixels: p1 p2 p3 p4 p5 // Say the image was thresholded at threshold t, making p1, p2, p3 black // and p4, p5 white (p1, p2, p3 < t, and p4, p5 >= t), but suppose that // max(p[i+1] - p[i]) is p3 - p2. Then the extrapolated position of the edge, // based on the maximum gradient, is at the crack between p2 and p3 plus the // offset (t - (p2+p3)/2)/(p3 - p2). We store the pixel difference p3-p2 // denominator in pixel_diff and the offset numerator, relative to the original // binary edge (t - (p2+p3)/2) - (p3 -p2) in offset_numerator. // The sign of offset_numerator and pixel_diff are manipulated to ensure // that the pixel_diff, which will be used as a weight, is always positive. // The direction stores the quantized feature direction for the given step // computed from the edge gradient. (Using binary_angle_plus_pi.) // If the pixel_diff is zero, it means that the direction of the gradient // is in conflict with the step direction, so this step is to be ignored. struct EdgeOffset { inT8 offset_numerator; uinT8 pixel_diff; uinT8 direction; }; class DLLSYM C_OUTLINE; //forward declaration struct Pix; ELISTIZEH (C_OUTLINE) class DLLSYM C_OUTLINE:public ELIST_LINK { public: C_OUTLINE() { //empty constructor steps = NULL; offsets = NULL; } C_OUTLINE( //constructor CRACKEDGE *startpt, //from edge detector ICOORD bot_left, //bounding box //length of loop ICOORD top_right, inT16 length); C_OUTLINE(ICOORD startpt, //start of loop DIR128 *new_steps, //steps in loop inT16 length); //length of loop //outline to copy C_OUTLINE(C_OUTLINE *srcline, FCOORD rotation); //and rotate // Build a fake outline, given just a bounding box and append to the list. static void FakeOutline(const TBOX& box, C_OUTLINE_LIST* outlines); ~C_OUTLINE () { //destructor if (steps != NULL) free_mem(steps); steps = NULL; delete [] offsets; } BOOL8 flag( //test flag C_OUTLINE_FLAGS mask) const { //flag to test return flags.bit (mask); } void set_flag( //set flag value C_OUTLINE_FLAGS mask, //flag to test BOOL8 value) { //value to set flags.set_bit (mask, value); } C_OUTLINE_LIST *child() { //get child list return &children; } //access function const TBOX &bounding_box() const { return box; } void set_step( //set a step inT16 stepindex, //index of step inT8 stepdir) { //chain code int shift = stepindex%4 * 2; uinT8 mask = 3 << shift; steps[stepindex/4] = ((stepdir << shift) & mask) | (steps[stepindex/4] & ~mask); //squeeze 4 into byte } void set_step( //set a step inT16 stepindex, //index of step DIR128 stepdir) { //direction //clean it inT8 chaindir = stepdir.get_dir() >> (DIRBITS - 2); //difference set_step(stepindex, chaindir); //squeeze 4 into byte } inT32 pathlength() const { //get path length return stepcount; } // Return step at a given index as a DIR128. DIR128 step_dir(int index) const { return DIR128((inT16)(((steps[index/4] >> (index%4 * 2)) & STEP_MASK) << (DIRBITS - 2))); } // Return the step vector for the given outline position. ICOORD step(int index) const { // index of step return step_coords[chain_code(index)]; } // get start position const ICOORD &start_pos() const { return start; } // Returns the position at the given index on the outline. // NOT to be used lightly, as it has to iterate the outline to find out. ICOORD position_at_index(int index) const { ICOORD pos = start; for (int i = 0; i < index; ++i) pos += step(i); return pos; } // Returns the sub-pixel accurate position given the integer position pos // at the given index on the outline. pos may be a return value of // position_at_index, or computed by repeatedly adding step to the // start_pos() in the usual way. FCOORD sub_pixel_pos_at_index(const ICOORD& pos, int index) const { const ICOORD& step_to_next(step(index)); FCOORD f_pos(pos.x() + step_to_next.x() / 2.0f, pos.y() + step_to_next.y() / 2.0f); if (offsets != NULL && offsets[index].pixel_diff > 0) { float offset = offsets[index].offset_numerator; offset /= offsets[index].pixel_diff; if (step_to_next.x() != 0) f_pos.set_y(f_pos.y() + offset); else f_pos.set_x(f_pos.x() + offset); } return f_pos; } // Returns the step direction for the given index or -1 if there is none. int direction_at_index(int index) const { if (offsets != NULL && offsets[index].pixel_diff > 0) return offsets[index].direction; return -1; } // Returns the edge strength for the given index. // If there are no recorded edge strengths, returns 1 (assuming the image // is binary). Returns 0 if the gradient direction conflicts with the // step direction, indicating that this position could be skipped. int edge_strength_at_index(int index) const { if (offsets != NULL) return offsets[index].pixel_diff; return 1; } // Return the step as a chain code (0-3) related to the standard feature // direction of binary_angle_plus_pi by: // chain_code * 64 = feature direction. int chain_code(int index) const { // index of step return (steps[index / 4] >> (index % 4 * 2)) & STEP_MASK; } inT32 area() const; // Returns area of self and 1st level children. inT32 perimeter() const; // Total perimeter of self and 1st level children. inT32 outer_area() const; // Returns area of self only. inT32 count_transitions( //count maxima inT32 threshold); //size threshold BOOL8 operator< ( //containment test const C_OUTLINE & other) const; BOOL8 operator> ( //containment test C_OUTLINE & other) const { return other < *this; //use the < to do it } inT16 winding_number( //get winding number ICOORD testpt) const; //around this point //get direction inT16 turn_direction() const; void reverse(); //reverse direction void move( // reposition outline const ICOORD vec); // by vector // Returns true if *this and its children are legally nested. // The outer area of a child should have the opposite sign to the // parent. If not, it means we have discarded an outline in between // (probably due to excessive length). bool IsLegallyNested() const; // If this outline is smaller than the given min_size, delete this and // remove from its list, via *it, after checking that *it points to this. // Otherwise, if any children of this are too small, delete them. // On entry, *it must be an iterator pointing to this. If this gets deleted // then this is extracted from *it, so an iteration can continue. void RemoveSmallRecursive(int min_size, C_OUTLINE_IT* it); // Adds sub-pixel resolution EdgeOffsets for the outline if the supplied // pix is 8-bit. Does nothing otherwise. void ComputeEdgeOffsets(int threshold, Pix* pix); // Adds sub-pixel resolution EdgeOffsets for the outline using only // a binary image source. void ComputeBinaryOffsets(); // Renders the outline to the given pix, with left and top being // the coords of the upper-left corner of the pix. void render(int left, int top, Pix* pix) const; // Renders just the outline to the given pix (no fill), with left and top // being the coords of the upper-left corner of the pix. void render_outline(int left, int top, Pix* pix) const; #ifndef GRAPHICS_DISABLED void plot( //draw one ScrollView* window, //window to draw in ScrollView::Color colour) const; //colour to draw it // Draws the outline in the given colour, normalized using the given denorm, // making use of sub-pixel accurate information if available. void plot_normed(const DENORM& denorm, ScrollView::Color colour, ScrollView* window) const; #endif // GRAPHICS_DISABLED C_OUTLINE& operator=(const C_OUTLINE& source); static C_OUTLINE* deep_copy(const C_OUTLINE* src) { C_OUTLINE* outline = new C_OUTLINE; *outline = *src; return outline; } static ICOORD chain_step(int chaindir); // The maximum length of any outline. The stepcount is stored as 16 bits, // but it is probably not a good idea to increase this constant by much // and switch to 32 bits, as it plays an important role in keeping huge // outlines invisible, which prevents bad speed behavior. static const int kMaxOutlineLength = 16000; private: // Helper for ComputeBinaryOffsets. Increments pos, dir_counts, pos_totals // by the step, increment, and vertical step ? x : y position * increment // at step s Mod stepcount respectively. Used to add or subtract the // direction and position to/from accumulators of a small neighbourhood. void increment_step(int s, int increment, ICOORD* pos, int* dir_counts, int* pos_totals) const; int step_mem() const { return (stepcount+3) / 4; } TBOX box; // bounding box ICOORD start; // start coord inT16 stepcount; // no of steps BITS16 flags; // flags about outline uinT8 *steps; // step array EdgeOffset* offsets; // Higher precision edge. C_OUTLINE_LIST children; // child elements static ICOORD step_coords[4]; }; #endif
1080228-arabicocr11
ccstruct/coutln.h
C++
asf20
12,078
/********************************************************************** * File: werd.cpp (Formerly word.c) * Description: Code for the WERD class. * Author: Ray Smith * Created: Tue Oct 08 14:32:12 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "blckerr.h" #include "helpers.h" #include "linlsq.h" #include "werd.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #define FIRST_COLOUR ScrollView::RED //< first rainbow colour #define LAST_COLOUR ScrollView::AQUAMARINE //< last rainbow colour #define CHILD_COLOUR ScrollView::BROWN //< colour of children const ERRCODE CANT_SCALE_EDGESTEPS = "Attempted to scale an edgestep format word"; ELIST2IZE(WERD) /** * WERD::WERD * * Constructor to build a WERD from a list of C_BLOBs. * blob_list The C_BLOBs (in word order) are not copied; * we take its elements and put them in our lists. * blank_count blanks in front of the word * text correct text, outlives this WERD */ WERD::WERD(C_BLOB_LIST *blob_list, uinT8 blank_count, const char *text) : blanks(blank_count), flags(0), script_id_(0), correct(text) { C_BLOB_IT start_it = blob_list; C_BLOB_IT end_it = blob_list; C_BLOB_IT rej_cblob_it = &rej_cblobs; C_OUTLINE_IT c_outline_it; inT16 inverted_vote = 0; inT16 non_inverted_vote = 0; // Move blob_list's elements into cblobs. while (!end_it.at_last()) end_it.forward(); cblobs.assign_to_sublist(&start_it, &end_it); /* Set white on black flag for the WERD, moving any duff blobs onto the rej_cblobs list. First, walk the cblobs checking the inverse flag for each outline of each cblob. If a cblob has inconsistent flag settings for its different outlines, move the blob to the reject list. Otherwise, increment the appropriate w-on-b or b-on-w vote for the word. Now set the inversion flag for the WERD by maximum vote. Walk the blobs again, moving any blob whose inversion flag does not agree with the concencus onto the reject list. */ start_it.set_to_list(&cblobs); if (start_it.empty()) return; for (start_it.mark_cycle_pt(); !start_it.cycled_list(); start_it.forward()) { BOOL8 reject_blob = FALSE; BOOL8 blob_inverted; c_outline_it.set_to_list(start_it.data()->out_list()); blob_inverted = c_outline_it.data()->flag(COUT_INVERSE); for (c_outline_it.mark_cycle_pt(); !c_outline_it.cycled_list() && !reject_blob; c_outline_it.forward()) { reject_blob = c_outline_it.data()->flag(COUT_INVERSE) != blob_inverted; } if (reject_blob) { rej_cblob_it.add_after_then_move(start_it.extract()); } else { if (blob_inverted) inverted_vote++; else non_inverted_vote++; } } flags.set_bit(W_INVERSE, (inverted_vote > non_inverted_vote)); start_it.set_to_list(&cblobs); if (start_it.empty()) return; for (start_it.mark_cycle_pt(); !start_it.cycled_list(); start_it.forward()) { c_outline_it.set_to_list(start_it.data()->out_list()); if (c_outline_it.data()->flag(COUT_INVERSE) != flags.bit(W_INVERSE)) rej_cblob_it.add_after_then_move(start_it.extract()); } } /** * WERD::WERD * * Constructor to build a WERD from a list of C_BLOBs. * The C_BLOBs are not copied so the source list is emptied. */ WERD::WERD(C_BLOB_LIST * blob_list, //< In word order WERD * clone) //< Source of flags : flags(clone->flags), script_id_(clone->script_id_), correct(clone->correct) { C_BLOB_IT start_it = blob_list; // iterator C_BLOB_IT end_it = blob_list; // another while (!end_it.at_last ()) end_it.forward (); //move to last ((C_BLOB_LIST *) (&cblobs))->assign_to_sublist (&start_it, &end_it); //move to our list blanks = clone->blanks; // fprintf(stderr,"Wrong constructor!!!!\n"); } // Construct a WERD from a single_blob and clone the flags from this. // W_BOL and W_EOL flags are set according to the given values. WERD* WERD::ConstructFromSingleBlob(bool bol, bool eol, C_BLOB* blob) { C_BLOB_LIST temp_blobs; C_BLOB_IT temp_it(&temp_blobs); temp_it.add_after_then_move(blob); WERD* blob_word = new WERD(&temp_blobs, this); blob_word->set_flag(W_BOL, bol); blob_word->set_flag(W_EOL, eol); return blob_word; } /** * WERD::bounding_box * * Return the bounding box of the WERD. * This is quite a mess to compute! * ORIGINALLY, REJECT CBLOBS WERE EXCLUDED, however, this led to bugs when the * words on the row were re-sorted. The original words were built with reject * blobs included. The FUZZY SPACE flags were set accordingly. If ALL the * blobs in a word are rejected the BB for the word is NULL, causing the sort * to screw up, leading to the erroneous possibility of the first word in a * row being marked as FUZZY space. */ TBOX WERD::bounding_box() { TBOX box; // box being built C_BLOB_IT rej_cblob_it = &rej_cblobs; // rejected blobs for (rej_cblob_it.mark_cycle_pt(); !rej_cblob_it.cycled_list(); rej_cblob_it.forward()) { box += rej_cblob_it.data()->bounding_box(); } C_BLOB_IT it = &cblobs; // blobs of WERD for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { box += it.data()->bounding_box(); } return box; } /** * WERD::move * * Reposition WERD by vector * NOTE!! REJECT CBLOBS ARE NOT MOVED */ void WERD::move(const ICOORD vec) { C_BLOB_IT cblob_it(&cblobs); // cblob iterator for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list(); cblob_it.forward()) cblob_it.data()->move(vec); } /** * WERD::join_on * * Join other word onto this one. Delete the old word. */ void WERD::join_on(WERD* other) { C_BLOB_IT blob_it(&cblobs); C_BLOB_IT src_it(&other->cblobs); C_BLOB_IT rej_cblob_it(&rej_cblobs); C_BLOB_IT src_rej_it(&other->rej_cblobs); while (!src_it.empty()) { blob_it.add_to_end(src_it.extract()); src_it.forward(); } while (!src_rej_it.empty()) { rej_cblob_it.add_to_end(src_rej_it.extract()); src_rej_it.forward(); } } /** * WERD::copy_on * * Copy blobs from other word onto this one. */ void WERD::copy_on(WERD* other) { bool reversed = other->bounding_box().left() < bounding_box().left(); C_BLOB_IT c_blob_it(&cblobs); C_BLOB_LIST c_blobs; c_blobs.deep_copy(&other->cblobs, &C_BLOB::deep_copy); if (reversed) { c_blob_it.add_list_before(&c_blobs); } else { c_blob_it.move_to_last(); c_blob_it.add_list_after(&c_blobs); } if (!other->rej_cblobs.empty()) { C_BLOB_IT rej_c_blob_it(&rej_cblobs); C_BLOB_LIST new_rej_c_blobs; new_rej_c_blobs.deep_copy(&other->rej_cblobs, &C_BLOB::deep_copy); if (reversed) { rej_c_blob_it.add_list_before(&new_rej_c_blobs); } else { rej_c_blob_it.move_to_last(); rej_c_blob_it.add_list_after(&new_rej_c_blobs); } } } /** * WERD::print * * Display members */ void WERD::print() { tprintf("Blanks= %d\n", blanks); bounding_box().print(); tprintf("Flags = %d = 0%o\n", flags.val, flags.val); tprintf(" W_SEGMENTED = %s\n", flags.bit(W_SEGMENTED) ? "TRUE" : "FALSE "); tprintf(" W_ITALIC = %s\n", flags.bit(W_ITALIC) ? "TRUE" : "FALSE "); tprintf(" W_BOL = %s\n", flags.bit(W_BOL) ? "TRUE" : "FALSE "); tprintf(" W_EOL = %s\n", flags.bit(W_EOL) ? "TRUE" : "FALSE "); tprintf(" W_NORMALIZED = %s\n", flags.bit(W_NORMALIZED) ? "TRUE" : "FALSE "); tprintf(" W_SCRIPT_HAS_XHEIGHT = %s\n", flags.bit(W_SCRIPT_HAS_XHEIGHT) ? "TRUE" : "FALSE "); tprintf(" W_SCRIPT_IS_LATIN = %s\n", flags.bit(W_SCRIPT_IS_LATIN) ? "TRUE" : "FALSE "); tprintf(" W_DONT_CHOP = %s\n", flags.bit(W_DONT_CHOP) ? "TRUE" : "FALSE "); tprintf(" W_REP_CHAR = %s\n", flags.bit(W_REP_CHAR) ? "TRUE" : "FALSE "); tprintf(" W_FUZZY_SP = %s\n", flags.bit(W_FUZZY_SP) ? "TRUE" : "FALSE "); tprintf(" W_FUZZY_NON = %s\n", flags.bit(W_FUZZY_NON) ? "TRUE" : "FALSE "); tprintf("Correct= %s\n", correct.string()); tprintf("Rejected cblob count = %d\n", rej_cblobs.length()); tprintf("Script = %d\n", script_id_); } /** * WERD::plot * * Draw the WERD in the given colour. */ #ifndef GRAPHICS_DISABLED void WERD::plot(ScrollView *window, ScrollView::Color colour) { C_BLOB_IT it = &cblobs; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { it.data()->plot(window, colour, colour); } plot_rej_blobs(window); } // Get the next color in the (looping) rainbow. ScrollView::Color WERD::NextColor(ScrollView::Color colour) { ScrollView::Color next = static_cast<ScrollView::Color>(colour + 1); if (next >= LAST_COLOUR || next < FIRST_COLOUR) next = FIRST_COLOUR; return next; } /** * WERD::plot * * Draw the WERD in rainbow colours in window. */ void WERD::plot(ScrollView* window) { ScrollView::Color colour = FIRST_COLOUR; C_BLOB_IT it = &cblobs; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { it.data()->plot(window, colour, CHILD_COLOUR); colour = NextColor(colour); } plot_rej_blobs(window); } /** * WERD::plot_rej_blobs * * Draw the WERD rejected blobs in window - ALWAYS GREY */ void WERD::plot_rej_blobs(ScrollView *window) { C_BLOB_IT it = &rej_cblobs; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { it.data()->plot(window, ScrollView::GREY, ScrollView::GREY); } } #endif // GRAPHICS_DISABLED /** * WERD::shallow_copy() * * Make a shallow copy of a word */ WERD *WERD::shallow_copy() { WERD *new_word = new WERD; new_word->blanks = blanks; new_word->flags = flags; new_word->dummy = dummy; new_word->correct = correct; return new_word; } /** * WERD::operator= * * Assign a word, DEEP copying the blob list */ WERD & WERD::operator= (const WERD & source) { this->ELIST2_LINK::operator= (source); blanks = source.blanks; flags = source.flags; script_id_ = source.script_id_; dummy = source.dummy; correct = source.correct; if (!cblobs.empty()) cblobs.clear(); cblobs.deep_copy(&source.cblobs, &C_BLOB::deep_copy); if (!rej_cblobs.empty()) rej_cblobs.clear(); rej_cblobs.deep_copy(&source.rej_cblobs, &C_BLOB::deep_copy); return *this; } /** * word_comparator() * * word comparator used to sort a word list so that words are in increasing * order of left edge. */ int word_comparator(const void *word1p, const void *word2p) { WERD *word1 = *(WERD **)word1p; WERD *word2 = *(WERD **)word2p; return word1->bounding_box().left() - word2->bounding_box().left(); } /** * WERD::ConstructWerdWithNewBlobs() * * This method returns a new werd constructed using the blobs in the input * all_blobs list, which correspond to the blobs in this werd object. The * blobs used to construct the new word are consumed and removed from the * input all_blobs list. * Returns NULL if the word couldn't be constructed. * Returns original blobs for which no matches were found in the output list * orphan_blobs (appends). */ WERD* WERD::ConstructWerdWithNewBlobs(C_BLOB_LIST* all_blobs, C_BLOB_LIST* orphan_blobs) { C_BLOB_LIST current_blob_list; C_BLOB_IT werd_blobs_it(&current_blob_list); // Add the word's c_blobs. werd_blobs_it.add_list_after(cblob_list()); // New blob list. These contain the blobs which will form the new word. C_BLOB_LIST new_werd_blobs; C_BLOB_IT new_blobs_it(&new_werd_blobs); // not_found_blobs contains the list of current word's blobs for which a // corresponding blob wasn't found in the input all_blobs list. C_BLOB_LIST not_found_blobs; C_BLOB_IT not_found_it(&not_found_blobs); not_found_it.move_to_last(); werd_blobs_it.move_to_first(); for (werd_blobs_it.mark_cycle_pt(); !werd_blobs_it.cycled_list(); werd_blobs_it.forward()) { C_BLOB* werd_blob = werd_blobs_it.extract(); TBOX werd_blob_box = werd_blob->bounding_box(); bool found = false; // Now find the corresponding blob for this blob in the all_blobs // list. For now, follow the inefficient method of pairwise // comparisons. Ideally, one can pre-bucket the blobs by row. C_BLOB_IT all_blobs_it(all_blobs); for (all_blobs_it.mark_cycle_pt(); !all_blobs_it.cycled_list(); all_blobs_it.forward()) { C_BLOB* a_blob = all_blobs_it.data(); // Compute the overlap of the two blobs. If major, a_blob should // be added to the new blobs list. TBOX a_blob_box = a_blob->bounding_box(); if (a_blob_box.null_box()) { tprintf("Bounding box couldn't be ascertained\n"); } if (werd_blob_box.contains(a_blob_box) || werd_blob_box.major_overlap(a_blob_box)) { // Old blobs are from minimal splits, therefore are expected to be // bigger. The new small blobs should cover a significant portion. // This is it. all_blobs_it.extract(); new_blobs_it.add_after_then_move(a_blob); found = true; } } if (!found) { not_found_it.add_after_then_move(werd_blob); } else { delete werd_blob; } } // Iterate over all not found blobs. Some of them may be due to // under-segmentation (which is OK, since the corresponding blob is already // in the list in that case. not_found_it.move_to_first(); for (not_found_it.mark_cycle_pt(); !not_found_it.cycled_list(); not_found_it.forward()) { C_BLOB* not_found = not_found_it.data(); TBOX not_found_box = not_found->bounding_box(); C_BLOB_IT existing_blobs_it(new_blobs_it); for (existing_blobs_it.mark_cycle_pt(); !existing_blobs_it.cycled_list(); existing_blobs_it.forward()) { C_BLOB* a_blob = existing_blobs_it.data(); TBOX a_blob_box = a_blob->bounding_box(); if ((not_found_box.major_overlap(a_blob_box) || a_blob_box.major_overlap(not_found_box)) && not_found_box.y_overlap_fraction(a_blob_box) > 0.8) { // Already taken care of. delete not_found_it.extract(); break; } } } if (orphan_blobs) { C_BLOB_IT orphan_blobs_it(orphan_blobs); orphan_blobs_it.move_to_last(); orphan_blobs_it.add_list_after(&not_found_blobs); } // New blobs are ready. Create a new werd object with these. WERD* new_werd = NULL; if (!new_werd_blobs.empty()) { new_werd = new WERD(&new_werd_blobs, this); } else { // Add the blobs back to this word so that it can be reused. C_BLOB_IT this_list_it(cblob_list()); this_list_it.add_list_after(&not_found_blobs); } return new_werd; }
1080228-arabicocr11
ccstruct/werd.cpp
C++
asf20
15,365
/* -*-C-*- ******************************************************************************** * * File: vecfuncs.h (Formerly vecfuncs.h) * Description: Vector calculations * Author: Mark Seaman, OCR Technology * Created: Wed Dec 20 09:37:18 1989 * Modified: Tue Jul 9 17:44:37 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1989, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ #ifndef VECFUNCS_H #define VECFUNCS_H #include <math.h> #include "blobs.h" struct EDGEPT; /*---------------------------------------------------------------------- M a c r o s ----------------------------------------------------------------------*/ /********************************************************************** * point_diff * * Return the difference from point (p1) to point (p2). Put the value * into point (p). **********************************************************************/ #define point_diff(p,p1,p2) \ ((p).x = (p1).x - (p2).x, \ (p).y = (p1).y - (p2).y) /********************************************************************** * CROSS * * cross product **********************************************************************/ #define CROSS(a,b) \ ((a).x * (b).y - (a).y * (b).x) /********************************************************************** * SCALAR * * scalar vector product **********************************************************************/ #define SCALAR(a,b) \ ((a).x * (b).x + (a).y * (b).y) /********************************************************************** * LENGTH * * length of vector **********************************************************************/ #define LENGTH(a) \ ((a).x * (a).x + (a).y * (a).y) /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ int direction(EDGEPT *point); #endif
1080228-arabicocr11
ccstruct/vecfuncs.h
C
asf20
2,649
/********************************************************************** * File: quadlsq.h (Formerly qlsq.h) * Description: Code for least squares approximation of quadratics. * Author: Ray Smith * Created: Wed Oct 6 15:14:23 BST 1993 * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef QUADLSQ_H #define QUADLSQ_H #include "points.h" class QLSQ { public: QLSQ() { //constructor clear(); //set to zeros } void clear(); //initialize void add( //add element double x, //coords to add double y); void remove( //delete element double x, //coords to delete double y); inT32 count() { //no of elements return n; } void fit( //fit the given int degree); //return actual double get_a() { //get x squard return a; } double get_b() { //get x squard return b; } double get_c() { //get x squard return c; } private: inT32 n; //no of elements double a, b, c; //result double sigx; //sum of x double sigy; //sum of y double sigxx; //sum x squared double sigxy; //sum of xy double sigyy; //sum y squared long double sigxxx; //sum x cubed long double sigxxy; //sum xsquared y long double sigxxxx; //sum x fourth }; #endif
1080228-arabicocr11
ccstruct/quadlsq.h
C++
asf20
2,168
/////////////////////////////////////////////////////////////////////// // File: fontinfo.h // Description: Font information classes abstracted from intproto.h/cpp. // Author: rays@google.com (Ray Smith) // Created: Tue May 17 17:08:01 PDT 2011 // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCSTRUCT_FONTINFO_H_ #define TESSERACT_CCSTRUCT_FONTINFO_H_ #include "genericvector.h" #include "host.h" #include "unichar.h" template <typename T> class UnicityTable; namespace tesseract { class BitVector; // Struct for information about spacing between characters in a particular font. struct FontSpacingInfo { inT16 x_gap_before; inT16 x_gap_after; GenericVector<UNICHAR_ID> kerned_unichar_ids; GenericVector<inT16> kerned_x_gaps; }; /* * font_properties contains properties about boldness, italicness, fixed pitch, * serif, fraktur */ struct FontInfo { FontInfo() : name(NULL), properties(0), universal_id(0), spacing_vec(NULL) {} ~FontInfo() {} // Writes to the given file. Returns false in case of error. bool Serialize(FILE* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp); // Reserves unicharset_size spots in spacing_vec. void init_spacing(int unicharset_size) { spacing_vec = new GenericVector<FontSpacingInfo *>(); spacing_vec->init_to_size(unicharset_size, NULL); } // Adds the given pointer to FontSpacingInfo to spacing_vec member // (FontInfo class takes ownership of the pointer). // Note: init_spacing should be called before calling this function. void add_spacing(UNICHAR_ID uch_id, FontSpacingInfo *spacing_info) { ASSERT_HOST(spacing_vec != NULL && spacing_vec->size() > uch_id); (*spacing_vec)[uch_id] = spacing_info; } // Returns the pointer to FontSpacingInfo for the given UNICHAR_ID. const FontSpacingInfo *get_spacing(UNICHAR_ID uch_id) const { return (spacing_vec == NULL || spacing_vec->size() <= uch_id) ? NULL : (*spacing_vec)[uch_id]; } // Fills spacing with the value of the x gap expected between the two given // UNICHAR_IDs. Returns true on success. bool get_spacing(UNICHAR_ID prev_uch_id, UNICHAR_ID uch_id, int *spacing) const { const FontSpacingInfo *prev_fsi = this->get_spacing(prev_uch_id); const FontSpacingInfo *fsi = this->get_spacing(uch_id); if (prev_fsi == NULL || fsi == NULL) return false; int i = 0; for (; i < prev_fsi->kerned_unichar_ids.size(); ++i) { if (prev_fsi->kerned_unichar_ids[i] == uch_id) break; } if (i < prev_fsi->kerned_unichar_ids.size()) { *spacing = prev_fsi->kerned_x_gaps[i]; } else { *spacing = prev_fsi->x_gap_after + fsi->x_gap_before; } return true; } bool is_italic() const { return properties & 1; } bool is_bold() const { return (properties & 2) != 0; } bool is_fixed_pitch() const { return (properties & 4) != 0; } bool is_serif() const { return (properties & 8) != 0; } bool is_fraktur() const { return (properties & 16) != 0; } char* name; uinT32 properties; // The universal_id is a field reserved for the initialization process // to assign a unique id number to all fonts loaded for the current // combination of languages. This id will then be returned by // ResultIterator::WordFontAttributes. inT32 universal_id; // Horizontal spacing between characters (indexed by UNICHAR_ID). GenericVector<FontSpacingInfo *> *spacing_vec; }; // Every class (character) owns a FontSet that represents all the fonts that can // render this character. // Since almost all the characters from the same script share the same set of // fonts, the sets are shared over multiple classes (see // Classify::fontset_table_). Thus, a class only store an id to a set. // Because some fonts cannot render just one character of a set, there are a // lot of FontSet that differ only by one font. Rather than storing directly // the FontInfo in the FontSet structure, it's better to share FontInfos among // FontSets (Classify::fontinfo_table_). struct FontSet { int size; int* configs; // FontInfo ids }; // Class that adds a bit of functionality on top of GenericVector to // implement a table of FontInfo that replaces UniCityTable<FontInfo>. // TODO(rays) change all references once all existing traineddata files // are replaced. class FontInfoTable : public GenericVector<FontInfo> { public: FontInfoTable(); ~FontInfoTable(); // Writes to the given file. Returns false in case of error. bool Serialize(FILE* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp); // Returns true if the given set of fonts includes one with the same // properties as font_id. bool SetContainsFontProperties(int font_id, const GenericVector<int>& font_set) const; // Returns true if the given set of fonts includes multiple properties. bool SetContainsMultipleFontProperties( const GenericVector<int>& font_set) const; // Moves any non-empty FontSpacingInfo entries from other to this. void MoveSpacingInfoFrom(FontInfoTable* other); // Moves this to the target unicity table. void MoveTo(UnicityTable<FontInfo>* target); }; // Compare FontInfo structures. bool CompareFontInfo(const FontInfo& fi1, const FontInfo& fi2); // Compare FontSet structures. bool CompareFontSet(const FontSet& fs1, const FontSet& fs2); // Deletion callbacks for GenericVector. void FontInfoDeleteCallback(FontInfo f); void FontSetDeleteCallback(FontSet fs); // Callbacks used by UnicityTable to read/write FontInfo/FontSet structures. bool read_info(FILE* f, FontInfo* fi, bool swap); bool write_info(FILE* f, const FontInfo& fi); bool read_spacing_info(FILE *f, FontInfo* fi, bool swap); bool write_spacing_info(FILE* f, const FontInfo& fi); bool read_set(FILE* f, FontSet* fs, bool swap); bool write_set(FILE* f, const FontSet& fs); } // namespace tesseract. #endif /* THIRD_PARTY_TESSERACT_CCSTRUCT_FONTINFO_H_ */
1080228-arabicocr11
ccstruct/fontinfo.h
C++
asf20
6,853
/********************************************************************** * File: quadratc.h (Formerly quadrtic.h) * Description: Code for the QUAD_COEFFS class. * Author: Ray Smith * Created: Tue Oct 08 17:24:40 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef QUADRATC_H #define QUADRATC_H #include "points.h" class QUAD_COEFFS { public: QUAD_COEFFS() { } //empty constructor QUAD_COEFFS( //constructor double xsq, //coefficients float x, float constant) { a = xsq; b = x; c = constant; } float y( //evaluate float x) const { //at x return (float) ((a * x + b) * x + c); } void move( // reposition word ICOORD vec) { // by vector /************************************************************ y - q = a (x - p)^2 + b (x - p) + c y - q = ax^2 - 2apx + ap^2 + bx - bp + c y = ax^2 + (b - 2ap)x + (c - bp + ap^2 + q) ************************************************************/ inT16 p = vec.x (); inT16 q = vec.y (); c = (float) (c - b * p + a * p * p + q); b = (float) (b - 2 * a * p); } double a; //x squared float b; //x float c; //constant private: }; #endif
1080228-arabicocr11
ccstruct/quadratc.h
C++
asf20
2,096
/* -*-C-*- ******************************************************************************** * * File: blobs.h (Formerly blobs.h) * Description: Blob definition * Author: Mark Seaman, OCR Technology * Created: Fri Oct 27 15:39:52 1989 * Modified: Thu Mar 28 15:33:38 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1989, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ #ifndef BLOBS_H #define BLOBS_H /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "clst.h" #include "normalis.h" #include "publictypes.h" #include "rect.h" #include "vecfuncs.h" class BLOCK; class C_BLOB; class C_OUTLINE; class LLSQ; class ROW; class WERD; /*---------------------------------------------------------------------- T y p e s ----------------------------------------------------------------------*/ #define EDGEPTFLAGS 4 /*concavity,length etc. */ struct TPOINT { TPOINT(): x(0), y(0) {} TPOINT(inT16 vx, inT16 vy) : x(vx), y(vy) {} TPOINT(const ICOORD &ic) : x(ic.x()), y(ic.y()) {} void operator+=(const TPOINT& other) { x += other.x; y += other.y; } void operator/=(int divisor) { x /= divisor; y /= divisor; } inT16 x; // absolute x coord. inT16 y; // absolute y coord. }; typedef TPOINT VECTOR; // structure for coordinates. struct EDGEPT { EDGEPT() : next(NULL), prev(NULL), src_outline(NULL), start_step(0), step_count(0) { memset(flags, 0, EDGEPTFLAGS * sizeof(flags[0])); } EDGEPT(const EDGEPT& src) : next(NULL), prev(NULL) { CopyFrom(src); } EDGEPT& operator=(const EDGEPT& src) { CopyFrom(src); return *this; } // Copies the data elements, but leaves the pointers untouched. void CopyFrom(const EDGEPT& src) { pos = src.pos; vec = src.vec; memcpy(flags, src.flags, EDGEPTFLAGS * sizeof(flags[0])); src_outline = src.src_outline; start_step = src.start_step; step_count = src.step_count; } // Accessors to hide or reveal a cut edge from feature extractors. void Hide() { flags[0] = true; } void Reveal() { flags[0] = false; } bool IsHidden() const { return flags[0] != 0; } void MarkChop() { flags[2] = true; } void UnmarkChop() { flags[2] = false; } bool IsChopPt() const { return flags[2] != 0; } TPOINT pos; // position VECTOR vec; // vector to next point // TODO(rays) Remove flags and replace with // is_hidden, runlength, dir, and fixed. The only use // of the flags other than is_hidden is in polyaprx.cpp. char flags[EDGEPTFLAGS]; // concavity, length etc EDGEPT* next; // anticlockwise element EDGEPT* prev; // clockwise element C_OUTLINE* src_outline; // Outline it came from. // The following fields are not used if src_outline is NULL. int start_step; // Location of pos in src_outline. int step_count; // Number of steps used (may wrap around). }; // For use in chop and findseam to keep a list of which EDGEPTs were inserted. CLISTIZEH(EDGEPT); struct TESSLINE { TESSLINE() : is_hole(false), loop(NULL), next(NULL) {} TESSLINE(const TESSLINE& src) : loop(NULL), next(NULL) { CopyFrom(src); } ~TESSLINE() { Clear(); } TESSLINE& operator=(const TESSLINE& src) { CopyFrom(src); return *this; } // Consume the circular list of EDGEPTs to make a TESSLINE. static TESSLINE* BuildFromOutlineList(EDGEPT* outline); // Copies the data and the outline, but leaves next untouched. void CopyFrom(const TESSLINE& src); // Deletes owned data. void Clear(); // Normalize in-place using the DENORM. void Normalize(const DENORM& denorm); // Rotates by the given rotation in place. void Rotate(const FCOORD rotation); // Moves by the given vec in place. void Move(const ICOORD vec); // Scales by the given factor in place. void Scale(float factor); // Sets up the start and vec members of the loop from the pos members. void SetupFromPos(); // Recomputes the bounding box from the points in the loop. void ComputeBoundingBox(); // Computes the min and max cross product of the outline points with the // given vec and returns the results in min_xp and max_xp. Geometrically // this is the left and right edge of the outline perpendicular to the // given direction, but to get the distance units correct, you would // have to divide by the modulus of vec. void MinMaxCrossProduct(const TPOINT vec, int* min_xp, int* max_xp) const; TBOX bounding_box() const; // Returns true if the point is contained within the outline box. bool Contains(const TPOINT& pt) { return topleft.x <= pt.x && pt.x <= botright.x && botright.y <= pt.y && pt.y <= topleft.y; } #ifndef GRAPHICS_DISABLED void plot(ScrollView* window, ScrollView::Color color, ScrollView::Color child_color); #endif // GRAPHICS_DISABLED // Returns the first outline point that has a different src_outline to its // predecessor, or, if all the same, the lowest indexed point. EDGEPT* FindBestStartPt() const; int BBArea() const { return (botright.x - topleft.x) * (topleft.y - botright.y); } TPOINT topleft; // Top left of loop. TPOINT botright; // Bottom right of loop. TPOINT start; // Start of loop. bool is_hole; // True if this is a hole/child outline. EDGEPT *loop; // Edgeloop. TESSLINE *next; // Next outline in blob. }; // Outline structure. struct TBLOB { TBLOB() : outlines(NULL) {} TBLOB(const TBLOB& src) : outlines(NULL) { CopyFrom(src); } ~TBLOB() { Clear(); } TBLOB& operator=(const TBLOB& src) { CopyFrom(src); return *this; } // Factory to build a TBLOB from a C_BLOB with polygonal approximation along // the way. If allow_detailed_fx is true, the EDGEPTs in the returned TBLOB // contain pointers to the input C_OUTLINEs that enable higher-resolution // feature extraction that does not use the polygonal approximation. static TBLOB* PolygonalCopy(bool allow_detailed_fx, C_BLOB* src); // Factory builds a blob with no outlines, but copies the other member data. static TBLOB* ShallowCopy(const TBLOB& src); // Normalizes the blob for classification only if needed. // (Normally this means a non-zero classify rotation.) // If no Normalization is needed, then NULL is returned, and the input blob // can be used directly. Otherwise a new TBLOB is returned which must be // deleted after use. TBLOB* ClassifyNormalizeIfNeeded() const; // Copies the data and the outlines, but leaves next untouched. void CopyFrom(const TBLOB& src); // Deletes owned data. void Clear(); // Sets up the built-in DENORM and normalizes the blob in-place. // For parameters see DENORM::SetupNormalization, plus the inverse flag for // this blob and the Pix for the full image. void Normalize(const BLOCK* block, const FCOORD* rotation, const DENORM* predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift, bool inverse, Pix* pix); // Rotates by the given rotation in place. void Rotate(const FCOORD rotation); // Moves by the given vec in place. void Move(const ICOORD vec); // Scales by the given factor in place. void Scale(float factor); // Recomputes the bounding boxes of the outlines. void ComputeBoundingBoxes(); // Returns the number of outlines. int NumOutlines() const; TBOX bounding_box() const; const DENORM& denorm() const { return denorm_; } #ifndef GRAPHICS_DISABLED void plot(ScrollView* window, ScrollView::Color color, ScrollView::Color child_color); #endif // GRAPHICS_DISABLED int BBArea() const { int total_area = 0; for (TESSLINE* outline = outlines; outline != NULL; outline = outline->next) total_area += outline->BBArea(); return total_area; } // Computes the center of mass and second moments for the old baseline and // 2nd moment normalizations. Returns the outline length. // The input denorm should be the normalizations that have been applied from // the image to the current state of this TBLOB. int ComputeMoments(FCOORD* center, FCOORD* second_moments) const; // Computes the precise bounding box of the coords that are generated by // GetEdgeCoords. This may be different from the bounding box of the polygon. void GetPreciseBoundingBox(TBOX* precise_box) const; // Adds edges to the given vectors. // For all the edge steps in all the outlines, or polygonal approximation // where there are no edge steps, collects the steps into x_coords/y_coords. // x_coords is a collection of the x-coords of vertical edges for each // y-coord starting at box.bottom(). // y_coords is a collection of the y-coords of horizontal edges for each // x-coord starting at box.left(). // Eg x_coords[0] is a collection of the x-coords of edges at y=bottom. // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1. void GetEdgeCoords(const TBOX& box, GenericVector<GenericVector<int> >* x_coords, GenericVector<GenericVector<int> >* y_coords) const; TESSLINE *outlines; // List of outlines in blob. private: // TODO(rays) Someday the data members will be private too. // For all the edge steps in all the outlines, or polygonal approximation // where there are no edge steps, collects the steps into the bounding_box, // llsq and/or the x_coords/y_coords. Both are used in different kinds of // normalization. // For a description of x_coords, y_coords, see GetEdgeCoords above. void CollectEdges(const TBOX& box, TBOX* bounding_box, LLSQ* llsq, GenericVector<GenericVector<int> >* x_coords, GenericVector<GenericVector<int> >* y_coords) const; private: // DENORM indicating the transformations that this blob has undergone so far. DENORM denorm_; }; // Blob structure. struct TWERD { TWERD() : latin_script(false) {} TWERD(const TWERD& src) { CopyFrom(src); } ~TWERD() { Clear(); } TWERD& operator=(const TWERD& src) { CopyFrom(src); return *this; } // Factory to build a TWERD from a (C_BLOB) WERD, with polygonal // approximation along the way. static TWERD* PolygonalCopy(bool allow_detailed_fx, WERD* src); // Baseline normalizes the blobs in-place, recording the normalization in the // DENORMs in the blobs. void BLNormalize(const BLOCK* block, const ROW* row, Pix* pix, bool inverse, float x_height, bool numeric_mode, tesseract::OcrEngineMode hint, const TBOX* norm_box, DENORM* word_denorm); // Copies the data and the blobs, but leaves next untouched. void CopyFrom(const TWERD& src); // Deletes owned data. void Clear(); // Recomputes the bounding boxes of the blobs. void ComputeBoundingBoxes(); // Returns the number of blobs in the word. int NumBlobs() const { return blobs.size(); } TBOX bounding_box() const; // Merges the blobs from start to end, not including end, and deletes // the blobs between start and end. void MergeBlobs(int start, int end); void plot(ScrollView* window); GenericVector<TBLOB*> blobs; // Blobs in word. bool latin_script; // This word is in a latin-based script. }; /*---------------------------------------------------------------------- M a c r o s ----------------------------------------------------------------------*/ /********************************************************************** * free_widths * * Free the memory taken up by a width array. **********************************************************************/ #define free_widths(w) \ if (w) memfree (w) /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ // TODO(rays) This will become a member of TBLOB when TBLOB's definition // moves to blobs.h // Returns the center of blob's bounding box in origin. void blob_origin(TBLOB *blob, TPOINT *origin); bool divisible_blob(TBLOB *blob, bool italic_blob, TPOINT* location); void divide_blobs(TBLOB *blob, TBLOB *other_blob, bool italic_blob, const TPOINT& location); #endif
1080228-arabicocr11
ccstruct/blobs.h
C
asf20
13,593
/********************************************************************** * File: pageres.h (Formerly page_res.h) * Description: Results classes used by control.c * Author: Phil Cheatle * Created: Tue Sep 22 08:42:49 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef PAGERES_H #define PAGERES_H #include "blamer.h" #include "blobs.h" #include "boxword.h" #include "elst.h" #include "genericvector.h" #include "normalis.h" #include "ocrblock.h" #include "ocrrow.h" #include "params_training_featdef.h" #include "ratngs.h" #include "rejctmap.h" #include "seam.h" #include "werd.h" namespace tesseract { struct FontInfo; class Tesseract; } using tesseract::FontInfo; /* Forward declarations */ class BLOCK_RES; ELISTIZEH (BLOCK_RES) CLISTIZEH (BLOCK_RES) class ROW_RES; ELISTIZEH (ROW_RES) class WERD_RES; ELISTIZEH (WERD_RES) /************************************************************************* * PAGE_RES - Page results *************************************************************************/ class PAGE_RES { // page result public: inT32 char_count; inT32 rej_count; BLOCK_RES_LIST block_res_list; BOOL8 rejected; // Updated every time PAGE_RES_IT iterating on this PAGE_RES moves to // the next word. This pointer is not owned by PAGE_RES class. WERD_CHOICE **prev_word_best_choice; // Sums of blame reasons computed by the blamer. GenericVector<int> blame_reasons; // Debug information about all the misadaptions on this page. // Each BlamerBundle contains an index into this vector, so that words that // caused misadaption could be marked. However, since words could be // deleted/split/merged, the log is stored on the PAGE_RES level. GenericVector<STRING> misadaption_log; inline void Init() { char_count = 0; rej_count = 0; rejected = FALSE; prev_word_best_choice = NULL; blame_reasons.init_to_size(IRR_NUM_REASONS, 0); } PAGE_RES() { Init(); } // empty constructor PAGE_RES(bool merge_similar_words, BLOCK_LIST *block_list, // real blocks WERD_CHOICE **prev_word_best_choice_ptr); ~PAGE_RES () { // destructor } }; /************************************************************************* * BLOCK_RES - Block results *************************************************************************/ class BLOCK_RES:public ELIST_LINK { public: BLOCK * block; // real block inT32 char_count; // chars in block inT32 rej_count; // rejected chars inT16 font_class; // inT16 row_count; float x_height; BOOL8 font_assigned; // block already // processed BOOL8 bold; // all bold BOOL8 italic; // all italic ROW_RES_LIST row_res_list; BLOCK_RES() { } // empty constructor BLOCK_RES(bool merge_similar_words, BLOCK *the_block); // real block ~BLOCK_RES () { // destructor } }; /************************************************************************* * ROW_RES - Row results *************************************************************************/ class ROW_RES:public ELIST_LINK { public: ROW * row; // real row inT32 char_count; // chars in block inT32 rej_count; // rejected chars inT32 whole_word_rej_count; // rejs in total rej wds WERD_RES_LIST word_res_list; ROW_RES() { } // empty constructor ROW_RES(bool merge_similar_words, ROW *the_row); // real row ~ROW_RES() { // destructor } }; /************************************************************************* * WERD_RES - Word results *************************************************************************/ enum CRUNCH_MODE { CR_NONE, CR_KEEP_SPACE, CR_LOOSE_SPACE, CR_DELETE }; // WERD_RES is a collection of publicly accessible members that gathers // information about a word result. class WERD_RES : public ELIST_LINK { public: // Which word is which? // There are 3 coordinate spaces in use here: a possibly rotated pixel space, // the original image coordinate space, and the BLN space in which the // baseline of a word is at kBlnBaselineOffset, the xheight is kBlnXHeight, // and the x-middle of the word is at 0. // In the rotated pixel space, coordinates correspond to the input image, // but may be rotated about the origin by a multiple of 90 degrees, // and may therefore be negative. // In any case a rotation by denorm.block()->re_rotation() will take them // back to the original image. // The other differences between words all represent different stages of // processing during recognition. // ---------------------------INPUT------------------------------------- // The word is the input C_BLOBs in the rotated pixel space. // word is NOT owned by the WERD_RES unless combination is true. // All the other word pointers ARE owned by the WERD_RES. WERD* word; // Input C_BLOB word. // -------------SETUP BY SetupFor*Recognition---READONLY-INPUT------------ // The bln_boxes contains the bounding boxes (only) of the input word, in the // BLN space. The lengths of word and bln_boxes // match as they are both before any chopping. // TODO(rays) determine if docqual does anything useful and delete bln_boxes // if it doesn't. tesseract::BoxWord* bln_boxes; // BLN input bounding boxes. // The ROW that this word sits in. NOT owned by the WERD_RES. ROW* blob_row; // The denorm provides the transformation to get back to the rotated image // coords from the chopped_word/rebuild_word BLN coords, but each blob also // has its own denorm. DENORM denorm; // For use on chopped_word. // Unicharset used by the classifier output in best_choice and raw_choice. const UNICHARSET* uch_set; // For converting back to utf8. // ----Initialized by SetupFor*Recognition---BUT OUTPUT FROM RECOGNITION---- // ----Setup to a (different!) state expected by the various classifiers---- // TODO(rays) Tidy and make more consistent. // The chopped_word is also in BLN space, and represents the fully chopped // character fragments that make up the word. // The length of chopped_word matches length of seam_array + 1 (if set). TWERD* chopped_word; // BLN chopped fragments output. // Vector of SEAM* holding chopping points matching chopped_word. GenericVector<SEAM*> seam_array; // Widths of blobs in chopped_word. GenericVector<int> blob_widths; // Gaps between blobs in chopped_word. blob_gaps[i] is the gap between // blob i and blob i+1. GenericVector<int> blob_gaps; // Ratings matrix contains classifier choices for each classified combination // of blobs. The dimension is the same as the number of blobs in chopped_word // and the leading diagonal corresponds to classifier results of the blobs // in chopped_word. The state_ members of best_choice, raw_choice and // best_choices all correspond to this ratings matrix and allow extraction // of the blob choices for any given WERD_CHOICE. MATRIX* ratings; // Owned pointer. // Pointer to the first WERD_CHOICE in best_choices. This is the result that // will be output from Tesseract. Note that this is now a borrowed pointer // and should NOT be deleted. WERD_CHOICE* best_choice; // Borrowed pointer. // The best raw_choice found during segmentation search. Differs from the // best_choice by being the best result according to just the character // classifier, not taking any language model information into account. // Unlike best_choice, the pointer IS owned by this WERD_RES. WERD_CHOICE* raw_choice; // Owned pointer. // Alternative results found during chopping/segmentation search stages. // Note that being an ELIST, best_choices owns the WERD_CHOICEs. WERD_CHOICE_LIST best_choices; // Truth bounding boxes, text and incorrect choice reason. BlamerBundle *blamer_bundle; // --------------OUTPUT FROM RECOGNITION------------------------------- // --------------Not all fields are necessarily set.------------------- // ---best_choice, raw_choice *must* end up set, with a box_word------- // ---In complete output, the number of blobs in rebuild_word matches--- // ---the number of boxes in box_word, the number of unichar_ids in--- // ---best_choice, the number of ints in best_state, and the number--- // ---of strings in correct_text-------------------------------------- // ---SetupFake Sets everything to appropriate values if the word is--- // ---known to be bad before recognition.------------------------------ // The rebuild_word is also in BLN space, but represents the final best // segmentation of the word. Its length is therefore the same as box_word. TWERD* rebuild_word; // BLN best segmented word. // The box_word is in the original image coordinate space. It is the // bounding boxes of the rebuild_word, after denormalization. // The length of box_word matches rebuild_word, best_state (if set) and // correct_text (if set), as well as best_choice and represents the // number of classified units in the output. tesseract::BoxWord* box_word; // Denormalized output boxes. // The best_state stores the relationship between chopped_word and // rebuild_word. Each blob[i] in rebuild_word is composed of best_state[i] // adjacent blobs in chopped_word. The seams in seam_array are hidden // within a rebuild_word blob and revealed between them. GenericVector<int> best_state; // Number of blobs in each best blob. // The correct_text is used during training and adaption to carry the // text to the training system without the need for a unicharset. There // is one entry in the vector for each blob in rebuild_word and box_word. GenericVector<STRING> correct_text; // The Tesseract that was used to recognize this word. Just a borrowed // pointer. Note: Tesseract's class definition is in a higher-level library. // We avoid introducing a cyclic dependency by not using the Tesseract // within WERD_RES. We are just storing it to provide access to it // for the top-level multi-language controller, and maybe for output of // the recognized language. tesseract::Tesseract* tesseract; // Less-well documented members. // TODO(rays) Add more documentation here. WERD_CHOICE *ep_choice; // ep text TODO(rays) delete this. REJMAP reject_map; // best_choice rejects BOOL8 tess_failed; /* If tess_failed is TRUE, one of the following tests failed when Tess returned: - The outword blob list was not the same length as the best_choice string; - The best_choice string contained ALL blanks; - The best_choice string was zero length */ BOOL8 tess_accepted; // Tess thinks its ok? BOOL8 tess_would_adapt; // Tess would adapt? BOOL8 done; // ready for output? bool small_caps; // word appears to be small caps bool odd_size; // word is bigger than line or leader dots. inT8 italic; inT8 bold; // The fontinfos are pointers to data owned by the classifier. const FontInfo* fontinfo; const FontInfo* fontinfo2; inT8 fontinfo_id_count; // number of votes inT8 fontinfo_id2_count; // number of votes BOOL8 guessed_x_ht; BOOL8 guessed_caps_ht; CRUNCH_MODE unlv_crunch_mode; float x_height; // post match estimate float caps_height; // post match estimate /* To deal with fuzzy spaces we need to be able to combine "words" to form combinations when we suspect that the gap is a non-space. The (new) text ord code generates separate words for EVERY fuzzy gap - flags in the word indicate whether the gap is below the threshold (fuzzy kern) and is thus NOT a real word break by default, or above the threshold (fuzzy space) and this is a real word break by default. The WERD_RES list contains all these words PLUS "combination" words built out of (copies of) the words split by fuzzy kerns. The separate parts have their "part_of_combo" flag set true and should be IGNORED on a default reading of the list. Combination words are FOLLOWED by the sequence of part_of_combo words which they combine. */ BOOL8 combination; //of two fuzzy gap wds BOOL8 part_of_combo; //part of a combo BOOL8 reject_spaces; //Reject spacing? // FontInfo ids for each unichar in best_choice. GenericVector<inT8> best_choice_fontinfo_ids; WERD_RES() { InitNonPointers(); InitPointers(); } WERD_RES(WERD *the_word) { InitNonPointers(); InitPointers(); word = the_word; } // Deep copies everything except the ratings MATRIX. // To get that use deep_copy below. WERD_RES(const WERD_RES &source) { InitPointers(); *this = source; // see operator= } ~WERD_RES(); // Returns the UTF-8 string for the given blob index in the best_choice word, // given that we know whether we are in a right-to-left reading context. // This matters for mirrorable characters such as parentheses. We recognize // characters purely based on their shape on the page, and by default produce // the corresponding unicode for a left-to-right context. const char* const BestUTF8(int blob_index, bool in_rtl_context) const { if (blob_index < 0 || best_choice == NULL || blob_index >= best_choice->length()) return NULL; UNICHAR_ID id = best_choice->unichar_id(blob_index); if (id < 0 || id >= uch_set->size() || id == INVALID_UNICHAR_ID) return NULL; UNICHAR_ID mirrored = uch_set->get_mirror(id); if (in_rtl_context && mirrored > 0 && mirrored != INVALID_UNICHAR_ID) id = mirrored; return uch_set->id_to_unichar_ext(id); } // Returns the UTF-8 string for the given blob index in the raw_choice word. const char* const RawUTF8(int blob_index) const { if (blob_index < 0 || blob_index >= raw_choice->length()) return NULL; UNICHAR_ID id = raw_choice->unichar_id(blob_index); if (id < 0 || id >= uch_set->size() || id == INVALID_UNICHAR_ID) return NULL; return uch_set->id_to_unichar(id); } UNICHARSET::Direction SymbolDirection(int blob_index) const { if (best_choice == NULL || blob_index >= best_choice->length() || blob_index < 0) return UNICHARSET::U_OTHER_NEUTRAL; return uch_set->get_direction(best_choice->unichar_id(blob_index)); } bool AnyRtlCharsInWord() const { if (uch_set == NULL || best_choice == NULL || best_choice->length() < 1) return false; for (int id = 0; id < best_choice->length(); id++) { int unichar_id = best_choice->unichar_id(id); if (unichar_id < 0 || unichar_id >= uch_set->size()) continue; // Ignore illegal chars. UNICHARSET::Direction dir = uch_set->get_direction(unichar_id); if (dir == UNICHARSET::U_RIGHT_TO_LEFT || dir == UNICHARSET::U_RIGHT_TO_LEFT_ARABIC || dir == UNICHARSET::U_ARABIC_NUMBER) return true; } return false; } bool AnyLtrCharsInWord() const { if (uch_set == NULL || best_choice == NULL || best_choice->length() < 1) return false; for (int id = 0; id < best_choice->length(); id++) { int unichar_id = best_choice->unichar_id(id); if (unichar_id < 0 || unichar_id >= uch_set->size()) continue; // Ignore illegal chars. UNICHARSET::Direction dir = uch_set->get_direction(unichar_id); if (dir == UNICHARSET::U_LEFT_TO_RIGHT) return true; } return false; } // Return whether the blobs in this WERD_RES 0, 1,... come from an engine // that gave us the unichars in reading order (as opposed to strict left // to right). bool UnicharsInReadingOrder() const { return best_choice->unichars_in_script_order(); } void InitNonPointers(); void InitPointers(); void Clear(); void ClearResults(); void ClearWordChoices(); void ClearRatings(); // Deep copies everything except the ratings MATRIX. // To get that use deep_copy below. WERD_RES& operator=(const WERD_RES& source); //from this void CopySimpleFields(const WERD_RES& source); // Initializes a blank (default constructed) WERD_RES from one that has // already been recognized. // Use SetupFor*Recognition afterwards to complete the setup and make // it ready for a retry recognition. void InitForRetryRecognition(const WERD_RES& source); // Sets up the members used in recognition: bln_boxes, chopped_word, // seam_array, denorm. Returns false if // the word is empty and sets up fake results. If use_body_size is // true and row->body_size is set, then body_size will be used for // blob normalization instead of xheight + ascrise. This flag is for // those languages that are using CJK pitch model and thus it has to // be true if and only if tesseract->textord_use_cjk_fp_model is // true. // If allow_detailed_fx is true, the feature extractor will receive fine // precision outline information, allowing smoother features and better // features on low resolution images. // The norm_mode sets the default mode for normalization in absence // of any of the above flags. It should really be a tesseract::OcrEngineMode // but is declared as int for ease of use with tessedit_ocr_engine_mode. // Returns false if the word is empty and sets up fake results. bool SetupForRecognition(const UNICHARSET& unicharset_in, tesseract::Tesseract* tesseract, Pix* pix, int norm_mode, const TBOX* norm_box, bool numeric_mode, bool use_body_size, bool allow_detailed_fx, ROW *row, const BLOCK* block); // Set up the seam array, bln_boxes, best_choice, and raw_choice to empty // accumulators from a made chopped word. We presume the fields are already // empty. void SetupBasicsFromChoppedWord(const UNICHARSET &unicharset_in); // Sets up the members used in recognition for an empty recognition result: // bln_boxes, chopped_word, seam_array, denorm, best_choice, raw_choice. void SetupFake(const UNICHARSET& uch); // Set the word as having the script of the input unicharset. void SetupWordScript(const UNICHARSET& unicharset_in); // Sets up the blamer_bundle if it is not null, using the initialized denorm. void SetupBlamerBundle(); // Computes the blob_widths and blob_gaps from the chopped_word. void SetupBlobWidthsAndGaps(); // Updates internal data to account for a new SEAM (chop) at the given // blob_number. Fixes the ratings matrix and states in the choices, as well // as the blob widths and gaps. void InsertSeam(int blob_number, SEAM* seam); // Returns true if all the word choices except the first have adjust_factors // worse than the given threshold. bool AlternativeChoiceAdjustmentsWorseThan(float threshold) const; // Returns true if the current word is ambiguous (by number of answers or // by dangerous ambigs.) bool IsAmbiguous(); // Returns true if the ratings matrix size matches the sum of each of the // segmentation states. bool StatesAllValid(); // Prints a list of words found if debug is true or the word result matches // the word_to_debug. void DebugWordChoices(bool debug, const char* word_to_debug); // Prints the top choice along with the accepted/done flags. void DebugTopChoice(const char* msg) const; // Removes from best_choices all choices which are not within a reasonable // range of the best choice. void FilterWordChoices(int debug_level); // Computes a set of distance thresholds used to control adaption. // Compares the best choice for the current word to the best raw choice // to determine which characters were classified incorrectly by the // classifier. Then places a separate threshold into thresholds for each // character in the word. If the classifier was correct, max_rating is placed // into thresholds. If the classifier was incorrect, the mean match rating // (error percentage) of the classifier's incorrect choice minus some margin // is placed into thresholds. This can then be used by the caller to try to // create a new template for the desired class that will classify the // character with a rating better than the threshold value. The match rating // placed into thresholds is never allowed to be below min_rating in order to // prevent trying to make overly tight templates. // min_rating limits how tight to make a template. // max_rating limits how loose to make a template. // rating_margin denotes the amount of margin to put in template. void ComputeAdaptionThresholds(float certainty_scale, float min_rating, float max_rating, float rating_margin, float* thresholds); // Saves a copy of the word_choice if it has the best unadjusted rating. // Returns true if the word_choice was the new best. bool LogNewRawChoice(WERD_CHOICE* word_choice); // Consumes word_choice by adding it to best_choices, (taking ownership) if // the certainty for word_choice is some distance of the best choice in // best_choices, or by deleting the word_choice and returning false. // The best_choices list is kept in sorted order by rating. Duplicates are // removed, and the list is kept no longer than max_num_choices in length. // Returns true if the word_choice is still a valid pointer. bool LogNewCookedChoice(int max_num_choices, bool debug, WERD_CHOICE* word_choice); // Prints a brief list of all the best choices. void PrintBestChoices() const; // Returns the sum of the widths of the blob between start_blob and last_blob // inclusive. int GetBlobsWidth(int start_blob, int last_blob); // Returns the width of a gap between the specified blob and the next one. int GetBlobsGap(int blob_index); // Returns the BLOB_CHOICE corresponding to the given index in the // best choice word taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. May return NULL if there is no // BLOB_CHOICE matching the unichar_id at the given index. BLOB_CHOICE* GetBlobChoice(int index) const; // Returns the BLOB_CHOICE_LIST corresponding to the given index in the // best choice word taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. BLOB_CHOICE_LIST* GetBlobChoices(int index) const; // Moves the results fields from word to this. This takes ownership of all // the data, so src can be destructed. // word1.ConsumeWordResult(word); // delete word; // is simpler and faster than: // word1 = *word; // delete word; // as it doesn't need to copy and reallocate anything. void ConsumeWordResults(WERD_RES* word); // Replace the best choice and rebuild box word. // choice must be from the current best_choices list. void ReplaceBestChoice(WERD_CHOICE* choice); // Builds the rebuild_word and sets the best_state from the chopped_word and // the best_choice->state. void RebuildBestState(); // Copies the chopped_word to the rebuild_word, faking a best_state as well. // Also sets up the output box_word. void CloneChoppedToRebuild(); // Sets/replaces the box_word with one made from the rebuild_word. void SetupBoxWord(); // Sets up the script positions in the best_choice using the best_choice // to get the unichars, and the unicharset to get the target positions. void SetScriptPositions(); // Sets all the blobs in all the words (best choice and alternates) to be // the given position. (When a sub/superscript is recognized as a separate // word, it falls victim to the rule that a whole word cannot be sub or // superscript, so this function overrides that problem.) void SetAllScriptPositions(tesseract::ScriptPos position); // Classifies the word with some already-calculated BLOB_CHOICEs. // The choices are an array of blob_count pointers to BLOB_CHOICE, // providing a single classifier result for each blob. // The BLOB_CHOICEs are consumed and the word takes ownership. // The number of blobs in the box_word must match blob_count. void FakeClassifyWord(int blob_count, BLOB_CHOICE** choices); // Creates a WERD_CHOICE for the word using the top choices from the leading // diagonal of the ratings matrix. void FakeWordFromRatings(); // Copies the best_choice strings to the correct_text for adaption/training. void BestChoiceToCorrectText(); // Merges 2 adjacent blobs in the result if the permanent callback // class_cb returns other than INVALID_UNICHAR_ID, AND the permanent // callback box_cb is NULL or returns true, setting the merged blob // result to the class returned from class_cb. // Returns true if anything was merged. bool ConditionalBlobMerge( TessResultCallback2<UNICHAR_ID, UNICHAR_ID, UNICHAR_ID>* class_cb, TessResultCallback2<bool, const TBOX&, const TBOX&>* box_cb); // Merges 2 adjacent blobs in the result (index and index+1) and corrects // all the data to account for the change. void MergeAdjacentBlobs(int index); // Callback helper for fix_quotes returns a double quote if both // arguments are quote, otherwise INVALID_UNICHAR_ID. UNICHAR_ID BothQuotes(UNICHAR_ID id1, UNICHAR_ID id2); void fix_quotes(); // Callback helper for fix_hyphens returns UNICHAR_ID of - if both // arguments are hyphen, otherwise INVALID_UNICHAR_ID. UNICHAR_ID BothHyphens(UNICHAR_ID id1, UNICHAR_ID id2); // Callback helper for fix_hyphens returns true if box1 and box2 overlap // (assuming both on the same textline, are in order and a chopped em dash.) bool HyphenBoxesOverlap(const TBOX& box1, const TBOX& box2); void fix_hyphens(); // Callback helper for merge_tess_fails returns a space if both // arguments are space, otherwise INVALID_UNICHAR_ID. UNICHAR_ID BothSpaces(UNICHAR_ID id1, UNICHAR_ID id2); void merge_tess_fails(); // Returns a really deep copy of *src, including the ratings MATRIX. static WERD_RES* deep_copy(const WERD_RES* src) { WERD_RES* result = new WERD_RES(*src); // That didn't copy the ratings, but we want a copy if there is one to // begin width. if (src->ratings != NULL) result->ratings = src->ratings->DeepCopy(); return result; } // Copy blobs from word_res onto this word (eliminating spaces between). // Since this may be called bidirectionally OR both the BOL and EOL flags. void copy_on(WERD_RES *word_res) { //from this word word->set_flag(W_BOL, word->flag(W_BOL) || word_res->word->flag(W_BOL)); word->set_flag(W_EOL, word->flag(W_EOL) || word_res->word->flag(W_EOL)); word->copy_on(word_res->word); } // Returns true if the collection of count pieces, starting at start, are all // natural connected components, ie there are no real chops involved. bool PiecesAllNatural(int start, int count) const; }; /************************************************************************* * PAGE_RES_IT - Page results iterator *************************************************************************/ class PAGE_RES_IT { public: PAGE_RES * page_res; // page being iterated PAGE_RES_IT() { } // empty contructor PAGE_RES_IT(PAGE_RES *the_page_res) { // page result page_res = the_page_res; restart_page(); // ready to scan } // Do two PAGE_RES_ITs point at the same word? // This is much cheaper than cmp(). bool operator ==(const PAGE_RES_IT &other) const; bool operator !=(const PAGE_RES_IT &other) const {return !(*this == other); } // Given another PAGE_RES_IT to the same page, // this before other: -1 // this equal to other: 0 // this later than other: 1 int cmp(const PAGE_RES_IT &other) const; WERD_RES *restart_page() { return start_page(false); // Skip empty blocks. } WERD_RES *restart_page_with_empties() { return start_page(true); // Allow empty blocks. } WERD_RES *start_page(bool empty_ok); WERD_RES *restart_row(); // ============ Methods that mutate the underling structures =========== // Note that these methods will potentially invalidate other PAGE_RES_ITs // and are intended to be used only while a single PAGE_RES_IT is active. // This problem needs to be taken into account if these mutation operators // are ever provided to PageIterator or its subclasses. // Inserts the new_word and a corresponding WERD_RES before the current // position. The simple fields of the WERD_RES are copied from clone_res and // the resulting WERD_RES is returned for further setup with best_choice etc. WERD_RES* InsertSimpleCloneWord(const WERD_RES& clone_res, WERD* new_word); // Replaces the current WERD/WERD_RES with the given words. The given words // contain fake blobs that indicate the position of the characters. These are // replaced with real blobs from the current word as much as possible. void ReplaceCurrentWord(tesseract::PointerVector<WERD_RES>* words); // Deletes the current WERD_RES and its underlying WERD. void DeleteCurrentWord(); WERD_RES *forward() { // Get next word. return internal_forward(false, false); } // Move forward, but allow empty blocks to show as single NULL words. WERD_RES *forward_with_empties() { return internal_forward(false, true); } WERD_RES *forward_paragraph(); // get first word in next non-empty paragraph WERD_RES *forward_block(); // get first word in next non-empty block WERD_RES *prev_word() const { // previous word return prev_word_res; } ROW_RES *prev_row() const { // row of prev word return prev_row_res; } BLOCK_RES *prev_block() const { // block of prev word return prev_block_res; } WERD_RES *word() const { // current word return word_res; } ROW_RES *row() const { // row of current word return row_res; } BLOCK_RES *block() const { // block of cur. word return block_res; } WERD_RES *next_word() const { // next word return next_word_res; } ROW_RES *next_row() const { // row of next word return next_row_res; } BLOCK_RES *next_block() const { // block of next word return next_block_res; } void rej_stat_word(); // for page/block/row private: void ResetWordIterator(); WERD_RES *internal_forward(bool new_block, bool empty_ok); WERD_RES * prev_word_res; // previous word ROW_RES *prev_row_res; // row of prev word BLOCK_RES *prev_block_res; // block of prev word WERD_RES *word_res; // current word ROW_RES *row_res; // row of current word BLOCK_RES *block_res; // block of cur. word WERD_RES *next_word_res; // next word ROW_RES *next_row_res; // row of next word BLOCK_RES *next_block_res; // block of next word BLOCK_RES_IT block_res_it; // iterators ROW_RES_IT row_res_it; WERD_RES_IT word_res_it; }; #endif
1080228-arabicocr11
ccstruct/pageres.h
C++
asf20
31,989
/********************************************************************** * File: ocrrow.h (Formerly row.h) * Description: Code for the ROW class. * Author: Ray Smith * Created: Tue Oct 08 15:58:04 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef OCRROW_H #define OCRROW_H #include <stdio.h> #include "quspline.h" #include "werd.h" class TO_ROW; struct PARA; class ROW:public ELIST_LINK { friend void tweak_row_baseline(ROW *, double, double); public: ROW() { } //empty constructor ROW( //constructor inT32 spline_size, //no of segments inT32 *xstarts, //segment boundaries double *coeffs, //coefficients //ascender size float x_height, float ascenders, float descenders, //descender size inT16 kern, //char gap inT16 space); //word gap ROW( //constructor TO_ROW *row, //textord row inT16 kern, //char gap inT16 space); //word gap WERD_LIST *word_list() { //get words return &words; } float base_line( //compute baseline float xpos) const { //at the position //get spline value return (float) baseline.y (xpos); } float x_height() const { //return x height return xheight; } void set_x_height(float new_xheight) { // set x height xheight = new_xheight; } inT32 kern() const { //return kerning return kerning; } float body_size() const { //return body size return bodysize; } void set_body_size(float new_size) { // set body size bodysize = new_size; } inT32 space() const { //return spacing return spacing; } float ascenders() const { //return size return ascrise; } float descenders() const { //return size return descdrop; } TBOX bounding_box() const { //return bounding box return bound_box; } void set_lmargin(inT16 lmargin) { lmargin_ = lmargin; } void set_rmargin(inT16 rmargin) { rmargin_ = rmargin; } inT16 lmargin() const { return lmargin_; } inT16 rmargin() const { return rmargin_; } void set_has_drop_cap(bool has) { has_drop_cap_ = has; } bool has_drop_cap() const { return has_drop_cap_; } void set_para(PARA *p) { para_ = p; } PARA *para() const { return para_; } void recalc_bounding_box(); //recalculate BB void move( // reposition row const ICOORD vec); // by vector void print( //print FILE *fp); //file to print on #ifndef GRAPHICS_DISABLED void plot( //draw one ScrollView* window, //window to draw in ScrollView::Color colour); //uniform colour void plot( //draw one ScrollView* window); //in rainbow colours void plot_baseline( //draw the baseline ScrollView* window, //window to draw in ScrollView::Color colour) { //colour to draw //draw it baseline.plot (window, colour); } #endif // GRAPHICS_DISABLED ROW& operator= (const ROW & source); private: inT32 kerning; //inter char gap inT32 spacing; //inter word gap TBOX bound_box; //bounding box float xheight; //height of line float ascrise; //size of ascenders float descdrop; //-size of descenders float bodysize; //CJK character size. (equals to //xheight+ascrise by default) WERD_LIST words; //words QSPLINE baseline; //baseline spline // These get set after blocks have been determined. bool has_drop_cap_; inT16 lmargin_; // Distance to left polyblock margin. inT16 rmargin_; // Distance to right polyblock margin. // This gets set during paragraph analysis. PARA *para_; // Paragraph of which this row is part. }; ELISTIZEH (ROW) #endif
1080228-arabicocr11
ccstruct/ocrrow.h
C++
asf20
4,980
/********************************************************************** * File: pageres.cpp (Formerly page_res.c) * Description: Results classes used by control.c * Author: Phil Cheatle * Created: Tue Sep 22 08:42:49 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdlib.h> #ifdef __UNIX__ #include <assert.h> #endif #include "blamer.h" #include "pageres.h" #include "blobs.h" ELISTIZE (BLOCK_RES) CLISTIZE (BLOCK_RES) ELISTIZE (ROW_RES) ELISTIZE (WERD_RES) // Gain factor for computing thresholds that determine the ambiguity of a word. static const double kStopperAmbiguityThresholdGain = 8.0; // Constant offset for computing thresholds that determine the ambiguity of a // word. static const double kStopperAmbiguityThresholdOffset = 1.5; // Max number of broken pieces to associate. const int kWordrecMaxNumJoinChunks = 4; // Max ratio of word box height to line size to allow it to be processed as // a line with other words. const double kMaxWordSizeRatio = 1.25; // Max ratio of line box height to line size to allow a new word to be added. const double kMaxLineSizeRatio = 1.25; // Max ratio of word gap to line size to allow a new word to be added. const double kMaxWordGapRatio = 2.0; // Computes and returns a threshold of certainty difference used to determine // which words to keep, based on the adjustment factors of the two words. // TODO(rays) This is horrible. Replace with an enhance params training model. static double StopperAmbigThreshold(double f1, double f2) { return (f2 - f1) * kStopperAmbiguityThresholdGain - kStopperAmbiguityThresholdOffset; } /************************************************************************* * PAGE_RES::PAGE_RES * * Constructor for page results *************************************************************************/ PAGE_RES::PAGE_RES( bool merge_similar_words, BLOCK_LIST *the_block_list, WERD_CHOICE **prev_word_best_choice_ptr) { Init(); BLOCK_IT block_it(the_block_list); BLOCK_RES_IT block_res_it(&block_res_list); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { block_res_it.add_to_end(new BLOCK_RES(merge_similar_words, block_it.data())); } prev_word_best_choice = prev_word_best_choice_ptr; } /************************************************************************* * BLOCK_RES::BLOCK_RES * * Constructor for BLOCK results *************************************************************************/ BLOCK_RES::BLOCK_RES(bool merge_similar_words, BLOCK *the_block) { ROW_IT row_it (the_block->row_list ()); ROW_RES_IT row_res_it(&row_res_list); char_count = 0; rej_count = 0; font_class = -1; //not assigned x_height = -1.0; font_assigned = FALSE; bold = FALSE; italic = FALSE; row_count = 0; block = the_block; for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { row_res_it.add_to_end(new ROW_RES(merge_similar_words, row_it.data())); } } /************************************************************************* * ROW_RES::ROW_RES * * Constructor for ROW results *************************************************************************/ ROW_RES::ROW_RES(bool merge_similar_words, ROW *the_row) { WERD_IT word_it(the_row->word_list()); WERD_RES_IT word_res_it(&word_res_list); WERD_RES *combo = NULL; // current combination of fuzzies WERD *copy_word; char_count = 0; rej_count = 0; whole_word_rej_count = 0; row = the_row; bool add_next_word = false; TBOX union_box; float line_height = the_row->x_height() + the_row->ascenders() - the_row->descenders(); for (word_it.mark_cycle_pt(); !word_it.cycled_list(); word_it.forward()) { WERD_RES* word_res = new WERD_RES(word_it.data()); word_res->x_height = the_row->x_height(); if (add_next_word) { ASSERT_HOST(combo != NULL); // We are adding this word to the combination. word_res->part_of_combo = TRUE; combo->copy_on(word_res); } else if (merge_similar_words) { union_box = word_res->word->bounding_box(); add_next_word = !word_res->word->flag(W_REP_CHAR) && union_box.height() <= line_height * kMaxWordSizeRatio; word_res->odd_size = !add_next_word; } WERD* next_word = word_it.data_relative(1); if (merge_similar_words) { if (add_next_word && !next_word->flag(W_REP_CHAR)) { // Next word will be added on if all of the following are true: // Not a rep char. // Box height small enough. // Union box height small enough. // Horizontal gap small enough. TBOX next_box = next_word->bounding_box(); int prev_right = union_box.right(); union_box += next_box; if (next_box.height() > line_height * kMaxWordSizeRatio || union_box.height() > line_height * kMaxLineSizeRatio || next_box.left() > prev_right + line_height * kMaxWordGapRatio) { add_next_word = false; } } } else { add_next_word = next_word->flag(W_FUZZY_NON); } if (add_next_word) { if (combo == NULL) { copy_word = new WERD; *copy_word = *(word_it.data()); // deep copy combo = new WERD_RES(copy_word); combo->x_height = the_row->x_height(); combo->combination = TRUE; word_res_it.add_to_end(combo); } word_res->part_of_combo = TRUE; } else { combo = NULL; } word_res_it.add_to_end(word_res); } } WERD_RES& WERD_RES::operator=(const WERD_RES & source) { this->ELIST_LINK::operator=(source); Clear(); if (source.combination) { word = new WERD; *word = *(source.word); // deep copy } else { word = source.word; // pt to same word } if (source.bln_boxes != NULL) bln_boxes = new tesseract::BoxWord(*source.bln_boxes); if (source.chopped_word != NULL) chopped_word = new TWERD(*source.chopped_word); if (source.rebuild_word != NULL) rebuild_word = new TWERD(*source.rebuild_word); // TODO(rays) Do we ever need to copy the seam_array? blob_row = source.blob_row; denorm = source.denorm; if (source.box_word != NULL) box_word = new tesseract::BoxWord(*source.box_word); best_state = source.best_state; correct_text = source.correct_text; blob_widths = source.blob_widths; blob_gaps = source.blob_gaps; // None of the uses of operator= require the ratings matrix to be copied, // so don't as it would be really slow. // Copy the cooked choices. WERD_CHOICE_IT wc_it(const_cast<WERD_CHOICE_LIST*>(&source.best_choices)); WERD_CHOICE_IT wc_dest_it(&best_choices); for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward()) { const WERD_CHOICE *choice = wc_it.data(); wc_dest_it.add_after_then_move(new WERD_CHOICE(*choice)); } if (!wc_dest_it.empty()) { wc_dest_it.move_to_first(); best_choice = wc_dest_it.data(); best_choice_fontinfo_ids = source.best_choice_fontinfo_ids; } else { best_choice = NULL; if (!best_choice_fontinfo_ids.empty()) { best_choice_fontinfo_ids.clear(); } } if (source.raw_choice != NULL) { raw_choice = new WERD_CHOICE(*source.raw_choice); } else { raw_choice = NULL; } if (source.ep_choice != NULL) { ep_choice = new WERD_CHOICE(*source.ep_choice); } else { ep_choice = NULL; } reject_map = source.reject_map; combination = source.combination; part_of_combo = source.part_of_combo; CopySimpleFields(source); if (source.blamer_bundle != NULL) { blamer_bundle = new BlamerBundle(*(source.blamer_bundle)); } return *this; } // Copies basic fields that don't involve pointers that might be useful // to copy when making one WERD_RES from another. void WERD_RES::CopySimpleFields(const WERD_RES& source) { tess_failed = source.tess_failed; tess_accepted = source.tess_accepted; tess_would_adapt = source.tess_would_adapt; done = source.done; unlv_crunch_mode = source.unlv_crunch_mode; small_caps = source.small_caps; odd_size = source.odd_size; italic = source.italic; bold = source.bold; fontinfo = source.fontinfo; fontinfo2 = source.fontinfo2; fontinfo_id_count = source.fontinfo_id_count; fontinfo_id2_count = source.fontinfo_id2_count; x_height = source.x_height; caps_height = source.caps_height; guessed_x_ht = source.guessed_x_ht; guessed_caps_ht = source.guessed_caps_ht; reject_spaces = source.reject_spaces; uch_set = source.uch_set; tesseract = source.tesseract; } // Initializes a blank (default constructed) WERD_RES from one that has // already been recognized. // Use SetupFor*Recognition afterwards to complete the setup and make // it ready for a retry recognition. void WERD_RES::InitForRetryRecognition(const WERD_RES& source) { word = source.word; CopySimpleFields(source); if (source.blamer_bundle != NULL) { blamer_bundle = new BlamerBundle(); blamer_bundle->CopyTruth(*source.blamer_bundle); } } // Sets up the members used in recognition: bln_boxes, chopped_word, // seam_array, denorm. Returns false if // the word is empty and sets up fake results. If use_body_size is // true and row->body_size is set, then body_size will be used for // blob normalization instead of xheight + ascrise. This flag is for // those languages that are using CJK pitch model and thus it has to // be true if and only if tesseract->textord_use_cjk_fp_model is // true. // If allow_detailed_fx is true, the feature extractor will receive fine // precision outline information, allowing smoother features and better // features on low resolution images. // The norm_mode_hint sets the default mode for normalization in absence // of any of the above flags. // norm_box is used to override the word bounding box to determine the // normalization scale and offset. // Returns false if the word is empty and sets up fake results. bool WERD_RES::SetupForRecognition(const UNICHARSET& unicharset_in, tesseract::Tesseract* tess, Pix* pix, int norm_mode, const TBOX* norm_box, bool numeric_mode, bool use_body_size, bool allow_detailed_fx, ROW *row, const BLOCK* block) { tesseract::OcrEngineMode norm_mode_hint = static_cast<tesseract::OcrEngineMode>(norm_mode); tesseract = tess; POLY_BLOCK* pb = block != NULL ? block->poly_block() : NULL; if ((norm_mode_hint != tesseract::OEM_CUBE_ONLY && word->cblob_list()->empty()) || (pb != NULL && !pb->IsText())) { // Empty words occur when all the blobs have been moved to the rej_blobs // list, which seems to occur frequently in junk. SetupFake(unicharset_in); word->set_flag(W_REP_CHAR, false); return false; } ClearResults(); SetupWordScript(unicharset_in); chopped_word = TWERD::PolygonalCopy(allow_detailed_fx, word); float word_xheight = use_body_size && row != NULL && row->body_size() > 0.0f ? row->body_size() : x_height; chopped_word->BLNormalize(block, row, pix, word->flag(W_INVERSE), word_xheight, numeric_mode, norm_mode_hint, norm_box, &denorm); blob_row = row; SetupBasicsFromChoppedWord(unicharset_in); SetupBlamerBundle(); int num_blobs = chopped_word->NumBlobs(); ratings = new MATRIX(num_blobs, kWordrecMaxNumJoinChunks); tess_failed = false; return true; } // Set up the seam array, bln_boxes, best_choice, and raw_choice to empty // accumulators from a made chopped word. We presume the fields are already // empty. void WERD_RES::SetupBasicsFromChoppedWord(const UNICHARSET &unicharset_in) { bln_boxes = tesseract::BoxWord::CopyFromNormalized(chopped_word); start_seam_list(chopped_word, &seam_array); SetupBlobWidthsAndGaps(); ClearWordChoices(); } // Sets up the members used in recognition for an empty recognition result: // bln_boxes, chopped_word, seam_array, denorm, best_choice, raw_choice. void WERD_RES::SetupFake(const UNICHARSET& unicharset_in) { ClearResults(); SetupWordScript(unicharset_in); chopped_word = new TWERD; rebuild_word = new TWERD; bln_boxes = new tesseract::BoxWord; box_word = new tesseract::BoxWord; int blob_count = word->cblob_list()->length(); if (blob_count > 0) { BLOB_CHOICE** fake_choices = new BLOB_CHOICE*[blob_count]; // For non-text blocks, just pass any blobs through to the box_word // and call the word failed with a fake classification. C_BLOB_IT b_it(word->cblob_list()); int blob_id = 0; for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { TBOX box = b_it.data()->bounding_box(); box_word->InsertBox(box_word->length(), box); fake_choices[blob_id++] = new BLOB_CHOICE; } FakeClassifyWord(blob_count, fake_choices); delete [] fake_choices; } else { WERD_CHOICE* word = new WERD_CHOICE(&unicharset_in); word->make_bad(); LogNewRawChoice(word); // Ownership of word is taken by *this WERD_RES in LogNewCookedChoice. LogNewCookedChoice(1, false, word); } tess_failed = true; } void WERD_RES::SetupWordScript(const UNICHARSET& uch) { uch_set = &uch; int script = uch.default_sid(); word->set_script_id(script); word->set_flag(W_SCRIPT_HAS_XHEIGHT, uch.script_has_xheight()); word->set_flag(W_SCRIPT_IS_LATIN, script == uch.latin_sid()); } // Sets up the blamer_bundle if it is not null, using the initialized denorm. void WERD_RES::SetupBlamerBundle() { if (blamer_bundle != NULL) { blamer_bundle->SetupNormTruthWord(denorm); } } // Computes the blob_widths and blob_gaps from the chopped_word. void WERD_RES::SetupBlobWidthsAndGaps() { blob_widths.truncate(0); blob_gaps.truncate(0); int num_blobs = chopped_word->NumBlobs(); for (int b = 0; b < num_blobs; ++b) { TBLOB *blob = chopped_word->blobs[b]; TBOX box = blob->bounding_box(); blob_widths.push_back(box.width()); if (b + 1 < num_blobs) { blob_gaps.push_back( chopped_word->blobs[b + 1]->bounding_box().left() - box.right()); } } } // Updates internal data to account for a new SEAM (chop) at the given // blob_number. Fixes the ratings matrix and states in the choices, as well // as the blob widths and gaps. void WERD_RES::InsertSeam(int blob_number, SEAM* seam) { // Insert the seam into the SEAMS array. insert_seam(chopped_word, blob_number, seam, &seam_array); if (ratings != NULL) { // Expand the ratings matrix. ratings = ratings->ConsumeAndMakeBigger(blob_number); // Fix all the segmentation states. if (raw_choice != NULL) raw_choice->UpdateStateForSplit(blob_number); WERD_CHOICE_IT wc_it(&best_choices); for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward()) { WERD_CHOICE* choice = wc_it.data(); choice->UpdateStateForSplit(blob_number); } SetupBlobWidthsAndGaps(); } } // Returns true if all the word choices except the first have adjust_factors // worse than the given threshold. bool WERD_RES::AlternativeChoiceAdjustmentsWorseThan(float threshold) const { // The choices are not changed by this iteration. WERD_CHOICE_IT wc_it(const_cast<WERD_CHOICE_LIST*>(&best_choices)); for (wc_it.forward(); !wc_it.at_first(); wc_it.forward()) { WERD_CHOICE* choice = wc_it.data(); if (choice->adjust_factor() <= threshold) return false; } return true; } // Returns true if the current word is ambiguous (by number of answers or // by dangerous ambigs.) bool WERD_RES::IsAmbiguous() { return !best_choices.singleton() || best_choice->dangerous_ambig_found(); } // Returns true if the ratings matrix size matches the sum of each of the // segmentation states. bool WERD_RES::StatesAllValid() { int ratings_dim = ratings->dimension(); if (raw_choice->TotalOfStates() != ratings_dim) { tprintf("raw_choice has total of states = %d vs ratings dim of %d\n", raw_choice->TotalOfStates(), ratings_dim); return false; } WERD_CHOICE_IT it(&best_choices); int index = 0; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward(), ++index) { WERD_CHOICE* choice = it.data(); if (choice->TotalOfStates() != ratings_dim) { tprintf("Cooked #%d has total of states = %d vs ratings dim of %d\n", choice->TotalOfStates(), ratings_dim); return false; } } return true; } // Prints a list of words found if debug is true or the word result matches // the word_to_debug. void WERD_RES::DebugWordChoices(bool debug, const char* word_to_debug) { if (debug || (word_to_debug != NULL && *word_to_debug != '\0' && best_choice != NULL && best_choice->unichar_string() == STRING(word_to_debug))) { if (raw_choice != NULL) raw_choice->print("\nBest Raw Choice"); WERD_CHOICE_IT it(&best_choices); int index = 0; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward(), ++index) { WERD_CHOICE* choice = it.data(); STRING label; label.add_str_int("\nCooked Choice #", index); choice->print(label.string()); } } } // Prints the top choice along with the accepted/done flags. void WERD_RES::DebugTopChoice(const char* msg) const { tprintf("Best choice: accepted=%d, adaptable=%d, done=%d : ", tess_accepted, tess_would_adapt, done); if (best_choice == NULL) tprintf("<Null choice>\n"); else best_choice->print(msg); } // Removes from best_choices all choices which are not within a reasonable // range of the best choice. // TODO(rays) incorporate the information used here into the params training // re-ranker, in place of this heuristic that is based on the previous // adjustment factor. void WERD_RES::FilterWordChoices(int debug_level) { if (best_choice == NULL || best_choices.singleton()) return; if (debug_level >= 2) best_choice->print("\nFiltering against best choice"); WERD_CHOICE_IT it(&best_choices); int index = 0; for (it.forward(); !it.at_first(); it.forward(), ++index) { WERD_CHOICE* choice = it.data(); float threshold = StopperAmbigThreshold(best_choice->adjust_factor(), choice->adjust_factor()); // i, j index the blob choice in choice, best_choice. // chunk is an index into the chopped_word blobs (AKA chunks). // Since the two words may use different segmentations of the chunks, we // iterate over the chunks to find out whether a comparable blob // classification is much worse than the best result. int i = 0, j = 0, chunk = 0; // Each iteration of the while deals with 1 chunk. On entry choice_chunk // and best_chunk are the indices of the first chunk in the NEXT blob, // i.e. we don't have to increment i, j while chunk < choice_chunk and // best_chunk respectively. int choice_chunk = choice->state(0), best_chunk = best_choice->state(0); while (i < choice->length() && j < best_choice->length()) { if (choice->unichar_id(i) != best_choice->unichar_id(j) && choice->certainty(i) - best_choice->certainty(j) < threshold) { if (debug_level >= 2) { STRING label; label.add_str_int("\nDiscarding bad choice #", index); choice->print(label.string()); tprintf("i %d j %d Chunk %d Choice->Blob[i].Certainty %.4g" " BestChoice->ChunkCertainty[Chunk] %g Threshold %g\n", i, j, chunk, choice->certainty(i), best_choice->certainty(j), threshold); } delete it.extract(); break; } ++chunk; // If needed, advance choice_chunk to keep up with chunk. while (choice_chunk < chunk && ++i < choice->length()) choice_chunk += choice->state(i); // If needed, advance best_chunk to keep up with chunk. while (best_chunk < chunk && ++j < best_choice->length()) best_chunk += best_choice->state(j); } } } void WERD_RES::ComputeAdaptionThresholds(float certainty_scale, float min_rating, float max_rating, float rating_margin, float* thresholds) { int chunk = 0; int end_chunk = best_choice->state(0); int end_raw_chunk = raw_choice->state(0); int raw_blob = 0; for (int i = 0; i < best_choice->length(); i++, thresholds++) { float avg_rating = 0.0f; int num_error_chunks = 0; // For each chunk in best choice blob i, count non-matching raw results. while (chunk < end_chunk) { if (chunk >= end_raw_chunk) { ++raw_blob; end_raw_chunk += raw_choice->state(raw_blob); } if (best_choice->unichar_id(i) != raw_choice->unichar_id(raw_blob)) { avg_rating += raw_choice->certainty(raw_blob); ++num_error_chunks; } ++chunk; } if (num_error_chunks > 0) { avg_rating /= num_error_chunks; *thresholds = (avg_rating / -certainty_scale) * (1.0 - rating_margin); } else { *thresholds = max_rating; } if (*thresholds > max_rating) *thresholds = max_rating; if (*thresholds < min_rating) *thresholds = min_rating; } } // Saves a copy of the word_choice if it has the best unadjusted rating. // Returns true if the word_choice was the new best. bool WERD_RES::LogNewRawChoice(WERD_CHOICE* word_choice) { if (raw_choice == NULL || word_choice->rating() < raw_choice->rating()) { delete raw_choice; raw_choice = new WERD_CHOICE(*word_choice); raw_choice->set_permuter(TOP_CHOICE_PERM); return true; } return false; } // Consumes word_choice by adding it to best_choices, (taking ownership) if // the certainty for word_choice is some distance of the best choice in // best_choices, or by deleting the word_choice and returning false. // The best_choices list is kept in sorted order by rating. Duplicates are // removed, and the list is kept no longer than max_num_choices in length. // Returns true if the word_choice is still a valid pointer. bool WERD_RES::LogNewCookedChoice(int max_num_choices, bool debug, WERD_CHOICE* word_choice) { if (best_choice != NULL) { // Throw out obviously bad choices to save some work. // TODO(rays) Get rid of this! This piece of code produces different // results according to the order in which words are found, which is an // undesirable behavior. It would be better to keep all the choices and // prune them later when more information is available. float max_certainty_delta = StopperAmbigThreshold(best_choice->adjust_factor(), word_choice->adjust_factor()); if (max_certainty_delta > -kStopperAmbiguityThresholdOffset) max_certainty_delta = -kStopperAmbiguityThresholdOffset; if (word_choice->certainty() - best_choice->certainty() < max_certainty_delta) { if (debug) { STRING bad_string; word_choice->string_and_lengths(&bad_string, NULL); tprintf("Discarding choice \"%s\" with an overly low certainty" " %.3f vs best choice certainty %.3f (Threshold: %.3f)\n", bad_string.string(), word_choice->certainty(), best_choice->certainty(), max_certainty_delta + best_choice->certainty()); } delete word_choice; return false; } } // Insert in the list in order of increasing rating, but knock out worse // string duplicates. WERD_CHOICE_IT it(&best_choices); const STRING& new_str = word_choice->unichar_string(); bool inserted = false; int num_choices = 0; if (!it.empty()) { do { WERD_CHOICE* choice = it.data(); if (choice->rating() > word_choice->rating() && !inserted) { // Time to insert. it.add_before_stay_put(word_choice); inserted = true; if (num_choices == 0) best_choice = word_choice; // This is the new best. ++num_choices; } if (choice->unichar_string() == new_str) { if (inserted) { // New is better. delete it.extract(); } else { // Old is better. if (debug) { tprintf("Discarding duplicate choice \"%s\", rating %g vs %g\n", new_str.string(), word_choice->rating(), choice->rating()); } delete word_choice; return false; } } else { ++num_choices; if (num_choices > max_num_choices) delete it.extract(); } it.forward(); } while (!it.at_first()); } if (!inserted && num_choices < max_num_choices) { it.add_to_end(word_choice); inserted = true; if (num_choices == 0) best_choice = word_choice; // This is the new best. } if (debug) { if (inserted) tprintf("New %s", best_choice == word_choice ? "Best" : "Secondary"); else tprintf("Poor"); word_choice->print(" Word Choice"); } if (!inserted) { delete word_choice; return false; } return true; } // Simple helper moves the ownership of the pointer data from src to dest, // first deleting anything in dest, and nulling out src afterwards. template<class T> static void MovePointerData(T** dest, T**src) { delete *dest; *dest = *src; *src = NULL; } // Prints a brief list of all the best choices. void WERD_RES::PrintBestChoices() const { STRING alternates_str; WERD_CHOICE_IT it(const_cast<WERD_CHOICE_LIST*>(&best_choices)); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { if (!it.at_first()) alternates_str += "\", \""; alternates_str += it.data()->unichar_string(); } tprintf("Alternates for \"%s\": {\"%s\"}\n", best_choice->unichar_string().string(), alternates_str.string()); } // Returns the sum of the widths of the blob between start_blob and last_blob // inclusive. int WERD_RES::GetBlobsWidth(int start_blob, int last_blob) { int result = 0; for (int b = start_blob; b <= last_blob; ++b) { result += blob_widths[b]; if (b < last_blob) result += blob_gaps[b]; } return result; } // Returns the width of a gap between the specified blob and the next one. int WERD_RES::GetBlobsGap(int blob_index) { if (blob_index < 0 || blob_index >= blob_gaps.size()) return 0; return blob_gaps[blob_index]; } // Returns the BLOB_CHOICE corresponding to the given index in the // best choice word taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. May return NULL if there is no // BLOB_CHOICE matching the unichar_id at the given index. BLOB_CHOICE* WERD_RES::GetBlobChoice(int index) const { if (index < 0 || index >= best_choice->length()) return NULL; BLOB_CHOICE_LIST* choices = GetBlobChoices(index); return FindMatchingChoice(best_choice->unichar_id(index), choices); } // Returns the BLOB_CHOICE_LIST corresponding to the given index in the // best choice word taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. BLOB_CHOICE_LIST* WERD_RES::GetBlobChoices(int index) const { return best_choice->blob_choices(index, ratings); } // Moves the results fields from word to this. This takes ownership of all // the data, so src can be destructed. void WERD_RES::ConsumeWordResults(WERD_RES* word) { denorm = word->denorm; blob_row = word->blob_row; MovePointerData(&chopped_word, &word->chopped_word); MovePointerData(&rebuild_word, &word->rebuild_word); MovePointerData(&box_word, &word->box_word); seam_array.delete_data_pointers(); seam_array = word->seam_array; word->seam_array.clear(); best_state.move(&word->best_state); correct_text.move(&word->correct_text); blob_widths.move(&word->blob_widths); blob_gaps.move(&word->blob_gaps); if (ratings != NULL) ratings->delete_matrix_pointers(); MovePointerData(&ratings, &word->ratings); best_choice = word->best_choice; MovePointerData(&raw_choice, &word->raw_choice); best_choices.clear(); WERD_CHOICE_IT wc_it(&best_choices); wc_it.add_list_after(&word->best_choices); reject_map = word->reject_map; if (word->blamer_bundle != NULL) { assert(blamer_bundle != NULL); blamer_bundle->CopyResults(*(word->blamer_bundle)); } CopySimpleFields(*word); } // Replace the best choice and rebuild box word. // choice must be from the current best_choices list. void WERD_RES::ReplaceBestChoice(WERD_CHOICE* choice) { best_choice = choice; RebuildBestState(); SetupBoxWord(); // Make up a fake reject map of the right length to keep the // rejection pass happy. reject_map.initialise(best_state.length()); done = tess_accepted = tess_would_adapt = true; SetScriptPositions(); } // Builds the rebuild_word and sets the best_state from the chopped_word and // the best_choice->state. void WERD_RES::RebuildBestState() { ASSERT_HOST(best_choice != NULL); if (rebuild_word != NULL) delete rebuild_word; rebuild_word = new TWERD; if (seam_array.empty()) start_seam_list(chopped_word, &seam_array); best_state.truncate(0); int start = 0; for (int i = 0; i < best_choice->length(); ++i) { int length = best_choice->state(i); best_state.push_back(length); if (length > 1) join_pieces(seam_array, start, start + length - 1, chopped_word); TBLOB* blob = chopped_word->blobs[start]; rebuild_word->blobs.push_back(new TBLOB(*blob)); if (length > 1) break_pieces(seam_array, start, start + length - 1, chopped_word); start += length; } } // Copies the chopped_word to the rebuild_word, faking a best_state as well. // Also sets up the output box_word. void WERD_RES::CloneChoppedToRebuild() { if (rebuild_word != NULL) delete rebuild_word; rebuild_word = new TWERD(*chopped_word); SetupBoxWord(); int word_len = box_word->length(); best_state.reserve(word_len); correct_text.reserve(word_len); for (int i = 0; i < word_len; ++i) { best_state.push_back(1); correct_text.push_back(STRING("")); } } // Sets/replaces the box_word with one made from the rebuild_word. void WERD_RES::SetupBoxWord() { if (box_word != NULL) delete box_word; rebuild_word->ComputeBoundingBoxes(); box_word = tesseract::BoxWord::CopyFromNormalized(rebuild_word); box_word->ClipToOriginalWord(denorm.block(), word); } // Sets up the script positions in the output best_choice using the best_choice // to get the unichars, and the unicharset to get the target positions. void WERD_RES::SetScriptPositions() { best_choice->SetScriptPositions(small_caps, chopped_word); } // Sets all the blobs in all the words (raw choice and best choices) to be // the given position. (When a sub/superscript is recognized as a separate // word, it falls victim to the rule that a whole word cannot be sub or // superscript, so this function overrides that problem.) void WERD_RES::SetAllScriptPositions(tesseract::ScriptPos position) { raw_choice->SetAllScriptPositions(position); WERD_CHOICE_IT wc_it(&best_choices); for (wc_it.mark_cycle_pt(); !wc_it.cycled_list(); wc_it.forward()) wc_it.data()->SetAllScriptPositions(position); } // Classifies the word with some already-calculated BLOB_CHOICEs. // The choices are an array of blob_count pointers to BLOB_CHOICE, // providing a single classifier result for each blob. // The BLOB_CHOICEs are consumed and the word takes ownership. // The number of blobs in the box_word must match blob_count. void WERD_RES::FakeClassifyWord(int blob_count, BLOB_CHOICE** choices) { // Setup the WERD_RES. ASSERT_HOST(box_word != NULL); ASSERT_HOST(blob_count == box_word->length()); ClearWordChoices(); ClearRatings(); ratings = new MATRIX(blob_count, 1); for (int c = 0; c < blob_count; ++c) { BLOB_CHOICE_LIST* choice_list = new BLOB_CHOICE_LIST; BLOB_CHOICE_IT choice_it(choice_list); choice_it.add_after_then_move(choices[c]); ratings->put(c, c, choice_list); } FakeWordFromRatings(); reject_map.initialise(blob_count); done = true; } // Creates a WERD_CHOICE for the word using the top choices from the leading // diagonal of the ratings matrix. void WERD_RES::FakeWordFromRatings() { int num_blobs = ratings->dimension(); WERD_CHOICE* word_choice = new WERD_CHOICE(uch_set, num_blobs); word_choice->set_permuter(TOP_CHOICE_PERM); for (int b = 0; b < num_blobs; ++b) { UNICHAR_ID unichar_id = UNICHAR_SPACE; float rating = MAX_INT32; float certainty = -MAX_INT32; BLOB_CHOICE_LIST* choices = ratings->get(b, b); if (choices != NULL && !choices->empty()) { BLOB_CHOICE_IT bc_it(choices); BLOB_CHOICE* choice = bc_it.data(); unichar_id = choice->unichar_id(); rating = choice->rating(); certainty = choice->certainty(); } word_choice->append_unichar_id_space_allocated(unichar_id, 1, rating, certainty); } LogNewRawChoice(word_choice); // Ownership of word_choice taken by word here. LogNewCookedChoice(1, false, word_choice); } // Copies the best_choice strings to the correct_text for adaption/training. void WERD_RES::BestChoiceToCorrectText() { correct_text.clear(); ASSERT_HOST(best_choice != NULL); for (int i = 0; i < best_choice->length(); ++i) { UNICHAR_ID choice_id = best_choice->unichar_id(i); const char* blob_choice = uch_set->id_to_unichar(choice_id); correct_text.push_back(STRING(blob_choice)); } } // Merges 2 adjacent blobs in the result if the permanent callback // class_cb returns other than INVALID_UNICHAR_ID, AND the permanent // callback box_cb is NULL or returns true, setting the merged blob // result to the class returned from class_cb. // Returns true if anything was merged. bool WERD_RES::ConditionalBlobMerge( TessResultCallback2<UNICHAR_ID, UNICHAR_ID, UNICHAR_ID>* class_cb, TessResultCallback2<bool, const TBOX&, const TBOX&>* box_cb) { ASSERT_HOST(best_choice->length() == 0 || ratings != NULL); bool modified = false; for (int i = 0; i + 1 < best_choice->length(); ++i) { UNICHAR_ID new_id = class_cb->Run(best_choice->unichar_id(i), best_choice->unichar_id(i+1)); if (new_id != INVALID_UNICHAR_ID && (box_cb == NULL || box_cb->Run(box_word->BlobBox(i), box_word->BlobBox(i + 1)))) { // Raw choice should not be fixed. best_choice->set_unichar_id(new_id, i); modified = true; MergeAdjacentBlobs(i); const MATRIX_COORD& coord = best_choice->MatrixCoord(i); if (!coord.Valid(*ratings)) { ratings->IncreaseBandSize(coord.row + 1 - coord.col); } BLOB_CHOICE_LIST* blob_choices = GetBlobChoices(i); if (FindMatchingChoice(new_id, blob_choices) == NULL) { // Insert a fake result. BLOB_CHOICE* blob_choice = new BLOB_CHOICE; blob_choice->set_unichar_id(new_id); BLOB_CHOICE_IT bc_it(blob_choices); bc_it.add_before_then_move(blob_choice); } } } delete class_cb; delete box_cb; return modified; } // Merges 2 adjacent blobs in the result (index and index+1) and corrects // all the data to account for the change. void WERD_RES::MergeAdjacentBlobs(int index) { if (reject_map.length() == best_choice->length()) reject_map.remove_pos(index); best_choice->remove_unichar_id(index + 1); rebuild_word->MergeBlobs(index, index + 2); box_word->MergeBoxes(index, index + 2); if (index + 1 < best_state.length()) { best_state[index] += best_state[index + 1]; best_state.remove(index + 1); } } // TODO(tkielbus) Decide between keeping this behavior here or modifying the // training data. // Utility function for fix_quotes // Return true if the next character in the string (given the UTF8 length in // bytes) is a quote character. static int is_simple_quote(const char* signed_str, int length) { const unsigned char* str = reinterpret_cast<const unsigned char*>(signed_str); // Standard 1 byte quotes. return (length == 1 && (*str == '\'' || *str == '`')) || // UTF-8 3 bytes curved quotes. (length == 3 && ((*str == 0xe2 && *(str + 1) == 0x80 && *(str + 2) == 0x98) || (*str == 0xe2 && *(str + 1) == 0x80 && *(str + 2) == 0x99))); } // Callback helper for fix_quotes returns a double quote if both // arguments are quote, otherwise INVALID_UNICHAR_ID. UNICHAR_ID WERD_RES::BothQuotes(UNICHAR_ID id1, UNICHAR_ID id2) { const char *ch = uch_set->id_to_unichar(id1); const char *next_ch = uch_set->id_to_unichar(id2); if (is_simple_quote(ch, strlen(ch)) && is_simple_quote(next_ch, strlen(next_ch))) return uch_set->unichar_to_id("\""); return INVALID_UNICHAR_ID; } // Change pairs of quotes to double quotes. void WERD_RES::fix_quotes() { if (!uch_set->contains_unichar("\"") || !uch_set->get_enabled(uch_set->unichar_to_id("\""))) return; // Don't create it if it is disallowed. ConditionalBlobMerge( NewPermanentTessCallback(this, &WERD_RES::BothQuotes), NULL); } // Callback helper for fix_hyphens returns UNICHAR_ID of - if both // arguments are hyphen, otherwise INVALID_UNICHAR_ID. UNICHAR_ID WERD_RES::BothHyphens(UNICHAR_ID id1, UNICHAR_ID id2) { const char *ch = uch_set->id_to_unichar(id1); const char *next_ch = uch_set->id_to_unichar(id2); if (strlen(ch) == 1 && strlen(next_ch) == 1 && (*ch == '-' || *ch == '~') && (*next_ch == '-' || *next_ch == '~')) return uch_set->unichar_to_id("-"); return INVALID_UNICHAR_ID; } // Callback helper for fix_hyphens returns true if box1 and box2 overlap // (assuming both on the same textline, are in order and a chopped em dash.) bool WERD_RES::HyphenBoxesOverlap(const TBOX& box1, const TBOX& box2) { return box1.right() >= box2.left(); } // Change pairs of hyphens to a single hyphen if the bounding boxes touch // Typically a long dash which has been segmented. void WERD_RES::fix_hyphens() { if (!uch_set->contains_unichar("-") || !uch_set->get_enabled(uch_set->unichar_to_id("-"))) return; // Don't create it if it is disallowed. ConditionalBlobMerge( NewPermanentTessCallback(this, &WERD_RES::BothHyphens), NewPermanentTessCallback(this, &WERD_RES::HyphenBoxesOverlap)); } // Callback helper for merge_tess_fails returns a space if both // arguments are space, otherwise INVALID_UNICHAR_ID. UNICHAR_ID WERD_RES::BothSpaces(UNICHAR_ID id1, UNICHAR_ID id2) { if (id1 == id2 && id1 == uch_set->unichar_to_id(" ")) return id1; else return INVALID_UNICHAR_ID; } // Change pairs of tess failures to a single one void WERD_RES::merge_tess_fails() { if (ConditionalBlobMerge( NewPermanentTessCallback(this, &WERD_RES::BothSpaces), NULL)) { int len = best_choice->length(); ASSERT_HOST(reject_map.length() == len); ASSERT_HOST(box_word->length() == len); } } // Returns true if the collection of count pieces, starting at start, are all // natural connected components, ie there are no real chops involved. bool WERD_RES::PiecesAllNatural(int start, int count) const { // all seams must have no splits. for (int index = start; index < start + count - 1; ++index) { if (index >= 0 && index < seam_array.size()) { SEAM* seam = seam_array[index]; if (seam != NULL && seam->split1 != NULL) return false; } } return true; } WERD_RES::~WERD_RES () { Clear(); } void WERD_RES::InitNonPointers() { tess_failed = FALSE; tess_accepted = FALSE; tess_would_adapt = FALSE; done = FALSE; unlv_crunch_mode = CR_NONE; small_caps = false; odd_size = false; italic = FALSE; bold = FALSE; // The fontinfos and tesseract count as non-pointers as they point to // data owned elsewhere. fontinfo = NULL; fontinfo2 = NULL; tesseract = NULL; fontinfo_id_count = 0; fontinfo_id2_count = 0; x_height = 0.0; caps_height = 0.0; guessed_x_ht = TRUE; guessed_caps_ht = TRUE; combination = FALSE; part_of_combo = FALSE; reject_spaces = FALSE; } void WERD_RES::InitPointers() { word = NULL; bln_boxes = NULL; blob_row = NULL; uch_set = NULL; chopped_word = NULL; rebuild_word = NULL; box_word = NULL; ratings = NULL; best_choice = NULL; raw_choice = NULL; ep_choice = NULL; blamer_bundle = NULL; } void WERD_RES::Clear() { if (word != NULL && combination) { delete word; } word = NULL; delete blamer_bundle; blamer_bundle = NULL; ClearResults(); } void WERD_RES::ClearResults() { done = false; fontinfo = NULL; fontinfo2 = NULL; fontinfo_id_count = 0; fontinfo_id2_count = 0; if (bln_boxes != NULL) { delete bln_boxes; bln_boxes = NULL; } blob_row = NULL; if (chopped_word != NULL) { delete chopped_word; chopped_word = NULL; } if (rebuild_word != NULL) { delete rebuild_word; rebuild_word = NULL; } if (box_word != NULL) { delete box_word; box_word = NULL; } best_state.clear(); correct_text.clear(); seam_array.delete_data_pointers(); seam_array.clear(); blob_widths.clear(); blob_gaps.clear(); ClearRatings(); ClearWordChoices(); if (blamer_bundle != NULL) blamer_bundle->ClearResults(); } void WERD_RES::ClearWordChoices() { best_choice = NULL; if (raw_choice != NULL) { delete raw_choice; raw_choice = NULL; } best_choices.clear(); if (ep_choice != NULL) { delete ep_choice; ep_choice = NULL; } } void WERD_RES::ClearRatings() { if (ratings != NULL) { ratings->delete_matrix_pointers(); delete ratings; ratings = NULL; } } bool PAGE_RES_IT::operator ==(const PAGE_RES_IT &other) const { return word_res == other.word_res && row_res == other.row_res && block_res == other.block_res; } int PAGE_RES_IT::cmp(const PAGE_RES_IT &other) const { ASSERT_HOST(page_res == other.page_res); if (other.block_res == NULL) { // other points to the end of the page. if (block_res == NULL) return 0; return -1; } if (block_res == NULL) { return 1; // we point to the end of the page. } if (block_res == other.block_res) { if (other.row_res == NULL || row_res == NULL) { // this should only happen if we hit an image block. return 0; } if (row_res == other.row_res) { // we point to the same block and row. ASSERT_HOST(other.word_res != NULL && word_res != NULL); if (word_res == other.word_res) { // we point to the same word! return 0; } WERD_RES_IT word_res_it(&row_res->word_res_list); for (word_res_it.mark_cycle_pt(); !word_res_it.cycled_list(); word_res_it.forward()) { if (word_res_it.data() == word_res) { return -1; } else if (word_res_it.data() == other.word_res) { return 1; } } ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL); } // we both point to the same block, but different rows. ROW_RES_IT row_res_it(&block_res->row_res_list); for (row_res_it.mark_cycle_pt(); !row_res_it.cycled_list(); row_res_it.forward()) { if (row_res_it.data() == row_res) { return -1; } else if (row_res_it.data() == other.row_res) { return 1; } } ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL); } // We point to different blocks. BLOCK_RES_IT block_res_it(&page_res->block_res_list); for (block_res_it.mark_cycle_pt(); !block_res_it.cycled_list(); block_res_it.forward()) { if (block_res_it.data() == block_res) { return -1; } else if (block_res_it.data() == other.block_res) { return 1; } } // Shouldn't happen... ASSERT_HOST("Error: Incomparable PAGE_RES_ITs" == NULL); return 0; } // Inserts the new_word and a corresponding WERD_RES before the current // position. The simple fields of the WERD_RES are copied from clone_res and // the resulting WERD_RES is returned for further setup with best_choice etc. WERD_RES* PAGE_RES_IT::InsertSimpleCloneWord(const WERD_RES& clone_res, WERD* new_word) { // Insert new_word into the ROW. WERD_IT w_it(row()->row->word_list()); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD* word = w_it.data(); if (word == word_res->word) break; } ASSERT_HOST(!w_it.cycled_list()); w_it.add_before_then_move(new_word); // Make a WERD_RES for the new_word. WERD_RES* new_res = new WERD_RES(new_word); new_res->CopySimpleFields(clone_res); // Insert into the appropriate place in the ROW_RES. WERD_RES_IT wr_it(&row()->word_res_list); for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) { WERD_RES* word = wr_it.data(); if (word == word_res) break; } ASSERT_HOST(!wr_it.cycled_list()); wr_it.add_before_then_move(new_res); if (wr_it.at_first()) { // This is the new first word, so reset the member iterator so it // detects the cycled_list state correctly. ResetWordIterator(); } return new_res; } // Helper computes the boundaries between blobs in the word. The blob bounds // are likely very poor, if they come from LSTM, where it only outputs the // character at one pixel within it, so we find the midpoints between them. static void ComputeBlobEnds(const WERD_RES& word, C_BLOB_LIST* next_word_blobs, GenericVector<int>* blob_ends) { C_BLOB_IT blob_it(word.word->cblob_list()); for (int i = 0; i < word.best_state.size(); ++i) { int length = word.best_state[i]; // Get the bounding box of the fake blobs TBOX blob_box = blob_it.data()->bounding_box(); blob_it.forward(); for (int b = 1; b < length; ++b) { blob_box += blob_it.data()->bounding_box(); blob_it.forward(); } // This blob_box is crap, so for now we are only looking for the // boundaries between them. int blob_end = MAX_INT32; if (!blob_it.at_first() || next_word_blobs != NULL) { if (blob_it.at_first()) blob_it.set_to_list(next_word_blobs); blob_end = (blob_box.right() + blob_it.data()->bounding_box().left()) / 2; } blob_ends->push_back(blob_end); } } // Replaces the current WERD/WERD_RES with the given words. The given words // contain fake blobs that indicate the position of the characters. These are // replaced with real blobs from the current word as much as possible. void PAGE_RES_IT::ReplaceCurrentWord( tesseract::PointerVector<WERD_RES>* words) { WERD_RES* input_word = word(); // Set the BOL/EOL flags on the words from the input word. if (input_word->word->flag(W_BOL)) { (*words)[0]->word->set_flag(W_BOL, true); } else { (*words)[0]->word->set_blanks(1); } words->back()->word->set_flag(W_EOL, input_word->word->flag(W_EOL)); // Move the blobs from the input word to the new set of words. // If the input word_res is a combination, then the replacements will also be // combinations, and will own their own words. If the input word_res is not a // combination, then the final replacements will not be either, (although it // is allowed for the input words to be combinations) and their words // will get put on the row list. This maintains the ownership rules. WERD_IT w_it(row()->row->word_list()); if (!input_word->combination) { for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { WERD* word = w_it.data(); if (word == input_word->word) break; } // w_it is now set to the input_word's word. ASSERT_HOST(!w_it.cycled_list()); } // Insert into the appropriate place in the ROW_RES. WERD_RES_IT wr_it(&row()->word_res_list); for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) { WERD_RES* word = wr_it.data(); if (word == input_word) break; } ASSERT_HOST(!wr_it.cycled_list()); // Since we only have an estimate of the bounds between blobs, use the blob // x-middle as the determiner of where to put the blobs C_BLOB_IT src_b_it(input_word->word->cblob_list()); src_b_it.sort(&C_BLOB::SortByXMiddle); C_BLOB_IT rej_b_it(input_word->word->rej_cblob_list()); rej_b_it.sort(&C_BLOB::SortByXMiddle); for (int w = 0; w < words->size(); ++w) { WERD_RES* word_w = (*words)[w]; // Compute blob boundaries. GenericVector<int> blob_ends; C_BLOB_LIST* next_word_blobs = w + 1 < words->size() ? (*words)[w + 1]->word->cblob_list() : NULL; ComputeBlobEnds(*word_w, next_word_blobs, &blob_ends); // Delete the fake blobs on the current word. word_w->word->cblob_list()->clear(); C_BLOB_IT dest_it(word_w->word->cblob_list()); // Build the box word as we move the blobs. tesseract::BoxWord* box_word = new tesseract::BoxWord; for (int i = 0; i < blob_ends.size(); ++i) { int end_x = blob_ends[i]; TBOX blob_box; // Add the blobs up to end_x. while (!src_b_it.empty() && src_b_it.data()->bounding_box().x_middle() < end_x) { blob_box += src_b_it.data()->bounding_box(); dest_it.add_after_then_move(src_b_it.extract()); src_b_it.forward(); } while (!rej_b_it.empty() && rej_b_it.data()->bounding_box().x_middle() < end_x) { blob_box += rej_b_it.data()->bounding_box(); dest_it.add_after_then_move(rej_b_it.extract()); rej_b_it.forward(); } // Clip to the previously computed bounds. Although imperfectly accurate, // it is good enough, and much more complicated to determine where else // to clip. if (i > 0 && blob_box.left() < blob_ends[i - 1]) blob_box.set_left(blob_ends[i - 1]); if (blob_box.right() > end_x) blob_box.set_right(end_x); box_word->InsertBox(i, blob_box); } // Fix empty boxes. If a very joined blob sits over multiple characters, // then we will have some empty boxes from using the middle, so look for // overlaps. for (int i = 0; i < box_word->length(); ++i) { TBOX box = box_word->BlobBox(i); if (box.null_box()) { // Nothing has its middle in the bounds of this blob, so use anything // that overlaps. for (dest_it.mark_cycle_pt(); !dest_it.cycled_list(); dest_it.forward()) { TBOX blob_box = dest_it.data()->bounding_box(); if (blob_box.left() < blob_ends[i] && (i == 0 || blob_box.right() >= blob_ends[i - 1])) { if (i > 0 && blob_box.left() < blob_ends[i - 1]) blob_box.set_left(blob_ends[i - 1]); if (blob_box.right() > blob_ends[i]) blob_box.set_right(blob_ends[i]); box_word->ChangeBox(i, blob_box); break; } } } } delete word_w->box_word; word_w->box_word = box_word; if (!input_word->combination) { // Insert word_w->word into the ROW. It doesn't own its word, so the // ROW needs to own it. w_it.add_before_stay_put(word_w->word); word_w->combination = false; } (*words)[w] = NULL; // We are taking ownership. wr_it.add_before_stay_put(word_w); } // We have taken ownership of the words. words->clear(); // Delete the current word, which has been replaced. We could just call // DeleteCurrentWord, but that would iterate both lists again, and we know // we are already in the right place. if (!input_word->combination) delete w_it.extract(); delete wr_it.extract(); ResetWordIterator(); } // Deletes the current WERD_RES and its underlying WERD. void PAGE_RES_IT::DeleteCurrentWord() { // Check that this word is as we expect. part_of_combos are NEVER iterated // by the normal iterator, so we should never be trying to delete them. ASSERT_HOST(!word_res->part_of_combo); if (!word_res->combination) { // Combinations own their own word, so we won't find the word on the // row's word_list, but it is legitimate to try to delete them. // Delete word from the ROW when not a combination. WERD_IT w_it(row()->row->word_list()); for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) { if (w_it.data() == word_res->word) { break; } } ASSERT_HOST(!w_it.cycled_list()); delete w_it.extract(); } // Remove the WERD_RES for the new_word. // Remove the WORD_RES from the ROW_RES. WERD_RES_IT wr_it(&row()->word_res_list); for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) { if (wr_it.data() == word_res) { word_res = NULL; break; } } ASSERT_HOST(!wr_it.cycled_list()); delete wr_it.extract(); ResetWordIterator(); } /************************************************************************* * PAGE_RES_IT::restart_page * * Set things up at the start of the page *************************************************************************/ WERD_RES *PAGE_RES_IT::start_page(bool empty_ok) { block_res_it.set_to_list(&page_res->block_res_list); block_res_it.mark_cycle_pt(); prev_block_res = NULL; prev_row_res = NULL; prev_word_res = NULL; block_res = NULL; row_res = NULL; word_res = NULL; next_block_res = NULL; next_row_res = NULL; next_word_res = NULL; internal_forward(true, empty_ok); return internal_forward(false, empty_ok); } // Recovers from operations on the current word, such as in InsertCloneWord // and DeleteCurrentWord. // Resets the word_res_it so that it is one past the next_word_res, as // it should be after internal_forward. If next_row_res != row_res, // then the next_word_res is in the next row, so there is no need to do // anything to word_res_it, but it is still a good idea to reset the pointers // word_res and prev_word_res, which are still in the current row. void PAGE_RES_IT::ResetWordIterator() { if (row_res == next_row_res) { // Reset the member iterator so it can move forward and detect the // cycled_list state correctly. word_res_it.move_to_first(); word_res_it.mark_cycle_pt(); while (!word_res_it.cycled_list() && word_res_it.data() != next_word_res) { if (prev_row_res == row_res) prev_word_res = word_res; word_res = word_res_it.data(); word_res_it.forward(); } ASSERT_HOST(!word_res_it.cycled_list()); word_res_it.forward(); } else { // word_res_it is OK, but reset word_res and prev_word_res if needed. WERD_RES_IT wr_it(&row_res->word_res_list); for (wr_it.mark_cycle_pt(); !wr_it.cycled_list(); wr_it.forward()) { if (prev_row_res == row_res) prev_word_res = word_res; word_res = wr_it.data(); } } } /************************************************************************* * PAGE_RES_IT::internal_forward * * Find the next word on the page. If empty_ok is true, then non-text blocks * and text blocks with no text are visited as if they contain a single * imaginary word in a single imaginary row. (word() and row() both return NULL * in such a block and the return value is NULL.) * If empty_ok is false, the old behaviour is maintained. Each real word * is visited and empty and non-text blocks and rows are skipped. * new_block is used to initialize the iterators for a new block. * The iterator maintains pointers to block, row and word for the previous, * current and next words. These are correct, regardless of block/row * boundaries. NULL values denote start and end of the page. *************************************************************************/ WERD_RES *PAGE_RES_IT::internal_forward(bool new_block, bool empty_ok) { bool new_row = false; prev_block_res = block_res; prev_row_res = row_res; prev_word_res = word_res; block_res = next_block_res; row_res = next_row_res; word_res = next_word_res; next_block_res = NULL; next_row_res = NULL; next_word_res = NULL; while (!block_res_it.cycled_list()) { if (new_block) { new_block = false; row_res_it.set_to_list(&block_res_it.data()->row_res_list); row_res_it.mark_cycle_pt(); if (row_res_it.empty() && empty_ok) { next_block_res = block_res_it.data(); break; } new_row = true; } while (!row_res_it.cycled_list()) { if (new_row) { new_row = false; word_res_it.set_to_list(&row_res_it.data()->word_res_list); word_res_it.mark_cycle_pt(); } // Skip any part_of_combo words. while (!word_res_it.cycled_list() && word_res_it.data()->part_of_combo) word_res_it.forward(); if (!word_res_it.cycled_list()) { next_block_res = block_res_it.data(); next_row_res = row_res_it.data(); next_word_res = word_res_it.data(); word_res_it.forward(); goto foundword; } // end of row reached row_res_it.forward(); new_row = true; } // end of block reached block_res_it.forward(); new_block = true; } foundword: // Update prev_word_best_choice pointer. if (page_res != NULL && page_res->prev_word_best_choice != NULL) { *page_res->prev_word_best_choice = (new_block || prev_word_res == NULL) ? NULL : prev_word_res->best_choice; } return word_res; } /************************************************************************* * PAGE_RES_IT::restart_row() * * Move to the beginning (leftmost word) of the current row. *************************************************************************/ WERD_RES *PAGE_RES_IT::restart_row() { ROW_RES *row = this->row(); if (!row) return NULL; for (restart_page(); this->row() != row; forward()) { // pass } return word(); } /************************************************************************* * PAGE_RES_IT::forward_paragraph * * Move to the beginning of the next paragraph, allowing empty blocks. *************************************************************************/ WERD_RES *PAGE_RES_IT::forward_paragraph() { while (block_res == next_block_res && (next_row_res != NULL && next_row_res->row != NULL && row_res->row->para() == next_row_res->row->para())) { internal_forward(false, true); } return internal_forward(false, true); } /************************************************************************* * PAGE_RES_IT::forward_block * * Move to the beginning of the next block, allowing empty blocks. *************************************************************************/ WERD_RES *PAGE_RES_IT::forward_block() { while (block_res == next_block_res) { internal_forward(false, true); } return internal_forward(false, true); } void PAGE_RES_IT::rej_stat_word() { inT16 chars_in_word; inT16 rejects_in_word = 0; chars_in_word = word_res->reject_map.length (); page_res->char_count += chars_in_word; block_res->char_count += chars_in_word; row_res->char_count += chars_in_word; rejects_in_word = word_res->reject_map.reject_count (); page_res->rej_count += rejects_in_word; block_res->rej_count += rejects_in_word; row_res->rej_count += rejects_in_word; if (chars_in_word == rejects_in_word) row_res->whole_word_rej_count += rejects_in_word; }
1080228-arabicocr11
ccstruct/pageres.cpp
C++
asf20
60,192
/********************************************************************** * File: statistc.c (Formerly stats.c) * Description: Simple statistical package for integer values. * Author: Ray Smith * Created: Mon Feb 04 16:56:05 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "statistc.h" #include <string.h> #include <math.h> #include <stdlib.h> #include "helpers.h" #include "scrollview.h" #include "tprintf.h" using tesseract::KDPairInc; /********************************************************************** * STATS::STATS * * Construct a new stats element by allocating and zeroing the memory. **********************************************************************/ STATS::STATS(inT32 min_bucket_value, inT32 max_bucket_value_plus_1) { if (max_bucket_value_plus_1 <= min_bucket_value) { min_bucket_value = 0; max_bucket_value_plus_1 = 1; } rangemin_ = min_bucket_value; // setup rangemax_ = max_bucket_value_plus_1; buckets_ = new inT32[rangemax_ - rangemin_]; clear(); } STATS::STATS() { rangemax_ = 0; rangemin_ = 0; buckets_ = NULL; } /********************************************************************** * STATS::set_range * * Alter the range on an existing stats element. **********************************************************************/ bool STATS::set_range(inT32 min_bucket_value, inT32 max_bucket_value_plus_1) { if (max_bucket_value_plus_1 <= min_bucket_value) { return false; } if (rangemax_ - rangemin_ != max_bucket_value_plus_1 - min_bucket_value) { delete [] buckets_; buckets_ = new inT32[max_bucket_value_plus_1 - min_bucket_value]; } rangemin_ = min_bucket_value; // setup rangemax_ = max_bucket_value_plus_1; clear(); // zero it return true; } /********************************************************************** * STATS::clear * * Clear out the STATS class by zeroing all the buckets. **********************************************************************/ void STATS::clear() { // clear out buckets total_count_ = 0; if (buckets_ != NULL) memset(buckets_, 0, (rangemax_ - rangemin_) * sizeof(buckets_[0])); } /********************************************************************** * STATS::~STATS * * Destructor for a stats class. **********************************************************************/ STATS::~STATS () { if (buckets_ != NULL) { delete [] buckets_; buckets_ = NULL; } } /********************************************************************** * STATS::add * * Add a set of samples to (or delete from) a pile. **********************************************************************/ void STATS::add(inT32 value, inT32 count) { if (buckets_ == NULL) { return; } value = ClipToRange(value, rangemin_, rangemax_ - 1); buckets_[value - rangemin_] += count; total_count_ += count; // keep count of total } /********************************************************************** * STATS::mode * * Find the mode of a stats class. **********************************************************************/ inT32 STATS::mode() const { // get mode of samples if (buckets_ == NULL) { return rangemin_; } inT32 max = buckets_[0]; // max cell count inT32 maxindex = 0; // index of max for (int index = rangemax_ - rangemin_ - 1; index > 0; --index) { if (buckets_[index] > max) { max = buckets_[index]; // find biggest maxindex = index; } } return maxindex + rangemin_; // index of biggest } /********************************************************************** * STATS::mean * * Find the mean of a stats class. **********************************************************************/ double STATS::mean() const { //get mean of samples if (buckets_ == NULL || total_count_ <= 0) { return static_cast<double>(rangemin_); } inT64 sum = 0; for (int index = rangemax_ - rangemin_ - 1; index >= 0; --index) { sum += static_cast<inT64>(index) * buckets_[index]; } return static_cast<double>(sum) / total_count_ + rangemin_; } /********************************************************************** * STATS::sd * * Find the standard deviation of a stats class. **********************************************************************/ double STATS::sd() const { //standard deviation if (buckets_ == NULL || total_count_ <= 0) { return 0.0; } inT64 sum = 0; double sqsum = 0.0; for (int index = rangemax_ - rangemin_ - 1; index >= 0; --index) { sum += static_cast<inT64>(index) * buckets_[index]; sqsum += static_cast<double>(index) * index * buckets_[index]; } double variance = static_cast<double>(sum) / total_count_; variance = sqsum / total_count_ - variance * variance; if (variance > 0.0) return sqrt(variance); return 0.0; } /********************************************************************** * STATS::ile * * Returns the fractile value such that frac fraction (in [0,1]) of samples * has a value less than the return value. **********************************************************************/ double STATS::ile(double frac) const { if (buckets_ == NULL || total_count_ == 0) { return static_cast<double>(rangemin_); } #if 0 // TODO(rays) The existing code doesn't seem to be doing the right thing // with target a double but this substitute crashes the code that uses it. // Investigate and fix properly. int target = IntCastRounded(frac * total_count_); target = ClipToRange(target, 1, total_count_); #else double target = frac * total_count_; target = ClipToRange(target, 1.0, static_cast<double>(total_count_)); #endif int sum = 0; int index = 0; for (index = 0; index < rangemax_ - rangemin_ && sum < target; sum += buckets_[index++]); if (index > 0) { ASSERT_HOST(buckets_[index - 1] > 0); return rangemin_ + index - static_cast<double>(sum - target) / buckets_[index - 1]; } else { return static_cast<double>(rangemin_); } } /********************************************************************** * STATS::min_bucket * * Find REAL minimum bucket - ile(0.0) isnt necessarily correct **********************************************************************/ inT32 STATS::min_bucket() const { // Find min if (buckets_ == NULL || total_count_ == 0) { return rangemin_; } inT32 min = 0; for (min = 0; (min < rangemax_ - rangemin_) && (buckets_[min] == 0); min++); return rangemin_ + min; } /********************************************************************** * STATS::max_bucket * * Find REAL maximum bucket - ile(1.0) isnt necessarily correct **********************************************************************/ inT32 STATS::max_bucket() const { // Find max if (buckets_ == NULL || total_count_ == 0) { return rangemin_; } inT32 max; for (max = rangemax_ - rangemin_ - 1; max > 0 && buckets_[max] == 0; max--); return rangemin_ + max; } /********************************************************************** * STATS::median * * Finds a more useful estimate of median than ile(0.5). * * Overcomes a problem with ile() - if the samples are, for example, * 6,6,13,14 ile(0.5) return 7.0 - when a more useful value would be midway * between 6 and 13 = 9.5 **********************************************************************/ double STATS::median() const { //get median if (buckets_ == NULL) { return static_cast<double>(rangemin_); } double median = ile(0.5); int median_pile = static_cast<int>(floor(median)); if ((total_count_ > 1) && (pile_count(median_pile) == 0)) { inT32 min_pile; inT32 max_pile; /* Find preceeding non zero pile */ for (min_pile = median_pile; pile_count(min_pile) == 0; min_pile--); /* Find following non zero pile */ for (max_pile = median_pile; pile_count(max_pile) == 0; max_pile++); median = (min_pile + max_pile) / 2.0; } return median; } /********************************************************************** * STATS::local_min * * Return TRUE if this point is a local min. **********************************************************************/ bool STATS::local_min(inT32 x) const { if (buckets_ == NULL) { return false; } x = ClipToRange(x, rangemin_, rangemax_ - 1) - rangemin_; if (buckets_[x] == 0) return true; inT32 index; // table index for (index = x - 1; index >= 0 && buckets_[index] == buckets_[x]; --index); if (index >= 0 && buckets_[index] < buckets_[x]) return false; for (index = x + 1; index < rangemax_ - rangemin_ && buckets_[index] == buckets_[x]; ++index); if (index < rangemax_ - rangemin_ && buckets_[index] < buckets_[x]) return false; else return true; } /********************************************************************** * STATS::smooth * * Apply a triangular smoothing filter to the stats. * This makes the modes a bit more useful. * The factor gives the height of the triangle, i.e. the weight of the * centre. **********************************************************************/ void STATS::smooth(inT32 factor) { if (buckets_ == NULL || factor < 2) { return; } STATS result(rangemin_, rangemax_); int entrycount = rangemax_ - rangemin_; for (int entry = 0; entry < entrycount; entry++) { //centre weight int count = buckets_[entry] * factor; for (int offset = 1; offset < factor; offset++) { if (entry - offset >= 0) count += buckets_[entry - offset] * (factor - offset); if (entry + offset < entrycount) count += buckets_[entry + offset] * (factor - offset); } result.add(entry + rangemin_, count); } total_count_ = result.total_count_; memcpy(buckets_, result.buckets_, entrycount * sizeof(buckets_[0])); } /********************************************************************** * STATS::cluster * * Cluster the samples into max_cluster clusters. * Each call runs one iteration. The array of clusters must be * max_clusters+1 in size as cluster 0 is used to indicate which samples * have been used. * The return value is the current number of clusters. **********************************************************************/ inT32 STATS::cluster(float lower, // thresholds float upper, float multiple, // distance threshold inT32 max_clusters, // max no to make STATS *clusters) { // array of clusters BOOL8 new_cluster; // added one float *centres; // cluster centres inT32 entry; // bucket index inT32 cluster; // cluster index inT32 best_cluster; // one to assign to inT32 new_centre = 0; // residual mode inT32 new_mode; // pile count of new_centre inT32 count; // pile to place float dist; // from cluster float min_dist; // from best_cluster inT32 cluster_count; // no of clusters if (buckets_ == NULL || max_clusters < 1) return 0; centres = new float[max_clusters + 1]; for (cluster_count = 1; cluster_count <= max_clusters && clusters[cluster_count].buckets_ != NULL && clusters[cluster_count].total_count_ > 0; cluster_count++) { centres[cluster_count] = static_cast<float>(clusters[cluster_count].ile(0.5)); new_centre = clusters[cluster_count].mode(); for (entry = new_centre - 1; centres[cluster_count] - entry < lower && entry >= rangemin_ && pile_count(entry) <= pile_count(entry + 1); entry--) { count = pile_count(entry) - clusters[0].pile_count(entry); if (count > 0) { clusters[cluster_count].add(entry, count); clusters[0].add (entry, count); } } for (entry = new_centre + 1; entry - centres[cluster_count] < lower && entry < rangemax_ && pile_count(entry) <= pile_count(entry - 1); entry++) { count = pile_count(entry) - clusters[0].pile_count(entry); if (count > 0) { clusters[cluster_count].add(entry, count); clusters[0].add(entry, count); } } } cluster_count--; if (cluster_count == 0) { clusters[0].set_range(rangemin_, rangemax_); } do { new_cluster = FALSE; new_mode = 0; for (entry = 0; entry < rangemax_ - rangemin_; entry++) { count = buckets_[entry] - clusters[0].buckets_[entry]; //remaining pile if (count > 0) { //any to handle min_dist = static_cast<float>(MAX_INT32); best_cluster = 0; for (cluster = 1; cluster <= cluster_count; cluster++) { dist = entry + rangemin_ - centres[cluster]; //find distance if (dist < 0) dist = -dist; if (dist < min_dist) { min_dist = dist; //find least best_cluster = cluster; } } if (min_dist > upper //far enough for new && (best_cluster == 0 || entry + rangemin_ > centres[best_cluster] * multiple || entry + rangemin_ < centres[best_cluster] / multiple)) { if (count > new_mode) { new_mode = count; new_centre = entry + rangemin_; } } } } // need new and room if (new_mode > 0 && cluster_count < max_clusters) { cluster_count++; new_cluster = TRUE; if (!clusters[cluster_count].set_range(rangemin_, rangemax_)) { delete [] centres; return 0; } centres[cluster_count] = static_cast<float>(new_centre); clusters[cluster_count].add(new_centre, new_mode); clusters[0].add(new_centre, new_mode); for (entry = new_centre - 1; centres[cluster_count] - entry < lower && entry >= rangemin_ && pile_count (entry) <= pile_count(entry + 1); entry--) { count = pile_count(entry) - clusters[0].pile_count(entry); if (count > 0) { clusters[cluster_count].add(entry, count); clusters[0].add(entry, count); } } for (entry = new_centre + 1; entry - centres[cluster_count] < lower && entry < rangemax_ && pile_count (entry) <= pile_count(entry - 1); entry++) { count = pile_count(entry) - clusters[0].pile_count(entry); if (count > 0) { clusters[cluster_count].add(entry, count); clusters[0].add (entry, count); } } centres[cluster_count] = static_cast<float>(clusters[cluster_count].ile(0.5)); } } while (new_cluster && cluster_count < max_clusters); delete [] centres; return cluster_count; } // Helper tests that the current index is still part of the peak and gathers // the data into the peak, returning false when the peak is ended. // src_buckets[index] - used_buckets[index] is the unused part of the histogram. // prev_count is the histogram count of the previous index on entry and is // updated to the current index on return. // total_count and total_value are accumulating the mean of the peak. static bool GatherPeak(int index, const int* src_buckets, int* used_buckets, int* prev_count, int* total_count, double* total_value) { int pile_count = src_buckets[index] - used_buckets[index]; if (pile_count <= *prev_count && pile_count > 0) { // Accumulate count and index.count product. *total_count += pile_count; *total_value += index * pile_count; // Mark this index as used used_buckets[index] = src_buckets[index]; *prev_count = pile_count; return true; } else { return false; } } // Finds (at most) the top max_modes modes, well actually the whole peak around // each mode, returning them in the given modes vector as a <mean of peak, // total count of peak> pair in order of decreasing total count. // Since the mean is the key and the count the data in the pair, a single call // to sort on the output will re-sort by increasing mean of peak if that is // more useful than decreasing total count. // Returns the actual number of modes found. int STATS::top_n_modes(int max_modes, GenericVector<KDPairInc<float, int> >* modes) const { if (max_modes <= 0) return 0; int src_count = rangemax_ - rangemin_; // Used copies the counts in buckets_ as they get used. STATS used(rangemin_, rangemax_); modes->truncate(0); // Total count of the smallest peak found so far. int least_count = 1; // Mode that is used as a seed for each peak int max_count = 0; do { // Find an unused mode. max_count = 0; int max_index = 0; for (int src_index = 0; src_index < src_count; src_index++) { int pile_count = buckets_[src_index] - used.buckets_[src_index]; if (pile_count > max_count) { max_count = pile_count; max_index = src_index; } } if (max_count > 0) { // Copy the bucket count to used so it doesn't get found again. used.buckets_[max_index] = max_count; // Get the entire peak. double total_value = max_index * max_count; int total_count = max_count; int prev_pile = max_count; for (int offset = 1; max_index + offset < src_count; ++offset) { if (!GatherPeak(max_index + offset, buckets_, used.buckets_, &prev_pile, &total_count, &total_value)) break; } prev_pile = buckets_[max_index]; for (int offset = 1; max_index - offset >= 0; ++offset) { if (!GatherPeak(max_index - offset, buckets_, used.buckets_, &prev_pile, &total_count, &total_value)) break; } if (total_count > least_count || modes->size() < max_modes) { // We definitely want this mode, so if we have enough discard the least. if (modes->size() == max_modes) modes->truncate(max_modes - 1); int target_index = 0; // Linear search for the target insertion point. while (target_index < modes->size() && (*modes)[target_index].data >= total_count) ++target_index; float peak_mean = static_cast<float>(total_value / total_count + rangemin_); modes->insert(KDPairInc<float, int>(peak_mean, total_count), target_index); least_count = modes->back().data; } } } while (max_count > 0); return modes->size(); } /********************************************************************** * STATS::print * * Prints a summary and table of the histogram. **********************************************************************/ void STATS::print() const { if (buckets_ == NULL) { return; } inT32 min = min_bucket() - rangemin_; inT32 max = max_bucket() - rangemin_; int num_printed = 0; for (int index = min; index <= max; index++) { if (buckets_[index] != 0) { tprintf("%4d:%-3d ", rangemin_ + index, buckets_[index]); if (++num_printed % 8 == 0) tprintf ("\n"); } } tprintf ("\n"); print_summary(); } /********************************************************************** * STATS::print_summary * * Print a summary of the stats. **********************************************************************/ void STATS::print_summary() const { if (buckets_ == NULL) { return; } inT32 min = min_bucket(); inT32 max = max_bucket(); tprintf("Total count=%d\n", total_count_); tprintf("Min=%.2f Really=%d\n", ile(0.0), min); tprintf("Lower quartile=%.2f\n", ile(0.25)); tprintf("Median=%.2f, ile(0.5)=%.2f\n", median(), ile(0.5)); tprintf("Upper quartile=%.2f\n", ile(0.75)); tprintf("Max=%.2f Really=%d\n", ile(1.0), max); tprintf("Range=%d\n", max + 1 - min); tprintf("Mean= %.2f\n", mean()); tprintf("SD= %.2f\n", sd()); } /********************************************************************** * STATS::plot * * Draw a histogram of the stats table. **********************************************************************/ #ifndef GRAPHICS_DISABLED void STATS::plot(ScrollView* window, // to draw in float xorigin, // bottom left float yorigin, float xscale, // one x unit float yscale, // one y unit ScrollView::Color colour) const { // colour to draw in if (buckets_ == NULL) { return; } window->Pen(colour); for (int index = 0; index < rangemax_ - rangemin_; index++) { window->Rectangle( xorigin + xscale * index, yorigin, xorigin + xscale * (index + 1), yorigin + yscale * buckets_[index]); } } #endif /********************************************************************** * STATS::plotline * * Draw a histogram of the stats table. (Line only) **********************************************************************/ #ifndef GRAPHICS_DISABLED void STATS::plotline(ScrollView* window, // to draw in float xorigin, // bottom left float yorigin, float xscale, // one x unit float yscale, // one y unit ScrollView::Color colour) const { // colour to draw in if (buckets_ == NULL) { return; } window->Pen(colour); window->SetCursor(xorigin, yorigin + yscale * buckets_[0]); for (int index = 0; index < rangemax_ - rangemin_; index++) { window->DrawTo(xorigin + xscale * index, yorigin + yscale * buckets_[index]); } } #endif /********************************************************************** * choose_nth_item * * Returns the index of what would b the nth item in the array * if the members were sorted, without actually sorting. **********************************************************************/ inT32 choose_nth_item(inT32 index, float *array, inT32 count) { inT32 next_sample; // next one to do inT32 next_lesser; // space for new inT32 prev_greater; // last one saved inT32 equal_count; // no of equal ones float pivot; // proposed median float sample; // current sample if (count <= 1) return 0; if (count == 2) { if (array[0] < array[1]) { return index >= 1 ? 1 : 0; } else { return index >= 1 ? 0 : 1; } } else { if (index < 0) index = 0; // ensure legal else if (index >= count) index = count - 1; equal_count = (inT32) (rand() % count); pivot = array[equal_count]; // fill gap array[equal_count] = array[0]; next_lesser = 0; prev_greater = count; equal_count = 1; for (next_sample = 1; next_sample < prev_greater;) { sample = array[next_sample]; if (sample < pivot) { // shuffle array[next_lesser++] = sample; next_sample++; } else if (sample > pivot) { prev_greater--; // juggle array[next_sample] = array[prev_greater]; array[prev_greater] = sample; } else { equal_count++; next_sample++; } } for (next_sample = next_lesser; next_sample < prev_greater;) array[next_sample++] = pivot; if (index < next_lesser) return choose_nth_item (index, array, next_lesser); else if (index < prev_greater) return next_lesser; // in equal bracket else return choose_nth_item (index - prev_greater, array + prev_greater, count - prev_greater) + prev_greater; } } /********************************************************************** * choose_nth_item * * Returns the index of what would be the nth item in the array * if the members were sorted, without actually sorting. **********************************************************************/ inT32 choose_nth_item(inT32 index, void *array, inT32 count, size_t size, int (*compar)(const void*, const void*)) { int result; // of compar inT32 next_sample; // next one to do inT32 next_lesser; // space for new inT32 prev_greater; // last one saved inT32 equal_count; // no of equal ones inT32 pivot; // proposed median if (count <= 1) return 0; if (count == 2) { if (compar (array, (char *) array + size) < 0) { return index >= 1 ? 1 : 0; } else { return index >= 1 ? 0 : 1; } } if (index < 0) index = 0; // ensure legal else if (index >= count) index = count - 1; pivot = (inT32) (rand () % count); swap_entries (array, size, pivot, 0); next_lesser = 0; prev_greater = count; equal_count = 1; for (next_sample = 1; next_sample < prev_greater;) { result = compar ((char *) array + size * next_sample, (char *) array + size * next_lesser); if (result < 0) { swap_entries (array, size, next_lesser++, next_sample++); // shuffle } else if (result > 0) { prev_greater--; swap_entries(array, size, prev_greater, next_sample); } else { equal_count++; next_sample++; } } if (index < next_lesser) return choose_nth_item (index, array, next_lesser, size, compar); else if (index < prev_greater) return next_lesser; // in equal bracket else return choose_nth_item (index - prev_greater, (char *) array + size * prev_greater, count - prev_greater, size, compar) + prev_greater; } /********************************************************************** * swap_entries * * Swap 2 entries of arbitrary size in-place in a table. **********************************************************************/ void swap_entries(void *array, // array of entries size_t size, // size of entry inT32 index1, // entries to swap inT32 index2) { char tmp; char *ptr1; // to entries char *ptr2; size_t count; // of bytes ptr1 = reinterpret_cast<char*>(array) + index1 * size; ptr2 = reinterpret_cast<char*>(array) + index2 * size; for (count = 0; count < size; count++) { tmp = *ptr1; *ptr1++ = *ptr2; *ptr2++ = tmp; // tedious! } }
1080228-arabicocr11
ccstruct/statistc.cpp
C++
asf20
27,428
/********************************************************************** * File: rejctmap.h (Formerly rejmap.h) * Description: REJ and REJMAP class functions. * Author: Phil Cheatle * Created: Thu Jun 9 13:46:38 BST 1994 * * (C) Copyright 1994, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * This module may look unneccessarily verbose, but here's the philosophy... ALL processing of the reject map is done in this module. There are lots of separate calls to set reject/accept flags. These have DELIBERATELY been kept distinct so that this module can decide what to do. Basically, there is a flag for each sort of rejection or acceptance. This provides a history of what has happened to EACH character. Determining whether a character is CURRENTLY rejected depends on implicit understanding of the SEQUENCE of possible calls. The flags are defined and grouped in the REJ_FLAGS enum. These groupings are used in determining a characters CURRENT rejection status. Basically, a character is ACCEPTED if none of the permanent rej flags are set AND ( the character has never been rejected OR an accept flag is set which is LATER than the latest reject flag ) IT IS FUNDAMENTAL THAT ANYONE HACKING THIS CODE UNDERSTANDS THE SIGNIFICANCE OF THIS IMPLIED TEMPORAL ORDERING OF THE FLAGS!!!! **********************************************************************/ #ifndef REJCTMAP_H #define REJCTMAP_H #ifdef __UNIX__ #include <assert.h> #endif #include "memry.h" #include "bits16.h" #include "params.h" enum REJ_FLAGS { /* Reject modes which are NEVER overridden */ R_TESS_FAILURE, // PERM Tess didnt classify R_SMALL_XHT, // PERM Xht too small R_EDGE_CHAR, // PERM Too close to edge of image R_1IL_CONFLICT, // PERM 1Il confusion R_POSTNN_1IL, // PERM 1Il unrejected by NN R_REJ_CBLOB, // PERM Odd blob R_MM_REJECT, // PERM Matrix match rejection (m's) R_BAD_REPETITION, // TEMP Repeated char which doesn't match trend /* Initial reject modes (pre NN_ACCEPT) */ R_POOR_MATCH, // TEMP Ray's original heuristic (Not used) R_NOT_TESS_ACCEPTED, // TEMP Tess didnt accept WERD R_CONTAINS_BLANKS, // TEMP Tess failed on other chs in WERD R_BAD_PERMUTER, // POTENTIAL Bad permuter for WERD /* Reject modes generated after NN_ACCEPT but before MM_ACCEPT */ R_HYPHEN, // TEMP Post NN dodgy hyphen or full stop R_DUBIOUS, // TEMP Post NN dodgy chars R_NO_ALPHANUMS, // TEMP No alphanumerics in word after NN R_MOSTLY_REJ, // TEMP Most of word rejected so rej the rest R_XHT_FIXUP, // TEMP Xht tests unsure /* Reject modes generated after MM_ACCEPT but before QUALITY_ACCEPT */ R_BAD_QUALITY, // TEMP Quality metrics bad for WERD /* Reject modes generated after QUALITY_ACCEPT but before MINIMAL_REJ accep*/ R_DOC_REJ, // TEMP Document rejection R_BLOCK_REJ, // TEMP Block rejection R_ROW_REJ, // TEMP Row rejection R_UNLV_REJ, // TEMP ~ turned to - or ^ turned to space /* Accept modes which occur inbetween the above rejection groups */ R_NN_ACCEPT, //NN acceptance R_HYPHEN_ACCEPT, //Hyphen acceptance R_MM_ACCEPT, //Matrix match acceptance R_QUALITY_ACCEPT, //Accept word in good quality doc R_MINIMAL_REJ_ACCEPT //Accept EVERYTHING except tess failures }; /* REJECT MAP VALUES */ #define MAP_ACCEPT '1' #define MAP_REJECT_PERM '0' #define MAP_REJECT_TEMP '2' #define MAP_REJECT_POTENTIAL '3' class REJ { BITS16 flags1; BITS16 flags2; void set_flag(REJ_FLAGS rej_flag) { if (rej_flag < 16) flags1.turn_on_bit (rej_flag); else flags2.turn_on_bit (rej_flag - 16); } BOOL8 rej_before_nn_accept(); BOOL8 rej_between_nn_and_mm(); BOOL8 rej_between_mm_and_quality_accept(); BOOL8 rej_between_quality_and_minimal_rej_accept(); BOOL8 rej_before_mm_accept(); BOOL8 rej_before_quality_accept(); public: REJ() { //constructor } REJ( //classwise copy const REJ &source) { flags1 = source.flags1; flags2 = source.flags2; } REJ & operator= ( //assign REJ const REJ & source) { //from this flags1 = source.flags1; flags2 = source.flags2; return *this; } BOOL8 flag(REJ_FLAGS rej_flag) { if (rej_flag < 16) return flags1.bit (rej_flag); else return flags2.bit (rej_flag - 16); } char display_char() { if (perm_rejected ()) return MAP_REJECT_PERM; else if (accept_if_good_quality ()) return MAP_REJECT_POTENTIAL; else if (rejected ()) return MAP_REJECT_TEMP; else return MAP_ACCEPT; } BOOL8 perm_rejected(); //Is char perm reject? BOOL8 rejected(); //Is char rejected? BOOL8 accepted() { //Is char accepted? return !rejected (); } //potential rej? BOOL8 accept_if_good_quality(); BOOL8 recoverable() { return (rejected () && !perm_rejected ()); } void setrej_tess_failure(); //Tess generated blank void setrej_small_xht(); //Small xht char/wd void setrej_edge_char(); //Close to image edge void setrej_1Il_conflict(); //Initial reject map void setrej_postNN_1Il(); //1Il after NN void setrej_rej_cblob(); //Insert duff blob void setrej_mm_reject(); //Matrix matcher //Odd repeated char void setrej_bad_repetition(); void setrej_poor_match(); //Failed Rays heuristic //TEMP reject_word void setrej_not_tess_accepted(); //TEMP reject_word void setrej_contains_blanks(); void setrej_bad_permuter(); //POTENTIAL reject_word void setrej_hyphen(); //PostNN dubious hyph or . void setrej_dubious(); //PostNN dubious limit void setrej_no_alphanums(); //TEMP reject_word void setrej_mostly_rej(); //TEMP reject_word void setrej_xht_fixup(); //xht fixup void setrej_bad_quality(); //TEMP reject_word void setrej_doc_rej(); //TEMP reject_word void setrej_block_rej(); //TEMP reject_word void setrej_row_rej(); //TEMP reject_word void setrej_unlv_rej(); //TEMP reject_word void setrej_nn_accept(); //NN Flipped a char void setrej_hyphen_accept(); //Good aspect ratio void setrej_mm_accept(); //Matrix matcher //Quality flip a char void setrej_quality_accept(); //Accept all except blank void setrej_minimal_rej_accept(); void full_print(FILE *fp); }; class REJMAP { REJ *ptr; //ptr to the chars inT16 len; //Number of chars public: REJMAP() { //constructor ptr = NULL; len = 0; } REJMAP( //classwise copy const REJMAP &rejmap); REJMAP & operator= ( //assign REJMAP const REJMAP & source); //from this ~REJMAP () { //destructor if (ptr != NULL) free_struct (ptr, len * sizeof (REJ), "REJ"); } void initialise( //Redefine map inT16 length); REJ & operator[]( //access function inT16 index) const //map index { ASSERT_HOST (index < len); return ptr[index]; //no bounds checks } inT32 length() const { //map length return len; } inT16 accept_count(); //How many accepted? inT16 reject_count() { //How many rejects? return len - accept_count (); } void remove_pos( //Cut out an element inT16 pos); //element to remove void print(FILE *fp); void full_print(FILE *fp); BOOL8 recoverable_rejects(); //Any non perm rejs? BOOL8 quality_recoverable_rejects(); //Any potential rejs? void rej_word_small_xht(); //Reject whole word //Reject whole word void rej_word_tess_failure(); void rej_word_not_tess_accepted(); //Reject whole word //Reject whole word void rej_word_contains_blanks(); //Reject whole word void rej_word_bad_permuter(); void rej_word_xht_fixup(); //Reject whole word //Reject whole word void rej_word_no_alphanums(); void rej_word_mostly_rej(); //Reject whole word void rej_word_bad_quality(); //Reject whole word void rej_word_doc_rej(); //Reject whole word void rej_word_block_rej(); //Reject whole word void rej_word_row_rej(); //Reject whole word }; #endif
1080228-arabicocr11
ccstruct/rejctmap.h
C++
asf20
9,658
/********************************************************************** * File: ratngs.cpp (Formerly ratings.c) * Description: Code to manipulate the BLOB_CHOICE and WERD_CHOICE classes. * Author: Ray Smith * Created: Thu Apr 23 13:23:29 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #include "ratngs.h" #include "blobs.h" #include "callcpp.h" #include "genericvector.h" #include "matrix.h" #include "normalis.h" // kBlnBaselineOffset. #include "unicharset.h" using tesseract::ScriptPos; ELISTIZE(BLOB_CHOICE); ELISTIZE(WERD_CHOICE); const float WERD_CHOICE::kBadRating = 100000.0; // Min offset in baseline-normalized coords to make a character a subscript. const int kMinSubscriptOffset = 20; // Min offset in baseline-normalized coords to make a character a superscript. const int kMinSuperscriptOffset = 20; // Max y of bottom of a drop-cap blob. const int kMaxDropCapBottom = -128; // Max fraction of x-height to use as denominator in measuring x-height overlap. const double kMaxOverlapDenominator = 0.125; // Min fraction of x-height range that should be in agreement for matching // x-heights. const double kMinXHeightMatch = 0.5; // Max tolerance on baseline position as a fraction of x-height for matching // baselines. const double kMaxBaselineDrift = 0.0625; static const char kPermuterTypeNoPerm[] = "None"; static const char kPermuterTypePuncPerm[] = "Punctuation"; static const char kPermuterTypeTopPerm[] = "Top Choice"; static const char kPermuterTypeLowerPerm[] = "Top Lower Case"; static const char kPermuterTypeUpperPerm[] = "Top Upper Case"; static const char kPermuterTypeNgramPerm[] = "Ngram"; static const char kPermuterTypeNumberPerm[] = "Number"; static const char kPermuterTypeUserPatPerm[] = "User Pattern"; static const char kPermuterTypeSysDawgPerm[] = "System Dictionary"; static const char kPermuterTypeDocDawgPerm[] = "Document Dictionary"; static const char kPermuterTypeUserDawgPerm[] = "User Dictionary"; static const char kPermuterTypeFreqDawgPerm[] = "Frequent Words Dictionary"; static const char kPermuterTypeCompoundPerm[] = "Compound"; static const char * const kPermuterTypeNames[] = { kPermuterTypeNoPerm, // 0 kPermuterTypePuncPerm, // 1 kPermuterTypeTopPerm, // 2 kPermuterTypeLowerPerm, // 3 kPermuterTypeUpperPerm, // 4 kPermuterTypeNgramPerm, // 5 kPermuterTypeNumberPerm, // 6 kPermuterTypeUserPatPerm, // 7 kPermuterTypeSysDawgPerm, // 8 kPermuterTypeDocDawgPerm, // 9 kPermuterTypeUserDawgPerm, // 10 kPermuterTypeFreqDawgPerm, // 11 kPermuterTypeCompoundPerm // 12 }; /** * BLOB_CHOICE::BLOB_CHOICE * * Constructor to build a BLOB_CHOICE from a char, rating and certainty. */ BLOB_CHOICE::BLOB_CHOICE(UNICHAR_ID src_unichar_id, // character id float src_rating, // rating float src_cert, // certainty inT16 src_fontinfo_id, // font inT16 src_fontinfo_id2, // 2nd choice font int src_script_id, // script float min_xheight, // min xheight allowed float max_xheight, // max xheight by this char float yshift, // yshift out of position BlobChoiceClassifier c) { // adapted match or other unichar_id_ = src_unichar_id; rating_ = src_rating; certainty_ = src_cert; fontinfo_id_ = src_fontinfo_id; fontinfo_id2_ = src_fontinfo_id2; script_id_ = src_script_id; min_xheight_ = min_xheight; max_xheight_ = max_xheight; yshift_ = yshift; classifier_ = c; } /** * BLOB_CHOICE::BLOB_CHOICE * * Constructor to build a BLOB_CHOICE from another BLOB_CHOICE. */ BLOB_CHOICE::BLOB_CHOICE(const BLOB_CHOICE &other) { unichar_id_ = other.unichar_id(); rating_ = other.rating(); certainty_ = other.certainty(); fontinfo_id_ = other.fontinfo_id(); fontinfo_id2_ = other.fontinfo_id2(); script_id_ = other.script_id(); matrix_cell_ = other.matrix_cell_; min_xheight_ = other.min_xheight_; max_xheight_ = other.max_xheight_; yshift_ = other.yshift(); classifier_ = other.classifier_; } // Returns true if *this and other agree on the baseline and x-height // to within some tolerance based on a given estimate of the x-height. bool BLOB_CHOICE::PosAndSizeAgree(const BLOB_CHOICE& other, float x_height, bool debug) const { double baseline_diff = fabs(yshift() - other.yshift()); if (baseline_diff > kMaxBaselineDrift * x_height) { if (debug) { tprintf("Baseline diff %g for %d v %d\n", baseline_diff, unichar_id_, other.unichar_id_); } return false; } double this_range = max_xheight() - min_xheight(); double other_range = other.max_xheight() - other.min_xheight(); double denominator = ClipToRange(MIN(this_range, other_range), 1.0, kMaxOverlapDenominator * x_height); double overlap = MIN(max_xheight(), other.max_xheight()) - MAX(min_xheight(), other.min_xheight()); overlap /= denominator; if (debug) { tprintf("PosAndSize for %d v %d: bl diff = %g, ranges %g, %g / %g ->%g\n", unichar_id_, other.unichar_id_, baseline_diff, this_range, other_range, denominator, overlap); } return overlap >= kMinXHeightMatch; } // Helper to find the BLOB_CHOICE in the bc_list that matches the given // unichar_id, or NULL if there is no match. BLOB_CHOICE* FindMatchingChoice(UNICHAR_ID char_id, BLOB_CHOICE_LIST* bc_list) { // Find the corresponding best BLOB_CHOICE. BLOB_CHOICE_IT choice_it(bc_list); for (choice_it.mark_cycle_pt(); !choice_it.cycled_list(); choice_it.forward()) { BLOB_CHOICE* choice = choice_it.data(); if (choice->unichar_id() == char_id) { return choice; } } return NULL; } const char *WERD_CHOICE::permuter_name(uinT8 permuter) { return kPermuterTypeNames[permuter]; } namespace tesseract { const char *ScriptPosToString(enum ScriptPos script_pos) { switch (script_pos) { case SP_NORMAL: return "NORM"; case SP_SUBSCRIPT: return "SUB"; case SP_SUPERSCRIPT: return "SUPER"; case SP_DROPCAP: return "DROPC"; } return "SP_UNKNOWN"; } } // namespace tesseract. /** * WERD_CHOICE::WERD_CHOICE * * Constructor to build a WERD_CHOICE from the given string. * The function assumes that src_string is not NULL. */ WERD_CHOICE::WERD_CHOICE(const char *src_string, const UNICHARSET &unicharset) : unicharset_(&unicharset){ GenericVector<UNICHAR_ID> encoding; GenericVector<char> lengths; if (unicharset.encode_string(src_string, true, &encoding, &lengths, NULL)) { lengths.push_back('\0'); STRING src_lengths = &lengths[0]; this->init(src_string, src_lengths.string(), 0.0, 0.0, NO_PERM); } else { // There must have been an invalid unichar in the string. this->init(8); this->make_bad(); } } /** * WERD_CHOICE::init * * Helper function to build a WERD_CHOICE from the given string, * fragment lengths, rating, certainty and permuter. * * The function assumes that src_string is not NULL. * src_lengths argument could be NULL, in which case the unichars * in src_string are assumed to all be of length 1. */ void WERD_CHOICE::init(const char *src_string, const char *src_lengths, float src_rating, float src_certainty, uinT8 src_permuter) { int src_string_len = strlen(src_string); if (src_string_len == 0) { this->init(8); } else { this->init(src_lengths ? strlen(src_lengths): src_string_len); length_ = reserved_; int offset = 0; for (int i = 0; i < length_; ++i) { int unichar_length = src_lengths ? src_lengths[i] : 1; unichar_ids_[i] = unicharset_->unichar_to_id(src_string+offset, unichar_length); state_[i] = 1; certainties_[i] = src_certainty; offset += unichar_length; } } adjust_factor_ = 1.0f; rating_ = src_rating; certainty_ = src_certainty; permuter_ = src_permuter; dangerous_ambig_found_ = false; } /** * WERD_CHOICE::~WERD_CHOICE */ WERD_CHOICE::~WERD_CHOICE() { delete[] unichar_ids_; delete[] script_pos_; delete[] state_; delete[] certainties_; } const char *WERD_CHOICE::permuter_name() const { return kPermuterTypeNames[permuter_]; } // Returns the BLOB_CHOICE_LIST corresponding to the given index in the word, // taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. BLOB_CHOICE_LIST* WERD_CHOICE::blob_choices(int index, MATRIX* ratings) const { MATRIX_COORD coord = MatrixCoord(index); BLOB_CHOICE_LIST* result = ratings->get(coord.col, coord.row); if (result == NULL) { result = new BLOB_CHOICE_LIST; ratings->put(coord.col, coord.row, result); } return result; } // Returns the MATRIX_COORD corresponding to the location in the ratings // MATRIX for the given index into the word. MATRIX_COORD WERD_CHOICE::MatrixCoord(int index) const { int col = 0; for (int i = 0; i < index; ++i) col += state_[i]; int row = col + state_[index] - 1; return MATRIX_COORD(col, row); } // Sets the entries for the given index from the BLOB_CHOICE, assuming // unit fragment lengths, but setting the state for this index to blob_count. void WERD_CHOICE::set_blob_choice(int index, int blob_count, const BLOB_CHOICE* blob_choice) { unichar_ids_[index] = blob_choice->unichar_id(); script_pos_[index] = tesseract::SP_NORMAL; state_[index] = blob_count; certainties_[index] = blob_choice->certainty(); } /** * contains_unichar_id * * Returns true if unichar_ids_ contain the given unichar_id, false otherwise. */ bool WERD_CHOICE::contains_unichar_id(UNICHAR_ID unichar_id) const { for (int i = 0; i < length_; ++i) { if (unichar_ids_[i] == unichar_id) { return true; } } return false; } /** * remove_unichar_ids * * Removes num unichar ids starting from index start from unichar_ids_ * and updates length_ and fragment_lengths_ to reflect this change. * Note: this function does not modify rating_ and certainty_. */ void WERD_CHOICE::remove_unichar_ids(int start, int num) { ASSERT_HOST(start >= 0 && start + num <= length_); // Accumulate the states to account for the merged blobs. for (int i = 0; i < num; ++i) { if (start > 0) state_[start - 1] += state_[start + i]; else if (start + num < length_) state_[start + num] += state_[start + i]; } for (int i = start; i + num < length_; ++i) { unichar_ids_[i] = unichar_ids_[i + num]; script_pos_[i] = script_pos_[i + num]; state_[i] = state_[i + num]; certainties_[i] = certainties_[i + num]; } length_ -= num; } /** * reverse_and_mirror_unichar_ids * * Reverses and mirrors unichars in unichar_ids. */ void WERD_CHOICE::reverse_and_mirror_unichar_ids() { for (int i = 0; i < length_ / 2; ++i) { UNICHAR_ID tmp_id = unichar_ids_[i]; unichar_ids_[i] = unicharset_->get_mirror(unichar_ids_[length_-1-i]); unichar_ids_[length_-1-i] = unicharset_->get_mirror(tmp_id); } if (length_ % 2 != 0) { unichar_ids_[length_/2] = unicharset_->get_mirror(unichar_ids_[length_/2]); } } /** * punct_stripped * * Returns the half-open interval of unichar_id indices [start, end) which * enclose the core portion of this word -- the part after stripping * punctuation from the left and right. */ void WERD_CHOICE::punct_stripped(int *start, int *end) const { *start = 0; *end = length() - 1; while (*start < length() && unicharset()->get_ispunctuation(unichar_id(*start))) { (*start)++; } while (*end > -1 && unicharset()->get_ispunctuation(unichar_id(*end))) { (*end)--; } (*end)++; } void WERD_CHOICE::GetNonSuperscriptSpan(int *pstart, int *pend) const { int end = length(); while (end > 0 && unicharset_->get_isdigit(unichar_ids_[end - 1]) && BlobPosition(end - 1) == tesseract::SP_SUPERSCRIPT) { end--; } int start = 0; while (start < end && unicharset_->get_isdigit(unichar_ids_[start]) && BlobPosition(start) == tesseract::SP_SUPERSCRIPT) { start++; } *pstart = start; *pend = end; } WERD_CHOICE WERD_CHOICE::shallow_copy(int start, int end) const { ASSERT_HOST(start >= 0 && start <= length_); ASSERT_HOST(end >= 0 && end <= length_); if (end < start) { end = start; } WERD_CHOICE retval(unicharset_, end - start); for (int i = start; i < end; i++) { retval.append_unichar_id_space_allocated( unichar_ids_[i], state_[i], 0.0f, certainties_[i]); } return retval; } /** * has_rtl_unichar_id * * Returns true if unichar_ids contain at least one "strongly" RTL unichar. */ bool WERD_CHOICE::has_rtl_unichar_id() const { int i; for (i = 0; i < length_; ++i) { UNICHARSET::Direction dir = unicharset_->get_direction(unichar_ids_[i]); if (dir == UNICHARSET::U_RIGHT_TO_LEFT || dir == UNICHARSET::U_RIGHT_TO_LEFT_ARABIC) { return true; } } return false; } /** * string_and_lengths * * Populates the given word_str with unichars from unichar_ids and * and word_lengths_str with the corresponding unichar lengths. */ void WERD_CHOICE::string_and_lengths(STRING *word_str, STRING *word_lengths_str) const { *word_str = ""; if (word_lengths_str != NULL) *word_lengths_str = ""; for (int i = 0; i < length_; ++i) { const char *ch = unicharset_->id_to_unichar_ext(unichar_ids_[i]); *word_str += ch; if (word_lengths_str != NULL) { *word_lengths_str += strlen(ch); } } } /** * append_unichar_id * * Make sure there is enough space in the word for the new unichar id * and call append_unichar_id_space_allocated(). */ void WERD_CHOICE::append_unichar_id( UNICHAR_ID unichar_id, int blob_count, float rating, float certainty) { if (length_ == reserved_) { this->double_the_size(); } this->append_unichar_id_space_allocated(unichar_id, blob_count, rating, certainty); } /** * WERD_CHOICE::operator+= * * Cat a second word rating on the end of this current one. * The ratings are added and the confidence is the min. * If the permuters are NOT the same the permuter is set to COMPOUND_PERM */ WERD_CHOICE & WERD_CHOICE::operator+= (const WERD_CHOICE & second) { ASSERT_HOST(unicharset_ == second.unicharset_); while (reserved_ < length_ + second.length()) { this->double_the_size(); } const UNICHAR_ID *other_unichar_ids = second.unichar_ids(); for (int i = 0; i < second.length(); ++i) { unichar_ids_[length_ + i] = other_unichar_ids[i]; state_[length_ + i] = second.state_[i]; certainties_[length_ + i] = second.certainties_[i]; script_pos_[length_ + i] = second.BlobPosition(i); } length_ += second.length(); if (second.adjust_factor_ > adjust_factor_) adjust_factor_ = second.adjust_factor_; rating_ += second.rating(); // add ratings if (second.certainty() < certainty_) // take min certainty_ = second.certainty(); if (second.dangerous_ambig_found_) dangerous_ambig_found_ = true; if (permuter_ == NO_PERM) { permuter_ = second.permuter(); } else if (second.permuter() != NO_PERM && second.permuter() != permuter_) { permuter_ = COMPOUND_PERM; } return *this; } /** * WERD_CHOICE::operator= * * Allocate enough memory to hold a copy of source and copy over * all the information from source to this WERD_CHOICE. */ WERD_CHOICE& WERD_CHOICE::operator=(const WERD_CHOICE& source) { while (reserved_ < source.length()) { this->double_the_size(); } unicharset_ = source.unicharset_; const UNICHAR_ID *other_unichar_ids = source.unichar_ids(); for (int i = 0; i < source.length(); ++i) { unichar_ids_[i] = other_unichar_ids[i]; state_[i] = source.state_[i]; certainties_[i] = source.certainties_[i]; script_pos_[i] = source.BlobPosition(i); } length_ = source.length(); adjust_factor_ = source.adjust_factor_; rating_ = source.rating(); certainty_ = source.certainty(); min_x_height_ = source.min_x_height(); max_x_height_ = source.max_x_height(); permuter_ = source.permuter(); dangerous_ambig_found_ = source.dangerous_ambig_found_; return *this; } // Sets up the script_pos_ member using the blobs_list to get the bln // bounding boxes, *this to get the unichars, and this->unicharset // to get the target positions. If small_caps is true, sub/super are not // considered, but dropcaps are. // NOTE: blobs_list should be the chopped_word blobs. (Fully segemented.) void WERD_CHOICE::SetScriptPositions(bool small_caps, TWERD* word) { // Since WERD_CHOICE isn't supposed to depend on a Tesseract, // we don't have easy access to the flags Tesseract stores. Therefore, debug // for this module is hard compiled in. int debug = 0; // Initialize to normal. for (int i = 0; i < length_; ++i) script_pos_[i] = tesseract::SP_NORMAL; if (word->blobs.empty() || word->NumBlobs() != TotalOfStates()) { return; } int position_counts[4]; for (int i = 0; i < 4; i++) { position_counts[i] = 0; } int chunk_index = 0; for (int blob_index = 0; blob_index < length_; ++blob_index, ++chunk_index) { TBLOB* tblob = word->blobs[chunk_index]; int uni_id = unichar_id(blob_index); TBOX blob_box = tblob->bounding_box(); if (state_ != NULL) { for (int i = 1; i < state_[blob_index]; ++i) { ++chunk_index; tblob = word->blobs[chunk_index]; blob_box += tblob->bounding_box(); } } script_pos_[blob_index] = ScriptPositionOf(false, *unicharset_, blob_box, uni_id); if (small_caps && script_pos_[blob_index] != tesseract::SP_DROPCAP) { script_pos_[blob_index] = tesseract::SP_NORMAL; } position_counts[script_pos_[blob_index]]++; } // If almost everything looks like a superscript or subscript, // we most likely just got the baseline wrong. if (position_counts[tesseract::SP_SUBSCRIPT] > 0.75 * length_ || position_counts[tesseract::SP_SUPERSCRIPT] > 0.75 * length_) { if (debug >= 2) { tprintf("Most characters of %s are subscript or superscript.\n" "That seems wrong, so I'll assume we got the baseline wrong\n", unichar_string().string()); } for (int i = 0; i < length_; i++) { ScriptPos sp = script_pos_[i]; if (sp == tesseract::SP_SUBSCRIPT || sp == tesseract::SP_SUPERSCRIPT) { position_counts[sp]--; position_counts[tesseract::SP_NORMAL]++; script_pos_[i] = tesseract::SP_NORMAL; } } } if ((debug >= 1 && position_counts[tesseract::SP_NORMAL] < length_) || debug >= 2) { tprintf("SetScriptPosition on %s\n", unichar_string().string()); int chunk_index = 0; for (int blob_index = 0; blob_index < length_; ++blob_index) { if (debug >= 2 || script_pos_[blob_index] != tesseract::SP_NORMAL) { TBLOB* tblob = word->blobs[chunk_index]; ScriptPositionOf(true, *unicharset_, tblob->bounding_box(), unichar_id(blob_index)); } chunk_index += state_ != NULL ? state_[blob_index] : 1; } } } // Sets the script_pos_ member from some source positions with a given length. void WERD_CHOICE::SetScriptPositions(const tesseract::ScriptPos* positions, int length) { ASSERT_HOST(length == length_); if (positions != script_pos_) { delete [] script_pos_; script_pos_ = new ScriptPos[length]; memcpy(script_pos_, positions, sizeof(positions[0]) * length); } } // Sets all the script_pos_ positions to the given position. void WERD_CHOICE::SetAllScriptPositions(tesseract::ScriptPos position) { for (int i = 0; i < length_; ++i) script_pos_[i] = position; } /* static */ ScriptPos WERD_CHOICE::ScriptPositionOf(bool print_debug, const UNICHARSET& unicharset, const TBOX& blob_box, UNICHAR_ID unichar_id) { ScriptPos retval = tesseract::SP_NORMAL; int top = blob_box.top(); int bottom = blob_box.bottom(); int min_bottom, max_bottom, min_top, max_top; unicharset.get_top_bottom(unichar_id, &min_bottom, &max_bottom, &min_top, &max_top); int sub_thresh_top = min_top - kMinSubscriptOffset; int sub_thresh_bot = kBlnBaselineOffset - kMinSubscriptOffset; int sup_thresh_bot = max_bottom + kMinSuperscriptOffset; if (bottom <= kMaxDropCapBottom) { retval = tesseract::SP_DROPCAP; } else if (top < sub_thresh_top && bottom < sub_thresh_bot) { retval = tesseract::SP_SUBSCRIPT; } else if (bottom > sup_thresh_bot) { retval = tesseract::SP_SUPERSCRIPT; } if (print_debug) { const char *pos = ScriptPosToString(retval); tprintf("%s Character %s[bot:%d top: %d] " "bot_range[%d,%d] top_range[%d, %d] " "sub_thresh[bot:%d top:%d] sup_thresh_bot %d\n", pos, unicharset.id_to_unichar(unichar_id), bottom, top, min_bottom, max_bottom, min_top, max_top, sub_thresh_bot, sub_thresh_top, sup_thresh_bot); } return retval; } // Returns the script-id (eg Han) of the dominant script in the word. int WERD_CHOICE::GetTopScriptID() const { int max_script = unicharset_->get_script_table_size(); int *sid = new int[max_script]; int x; for (x = 0; x < max_script; x++) sid[x] = 0; for (x = 0; x < length_; ++x) { int script_id = unicharset_->get_script(unichar_id(x)); sid[script_id]++; } if (unicharset_->han_sid() != unicharset_->null_sid()) { // Add the Hiragana & Katakana counts to Han and zero them out. if (unicharset_->hiragana_sid() != unicharset_->null_sid()) { sid[unicharset_->han_sid()] += sid[unicharset_->hiragana_sid()]; sid[unicharset_->hiragana_sid()] = 0; } if (unicharset_->katakana_sid() != unicharset_->null_sid()) { sid[unicharset_->han_sid()] += sid[unicharset_->katakana_sid()]; sid[unicharset_->katakana_sid()] = 0; } } // Note that high script ID overrides lower one on a tie, thus biasing // towards non-Common script (if sorted that way in unicharset file). int max_sid = 0; for (x = 1; x < max_script; x++) if (sid[x] >= sid[max_sid]) max_sid = x; if (sid[max_sid] < length_ / 2) max_sid = unicharset_->null_sid(); delete[] sid; return max_sid; } // Fixes the state_ for a chop at the given blob_posiiton. void WERD_CHOICE::UpdateStateForSplit(int blob_position) { int total_chunks = 0; for (int i = 0; i < length_; ++i) { total_chunks += state_[i]; if (total_chunks > blob_position) { ++state_[i]; return; } } } // Returns the sum of all the state elements, being the total number of blobs. int WERD_CHOICE::TotalOfStates() const { int total_chunks = 0; for (int i = 0; i < length_; ++i) { total_chunks += state_[i]; } return total_chunks; } /** * WERD_CHOICE::print * * Print WERD_CHOICE to stdout. */ void WERD_CHOICE::print(const char *msg) const { tprintf("%s : ", msg); for (int i = 0; i < length_; ++i) { tprintf("%s", unicharset_->id_to_unichar(unichar_ids_[i])); } tprintf(" : R=%g, C=%g, F=%g, Perm=%d, xht=[%g,%g], ambig=%d\n", rating_, certainty_, adjust_factor_, permuter_, min_x_height_, max_x_height_, dangerous_ambig_found_); tprintf("pos"); for (int i = 0; i < length_; ++i) { tprintf("\t%s", ScriptPosToString(script_pos_[i])); } tprintf("\nstr"); for (int i = 0; i < length_; ++i) { tprintf("\t%s", unicharset_->id_to_unichar(unichar_ids_[i])); } tprintf("\nstate:"); for (int i = 0; i < length_; ++i) { tprintf("\t%d ", state_[i]); } tprintf("\nC"); for (int i = 0; i < length_; ++i) { tprintf("\t%.3f", certainties_[i]); } tprintf("\n"); } // Prints the segmentation state with an introductory message. void WERD_CHOICE::print_state(const char *msg) const { tprintf("%s", msg); for (int i = 0; i < length_; ++i) tprintf(" %d", state_[i]); tprintf("\n"); } // Displays the segmentation state of *this (if not the same as the last // one displayed) and waits for a click in the window. void WERD_CHOICE::DisplaySegmentation(TWERD* word) { #ifndef GRAPHICS_DISABLED // Number of different colors to draw with. const int kNumColors = 6; static ScrollView *segm_window = NULL; // Check the state against the static prev_drawn_state. static GenericVector<int> prev_drawn_state; bool already_done = prev_drawn_state.size() == length_; if (!already_done) prev_drawn_state.init_to_size(length_, 0); for (int i = 0; i < length_; ++i) { if (prev_drawn_state[i] != state_[i]) { already_done = false; } prev_drawn_state[i] = state_[i]; } if (already_done || word->blobs.empty()) return; // Create the window if needed. if (segm_window == NULL) { segm_window = new ScrollView("Segmentation", 5, 10, 500, 256, 2000.0, 256.0, true); } else { segm_window->Clear(); } TBOX bbox; int blob_index = 0; for (int c = 0; c < length_; ++c) { ScrollView::Color color = static_cast<ScrollView::Color>(c % kNumColors + 3); for (int i = 0; i < state_[c]; ++i, ++blob_index) { TBLOB* blob = word->blobs[blob_index]; bbox += blob->bounding_box(); blob->plot(segm_window, color, color); } } segm_window->ZoomToRectangle(bbox.left(), bbox.top(), bbox.right(), bbox.bottom()); segm_window->Update(); window_wait(segm_window); #endif } bool EqualIgnoringCaseAndTerminalPunct(const WERD_CHOICE &word1, const WERD_CHOICE &word2) { const UNICHARSET *uchset = word1.unicharset(); if (word2.unicharset() != uchset) return false; int w1start, w1end; word1.punct_stripped(&w1start, &w1end); int w2start, w2end; word2.punct_stripped(&w2start, &w2end); if (w1end - w1start != w2end - w2start) return false; for (int i = 0; i < w1end - w1start; i++) { if (uchset->to_lower(word1.unichar_id(w1start + i)) != uchset->to_lower(word2.unichar_id(w2start + i))) { return false; } } return true; } /** * print_ratings_list * * Send all the ratings out to the logfile. * * @param msg intro message * @param ratings list of ratings * @param current_unicharset unicharset that can be used * for id-to-unichar conversion */ void print_ratings_list(const char *msg, BLOB_CHOICE_LIST *ratings, const UNICHARSET &current_unicharset) { if (ratings->length() == 0) { tprintf("%s:<none>\n", msg); return; } if (*msg != '\0') { tprintf("%s\n", msg); } BLOB_CHOICE_IT c_it; c_it.set_to_list(ratings); for (c_it.mark_cycle_pt(); !c_it.cycled_list(); c_it.forward()) { c_it.data()->print(&current_unicharset); if (!c_it.at_last()) tprintf("\n"); } tprintf("\n"); fflush(stdout); }
1080228-arabicocr11
ccstruct/ratngs.cpp
C++
asf20
28,152
/********************************************************************** * File: rect.h (Formerly box.h) * Description: Bounding box class definition. * Author: Phil Cheatle * Created: Wed Oct 16 15:18:45 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef RECT_H #define RECT_H #include <math.h> #include "points.h" #include "ndminx.h" #include "scrollview.h" #include "strngs.h" #include "tprintf.h" class DLLSYM TBOX { // bounding box public: TBOX (): // empty constructor making a null box bot_left (MAX_INT16, MAX_INT16), top_right (-MAX_INT16, -MAX_INT16) { } TBOX( // constructor const ICOORD pt1, // one corner const ICOORD pt2); // the other corner TBOX( // constructor inT16 left, inT16 bottom, inT16 right, inT16 top); TBOX( // box around FCOORD const FCOORD pt); bool null_box() const { // Is box null return ((left () >= right ()) || (top () <= bottom ())); } bool operator==(const TBOX& other) const { return bot_left == other.bot_left && top_right == other.top_right; } inT16 top() const { // coord of top return top_right.y (); } void set_top(int y) { top_right.set_y(y); } inT16 bottom() const { // coord of bottom return bot_left.y (); } void set_bottom(int y) { bot_left.set_y(y); } inT16 left() const { // coord of left return bot_left.x (); } void set_left(int x) { bot_left.set_x(x); } inT16 right() const { // coord of right return top_right.x (); } void set_right(int x) { top_right.set_x(x); } int x_middle() const { return (bot_left.x() + top_right.x()) / 2; } int y_middle() const { return (bot_left.y() + top_right.y()) / 2; } const ICOORD &botleft() const { // access function return bot_left; } ICOORD botright() const { // ~ access function return ICOORD (top_right.x (), bot_left.y ()); } ICOORD topleft() const { // ~ access function return ICOORD (bot_left.x (), top_right.y ()); } const ICOORD &topright() const { // access function return top_right; } inT16 height() const { // how high is it? if (!null_box ()) return top_right.y () - bot_left.y (); else return 0; } inT16 width() const { // how high is it? if (!null_box ()) return top_right.x () - bot_left.x (); else return 0; } inT32 area() const { // what is the area? if (!null_box ()) return width () * height (); else return 0; } // Pads the box on either side by the supplied x,y pad amounts. // NO checks for exceeding any bounds like 0 or an image size. void pad(int xpad, int ypad) { ICOORD pad(xpad, ypad); bot_left -= pad; top_right += pad; } void move_bottom_edge( // move one edge const inT16 y) { // by +/- y bot_left += ICOORD (0, y); } void move_left_edge( // move one edge const inT16 x) { // by +/- x bot_left += ICOORD (x, 0); } void move_right_edge( // move one edge const inT16 x) { // by +/- x top_right += ICOORD (x, 0); } void move_top_edge( // move one edge const inT16 y) { // by +/- y top_right += ICOORD (0, y); } void move( // move box const ICOORD vec) { // by vector bot_left += vec; top_right += vec; } void move( // move box const FCOORD vec) { // by float vector bot_left.set_x ((inT16) floor (bot_left.x () + vec.x ())); // round left bot_left.set_y ((inT16) floor (bot_left.y () + vec.y ())); // round down top_right.set_x ((inT16) ceil (top_right.x () + vec.x ())); // round right top_right.set_y ((inT16) ceil (top_right.y () + vec.y ())); // round up } void scale( // scale box const float f) { // by multiplier bot_left.set_x ((inT16) floor (bot_left.x () * f)); // round left bot_left.set_y ((inT16) floor (bot_left.y () * f)); // round down top_right.set_x ((inT16) ceil (top_right.x () * f)); // round right top_right.set_y ((inT16) ceil (top_right.y () * f)); // round up } void scale( // scale box const FCOORD vec) { // by float vector bot_left.set_x ((inT16) floor (bot_left.x () * vec.x ())); bot_left.set_y ((inT16) floor (bot_left.y () * vec.y ())); top_right.set_x ((inT16) ceil (top_right.x () * vec.x ())); top_right.set_y ((inT16) ceil (top_right.y () * vec.y ())); } // rotate doesn't enlarge the box - it just rotates the bottom-left // and top-right corners. Use rotate_large if you want to guarantee // that all content is contained within the rotated box. void rotate(const FCOORD& vec) { // by vector bot_left.rotate (vec); top_right.rotate (vec); *this = TBOX (bot_left, top_right); } // rotate_large constructs the containing bounding box of all 4 // corners after rotating them. It therefore guarantees that all // original content is contained within, but also slightly enlarges the box. void rotate_large(const FCOORD& vec); bool contains( // is pt inside box const FCOORD pt) const; bool contains( // is box inside box const TBOX &box) const; bool overlap( // do boxes overlap const TBOX &box) const; bool major_overlap( // do boxes overlap more than half const TBOX &box) const; // Do boxes overlap on x axis. bool x_overlap(const TBOX &box) const; // Return the horizontal gap between the boxes. If the boxes // overlap horizontally then the return value is negative, indicating // the amount of the overlap. int x_gap(const TBOX& box) const { return MAX(bot_left.x(), box.bot_left.x()) - MIN(top_right.x(), box.top_right.x()); } // Return the vertical gap between the boxes. If the boxes // overlap vertically then the return value is negative, indicating // the amount of the overlap. int y_gap(const TBOX& box) const { return MAX(bot_left.y(), box.bot_left.y()) - MIN(top_right.y(), box.top_right.y()); } // Do boxes overlap on x axis by more than // half of the width of the narrower box. bool major_x_overlap(const TBOX &box) const; // Do boxes overlap on y axis. bool y_overlap(const TBOX &box) const; // Do boxes overlap on y axis by more than // half of the height of the shorter box. bool major_y_overlap(const TBOX &box) const; // fraction of current box's area covered by other double overlap_fraction(const TBOX &box) const; // fraction of the current box's projected area covered by the other's double x_overlap_fraction(const TBOX& box) const; // fraction of the current box's projected area covered by the other's double y_overlap_fraction(const TBOX& box) const; // Returns true if the boxes are almost equal on x axis. bool x_almost_equal(const TBOX &box, int tolerance) const; // Returns true if the boxes are almost equal bool almost_equal(const TBOX &box, int tolerance) const; TBOX intersection( // shared area box const TBOX &box) const; TBOX bounding_union( // box enclosing both const TBOX &box) const; // Sets the box boundaries to the given coordinates. void set_to_given_coords(int x_min, int y_min, int x_max, int y_max) { bot_left.set_x(x_min); bot_left.set_y(y_min); top_right.set_x(x_max); top_right.set_y(y_max); } void print() const { // print tprintf("Bounding box=(%d,%d)->(%d,%d)\n", left(), bottom(), right(), top()); } // Appends the bounding box as (%d,%d)->(%d,%d) to a STRING. void print_to_str(STRING *str) const; #ifndef GRAPHICS_DISABLED void plot( // use current settings ScrollView* fd) const { // where to paint fd->Rectangle(bot_left.x (), bot_left.y (), top_right.x (), top_right.y ()); } void plot( // paint box ScrollView* fd, // where to paint ScrollView::Color fill_colour, // colour for inside ScrollView::Color border_colour) const; // colour for border #endif // Writes to the given file. Returns false in case of error. bool Serialize(FILE* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp); friend TBOX& operator+=(TBOX&, const TBOX&); // in place union friend TBOX& operator&=(TBOX&, const TBOX&); // in place intersection private: ICOORD bot_left; // bottom left corner ICOORD top_right; // top right corner }; /********************************************************************** * TBOX::TBOX() Constructor from 1 FCOORD * **********************************************************************/ inline TBOX::TBOX( // construtor const FCOORD pt // floating centre ) { bot_left = ICOORD ((inT16) floor (pt.x ()), (inT16) floor (pt.y ())); top_right = ICOORD ((inT16) ceil (pt.x ()), (inT16) ceil (pt.y ())); } /********************************************************************** * TBOX::contains() Is point within box * **********************************************************************/ inline bool TBOX::contains(const FCOORD pt) const { return ((pt.x () >= bot_left.x ()) && (pt.x () <= top_right.x ()) && (pt.y () >= bot_left.y ()) && (pt.y () <= top_right.y ())); } /********************************************************************** * TBOX::contains() Is box within box * **********************************************************************/ inline bool TBOX::contains(const TBOX &box) const { return (contains (box.bot_left) && contains (box.top_right)); } /********************************************************************** * TBOX::overlap() Do two boxes overlap? * **********************************************************************/ inline bool TBOX::overlap( // do boxes overlap const TBOX &box) const { return ((box.bot_left.x () <= top_right.x ()) && (box.top_right.x () >= bot_left.x ()) && (box.bot_left.y () <= top_right.y ()) && (box.top_right.y () >= bot_left.y ())); } /********************************************************************** * TBOX::major_overlap() Do two boxes overlap by at least half of the smallest? * **********************************************************************/ inline bool TBOX::major_overlap( // Do boxes overlap more that half. const TBOX &box) const { int overlap = MIN(box.top_right.x(), top_right.x()); overlap -= MAX(box.bot_left.x(), bot_left.x()); overlap += overlap; if (overlap < MIN(box.width(), width())) return false; overlap = MIN(box.top_right.y(), top_right.y()); overlap -= MAX(box.bot_left.y(), bot_left.y()); overlap += overlap; if (overlap < MIN(box.height(), height())) return false; return true; } /********************************************************************** * TBOX::overlap_fraction() Fraction of area covered by the other box * **********************************************************************/ inline double TBOX::overlap_fraction(const TBOX &box) const { double fraction = 0.0; if (this->area()) { fraction = this->intersection(box).area() * 1.0 / this->area(); } return fraction; } /********************************************************************** * TBOX::x_overlap() Do two boxes overlap on x-axis * **********************************************************************/ inline bool TBOX::x_overlap(const TBOX &box) const { return ((box.bot_left.x() <= top_right.x()) && (box.top_right.x() >= bot_left.x())); } /********************************************************************** * TBOX::major_x_overlap() Do two boxes overlap by more than half the * width of the narrower box on the x-axis * **********************************************************************/ inline bool TBOX::major_x_overlap(const TBOX &box) const { inT16 overlap = box.width(); if (this->left() > box.left()) { overlap -= this->left() - box.left(); } if (this->right() < box.right()) { overlap -= box.right() - this->right(); } return (overlap >= box.width() / 2 || overlap >= this->width() / 2); } /********************************************************************** * TBOX::y_overlap() Do two boxes overlap on y-axis * **********************************************************************/ inline bool TBOX::y_overlap(const TBOX &box) const { return ((box.bot_left.y() <= top_right.y()) && (box.top_right.y() >= bot_left.y())); } /********************************************************************** * TBOX::major_y_overlap() Do two boxes overlap by more than half the * height of the shorter box on the y-axis * **********************************************************************/ inline bool TBOX::major_y_overlap(const TBOX &box) const { inT16 overlap = box.height(); if (this->bottom() > box.bottom()) { overlap -= this->bottom() - box.bottom(); } if (this->top() < box.top()) { overlap -= box.top() - this->top(); } return (overlap >= box.height() / 2 || overlap >= this->height() / 2); } /********************************************************************** * TBOX::x_overlap_fraction() Calculates the horizontal overlap of the * given boxes as a fraction of this boxes * width. * **********************************************************************/ inline double TBOX::x_overlap_fraction(const TBOX& other) const { int low = MAX(left(), other.left()); int high = MIN(right(), other.right()); int width = right() - left(); if (width == 0) { int x = left(); if (other.left() <= x && x <= other.right()) return 1.0; else return 0.0; } else { return MAX(0, static_cast<double>(high - low) / width); } } /********************************************************************** * TBOX::y_overlap_fraction() Calculates the vertical overlap of the * given boxes as a fraction of this boxes * height. * **********************************************************************/ inline double TBOX::y_overlap_fraction(const TBOX& other) const { int low = MAX(bottom(), other.bottom()); int high = MIN(top(), other.top()); int height = top() - bottom(); if (height == 0) { int y = bottom(); if (other.bottom() <= y && y <= other.top()) return 1.0; else return 0.0; } else { return MAX(0, static_cast<double>(high - low) / height); } } #endif
1080228-arabicocr11
ccstruct/rect.h
C++
asf20
16,226
/********************************************************************** * File: pdblock.h (Formerly pdblk.h) * Description: Page block class definition. * Author: Ray Smith * Created: Thu Mar 14 17:32:01 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef PDBLOCK_H #define PDBLOCK_H #include "clst.h" #include "strngs.h" #include "polyblk.h" class DLLSYM PDBLK; //forward decl struct Pix; CLISTIZEH (PDBLK) ///page block class PDBLK { friend class BLOCK_RECT_IT; //< block iterator public: ///empty constructor PDBLK() { hand_poly = NULL; index_ = 0; } ///simple constructor PDBLK(inT16 xmin, //< bottom left inT16 ymin, inT16 xmax, //< top right inT16 ymax); ///set vertex lists ///@param left list of left vertices ///@param right list of right vertices void set_sides(ICOORDELT_LIST *left, ICOORDELT_LIST *right); ///destructor ~PDBLK () { if (hand_poly) delete hand_poly; } POLY_BLOCK *poly_block() const { return hand_poly; } ///set the poly block void set_poly_block(POLY_BLOCK *blk) { hand_poly = blk; } ///get box void bounding_box(ICOORD &bottom_left, //bottom left ICOORD &top_right) const { //topright bottom_left = box.botleft (); top_right = box.topright (); } ///get real box const TBOX &bounding_box() const { return box; } int index() const { return index_; } void set_index(int value) { index_ = value; } ///is pt inside block BOOL8 contains(ICOORD pt); /// reposition block void move(const ICOORD vec); // by vector // Returns a binary Pix mask with a 1 pixel for every pixel within the // block. Rotates the coordinate system by rerotation prior to rendering. Pix* render_mask(const FCOORD& rerotation); #ifndef GRAPHICS_DISABLED ///draw histogram ///@param window window to draw in ///@param serial serial number ///@param colour colour to draw in void plot(ScrollView* window, inT32 serial, ScrollView::Color colour); #endif // GRAPHICS_DISABLED ///assignment ///@param source from this PDBLK & operator= (const PDBLK & source); protected: POLY_BLOCK *hand_poly; //< wierd as well ICOORDELT_LIST leftside; //< left side vertices ICOORDELT_LIST rightside; //< right side vertices TBOX box; //< bounding box int index_; //< Serial number of this block. }; class DLLSYM BLOCK_RECT_IT //rectangle iterator { public: ///constructor ///@param blkptr block to iterate BLOCK_RECT_IT(PDBLK *blkptr); ///start (new) block void set_to_block ( PDBLK * blkptr); //block to iterate ///start iteration void start_block(); ///next rectangle void forward(); ///test end BOOL8 cycled_rects() { return left_it.cycled_list () && right_it.cycled_list (); } ///current rectangle ///@param bleft bottom left ///@param tright top right void bounding_box(ICOORD &bleft, ICOORD &tright) { //bottom left bleft = ICOORD (left_it.data ()->x (), ymin); //top right tright = ICOORD (right_it.data ()->x (), ymax); } private: inT16 ymin; //< bottom of rectangle inT16 ymax; //< top of rectangle PDBLK *block; //< block to iterate ICOORDELT_IT left_it; //< boundary iterators ICOORDELT_IT right_it; }; ///rectangle iterator class DLLSYM BLOCK_LINE_IT { public: ///constructor ///@param blkptr from block BLOCK_LINE_IT (PDBLK * blkptr) :rect_it (blkptr) { block = blkptr; //remember block } ///start (new) block ///@param blkptr block to start void set_to_block (PDBLK * blkptr) { block = blkptr; //remember block //set iterator rect_it.set_to_block (blkptr); } ///get a line ///@param y line to get ///@param xext output extent inT16 get_line(inT16 y, inT16 &xext); private: PDBLK * block; //< block to iterate BLOCK_RECT_IT rect_it; //< rectangle iterator }; int decreasing_top_order(const void *row1, const void *row2); #endif
1080228-arabicocr11
ccstruct/pdblock.h
C++
asf20
5,272
/********************************************************************** * File: normalis.h (Formerly denorm.h) * Description: Code for the DENORM class. * Author: Ray Smith * Created: Thu Apr 23 09:22:43 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef NORMALIS_H #define NORMALIS_H #include <stdio.h> #include "genericvector.h" #include "host.h" const int kBlnCellHeight = 256; // Full-height for baseline normalization. const int kBlnXHeight = 128; // x-height for baseline normalization. const int kBlnBaselineOffset = 64; // offset for baseline normalization. struct Pix; class ROW; // Forward decl class BLOCK; class FCOORD; struct TBLOB; class TBOX; struct TPOINT; class UNICHARSET; namespace tesseract { // Possible normalization methods. Use NEGATIVE values as these also // double up as markers for the last sub-classifier. enum NormalizationMode { NM_BASELINE = -3, // The original BL normalization mode. NM_CHAR_ISOTROPIC = -2, // Character normalization but isotropic. NM_CHAR_ANISOTROPIC = -1 // The original CN normalization mode. }; } // namespace tesseract. class DENORM { public: DENORM(); // Copying a DENORM is allowed. DENORM(const DENORM &); DENORM& operator=(const DENORM&); ~DENORM(); // Setup the normalization transformation parameters. // The normalizations applied to a blob are as follows: // 1. An optional block layout rotation that was applied during layout // analysis to make the textlines horizontal. // 2. A normalization transformation (LocalNormTransform): // Subtract the "origin" // Apply an x,y scaling. // Apply an optional rotation. // Add back a final translation. // The origin is in the block-rotated space, and is usually something like // the x-middle of the word at the baseline. // 3. Zero or more further normalization transformations that are applied // in sequence, with a similar pattern to the first normalization transform. // // A DENORM holds the parameters of a single normalization, and can execute // both the LocalNormTransform (a forwards normalization), and the // LocalDenormTransform which is an inverse transform or de-normalization. // A DENORM may point to a predecessor DENORM, which is actually the earlier // normalization, so the full normalization sequence involves executing all // predecessors first and then the transform in "this". // Let x be image co-ordinates and that we have normalization classes A, B, C // where we first apply A then B then C to get normalized x': // x' = CBAx // Then the backwards (to original coordinates) would be: // x = A^-1 B^-1 C^-1 x' // and A = B->predecessor_ and B = C->predecessor_ // NormTransform executes all predecessors recursively, and then this. // NormTransform would be used to transform an image-based feature to // normalized space for use in a classifier // DenormTransform inverts this and then all predecessors. It can be // used to get back to the original image coordinates from normalized space. // The LocalNormTransform member executes just the transformation // in "this" without the layout rotation or any predecessors. It would be // used to run each successive normalization, eg the word normalization, // and later the character normalization. // Arguments: // block: if not NULL, then this is the first transformation, and // block->re_rotation() needs to be used after the Denorm // transformation to get back to the image coords. // rotation: if not NULL, apply this rotation after translation to the // origin and scaling. (Usually a classify rotation.) // predecessor: if not NULL, then predecessor has been applied to the // input space and needs to be undone to complete the inverse. // The above pointers are not owned by this DENORM and are assumed to live // longer than this denorm, except rotation, which is deep copied on input. // // x_origin: The x origin which will be mapped to final_xshift in the result. // y_origin: The y origin which will be mapped to final_yshift in the result. // Added to result of row->baseline(x) if not NULL. // // x_scale: scale factor for the x-coordinate. // y_scale: scale factor for the y-coordinate. Ignored if segs is given. // Note that these scale factors apply to the same x and y system as the // x-origin and y-origin apply, ie after any block rotation, but before // the rotation argument is applied. // // final_xshift: The x component of the final translation. // final_yshift: The y component of the final translation. // // In theory, any of the commonly used normalizations can be setup here: // * Traditional baseline normalization on a word: // SetupNormalization(block, NULL, NULL, // box.x_middle(), baseline, // kBlnXHeight / x_height, kBlnXHeight / x_height, // 0, kBlnBaselineOffset); // * "Numeric mode" baseline normalization on a word, in which the blobs // are positioned with the bottom as the baseline is achieved by making // a separate DENORM for each blob. // SetupNormalization(block, NULL, NULL, // box.x_middle(), box.bottom(), // kBlnXHeight / x_height, kBlnXHeight / x_height, // 0, kBlnBaselineOffset); // * Anisotropic character normalization used by IntFx. // SetupNormalization(NULL, NULL, denorm, // centroid_x, centroid_y, // 51.2 / ry, 51.2 / rx, 128, 128); // * Normalize blob height to x-height (current OSD): // SetupNormalization(NULL, &rotation, NULL, // box.rotational_x_middle(rotation), // box.rotational_y_middle(rotation), // kBlnXHeight / box.rotational_height(rotation), // kBlnXHeight / box.rotational_height(rotation), // 0, kBlnBaselineOffset); // * Secondary normalization for classification rotation (current): // FCOORD rotation = block->classify_rotation(); // float target_height = kBlnXHeight / CCStruct::kXHeightCapRatio; // SetupNormalization(NULL, &rotation, denorm, // box.rotational_x_middle(rotation), // box.rotational_y_middle(rotation), // target_height / box.rotational_height(rotation), // target_height / box.rotational_height(rotation), // 0, kBlnBaselineOffset); // * Proposed new normalizations for CJK: Between them there is then // no need for further normalization at all, and the character fills the cell. // ** Replacement for baseline normalization on a word: // Scales height and width independently so that modal height and pitch // fill the cell respectively. // float cap_height = x_height / CCStruct::kXHeightCapRatio; // SetupNormalization(block, NULL, NULL, // box.x_middle(), cap_height / 2.0f, // kBlnCellHeight / fixed_pitch, // kBlnCellHeight / cap_height, // 0, 0); // ** Secondary normalization for classification (with rotation) (proposed): // Requires a simple translation to the center of the appropriate character // cell, no further scaling and a simple rotation (or nothing) about the // cell center. // FCOORD rotation = block->classify_rotation(); // SetupNormalization(NULL, &rotation, denorm, // fixed_pitch_cell_center, // 0.0f, // 1.0f, // 1.0f, // 0, 0); void SetupNormalization(const BLOCK* block, const FCOORD* rotation, const DENORM* predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift); // Sets up the DENORM to execute a non-linear transformation based on // preserving an even distribution of stroke edges. The transformation // operates only within the given box, scaling input coords within the box // non-linearly to a box of target_width by target_height, with all other // coords being clipped to the box edge. As with SetupNormalization above, // final_xshift and final_yshift are applied after scaling, and the bottom- // left of box is used as a pre-scaling origin. // x_coords is a collection of the x-coords of vertical edges for each // y-coord starting at box.bottom(). // y_coords is a collection of the y-coords of horizontal edges for each // x-coord starting at box.left(). // Eg x_coords[0] is a collection of the x-coords of edges at y=bottom. // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1. // The second-level vectors must all be sorted in ascending order. void SetupNonLinear(const DENORM* predecessor, const TBOX& box, float target_width, float target_height, float final_xshift, float final_yshift, const GenericVector<GenericVector<int> >& x_coords, const GenericVector<GenericVector<int> >& y_coords); // Transforms the given coords one step forward to normalized space, without // using any block rotation or predecessor. void LocalNormTransform(const TPOINT& pt, TPOINT* transformed) const; void LocalNormTransform(const FCOORD& pt, FCOORD* transformed) const; // Transforms the given coords forward to normalized space using the // full transformation sequence defined by the block rotation, the // predecessors, deepest first, and finally this. If first_norm is not NULL, // then the first and deepest transformation used is first_norm, ending // with this, and the block rotation will not be applied. void NormTransform(const DENORM* first_norm, const TPOINT& pt, TPOINT* transformed) const; void NormTransform(const DENORM* first_norm, const FCOORD& pt, FCOORD* transformed) const; // Transforms the given coords one step back to source space, without // using to any block rotation or predecessor. void LocalDenormTransform(const TPOINT& pt, TPOINT* original) const; void LocalDenormTransform(const FCOORD& pt, FCOORD* original) const; // Transforms the given coords all the way back to source image space using // the full transformation sequence defined by this and its predecesors // recursively, shallowest first, and finally any block re_rotation. // If last_denorm is not NULL, then the last transformation used will // be last_denorm, and the block re_rotation will never be executed. void DenormTransform(const DENORM* last_denorm, const TPOINT& pt, TPOINT* original) const; void DenormTransform(const DENORM* last_denorm, const FCOORD& pt, FCOORD* original) const; // Normalize a blob using blob transformations. Less accurate, but // more accurately copies the old way. void LocalNormBlob(TBLOB* blob) const; // Fills in the x-height range accepted by the given unichar_id in blob // coordinates, given its bounding box in the usual baseline-normalized // coordinates, with some initial crude x-height estimate (such as word // size) and this denoting the transformation that was used. // Also returns the amount the character must have shifted up or down. void XHeightRange(int unichar_id, const UNICHARSET& unicharset, const TBOX& bbox, float* min_xht, float* max_xht, float* yshift) const; // Prints the content of the DENORM for debug purposes. void Print() const; Pix* pix() const { return pix_; } void set_pix(Pix* pix) { pix_ = pix; } bool inverse() const { return inverse_; } void set_inverse(bool value) { inverse_ = value; } const DENORM* RootDenorm() const { if (predecessor_ != NULL) return predecessor_->RootDenorm(); return this; } const DENORM* predecessor() const { return predecessor_; } // Accessors - perhaps should not be needed. float x_scale() const { return x_scale_; } float y_scale() const { return y_scale_; } const BLOCK* block() const { return block_; } void set_block(const BLOCK* block) { block_ = block; } private: // Free allocated memory and clear pointers. void Clear(); // Setup default values. void Init(); // Best available image. Pix* pix_; // True if the source image is white-on-black. bool inverse_; // Block the word came from. If not null, block->re_rotation() takes the // "untransformed" coordinates even further back to the original image. // Used only on the first DENORM in a chain. const BLOCK* block_; // Rotation to apply between translation to the origin and scaling. const FCOORD* rotation_; // Previous transformation in a chain. const DENORM* predecessor_; // Non-linear transformation maps directly from each integer offset from the // origin to the corresponding x-coord. Owned by the DENORM. GenericVector<float>* x_map_; // Non-linear transformation maps directly from each integer offset from the // origin to the corresponding y-coord. Owned by the DENORM. GenericVector<float>* y_map_; // x-coordinate to be mapped to final_xshift_ in the result. float x_origin_; // y-coordinate to be mapped to final_yshift_ in the result. float y_origin_; // Scale factors for x and y coords. Applied to pre-rotation system. float x_scale_; float y_scale_; // Destination coords of the x_origin_ and y_origin_. float final_xshift_; float final_yshift_; }; #endif
1080228-arabicocr11
ccstruct/normalis.h
C++
asf20
14,549
///////////////////////////////////////////////////////////////////// // File: ocrpara.h // Description: OCR Paragraph Output Type // Author: David Eger // Created: 2010-11-15 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include <stdio.h> #include "ocrpara.h" #include "host.h" // For NearlyEqual() ELISTIZE(PARA) using tesseract::JUSTIFICATION_LEFT; using tesseract::JUSTIFICATION_RIGHT; using tesseract::JUSTIFICATION_CENTER; using tesseract::JUSTIFICATION_UNKNOWN; static STRING ParagraphJustificationToString( tesseract::ParagraphJustification justification) { switch (justification) { case JUSTIFICATION_LEFT: return "LEFT"; case JUSTIFICATION_RIGHT: return "RIGHT"; case JUSTIFICATION_CENTER: return "CENTER"; default: return "UNKNOWN"; } } bool ParagraphModel::ValidFirstLine(int lmargin, int lindent, int rindent, int rmargin) const { switch (justification_) { case JUSTIFICATION_LEFT: return NearlyEqual(lmargin + lindent, margin_ + first_indent_, tolerance_); case JUSTIFICATION_RIGHT: return NearlyEqual(rmargin + rindent, margin_ + first_indent_, tolerance_); case JUSTIFICATION_CENTER: return NearlyEqual(lindent, rindent, tolerance_ * 2); default: // shouldn't happen return false; } } bool ParagraphModel::ValidBodyLine(int lmargin, int lindent, int rindent, int rmargin) const { switch (justification_) { case JUSTIFICATION_LEFT: return NearlyEqual(lmargin + lindent, margin_ + body_indent_, tolerance_); case JUSTIFICATION_RIGHT: return NearlyEqual(rmargin + rindent, margin_ + body_indent_, tolerance_); case JUSTIFICATION_CENTER: return NearlyEqual(lindent, rindent, tolerance_ * 2); default: // shouldn't happen return false; } } bool ParagraphModel::Comparable(const ParagraphModel &other) const { if (justification_ != other.justification_) return false; if (justification_ == JUSTIFICATION_CENTER || justification_ == JUSTIFICATION_UNKNOWN) return true; int tolerance = (tolerance_ + other.tolerance_) / 4; return NearlyEqual(margin_ + first_indent_, other.margin_ + other.first_indent_, tolerance) && NearlyEqual(margin_ + body_indent_, other.margin_ + other.body_indent_, tolerance); } STRING ParagraphModel::ToString() const { char buffer[200]; const STRING &alignment = ParagraphJustificationToString(justification_); snprintf(buffer, sizeof(buffer), "margin: %d, first_indent: %d, body_indent: %d, alignment: %s", margin_, first_indent_, body_indent_, alignment.string()); return STRING(buffer); }
1080228-arabicocr11
ccstruct/ocrpara.cpp
C++
asf20
3,488
/********************************************************************** * File: crakedge.h (Formerly: crkedge.h) * Description: Sturctures for the Crack following edge detector. * Author: Ray Smith * Created: Fri Mar 22 16:06:38 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef CRAKEDGE_H #define CRAKEDGE_H #include "points.h" #include "mod128.h" class CRACKEDGE { public: CRACKEDGE() {} ICOORD pos; /*position of crack */ inT8 stepx; //edge step inT8 stepy; inT8 stepdir; //chaincode CRACKEDGE *prev; /*previous point */ CRACKEDGE *next; /*next point */ }; #endif
1080228-arabicocr11
ccstruct/crakedge.h
C++
asf20
1,363
/********************************************************************** * File: polyaprx.h (Formerly polygon.h) * Description: Code for polygonal approximation from old edgeprog. * Author: Ray Smith * Created: Thu Nov 25 11:42:04 GMT 1993 * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef POLYAPRX_H #define POLYAPRX_H #include "blobs.h" #include "coutln.h" // convert a chain-coded input to the old OUTLINE approximation TESSLINE* ApproximateOutline(bool allow_detailed_fx, C_OUTLINE *c_outline); EDGEPT *edgesteps_to_edgepts ( //convert outline C_OUTLINE * c_outline, //input EDGEPT edgepts[] //output is array ); void fix2( //polygonal approx EDGEPT *start, /*loop to approimate */ int area); EDGEPT *poly2( //second poly EDGEPT *startpt, /*start of loop */ int area /*area of blob box */ ); void cutline( //recursive refine EDGEPT *first, /*ends of line */ EDGEPT *last, int area /*area of object */ ); #endif
1080228-arabicocr11
ccstruct/polyaprx.h
C
asf20
1,810
/********************************************************************** * File: mod128.h (Formerly dir128.h) * Description: Header for class which implements modulo arithmetic. * Author: Ray Smith * Created: Tue Mar 26 17:48:13 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef MOD128_H #define MOD128_H #include "points.h" #define MODULUS 128 /*range of directions */ #define DIRBITS 7 //no of bits used #define DIRSCALE 1000 //length of vector class DLLSYM DIR128 { public: DIR128() { } //empty constructor DIR128( //constructor inT16 value) { //value to assign value %= MODULUS; //modulo arithmetic if (value < 0) value += MODULUS; //done properly dir = (inT8) value; } DIR128(const FCOORD fc); //quantize vector DIR128 & operator= ( //assign of inT16 inT16 value) { //value to assign value %= MODULUS; //modulo arithmetic if (value < 0) value += MODULUS; //done properly dir = (inT8) value; return *this; } inT8 operator- ( //subtraction const DIR128 & minus) const//for signed result { //result inT16 result = dir - minus.dir; if (result > MODULUS / 2) result -= MODULUS; //get in range else if (result < -MODULUS / 2) result += MODULUS; return (inT8) result; } DIR128 operator+ ( //addition const DIR128 & add) const //of itself { DIR128 result; //sum result = dir + add.dir; //let = do the work return result; } DIR128 & operator+= ( //same as + const DIR128 & add) { *this = dir + add.dir; //let = do the work return *this; } inT8 get_dir() const { //access function return dir; } ICOORD vector() const; //turn to vector private: inT8 dir; //a direction }; #endif
1080228-arabicocr11
ccstruct/mod128.h
C++
asf20
2,765
/////////////////////////////////////////////////////////////////////// // File: fontinfo.cpp // Description: Font information classes abstracted from intproto.h/cpp. // Author: rays@google.com (Ray Smith) // Created: Wed May 18 10:39:01 PDT 2011 // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "fontinfo.h" #include "bitvector.h" #include "unicity_table.h" namespace tesseract { // Writes to the given file. Returns false in case of error. bool FontInfo::Serialize(FILE* fp) const { if (!write_info(fp, *this)) return false; if (!write_spacing_info(fp, *this)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool FontInfo::DeSerialize(bool swap, FILE* fp) { if (!read_info(fp, this, swap)) return false; if (!read_spacing_info(fp, this, swap)) return false; return true; } FontInfoTable::FontInfoTable() { set_compare_callback(NewPermanentTessCallback(CompareFontInfo)); set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback)); } FontInfoTable::~FontInfoTable() { } // Writes to the given file. Returns false in case of error. bool FontInfoTable::Serialize(FILE* fp) const { return this->SerializeClasses(fp); } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool FontInfoTable::DeSerialize(bool swap, FILE* fp) { truncate(0); return this->DeSerializeClasses(swap, fp); } // Returns true if the given set of fonts includes one with the same // properties as font_id. bool FontInfoTable::SetContainsFontProperties( int font_id, const GenericVector<int>& font_set) const { uinT32 properties = get(font_id).properties; for (int f = 0; f < font_set.size(); ++f) { if (get(font_set[f]).properties == properties) return true; } return false; } // Returns true if the given set of fonts includes multiple properties. bool FontInfoTable::SetContainsMultipleFontProperties( const GenericVector<int>& font_set) const { if (font_set.empty()) return false; int first_font = font_set[0]; uinT32 properties = get(first_font).properties; for (int f = 1; f < font_set.size(); ++f) { if (get(font_set[f]).properties != properties) return true; } return false; } // Moves any non-empty FontSpacingInfo entries from other to this. void FontInfoTable::MoveSpacingInfoFrom(FontInfoTable* other) { set_compare_callback(NewPermanentTessCallback(CompareFontInfo)); set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback)); for (int i = 0; i < other->size(); ++i) { GenericVector<FontSpacingInfo*>* spacing_vec = other->get(i).spacing_vec; if (spacing_vec != NULL) { int target_index = get_index(other->get(i)); if (target_index < 0) { // Bit copy the FontInfo and steal all the pointers. push_back(other->get(i)); other->get(i).name = NULL; } else { delete [] get(target_index).spacing_vec; get(target_index).spacing_vec = other->get(i).spacing_vec; } other->get(i).spacing_vec = NULL; } } } // Moves this to the target unicity table. void FontInfoTable::MoveTo(UnicityTable<FontInfo>* target) { target->clear(); target->set_compare_callback(NewPermanentTessCallback(CompareFontInfo)); target->set_clear_callback(NewPermanentTessCallback(FontInfoDeleteCallback)); for (int i = 0; i < size(); ++i) { // Bit copy the FontInfo and steal all the pointers. target->push_back(get(i)); get(i).name = NULL; get(i).spacing_vec = NULL; } } // Compare FontInfo structures. bool CompareFontInfo(const FontInfo& fi1, const FontInfo& fi2) { // The font properties are required to be the same for two font with the same // name, so there is no need to test them. // Consequently, querying the table with only its font name as information is // enough to retrieve its properties. return strcmp(fi1.name, fi2.name) == 0; } // Compare FontSet structures. bool CompareFontSet(const FontSet& fs1, const FontSet& fs2) { if (fs1.size != fs2.size) return false; for (int i = 0; i < fs1.size; ++i) { if (fs1.configs[i] != fs2.configs[i]) return false; } return true; } // Callbacks for GenericVector. void FontInfoDeleteCallback(FontInfo f) { if (f.spacing_vec != NULL) { f.spacing_vec->delete_data_pointers(); delete f.spacing_vec; } delete[] f.name; } void FontSetDeleteCallback(FontSet fs) { delete[] fs.configs; } /*---------------------------------------------------------------------------*/ // Callbacks used by UnicityTable to read/write FontInfo/FontSet structures. bool read_info(FILE* f, FontInfo* fi, bool swap) { inT32 size; if (fread(&size, sizeof(size), 1, f) != 1) return false; if (swap) Reverse32(&size); char* font_name = new char[size + 1]; fi->name = font_name; if (static_cast<int>(fread(font_name, sizeof(*font_name), size, f)) != size) return false; font_name[size] = '\0'; if (fread(&fi->properties, sizeof(fi->properties), 1, f) != 1) return false; if (swap) Reverse32(&fi->properties); return true; } bool write_info(FILE* f, const FontInfo& fi) { inT32 size = strlen(fi.name); if (fwrite(&size, sizeof(size), 1, f) != 1) return false; if (static_cast<int>(fwrite(fi.name, sizeof(*fi.name), size, f)) != size) return false; if (fwrite(&fi.properties, sizeof(fi.properties), 1, f) != 1) return false; return true; } bool read_spacing_info(FILE *f, FontInfo* fi, bool swap) { inT32 vec_size, kern_size; if (fread(&vec_size, sizeof(vec_size), 1, f) != 1) return false; if (swap) Reverse32(&vec_size); ASSERT_HOST(vec_size >= 0); if (vec_size == 0) return true; fi->init_spacing(vec_size); for (int i = 0; i < vec_size; ++i) { FontSpacingInfo *fs = new FontSpacingInfo(); if (fread(&fs->x_gap_before, sizeof(fs->x_gap_before), 1, f) != 1 || fread(&fs->x_gap_after, sizeof(fs->x_gap_after), 1, f) != 1 || fread(&kern_size, sizeof(kern_size), 1, f) != 1) { delete fs; return false; } if (swap) { ReverseN(&(fs->x_gap_before), sizeof(fs->x_gap_before)); ReverseN(&(fs->x_gap_after), sizeof(fs->x_gap_after)); Reverse32(&kern_size); } if (kern_size < 0) { // indication of a NULL entry in fi->spacing_vec delete fs; continue; } if (kern_size > 0 && (!fs->kerned_unichar_ids.DeSerialize(swap, f) || !fs->kerned_x_gaps.DeSerialize(swap, f))) { delete fs; return false; } fi->add_spacing(i, fs); } return true; } bool write_spacing_info(FILE* f, const FontInfo& fi) { inT32 vec_size = (fi.spacing_vec == NULL) ? 0 : fi.spacing_vec->size(); if (fwrite(&vec_size, sizeof(vec_size), 1, f) != 1) return false; inT16 x_gap_invalid = -1; for (int i = 0; i < vec_size; ++i) { FontSpacingInfo *fs = fi.spacing_vec->get(i); inT32 kern_size = (fs == NULL) ? -1 : fs->kerned_x_gaps.size(); if (fs == NULL) { // Valid to have the identical fwrites. Writing invalid x-gaps. if (fwrite(&(x_gap_invalid), sizeof(x_gap_invalid), 1, f) != 1 || fwrite(&(x_gap_invalid), sizeof(x_gap_invalid), 1, f) != 1 || fwrite(&kern_size, sizeof(kern_size), 1, f) != 1) { return false; } } else { if (fwrite(&(fs->x_gap_before), sizeof(fs->x_gap_before), 1, f) != 1 || fwrite(&(fs->x_gap_after), sizeof(fs->x_gap_after), 1, f) != 1 || fwrite(&kern_size, sizeof(kern_size), 1, f) != 1) { return false; } } if (kern_size > 0 && (!fs->kerned_unichar_ids.Serialize(f) || !fs->kerned_x_gaps.Serialize(f))) { return false; } } return true; } bool read_set(FILE* f, FontSet* fs, bool swap) { if (fread(&fs->size, sizeof(fs->size), 1, f) != 1) return false; if (swap) Reverse32(&fs->size); fs->configs = new int[fs->size]; for (int i = 0; i < fs->size; ++i) { if (fread(&fs->configs[i], sizeof(fs->configs[i]), 1, f) != 1) return false; if (swap) Reverse32(&fs->configs[i]); } return true; } bool write_set(FILE* f, const FontSet& fs) { if (fwrite(&fs.size, sizeof(fs.size), 1, f) != 1) return false; for (int i = 0; i < fs.size; ++i) { if (fwrite(&fs.configs[i], sizeof(fs.configs[i]), 1, f) != 1) return false; } return true; } } // namespace tesseract.
1080228-arabicocr11
ccstruct/fontinfo.cpp
C++
asf20
9,091
/********************************************************************** * File: rect.c (Formerly box.c) * Description: Bounding box class definition. * Author: Phil Cheatle * Created: Wed Oct 16 15:18:45 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "rect.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif /********************************************************************** * TBOX::TBOX() Constructor from 2 ICOORDS * **********************************************************************/ TBOX::TBOX( //construtor const ICOORD pt1, //one corner const ICOORD pt2 //the other corner ) { if (pt1.x () <= pt2.x ()) { if (pt1.y () <= pt2.y ()) { bot_left = pt1; top_right = pt2; } else { bot_left = ICOORD (pt1.x (), pt2.y ()); top_right = ICOORD (pt2.x (), pt1.y ()); } } else { if (pt1.y () <= pt2.y ()) { bot_left = ICOORD (pt2.x (), pt1.y ()); top_right = ICOORD (pt1.x (), pt2.y ()); } else { bot_left = pt2; top_right = pt1; } } } /********************************************************************** * TBOX::TBOX() Constructor from 4 integer values. * Note: It is caller's responsibility to provide values in the right * order. **********************************************************************/ TBOX::TBOX( //constructor inT16 left, inT16 bottom, inT16 right, inT16 top) : bot_left(left, bottom), top_right(right, top) { } // rotate_large constructs the containing bounding box of all 4 // corners after rotating them. It therefore guarantees that all // original content is contained within, but also slightly enlarges the box. void TBOX::rotate_large(const FCOORD& vec) { ICOORD top_left(bot_left.x(), top_right.y()); ICOORD bottom_right(top_right.x(), bot_left.y()); top_left.rotate(vec); bottom_right.rotate(vec); rotate(vec); TBOX box2(top_left, bottom_right); *this += box2; } /********************************************************************** * TBOX::intersection() Build the largest box contained in both boxes * **********************************************************************/ TBOX TBOX::intersection( //shared area box const TBOX &box) const { inT16 left; inT16 bottom; inT16 right; inT16 top; if (overlap (box)) { if (box.bot_left.x () > bot_left.x ()) left = box.bot_left.x (); else left = bot_left.x (); if (box.top_right.x () < top_right.x ()) right = box.top_right.x (); else right = top_right.x (); if (box.bot_left.y () > bot_left.y ()) bottom = box.bot_left.y (); else bottom = bot_left.y (); if (box.top_right.y () < top_right.y ()) top = box.top_right.y (); else top = top_right.y (); } else { left = MAX_INT16; bottom = MAX_INT16; top = -MAX_INT16; right = -MAX_INT16; } return TBOX (left, bottom, right, top); } /********************************************************************** * TBOX::bounding_union() Build the smallest box containing both boxes * **********************************************************************/ TBOX TBOX::bounding_union( //box enclosing both const TBOX &box) const { ICOORD bl; //bottom left ICOORD tr; //top right if (box.bot_left.x () < bot_left.x ()) bl.set_x (box.bot_left.x ()); else bl.set_x (bot_left.x ()); if (box.top_right.x () > top_right.x ()) tr.set_x (box.top_right.x ()); else tr.set_x (top_right.x ()); if (box.bot_left.y () < bot_left.y ()) bl.set_y (box.bot_left.y ()); else bl.set_y (bot_left.y ()); if (box.top_right.y () > top_right.y ()) tr.set_y (box.top_right.y ()); else tr.set_y (top_right.y ()); return TBOX (bl, tr); } /********************************************************************** * TBOX::plot() Paint a box using specified settings * **********************************************************************/ #ifndef GRAPHICS_DISABLED void TBOX::plot( //paint box ScrollView* fd, //where to paint ScrollView::Color fill_colour, //colour for inside ScrollView::Color border_colour //colour for border ) const { fd->Brush(fill_colour); fd->Pen(border_colour); plot(fd); } #endif // Appends the bounding box as (%d,%d)->(%d,%d) to a STRING. void TBOX::print_to_str(STRING *str) const { // "(%d,%d)->(%d,%d)", left(), bottom(), right(), top() str->add_str_int("(", left()); str->add_str_int(",", bottom()); str->add_str_int(")->(", right()); str->add_str_int(",", top()); *str += ')'; } // Writes to the given file. Returns false in case of error. bool TBOX::Serialize(FILE* fp) const { if (!bot_left.Serialize(fp)) return false; if (!top_right.Serialize(fp)) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TBOX::DeSerialize(bool swap, FILE* fp) { if (!bot_left.DeSerialize(swap, fp)) return false; if (!top_right.DeSerialize(swap, fp)) return false; return true; } /********************************************************************** * operator+= * * Extend one box to include the other (In place union) **********************************************************************/ DLLSYM TBOX & operator+= ( //bounding bounding bx TBOX & op1, //operands const TBOX & op2) { if (op2.bot_left.x () < op1.bot_left.x ()) op1.bot_left.set_x (op2.bot_left.x ()); if (op2.top_right.x () > op1.top_right.x ()) op1.top_right.set_x (op2.top_right.x ()); if (op2.bot_left.y () < op1.bot_left.y ()) op1.bot_left.set_y (op2.bot_left.y ()); if (op2.top_right.y () > op1.top_right.y ()) op1.top_right.set_y (op2.top_right.y ()); return op1; } /********************************************************************** * operator&= * * Reduce one box to intersection with the other (In place intersection) **********************************************************************/ TBOX& operator&=(TBOX& op1, const TBOX& op2) { if (op1.overlap (op2)) { if (op2.bot_left.x () > op1.bot_left.x ()) op1.bot_left.set_x (op2.bot_left.x ()); if (op2.top_right.x () < op1.top_right.x ()) op1.top_right.set_x (op2.top_right.x ()); if (op2.bot_left.y () > op1.bot_left.y ()) op1.bot_left.set_y (op2.bot_left.y ()); if (op2.top_right.y () < op1.top_right.y ()) op1.top_right.set_y (op2.top_right.y ()); } else { op1.bot_left.set_x (MAX_INT16); op1.bot_left.set_y (MAX_INT16); op1.top_right.set_x (-MAX_INT16); op1.top_right.set_y (-MAX_INT16); } return op1; } bool TBOX::x_almost_equal(const TBOX &box, int tolerance) const { return (abs(left() - box.left()) <= tolerance && abs(right() - box.right()) <= tolerance); } bool TBOX::almost_equal(const TBOX &box, int tolerance) const { return (abs(left() - box.left()) <= tolerance && abs(right() - box.right()) <= tolerance && abs(top() - box.top()) <= tolerance && abs(bottom() - box.bottom()) <= tolerance); }
1080228-arabicocr11
ccstruct/rect.cpp
C++
asf20
8,120
/////////////////////////////////////////////////////////////////////// // File: blamer.cpp // Description: Module allowing precise error causes to be allocated. // Author: Rike Antonova // Refactored: Ray Smith // Created: Mon Feb 04 14:37:01 PST 2013 // // (C) Copyright 2013, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "blamer.h" #include "blobs.h" #include "matrix.h" #include "normalis.h" #include "pageres.h" // Names for each value of IncorrectResultReason enum. Keep in sync. const char kBlameCorrect[] = "corr"; const char kBlameClassifier[] = "cl"; const char kBlameChopper[] = "chop"; const char kBlameClassLMTradeoff[] = "cl/LM"; const char kBlamePageLayout[] = "pglt"; const char kBlameSegsearchHeur[] = "ss_heur"; const char kBlameSegsearchPP[] = "ss_pp"; const char kBlameClassOldLMTradeoff[] = "cl/old_LM"; const char kBlameAdaption[] = "adapt"; const char kBlameNoTruthSplit[] = "no_tr_spl"; const char kBlameNoTruth[] = "no_tr"; const char kBlameUnknown[] = "unkn"; const char * const kIncorrectResultReasonNames[] = { kBlameCorrect, kBlameClassifier, kBlameChopper, kBlameClassLMTradeoff, kBlamePageLayout, kBlameSegsearchHeur, kBlameSegsearchPP, kBlameClassOldLMTradeoff, kBlameAdaption, kBlameNoTruthSplit, kBlameNoTruth, kBlameUnknown }; const char *BlamerBundle::IncorrectReasonName(IncorrectResultReason irr) { return kIncorrectResultReasonNames[irr]; } const char *BlamerBundle::IncorrectReason() const { return kIncorrectResultReasonNames[incorrect_result_reason_]; } // Functions to setup the blamer. // Whole word string, whole word bounding box. void BlamerBundle::SetWordTruth(const UNICHARSET& unicharset, const char* truth_str, const TBOX& word_box) { truth_word_.InsertBox(0, word_box); truth_has_char_boxes_ = false; // Encode the string as UNICHAR_IDs. GenericVector<UNICHAR_ID> encoding; GenericVector<char> lengths; unicharset.encode_string(truth_str, false, &encoding, &lengths, NULL); int total_length = 0; for (int i = 0; i < encoding.size(); total_length += lengths[i++]) { STRING uch(truth_str + total_length); uch.truncate_at(lengths[i] - total_length); UNICHAR_ID id = encoding[i]; if (id != INVALID_UNICHAR_ID) uch = unicharset.get_normed_unichar(id); truth_text_.push_back(uch); } } // Single "character" string, "character" bounding box. // May be called multiple times to indicate the characters in a word. void BlamerBundle::SetSymbolTruth(const UNICHARSET& unicharset, const char* char_str, const TBOX& char_box) { STRING symbol_str(char_str); UNICHAR_ID id = unicharset.unichar_to_id(char_str); if (id != INVALID_UNICHAR_ID) { STRING normed_uch(unicharset.get_normed_unichar(id)); if (normed_uch.length() > 0) symbol_str = normed_uch; } int length = truth_word_.length(); truth_text_.push_back(symbol_str); truth_word_.InsertBox(length, char_box); if (length == 0) truth_has_char_boxes_ = true; else if (truth_word_.BlobBox(length - 1) == char_box) truth_has_char_boxes_ = false; } // Marks that there is something wrong with the truth text, like it contains // reject characters. void BlamerBundle::SetRejectedTruth() { incorrect_result_reason_ = IRR_NO_TRUTH; truth_has_char_boxes_ = false; } // Returns true if the provided word_choice is correct. bool BlamerBundle::ChoiceIsCorrect(const WERD_CHOICE* word_choice) const { if (word_choice == NULL) return false; const UNICHARSET* uni_set = word_choice->unicharset(); STRING normed_choice_str; for (int i = 0; i < word_choice->length(); ++i) { normed_choice_str += uni_set->get_normed_unichar(word_choice->unichar_id(i)); } STRING truth_str = TruthString(); return truth_str == normed_choice_str; } void BlamerBundle::FillDebugString(const STRING &msg, const WERD_CHOICE *choice, STRING *debug) { (*debug) += "Truth "; for (int i = 0; i < this->truth_text_.length(); ++i) { (*debug) += this->truth_text_[i]; } if (!this->truth_has_char_boxes_) (*debug) += " (no char boxes)"; if (choice != NULL) { (*debug) += " Choice "; STRING choice_str; choice->string_and_lengths(&choice_str, NULL); (*debug) += choice_str; } if (msg.length() > 0) { (*debug) += "\n"; (*debug) += msg; } (*debug) += "\n"; } // Sets up the norm_truth_word from truth_word using the given DENORM. void BlamerBundle::SetupNormTruthWord(const DENORM& denorm) { // TODO(rays) Is this the last use of denorm in WERD_RES and can it go? norm_box_tolerance_ = kBlamerBoxTolerance * denorm.x_scale(); TPOINT topleft; TPOINT botright; TPOINT norm_topleft; TPOINT norm_botright; for (int b = 0; b < truth_word_.length(); ++b) { const TBOX &box = truth_word_.BlobBox(b); topleft.x = box.left(); topleft.y = box.top(); botright.x = box.right(); botright.y = box.bottom(); denorm.NormTransform(NULL, topleft, &norm_topleft); denorm.NormTransform(NULL, botright, &norm_botright); TBOX norm_box(norm_topleft.x, norm_botright.y, norm_botright.x, norm_topleft.y); norm_truth_word_.InsertBox(b, norm_box); } } // Splits *this into two pieces in bundle1 and bundle2 (preallocated, empty // bundles) where the right edge/ of the left-hand word is word1_right, // and the left edge of the right-hand word is word2_left. void BlamerBundle::SplitBundle(int word1_right, int word2_left, bool debug, BlamerBundle* bundle1, BlamerBundle* bundle2) const { STRING debug_str; // Find truth boxes that correspond to the split in the blobs. int b; int begin2_truth_index = -1; if (incorrect_result_reason_ != IRR_NO_TRUTH && truth_has_char_boxes_) { debug_str = "Looking for truth split at"; debug_str.add_str_int(" end1_x ", word1_right); debug_str.add_str_int(" begin2_x ", word2_left); debug_str += "\nnorm_truth_word boxes:\n"; if (norm_truth_word_.length() > 1) { norm_truth_word_.BlobBox(0).print_to_str(&debug_str); for (b = 1; b < norm_truth_word_.length(); ++b) { norm_truth_word_.BlobBox(b).print_to_str(&debug_str); if ((abs(word1_right - norm_truth_word_.BlobBox(b - 1).right()) < norm_box_tolerance_) && (abs(word2_left - norm_truth_word_.BlobBox(b).left()) < norm_box_tolerance_)) { begin2_truth_index = b; debug_str += "Split found"; break; } } debug_str += '\n'; } } // Populate truth information in word and word2 with the first and second // part of the original truth. if (begin2_truth_index > 0) { bundle1->truth_has_char_boxes_ = true; bundle1->norm_box_tolerance_ = norm_box_tolerance_; bundle2->truth_has_char_boxes_ = true; bundle2->norm_box_tolerance_ = norm_box_tolerance_; BlamerBundle *curr_bb = bundle1; for (b = 0; b < norm_truth_word_.length(); ++b) { if (b == begin2_truth_index) curr_bb = bundle2; curr_bb->norm_truth_word_.InsertBox(b, norm_truth_word_.BlobBox(b)); curr_bb->truth_word_.InsertBox(b, truth_word_.BlobBox(b)); curr_bb->truth_text_.push_back(truth_text_[b]); } } else if (incorrect_result_reason_ == IRR_NO_TRUTH) { bundle1->incorrect_result_reason_ = IRR_NO_TRUTH; bundle2->incorrect_result_reason_ = IRR_NO_TRUTH; } else { debug_str += "Truth split not found"; debug_str += truth_has_char_boxes_ ? "\n" : " (no truth char boxes)\n"; bundle1->SetBlame(IRR_NO_TRUTH_SPLIT, debug_str, NULL, debug); bundle2->SetBlame(IRR_NO_TRUTH_SPLIT, debug_str, NULL, debug); } } // "Joins" the blames from bundle1 and bundle2 into *this. void BlamerBundle::JoinBlames(const BlamerBundle& bundle1, const BlamerBundle& bundle2, bool debug) { STRING debug_str; IncorrectResultReason irr = incorrect_result_reason_; if (irr != IRR_NO_TRUTH_SPLIT) debug_str = ""; if (bundle1.incorrect_result_reason_ != IRR_CORRECT && bundle1.incorrect_result_reason_ != IRR_NO_TRUTH && bundle1.incorrect_result_reason_ != IRR_NO_TRUTH_SPLIT) { debug_str += "Blame from part 1: "; debug_str += bundle1.debug_; irr = bundle1.incorrect_result_reason_; } if (bundle2.incorrect_result_reason_ != IRR_CORRECT && bundle2.incorrect_result_reason_ != IRR_NO_TRUTH && bundle2.incorrect_result_reason_ != IRR_NO_TRUTH_SPLIT) { debug_str += "Blame from part 2: "; debug_str += bundle2.debug_; if (irr == IRR_CORRECT) { irr = bundle2.incorrect_result_reason_; } else if (irr != bundle2.incorrect_result_reason_) { irr = IRR_UNKNOWN; } } incorrect_result_reason_ = irr; if (irr != IRR_CORRECT && irr != IRR_NO_TRUTH) { SetBlame(irr, debug_str, NULL, debug); } } // If a blob with the same bounding box as one of the truth character // bounding boxes is not classified as the corresponding truth character // blames character classifier for incorrect answer. void BlamerBundle::BlameClassifier(const UNICHARSET& unicharset, const TBOX& blob_box, const BLOB_CHOICE_LIST& choices, bool debug) { if (!truth_has_char_boxes_ || incorrect_result_reason_ != IRR_CORRECT) return; // Nothing to do here. for (int b = 0; b < norm_truth_word_.length(); ++b) { const TBOX &truth_box = norm_truth_word_.BlobBox(b); // Note that we are more strict on the bounding box boundaries here // than in other places (chopper, segmentation search), since we do // not have the ability to check the previous and next bounding box. if (blob_box.x_almost_equal(truth_box, norm_box_tolerance_/2)) { bool found = false; bool incorrect_adapted = false; UNICHAR_ID incorrect_adapted_id = INVALID_UNICHAR_ID; const char *truth_str = truth_text_[b].string(); // We promise not to modify the list or its contents, using a // const BLOB_CHOICE* below. BLOB_CHOICE_IT choices_it(const_cast<BLOB_CHOICE_LIST*>(&choices)); for (choices_it.mark_cycle_pt(); !choices_it.cycled_list(); choices_it.forward()) { const BLOB_CHOICE* choice = choices_it.data(); if (strcmp(truth_str, unicharset.get_normed_unichar( choice->unichar_id())) == 0) { found = true; break; } else if (choice->IsAdapted()) { incorrect_adapted = true; incorrect_adapted_id = choice->unichar_id(); } } // end choices_it for loop if (!found) { STRING debug_str = "unichar "; debug_str += truth_str; debug_str += " not found in classification list"; SetBlame(IRR_CLASSIFIER, debug_str, NULL, debug); } else if (incorrect_adapted) { STRING debug_str = "better rating for adapted "; debug_str += unicharset.id_to_unichar(incorrect_adapted_id); debug_str += " than for correct "; debug_str += truth_str; SetBlame(IRR_ADAPTION, debug_str, NULL, debug); } break; } } // end iterating over blamer_bundle->norm_truth_word } // Checks whether chops were made at all the character bounding box // boundaries in word->truth_word. If not - blames the chopper for an // incorrect answer. void BlamerBundle::SetChopperBlame(const WERD_RES* word, bool debug) { if (NoTruth() || !truth_has_char_boxes_ || word->chopped_word->blobs.empty()) { return; } STRING debug_str; bool missing_chop = false; int num_blobs = word->chopped_word->blobs.size(); int box_index = 0; int blob_index = 0; inT16 truth_x; while (box_index < truth_word_.length() && blob_index < num_blobs) { truth_x = norm_truth_word_.BlobBox(box_index).right(); TBLOB * curr_blob = word->chopped_word->blobs[blob_index]; if (curr_blob->bounding_box().right() < truth_x - norm_box_tolerance_) { ++blob_index; continue; // encountered an extra chop, keep looking } else if (curr_blob->bounding_box().right() > truth_x + norm_box_tolerance_) { missing_chop = true; break; } else { ++blob_index; } } if (missing_chop || box_index < norm_truth_word_.length()) { STRING debug_str; if (missing_chop) { debug_str.add_str_int("Detected missing chop (tolerance=", norm_box_tolerance_); debug_str += ") at Bounding Box="; TBLOB * curr_blob = word->chopped_word->blobs[blob_index]; curr_blob->bounding_box().print_to_str(&debug_str); debug_str.add_str_int("\nNo chop for truth at x=", truth_x); } else { debug_str.add_str_int("Missing chops for last ", norm_truth_word_.length() - box_index); debug_str += " truth box(es)"; } debug_str += "\nMaximally chopped word boxes:\n"; for (blob_index = 0; blob_index < num_blobs; ++blob_index) { TBLOB * curr_blob = word->chopped_word->blobs[blob_index]; curr_blob->bounding_box().print_to_str(&debug_str); debug_str += '\n'; } debug_str += "Truth bounding boxes:\n"; for (box_index = 0; box_index < norm_truth_word_.length(); ++box_index) { norm_truth_word_.BlobBox(box_index).print_to_str(&debug_str); debug_str += '\n'; } SetBlame(IRR_CHOPPER, debug_str, word->best_choice, debug); } } // Blames the classifier or the language model if, after running only the // chopper, best_choice is incorrect and no blame has been yet set. // Blames the classifier if best_choice is classifier's top choice and is a // dictionary word (i.e. language model could not have helped). // Otherwise, blames the language model (formerly permuter word adjustment). void BlamerBundle::BlameClassifierOrLangModel( const WERD_RES* word, const UNICHARSET& unicharset, bool valid_permuter, bool debug) { if (valid_permuter) { // Find out whether best choice is a top choice. best_choice_is_dict_and_top_choice_ = true; for (int i = 0; i < word->best_choice->length(); ++i) { BLOB_CHOICE_IT blob_choice_it(word->GetBlobChoices(i)); ASSERT_HOST(!blob_choice_it.empty()); BLOB_CHOICE *first_choice = NULL; for (blob_choice_it.mark_cycle_pt(); !blob_choice_it.cycled_list(); blob_choice_it.forward()) { // find first non-fragment choice if (!(unicharset.get_fragment(blob_choice_it.data()->unichar_id()))) { first_choice = blob_choice_it.data(); break; } } ASSERT_HOST(first_choice != NULL); if (first_choice->unichar_id() != word->best_choice->unichar_id(i)) { best_choice_is_dict_and_top_choice_ = false; break; } } } STRING debug_str; if (best_choice_is_dict_and_top_choice_) { debug_str = "Best choice is: incorrect, top choice, dictionary word"; debug_str += " with permuter "; debug_str += word->best_choice->permuter_name(); } else { debug_str = "Classifier/Old LM tradeoff is to blame"; } SetBlame(best_choice_is_dict_and_top_choice_ ? IRR_CLASSIFIER : IRR_CLASS_OLD_LM_TRADEOFF, debug_str, word->best_choice, debug); } // Sets up the correct_segmentation_* to mark the correct bounding boxes. void BlamerBundle::SetupCorrectSegmentation(const TWERD* word, bool debug) { params_training_bundle_.StartHypothesisList(); if (incorrect_result_reason_ != IRR_CORRECT || !truth_has_char_boxes_) return; // Nothing to do here. STRING debug_str; debug_str += "Blamer computing correct_segmentation_cols\n"; int curr_box_col = 0; int next_box_col = 0; int num_blobs = word->NumBlobs(); if (num_blobs == 0) return; // No blobs to play with. int blob_index = 0; inT16 next_box_x = word->blobs[blob_index]->bounding_box().right(); for (int truth_idx = 0; blob_index < num_blobs && truth_idx < norm_truth_word_.length(); ++blob_index) { ++next_box_col; inT16 curr_box_x = next_box_x; if (blob_index + 1 < num_blobs) next_box_x = word->blobs[blob_index + 1]->bounding_box().right(); inT16 truth_x = norm_truth_word_.BlobBox(truth_idx).right(); debug_str.add_str_int("Box x coord vs. truth: ", curr_box_x); debug_str.add_str_int(" ", truth_x); debug_str += "\n"; if (curr_box_x > (truth_x + norm_box_tolerance_)) { break; // failed to find a matching box } else if (curr_box_x >= truth_x - norm_box_tolerance_ && // matched (blob_index + 1 >= num_blobs || // next box can't be included next_box_x > truth_x + norm_box_tolerance_)) { correct_segmentation_cols_.push_back(curr_box_col); correct_segmentation_rows_.push_back(next_box_col-1); ++truth_idx; debug_str.add_str_int("col=", curr_box_col); debug_str.add_str_int(" row=", next_box_col-1); debug_str += "\n"; curr_box_col = next_box_col; } } if (blob_index < num_blobs || // trailing blobs correct_segmentation_cols_.length() != norm_truth_word_.length()) { debug_str.add_str_int("Blamer failed to find correct segmentation" " (tolerance=", norm_box_tolerance_); if (blob_index >= num_blobs) debug_str += " blob == NULL"; debug_str += ")\n"; debug_str.add_str_int(" path length ", correct_segmentation_cols_.length()); debug_str.add_str_int(" vs. truth ", norm_truth_word_.length()); debug_str += "\n"; SetBlame(IRR_UNKNOWN, debug_str, NULL, debug); correct_segmentation_cols_.clear(); correct_segmentation_rows_.clear(); } } // Returns true if a guided segmentation search is needed. bool BlamerBundle::GuidedSegsearchNeeded(const WERD_CHOICE *best_choice) const { return incorrect_result_reason_ == IRR_CORRECT && !segsearch_is_looking_for_blame_ && truth_has_char_boxes_ && !ChoiceIsCorrect(best_choice); } // Setup ready to guide the segmentation search to the correct segmentation. // The callback pp_cb is used to avoid a cyclic dependency. // It calls into LMPainPoints::GenerateForBlamer by pre-binding the // WERD_RES, and the LMPainPoints itself. // pp_cb must be a permanent callback, and should be deleted by the caller. void BlamerBundle::InitForSegSearch(const WERD_CHOICE *best_choice, MATRIX* ratings, UNICHAR_ID wildcard_id, bool debug, STRING *debug_str, TessResultCallback2<bool, int, int>* cb) { segsearch_is_looking_for_blame_ = true; if (debug) { tprintf("segsearch starting to look for blame\n"); } // Fill pain points for any unclassifed blob corresponding to the // correct segmentation state. *debug_str += "Correct segmentation:\n"; for (int idx = 0; idx < correct_segmentation_cols_.length(); ++idx) { debug_str->add_str_int("col=", correct_segmentation_cols_[idx]); debug_str->add_str_int(" row=", correct_segmentation_rows_[idx]); *debug_str += "\n"; if (!ratings->Classified(correct_segmentation_cols_[idx], correct_segmentation_rows_[idx], wildcard_id) && !cb->Run(correct_segmentation_cols_[idx], correct_segmentation_rows_[idx])) { segsearch_is_looking_for_blame_ = false; *debug_str += "\nFailed to insert pain point\n"; SetBlame(IRR_SEGSEARCH_HEUR, *debug_str, best_choice, debug); break; } } // end for blamer_bundle->correct_segmentation_cols/rows } // Returns true if the guided segsearch is in progress. bool BlamerBundle::GuidedSegsearchStillGoing() const { return segsearch_is_looking_for_blame_; } // The segmentation search has ended. Sets the blame appropriately. void BlamerBundle::FinishSegSearch(const WERD_CHOICE *best_choice, bool debug, STRING *debug_str) { // If we are still looking for blame (i.e. best_choice is incorrect, but a // path representing the correct segmentation could be constructed), we can // blame segmentation search pain point prioritization if the rating of the // path corresponding to the correct segmentation is better than that of // best_choice (i.e. language model would have done the correct thing, but // because of poor pain point prioritization the correct segmentation was // never explored). Otherwise we blame the tradeoff between the language model // and the classifier, since even after exploring the path corresponding to // the correct segmentation incorrect best_choice would have been chosen. // One special case when we blame the classifier instead is when best choice // is incorrect, but it is a dictionary word and it classifier's top choice. if (segsearch_is_looking_for_blame_) { segsearch_is_looking_for_blame_ = false; if (best_choice_is_dict_and_top_choice_) { *debug_str = "Best choice is: incorrect, top choice, dictionary word"; *debug_str += " with permuter "; *debug_str += best_choice->permuter_name(); SetBlame(IRR_CLASSIFIER, *debug_str, best_choice, debug); } else if (best_correctly_segmented_rating_ < best_choice->rating()) { *debug_str += "Correct segmentation state was not explored"; SetBlame(IRR_SEGSEARCH_PP, *debug_str, best_choice, debug); } else { if (best_correctly_segmented_rating_ >= WERD_CHOICE::kBadRating) { *debug_str += "Correct segmentation paths were pruned by LM\n"; } else { debug_str->add_str_double("Best correct segmentation rating ", best_correctly_segmented_rating_); debug_str->add_str_double(" vs. best choice rating ", best_choice->rating()); } SetBlame(IRR_CLASS_LM_TRADEOFF, *debug_str, best_choice, debug); } } } // If the bundle is null or still does not indicate the correct result, // fix it and use some backup reason for the blame. void BlamerBundle::LastChanceBlame(bool debug, WERD_RES* word) { if (word->blamer_bundle == NULL) { word->blamer_bundle = new BlamerBundle(); word->blamer_bundle->SetBlame(IRR_PAGE_LAYOUT, "LastChanceBlame", word->best_choice, debug); } else if (word->blamer_bundle->incorrect_result_reason_ == IRR_NO_TRUTH) { word->blamer_bundle->SetBlame(IRR_NO_TRUTH, "Rejected truth", word->best_choice, debug); } else { bool correct = word->blamer_bundle->ChoiceIsCorrect(word->best_choice); IncorrectResultReason irr = word->blamer_bundle->incorrect_result_reason_; if (irr == IRR_CORRECT && !correct) { STRING debug_str = "Choice is incorrect after recognition"; word->blamer_bundle->SetBlame(IRR_UNKNOWN, debug_str, word->best_choice, debug); } else if (irr != IRR_CORRECT && correct) { if (debug) { tprintf("Corrected %s\n", word->blamer_bundle->debug_.string()); } word->blamer_bundle->incorrect_result_reason_ = IRR_CORRECT; word->blamer_bundle->debug_ = ""; } } } // Sets the misadaption debug if this word is incorrect, as this word is // being adapted to. void BlamerBundle::SetMisAdaptionDebug(const WERD_CHOICE *best_choice, bool debug) { if (incorrect_result_reason_ != IRR_NO_TRUTH && !ChoiceIsCorrect(best_choice)) { misadaption_debug_ ="misadapt to word ("; misadaption_debug_ += best_choice->permuter_name(); misadaption_debug_ += "): "; FillDebugString("", best_choice, &misadaption_debug_); if (debug) { tprintf("%s\n", misadaption_debug_.string()); } } }
1080228-arabicocr11
ccstruct/blamer.cpp
C++
asf20
24,529
/* -*-C-*- ******************************************************************************** * * File: seam.h (Formerly seam.h) * Description: * Author: Mark Seaman, SW Productivity * Created: Fri Oct 16 14:37:00 1987 * Modified: Thu May 16 17:05:52 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ #ifndef SEAM_H #define SEAM_H /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "blobs.h" #include "split.h" /*---------------------------------------------------------------------- T y p e s ----------------------------------------------------------------------*/ typedef float PRIORITY; /* PRIORITY */ struct SEAM { // Constructor that was formerly new_seam. SEAM(PRIORITY priority0, const TPOINT& location0, SPLIT *splita, SPLIT *splitb, SPLIT *splitc) : priority(priority0), widthp(0), widthn(0), location(location0), split1(splita), split2(splitb), split3(splitc) {} // Copy constructor that was formerly clone_seam. SEAM(const SEAM& src) : priority(src.priority), widthp(src.widthp), widthn(src.widthn), location(src.location) { clone_split(split1, src.split1); clone_split(split2, src.split2); clone_split(split3, src.split3); } // Destructor was delete_seam. ~SEAM() { if (split1) delete_split(split1); if (split2) delete_split(split2); if (split3) delete_split(split3); } PRIORITY priority; inT8 widthp; inT8 widthn; TPOINT location; SPLIT *split1; SPLIT *split2; SPLIT *split3; }; /** * exact_point * * Return TRUE if the point positions are the exactly the same. The * parameters must be of type (EDGEPT*). */ #define exact_point(p1,p2) \ (! ((p1->pos.x - p2->pos.x) || (p1->pos.y - p2->pos.y))) /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ bool point_in_split(SPLIT *split, EDGEPT *point1, EDGEPT *point2); bool point_in_seam(const SEAM *seam, SPLIT *split); bool point_used_by_split(SPLIT *split, EDGEPT *point); bool point_used_by_seam(SEAM *seam, EDGEPT *point); void combine_seams(SEAM *dest_seam, SEAM *source_seam); void start_seam_list(TWERD *word, GenericVector<SEAM*>* seam_array); bool test_insert_seam(const GenericVector<SEAM*>& seam_array, TWERD *word, int index); void insert_seam(const TWERD *word, int index, SEAM *seam, GenericVector<SEAM*>* seam_array); int account_splits(const SEAM *seam, const TWERD *word, int blob_index, int blob_direction); bool find_split_in_blob(SPLIT *split, TBLOB *blob); SEAM *join_two_seams(const SEAM *seam1, const SEAM *seam2); void print_seam(const char *label, SEAM *seam); void print_seams(const char *label, const GenericVector<SEAM*>& seams); int shared_split_points(const SEAM *seam1, const SEAM *seam2); void break_pieces(const GenericVector<SEAM*>& seams, int first, int last, TWERD *word); void join_pieces(const GenericVector<SEAM*>& seams, int first, int last, TWERD *word); void hide_seam(SEAM *seam); void hide_edge_pair(EDGEPT *pt1, EDGEPT *pt2); void reveal_seam(SEAM *seam); void reveal_edge_pair(EDGEPT *pt1, EDGEPT *pt2); #endif
1080228-arabicocr11
ccstruct/seam.h
C
asf20
4,232
#ifndef HPDSIZES_H #define HPDSIZES_H #define NUM_TEXT_ATTR 10 #define NUM_BLOCK_ATTR 7 #define MAXLENGTH 128 #define NUM_BACKGROUNDS 8 #endif
1080228-arabicocr11
ccstruct/hpdsizes.h
C
asf20
170
/////////////////////////////////////////////////////////////////////// // File: detlinefit.cpp // Description: Deterministic least median squares line fitting. // Author: Ray Smith // Created: Thu Feb 28 14:45:01 PDT 2008 // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "detlinefit.h" #include "statistc.h" #include "ndminx.h" #include "tprintf.h" namespace tesseract { // The number of points to consider at each end. const int kNumEndPoints = 3; // The minimum number of points at which to switch to number of points // for badly fitted lines. // To ensure a sensible error metric, kMinPointsForErrorCount should be at // least kMaxRealDistance / (1 - %ile) where %ile is the fractile used in // ComputeUpperQuartileError. const int kMinPointsForErrorCount = 16; // The maximum real distance to use before switching to number of // mis-fitted points, which will get square-rooted for true distance. const int kMaxRealDistance = 2.0; DetLineFit::DetLineFit() : square_length_(0.0) { } DetLineFit::~DetLineFit() { } // Delete all Added points. void DetLineFit::Clear() { pts_.clear(); distances_.clear(); } // Add a new point. Takes a copy - the pt doesn't need to stay in scope. void DetLineFit::Add(const ICOORD& pt) { pts_.push_back(PointWidth(pt, 0)); } // Associates a half-width with the given point if a point overlaps the // previous point by more than half the width, and its distance is further // than the previous point, then the more distant point is ignored in the // distance calculation. Useful for ignoring i dots and other diacritics. void DetLineFit::Add(const ICOORD& pt, int halfwidth) { pts_.push_back(PointWidth(pt, halfwidth)); } // Fits a line to the points, ignoring the skip_first initial points and the // skip_last final points, returning the fitted line as a pair of points, // and the upper quartile error. double DetLineFit::Fit(int skip_first, int skip_last, ICOORD* pt1, ICOORD* pt2) { // Do something sensible with no points. if (pts_.empty()) { pt1->set_x(0); pt1->set_y(0); *pt2 = *pt1; return 0.0; } // Count the points and find the first and last kNumEndPoints. int pt_count = pts_.size(); ICOORD* starts[kNumEndPoints]; if (skip_first >= pt_count) skip_first = pt_count - 1; int start_count = 0; int end_i = MIN(skip_first + kNumEndPoints, pt_count); for (int i = skip_first; i < end_i; ++i) { starts[start_count++] = &pts_[i].pt; } ICOORD* ends[kNumEndPoints]; if (skip_last >= pt_count) skip_last = pt_count - 1; int end_count = 0; end_i = MAX(0, pt_count - kNumEndPoints - skip_last); for (int i = pt_count - 1 - skip_last; i >= end_i; --i) { ends[end_count++] = &pts_[i].pt; } // 1 or 2 points need special treatment. if (pt_count <= 2) { *pt1 = *starts[0]; if (pt_count > 1) *pt2 = *ends[0]; else *pt2 = *pt1; return 0.0; } // Although with between 2 and 2*kNumEndPoints-1 points, there will be // overlap in the starts, ends sets, this is OK and taken care of by the // if (*start != *end) test below, which also tests for equal input points. double best_uq = -1.0; // Iterate each pair of points and find the best fitting line. for (int i = 0; i < start_count; ++i) { ICOORD* start = starts[i]; for (int j = 0; j < end_count; ++j) { ICOORD* end = ends[j]; if (*start != *end) { ComputeDistances(*start, *end); // Compute the upper quartile error from the line. double dist = EvaluateLineFit(); if (dist < best_uq || best_uq < 0.0) { best_uq = dist; *pt1 = *start; *pt2 = *end; } } } } // Finally compute the square root to return the true distance. return best_uq > 0.0 ? sqrt(best_uq) : best_uq; } // Constrained fit with a supplied direction vector. Finds the best line_pt, // that is one of the supplied points having the median cross product with // direction, ignoring points that have a cross product outside of the range // [min_dist, max_dist]. Returns the resulting error metric using the same // reduced set of points. // *Makes use of floating point arithmetic* double DetLineFit::ConstrainedFit(const FCOORD& direction, double min_dist, double max_dist, bool debug, ICOORD* line_pt) { ComputeConstrainedDistances(direction, min_dist, max_dist); // Do something sensible with no points or computed distances. if (pts_.empty() || distances_.empty()) { line_pt->set_x(0); line_pt->set_y(0); return 0.0; } int median_index = distances_.choose_nth_item(distances_.size() / 2); *line_pt = distances_[median_index].data; if (debug) { tprintf("Constrained fit to dir %g, %g = %d, %d :%d distances:\n", direction.x(), direction.y(), line_pt->x(), line_pt->y(), distances_.size()); for (int i = 0; i < distances_.size(); ++i) { tprintf("%d: %d, %d -> %g\n", i, distances_[i].data.x(), distances_[i].data.y(), distances_[i].key); } tprintf("Result = %d\n", median_index); } // Center distances on the fitted point. double dist_origin = direction * *line_pt; for (int i = 0; i < distances_.size(); ++i) { distances_[i].key -= dist_origin; } return sqrt(EvaluateLineFit()); } // Returns true if there were enough points at the last call to Fit or // ConstrainedFit for the fitted points to be used on a badly fitted line. bool DetLineFit::SufficientPointsForIndependentFit() const { return distances_.size() >= kMinPointsForErrorCount; } // Backwards compatible fit returning a gradient and constant. // Deprecated. Prefer Fit(ICOORD*, ICOORD*) where possible, but use this // function in preference to the LMS class. double DetLineFit::Fit(float* m, float* c) { ICOORD start, end; double error = Fit(&start, &end); if (end.x() != start.x()) { *m = static_cast<float>(end.y() - start.y()) / (end.x() - start.x()); *c = start.y() - *m * start.x(); } else { *m = 0.0f; *c = 0.0f; } return error; } // Backwards compatible constrained fit with a supplied gradient. // Deprecated. Use ConstrainedFit(const FCOORD& direction) where possible // to avoid potential difficulties with infinite gradients. double DetLineFit::ConstrainedFit(double m, float* c) { // Do something sensible with no points. if (pts_.empty()) { *c = 0.0f; return 0.0; } double cos = 1.0 / sqrt(1.0 + m * m); FCOORD direction(cos, m * cos); ICOORD line_pt; double error = ConstrainedFit(direction, -MAX_FLOAT32, MAX_FLOAT32, false, &line_pt); *c = line_pt.y() - line_pt.x() * m; return error; } // Computes and returns the squared evaluation metric for a line fit. double DetLineFit::EvaluateLineFit() { // Compute the upper quartile error from the line. double dist = ComputeUpperQuartileError(); if (distances_.size() >= kMinPointsForErrorCount && dist > kMaxRealDistance * kMaxRealDistance) { // Use the number of mis-fitted points as the error metric, as this // gives a better measure of fit for badly fitted lines where more // than a quarter are badly fitted. double threshold = kMaxRealDistance * sqrt(square_length_); dist = NumberOfMisfittedPoints(threshold); } return dist; } // Computes the absolute error distances of the points from the line, // and returns the squared upper-quartile error distance. double DetLineFit::ComputeUpperQuartileError() { int num_errors = distances_.size(); if (num_errors == 0) return 0.0; // Get the absolute values of the errors. for (int i = 0; i < num_errors; ++i) { if (distances_[i].key < 0) distances_[i].key = -distances_[i].key; } // Now get the upper quartile distance. int index = distances_.choose_nth_item(3 * num_errors / 4); double dist = distances_[index].key; // The true distance is the square root of the dist squared / square_length. // Don't bother with the square root. Just return the square distance. return square_length_ > 0.0 ? dist * dist / square_length_ : 0.0; } // Returns the number of sample points that have an error more than threshold. int DetLineFit::NumberOfMisfittedPoints(double threshold) const { int num_misfits = 0; int num_dists = distances_.size(); // Get the absolute values of the errors. for (int i = 0; i < num_dists; ++i) { if (distances_[i].key > threshold) ++num_misfits; } return num_misfits; } // Computes all the cross product distances of the points from the line, // storing the actual (signed) cross products in distances. // Ignores distances of points that are further away than the previous point, // and overlaps the previous point by at least half. void DetLineFit::ComputeDistances(const ICOORD& start, const ICOORD& end) { distances_.truncate(0); ICOORD line_vector = end; line_vector -= start; square_length_ = line_vector.sqlength(); int line_length = IntCastRounded(sqrt(square_length_)); // Compute the distance of each point from the line. int prev_abs_dist = 0; int prev_dot = 0; for (int i = 0; i < pts_.size(); ++i) { ICOORD pt_vector = pts_[i].pt; pt_vector -= start; int dot = line_vector % pt_vector; // Compute |line_vector||pt_vector|sin(angle between) int dist = line_vector * pt_vector; int abs_dist = dist < 0 ? -dist : dist; if (abs_dist > prev_abs_dist && i > 0) { // Ignore this point if it overlaps the previous one. int separation = abs(dot - prev_dot); if (separation < line_length * pts_[i].halfwidth || separation < line_length * pts_[i - 1].halfwidth) continue; } distances_.push_back(DistPointPair(dist, pts_[i].pt)); prev_abs_dist = abs_dist; prev_dot = dot; } } // Computes all the cross product distances of the points perpendicular to // the given direction, ignoring distances outside of the give distance range, // storing the actual (signed) cross products in distances_. void DetLineFit::ComputeConstrainedDistances(const FCOORD& direction, double min_dist, double max_dist) { distances_.truncate(0); square_length_ = direction.sqlength(); // Compute the distance of each point from the line. for (int i = 0; i < pts_.size(); ++i) { FCOORD pt_vector = pts_[i].pt; // Compute |line_vector||pt_vector|sin(angle between) double dist = direction * pt_vector; if (min_dist <= dist && dist <= max_dist) distances_.push_back(DistPointPair(dist, pts_[i].pt)); } } } // namespace tesseract.
1080228-arabicocr11
ccstruct/detlinefit.cpp
C++
asf20
11,252
/********************************************************************** * File: genblob.cpp (Formerly gblob.c) * Description: Generic Blob processing routines * Author: Phil Cheatle * Created: Mon Nov 25 10:53:26 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "genblob.h" #include "stepblob.h" /********************************************************************** * c_blob_comparator() * * Blob comparator used to sort a blob list so that blobs are in increasing * order of left edge. **********************************************************************/ int c_blob_comparator( // sort blobs const void *blob1p, // ptr to ptr to blob1 const void *blob2p // ptr to ptr to blob2 ) { C_BLOB *blob1 = *(C_BLOB **) blob1p; C_BLOB *blob2 = *(C_BLOB **) blob2p; return blob1->bounding_box ().left () - blob2->bounding_box ().left (); }
1080228-arabicocr11
ccstruct/genblob.cpp
C++
asf20
1,626
/********************************************************************** * File: blckerr.h (Formerly blockerr.h) * Description: Error codes for the page block classes. * Author: Ray Smith * Created: Tue Mar 19 17:43:30 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef BLCKERR_H #define BLCKERR_H #include "errcode.h" const ERRCODE BADBLOCKLINE = "Y coordinate in block out of bounds"; const ERRCODE LOSTBLOCKLINE = "Can't find rectangle for line"; const ERRCODE ILLEGAL_GRADIENT = "Gradient wrong side of edge step!"; const ERRCODE WRONG_WORD = "Word doesn't have blobs of that type"; #endif
1080228-arabicocr11
ccstruct/blckerr.h
C
asf20
1,288
/********************************************************************** * File: mod128.c (Formerly dir128.c) * Description: Code to convert a DIR128 to an ICOORD. * Author: Ray Smith * Created: Tue Oct 22 11:56:09 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "mod128.h" const inT16 idirtab[] = { 1000, 0, 998, 49, 995, 98, 989, 146, 980, 195, 970, 242, 956, 290, 941, 336, 923, 382, 903, 427, 881, 471, 857, 514, 831, 555, 803, 595, 773, 634, 740, 671, 707, 707, 671, 740, 634, 773, 595, 803, 555, 831, 514, 857, 471, 881, 427, 903, 382, 923, 336, 941, 290, 956, 242, 970, 195, 980, 146, 989, 98, 995, 49, 998, 0, 1000, -49, 998, -98, 995, -146, 989, -195, 980, -242, 970, -290, 956, -336, 941, -382, 923, -427, 903, -471, 881, -514, 857, -555, 831, -595, 803, -634, 773, -671, 740, -707, 707, -740, 671, -773, 634, -803, 595, -831, 555, -857, 514, -881, 471, -903, 427, -923, 382, -941, 336, -956, 290, -970, 242, -980, 195, -989, 146, -995, 98, -998, 49, -1000, 0, -998, -49, -995, -98, -989, -146, -980, -195, -970, -242, -956, -290, -941, -336, -923, -382, -903, -427, -881, -471, -857, -514, -831, -555, -803, -595, -773, -634, -740, -671, -707, -707, -671, -740, -634, -773, -595, -803, -555, -831, -514, -857, -471, -881, -427, -903, -382, -923, -336, -941, -290, -956, -242, -970, -195, -980, -146, -989, -98, -995, -49, -998, 0, -1000, 49, -998, 98, -995, 146, -989, 195, -980, 242, -970, 290, -956, 336, -941, 382, -923, 427, -903, 471, -881, 514, -857, 555, -831, 595, -803, 634, -773, 671, -740, 707, -707, 740, -671, 773, -634, 803, -595, 831, -555, 857, -514, 881, -471, 903, -427, 923, -382, 941, -336, 956, -290, 970, -242, 980, -195, 989, -146, 995, -98, 998, -49 }; const ICOORD *dirtab = (ICOORD *) idirtab; /********************************************************************** * DIR128::DIR128 * * Quantize the direction of an FCOORD to make a DIR128. **********************************************************************/ DIR128::DIR128( //from fcoord const FCOORD fc //vector to quantize ) { int high, low, current; //binary search low = 0; if (fc.y () == 0) { if (fc.x () >= 0) dir = 0; else dir = MODULUS / 2; return; } high = MODULUS; do { current = (high + low) / 2; if (dirtab[current] * fc >= 0) low = current; else high = current; } while (high - low > 1); dir = low; } /********************************************************************** * dir_to_gradient * * Convert a direction to a vector. **********************************************************************/ ICOORD DIR128::vector() const { //convert to vector return dirtab[dir]; //easy really }
1080228-arabicocr11
ccstruct/mod128.cpp
C++
asf20
3,482
/////////////////////////////////////////////////////////////////////// // File: params_training_featdef.h // Description: Feature definitions for params training. // Author: Rika Antonova // Created: Mon Nov 28 11:26:42 PDT 2011 // // (C) Copyright 2011, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_WORDREC_PARAMS_TRAINING_FEATDEF_H_ #define TESSERACT_WORDREC_PARAMS_TRAINING_FEATDEF_H_ #include "genericvector.h" #include "strngs.h" namespace tesseract { // Maximum number of unichars in the small and medium sized words static const int kMaxSmallWordUnichars = 3; static const int kMaxMediumWordUnichars = 6; // Raw features extracted from a single OCR hypothesis. // The features are normalized (by outline length or number of unichars as // appropriate) real-valued quantities with unbounded range and // unknown distribution. // Normalization / binarization of these features is done at a later stage. // Note: when adding new fields to this enum make sure to modify // kParamsTrainingFeatureTypeName enum kParamsTrainingFeatureType { // Digits PTRAIN_DIGITS_SHORT, // 0 PTRAIN_DIGITS_MED, // 1 PTRAIN_DIGITS_LONG, // 2 // Number or pattern (NUMBER_PERM, USER_PATTERN_PERM) PTRAIN_NUM_SHORT, // 3 PTRAIN_NUM_MED, // 4 PTRAIN_NUM_LONG, // 5 // Document word (DOC_DAWG_PERM) PTRAIN_DOC_SHORT, // 6 PTRAIN_DOC_MED, // 7 PTRAIN_DOC_LONG, // 8 // Word (SYSTEM_DAWG_PERM, USER_DAWG_PERM, COMPOUND_PERM) PTRAIN_DICT_SHORT, // 9 PTRAIN_DICT_MED, // 10 PTRAIN_DICT_LONG, // 11 // Frequent word (FREQ_DAWG_PERM) PTRAIN_FREQ_SHORT, // 12 PTRAIN_FREQ_MED, // 13 PTRAIN_FREQ_LONG, // 14 PTRAIN_SHAPE_COST_PER_CHAR, // 15 PTRAIN_NGRAM_COST_PER_CHAR, // 16 PTRAIN_NUM_BAD_PUNC, // 17 PTRAIN_NUM_BAD_CASE, // 18 PTRAIN_XHEIGHT_CONSISTENCY, // 19 PTRAIN_NUM_BAD_CHAR_TYPE, // 20 PTRAIN_NUM_BAD_SPACING, // 21 PTRAIN_NUM_BAD_FONT, // 22 PTRAIN_RATING_PER_CHAR, // 23 PTRAIN_NUM_FEATURE_TYPES }; static const char * const kParamsTrainingFeatureTypeName[] = { "PTRAIN_DIGITS_SHORT", // 0 "PTRAIN_DIGITS_MED", // 1 "PTRAIN_DIGITS_LONG", // 2 "PTRAIN_NUM_SHORT", // 3 "PTRAIN_NUM_MED", // 4 "PTRAIN_NUM_LONG", // 5 "PTRAIN_DOC_SHORT", // 6 "PTRAIN_DOC_MED", // 7 "PTRAIN_DOC_LONG", // 8 "PTRAIN_DICT_SHORT", // 9 "PTRAIN_DICT_MED", // 10 "PTRAIN_DICT_LONG", // 11 "PTRAIN_FREQ_SHORT", // 12 "PTRAIN_FREQ_MED", // 13 "PTRAIN_FREQ_LONG", // 14 "PTRAIN_SHAPE_COST_PER_CHAR", // 15 "PTRAIN_NGRAM_COST_PER_CHAR", // 16 "PTRAIN_NUM_BAD_PUNC", // 17 "PTRAIN_NUM_BAD_CASE", // 18 "PTRAIN_XHEIGHT_CONSISTENCY", // 19 "PTRAIN_NUM_BAD_CHAR_TYPE", // 20 "PTRAIN_NUM_BAD_SPACING", // 21 "PTRAIN_NUM_BAD_FONT", // 22 "PTRAIN_RATING_PER_CHAR", // 23 }; // Returns the index of the given feature (by name), // or -1 meaning the feature is unknown. int ParamsTrainingFeatureByName(const char *name); // Entry with features extracted from a single OCR hypothesis for a word. struct ParamsTrainingHypothesis { ParamsTrainingHypothesis() : cost(0.0) { memset(features, 0, sizeof(float) * PTRAIN_NUM_FEATURE_TYPES); } ParamsTrainingHypothesis(const ParamsTrainingHypothesis &other) { memcpy(features, other.features, sizeof(float) * PTRAIN_NUM_FEATURE_TYPES); str = other.str; cost = other.cost; } float features[PTRAIN_NUM_FEATURE_TYPES]; STRING str; // string corresponding to word hypothesis (for debugging) float cost; // path cost computed by segsearch }; // A list of hypotheses explored during one run of segmentation search. typedef GenericVector<ParamsTrainingHypothesis> ParamsTrainingHypothesisList; // A bundle that accumulates all of the hypothesis lists explored during all // of the runs of segmentation search on a word (e.g. a list of hypotheses // explored on PASS1, PASS2, fix xheight pass, etc). class ParamsTrainingBundle { public: ParamsTrainingBundle() {}; // Starts a new hypothesis list. // Should be called at the beginning of a new run of the segmentation search. void StartHypothesisList() { hyp_list_vec.push_back(ParamsTrainingHypothesisList()); } // Adds a new ParamsTrainingHypothesis to the current hypothesis list // and returns the reference to the newly added entry. ParamsTrainingHypothesis &AddHypothesis( const ParamsTrainingHypothesis &other) { if (hyp_list_vec.empty()) StartHypothesisList(); hyp_list_vec.back().push_back(ParamsTrainingHypothesis(other)); return hyp_list_vec.back().back(); } GenericVector<ParamsTrainingHypothesisList> hyp_list_vec; }; } // namespace tesseract #endif // TESSERACT_WORDREC_PARAMS_TRAINING_FEATDEF_H_
1080228-arabicocr11
ccstruct/params_training_featdef.h
C++
asf20
5,922
/////////////////////////////////////////////////////////////////////// // File: ccstruct.h // Description: ccstruct class. // Author: Samuel Charron // // (C) Copyright 2006, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCSTRUCT_CCSTRUCT_H__ #define TESSERACT_CCSTRUCT_CCSTRUCT_H__ #include "cutil.h" namespace tesseract { class CCStruct : public CUtil { public: CCStruct(); ~CCStruct(); // Globally accessible constants. // APPROXIMATIONS of the fractions of the character cell taken by // the descenders, ascenders, and x-height. static const double kDescenderFraction; // = 0.25; static const double kXHeightFraction; // = 0.5; static const double kAscenderFraction; // = 0.25; // Derived value giving the x-height as a fraction of cap-height. static const double kXHeightCapRatio; // = XHeight/(XHeight + Ascender). }; class Tesseract; } // namespace tesseract #endif // TESSERACT_CCSTRUCT_CCSTRUCT_H__
1080228-arabicocr11
ccstruct/ccstruct.h
C++
asf20
1,564
/* -*-C-*- ****************************************************************************** * * File: matrix.h (Formerly matrix.h) * Description: Ratings matrix code. (Used by associator) * Author: Mark Seaman, OCR Technology * Created: Wed May 16 13:22:06 1990 * Modified: Tue Mar 19 16:00:20 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1990, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ #ifndef TESSERACT_CCSTRUCT_MATRIX_H__ #define TESSERACT_CCSTRUCT_MATRIX_H__ #include "kdpair.h" #include "unicharset.h" class BLOB_CHOICE_LIST; #define NOT_CLASSIFIED reinterpret_cast<BLOB_CHOICE_LIST*>(NULL) // A generic class to hold a 2-D matrix with entries of type T, but can also // act as a base class for other implementations, such as a triangular or // banded matrix. template <class T> class GENERIC_2D_ARRAY { public: // Initializes the array size, and empty element, but cannot allocate memory // for the subclasses or initialize because calls to the num_elements // member will be routed to the base class implementation. Subclasses can // either pass the memory in, or allocate after by calling Resize(). GENERIC_2D_ARRAY(int dim1, int dim2, const T& empty, T* array) : empty_(empty), dim1_(dim1), dim2_(dim2), array_(array) { } // Original constructor for a full rectangular matrix DOES allocate memory // and initialize it to empty. GENERIC_2D_ARRAY(int dim1, int dim2, const T& empty) : empty_(empty), dim1_(dim1), dim2_(dim2) { array_ = new T[dim1_ * dim2_]; for (int x = 0; x < dim1_; x++) for (int y = 0; y < dim2_; y++) this->put(x, y, empty_); } virtual ~GENERIC_2D_ARRAY() { delete[] array_; } // Reallocate the array to the given size. Does not keep old data. void Resize(int size1, int size2, const T& empty) { empty_ = empty; if (size1 != dim1_ || size2 != dim2_) { dim1_ = size1; dim2_ = size2; delete [] array_; array_ = new T[dim1_ * dim2_]; } Clear(); } // Reallocate the array to the given size, keeping old data. void ResizeWithCopy(int size1, int size2) { if (size1 != dim1_ || size2 != dim2_) { T* new_array = new T[size1 * size2]; for (int col = 0; col < size1; ++col) { for (int row = 0; row < size2; ++row) { int old_index = col * dim2() + row; int new_index = col * size2 + row; if (col < dim1_ && row < dim2_) { new_array[new_index] = array_[old_index]; } else { new_array[new_index] = empty_; } } } delete[] array_; array_ = new_array; dim1_ = size1; dim2_ = size2; } } // Sets all the elements of the array to the empty value. void Clear() { int total_size = num_elements(); for (int i = 0; i < total_size; ++i) array_[i] = empty_; } // Writes to the given file. Returns false in case of error. // Only works with bitwise-serializeable types! bool Serialize(FILE* fp) const { if (!SerializeSize(fp)) return false; if (fwrite(&empty_, sizeof(empty_), 1, fp) != 1) return false; int size = num_elements(); if (fwrite(array_, sizeof(*array_), size, fp) != size) return false; return true; } // Reads from the given file. Returns false in case of error. // Only works with bitwise-serializeable typ // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp) { if (!DeSerializeSize(swap, fp)) return false; if (fread(&empty_, sizeof(empty_), 1, fp) != 1) return false; if (swap) ReverseN(&empty_, sizeof(empty_)); int size = num_elements(); if (fread(array_, sizeof(*array_), size, fp) != size) return false; if (swap) { for (int i = 0; i < size; ++i) ReverseN(&array_[i], sizeof(array_[i])); } return true; } // Writes to the given file. Returns false in case of error. // Assumes a T::Serialize(FILE*) const function. bool SerializeClasses(FILE* fp) const { if (!SerializeSize(fp)) return false; if (!empty_.Serialize(fp)) return false; int size = num_elements(); for (int i = 0; i < size; ++i) { if (!array_[i].Serialize(fp)) return false; } return true; } // Reads from the given file. Returns false in case of error. // Assumes a T::DeSerialize(bool swap, FILE*) function. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerializeClasses(bool swap, FILE* fp) { if (!DeSerializeSize(swap, fp)) return false; if (!empty_.DeSerialize(swap, fp)) return false; int size = num_elements(); for (int i = 0; i < size; ++i) { if (!array_[i].DeSerialize(swap, fp)) return false; } return true; } // Provide the dimensions of this rectangular matrix. int dim1() const { return dim1_; } int dim2() const { return dim2_; } // Returns the number of elements in the array. // Banded/triangular matrices may override. virtual int num_elements() const { return dim1_ * dim2_; } // Expression to select a specific location in the matrix. The matrix is // stored COLUMN-major, so the left-most index is the most significant. // This allows [][] access to use indices in the same order as (,). virtual int index(int column, int row) const { return (column * dim2_ + row); } // Put a list element into the matrix at a specific location. void put(int column, int row, const T& thing) { array_[this->index(column, row)] = thing; } // Get the item at a specified location from the matrix. T get(int column, int row) const { return array_[this->index(column, row)]; } // Return a reference to the element at the specified location. const T& operator()(int column, int row) const { return array_[this->index(column, row)]; } T& operator()(int column, int row) { return array_[this->index(column, row)]; } // Allow access using array[column][row]. NOTE that the indices are // in the same left-to-right order as the () indexing. T* operator[](int column) { return &array_[this->index(column, 0)]; } const T* operator[](int column) const { return &array_[this->index(column, 0)]; } // Delete objects pointed to by array_[i]. void delete_matrix_pointers() { int size = num_elements(); for (int i = 0; i < size; ++i) { T matrix_cell = array_[i]; if (matrix_cell != empty_) delete matrix_cell; } } protected: // Factored helper to serialize the size. bool SerializeSize(FILE* fp) const { inT32 size = dim1_; if (fwrite(&size, sizeof(size), 1, fp) != 1) return false; size = dim2_; if (fwrite(&size, sizeof(size), 1, fp) != 1) return false; return true; } // Factored helper to deserialize the size. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerializeSize(bool swap, FILE* fp) { inT32 size1, size2; if (fread(&size1, sizeof(size1), 1, fp) != 1) return false; if (fread(&size2, sizeof(size2), 1, fp) != 1) return false; if (swap) { ReverseN(&size1, sizeof(size1)); ReverseN(&size2, sizeof(size2)); } Resize(size1, size2, empty_); return true; } T* array_; T empty_; // The unused cell. int dim1_; // Size of the 1st dimension in indexing functions. int dim2_; // Size of the 2nd dimension in indexing functions. }; // A generic class to store a banded triangular matrix with entries of type T. // In this array, the nominally square matrix is dim1_ x dim1_, and dim2_ is // the number of bands, INCLUDING the diagonal. The storage is thus of size // dim1_ * dim2_ and index(col, row) = col * dim2_ + row - col, and an // assert will fail if row < col or row - col >= dim2. template <class T> class BandTriMatrix : public GENERIC_2D_ARRAY<T> { public: // Allocate a piece of memory to hold a 2d-array of the given dimension. // Initialize all the elements of the array to empty instead of assuming // that a default constructor can be used. BandTriMatrix(int dim1, int dim2, const T& empty) : GENERIC_2D_ARRAY<T>(dim1, dim2, empty) { } // The default destructor will do. // Provide the dimensions of this matrix. // dimension is the size of the nominally square matrix. int dimension() const { return this->dim1_; } // bandwidth is the number of bands in the matrix, INCLUDING the diagonal. int bandwidth() const { return this->dim2_; } // Expression to select a specific location in the matrix. The matrix is // stored COLUMN-major, so the left-most index is the most significant. // This allows [][] access to use indices in the same order as (,). virtual int index(int column, int row) const { ASSERT_HOST(row >= column); ASSERT_HOST(row - column < this->dim2_); return column * this->dim2_ + row - column; } // Appends array2 corner-to-corner to *this, making an array of dimension // equal to the sum of the individual dimensions. // array2 is not destroyed, but is left empty, as all elements are moved // to *this. void AttachOnCorner(BandTriMatrix<T>* array2) { int new_dim1 = this->dim1_ + array2->dim1_; int new_dim2 = MAX(this->dim2_, array2->dim2_); T* new_array = new T[new_dim1 * new_dim2]; for (int col = 0; col < new_dim1; ++col) { for (int j = 0; j < new_dim2; ++j) { int new_index = col * new_dim2 + j; if (col < this->dim1_ && j < this->dim2_) { new_array[new_index] = this->get(col, col + j); } else if (col >= this->dim1_ && j < array2->dim2_) { new_array[new_index] = array2->get(col - this->dim1_, col - this->dim1_ + j); array2->put(col - this->dim1_, col - this->dim1_ + j, NULL); } else { new_array[new_index] = this->empty_; } } } delete[] this->array_; this->array_ = new_array; this->dim1_ = new_dim1; this->dim2_ = new_dim2; } }; class MATRIX : public BandTriMatrix<BLOB_CHOICE_LIST *> { public: MATRIX(int dimension, int bandwidth) : BandTriMatrix<BLOB_CHOICE_LIST *>(dimension, bandwidth, NOT_CLASSIFIED) {} // Returns true if there are any real classification results. bool Classified(int col, int row, int wildcard_id) const; // Expands the existing matrix in-place to make the band wider, without // losing any existing data. void IncreaseBandSize(int bandwidth); // Returns a bigger MATRIX with a new column and row in the matrix in order // to split the blob at the given (ind,ind) diagonal location. // Entries are relocated to the new MATRIX using the transformation defined // by MATRIX_COORD::MapForSplit. // Transfers the pointer data to the new MATRIX and deletes *this. MATRIX* ConsumeAndMakeBigger(int ind); // Makes and returns a deep copy of *this, including all the BLOB_CHOICEs // on the lists, but not any LanguageModelState that may be attached to the // BLOB_CHOICEs. MATRIX* DeepCopy() const; // Print a shortened version of the contents of the matrix. void print(const UNICHARSET &unicharset) const; }; struct MATRIX_COORD { static void Delete(void *arg) { MATRIX_COORD *c = static_cast<MATRIX_COORD *>(arg); delete c; } // Default constructor required by GenericHeap. MATRIX_COORD() : col(0), row(0) {} MATRIX_COORD(int c, int r): col(c), row(r) {} ~MATRIX_COORD() {} bool Valid(const MATRIX &m) const { return 0 <= col && col < m.dimension() && col <= row && row < col + m.bandwidth() && row < m.dimension(); } // Remaps the col,row pair to split the blob at the given (ind,ind) diagonal // location. // Entries at (i,j) for i in [0,ind] and j in [ind,dim) move to (i,j+1), // making a new row at ind. // Entries at (i,j) for i in [ind+1,dim) and j in [i,dim) move to (i+i,j+1), // making a new column at ind+1. void MapForSplit(int ind) { ASSERT_HOST(row >= col); if (col > ind) ++col; if (row >= ind) ++row; ASSERT_HOST(row >= col); } int col; int row; }; // The MatrixCoordPair contains a MATRIX_COORD and its priority. typedef tesseract::KDPairInc<float, MATRIX_COORD> MatrixCoordPair; #endif // TESSERACT_CCSTRUCT_MATRIX_H__
1080228-arabicocr11
ccstruct/matrix.h
C
asf20
12,949
/********************************************************************** * File: boxread.cpp * Description: Read data from a box file. * Author: Ray Smith * Created: Fri Aug 24 17:47:23 PDT 2007 * * (C) Copyright 2007, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCUTIL_BOXREAD_H__ #define TESSERACT_CCUTIL_BOXREAD_H__ #include <stdio.h> #include "genericvector.h" #include "strngs.h" class STRING; class TBOX; // Size of buffer used to read a line from a box file. const int kBoxReadBufSize = 1024; // Open the boxfile based on the given image filename. // Returns NULL if the box file cannot be opened. FILE* OpenBoxFile(const STRING& fname); // Reads all boxes from the given filename. // Reads a specific target_page number if >= 0, or all pages otherwise. // Skips blanks if skip_blanks is true. // The UTF-8 label of the box is put in texts, and the full box definition as // a string is put in box_texts, with the corresponding page number in pages. // Each of the output vectors is optional (may be NULL). // Returns false if no boxes are found. bool ReadAllBoxes(int target_page, bool skip_blanks, const STRING& filename, GenericVector<TBOX>* boxes, GenericVector<STRING>* texts, GenericVector<STRING>* box_texts, GenericVector<int>* pages); // Reads all boxes from the string. Otherwise, as ReadAllBoxes. bool ReadMemBoxes(int target_page, bool skip_blanks, const char* box_data, GenericVector<TBOX>* boxes, GenericVector<STRING>* texts, GenericVector<STRING>* box_texts, GenericVector<int>* pages); // Returns the box file name corresponding to the given image_filename. STRING BoxFileName(const STRING& image_filename); // ReadNextBox factors out the code to interpret a line of a box // file so that applybox and unicharset_extractor interpret the same way. // This function returns the next valid box file utf8 string and coords // and returns true, or false on eof (and closes the file). // It ignores the utf8 file signature ByteOrderMark (U+FEFF=EF BB BF), checks // for valid utf-8 and allows space or tab between fields. // utf8_str is set with the unichar string, and bounding box with the box. // If there are page numbers in the file, it reads them all. bool ReadNextBox(int *line_number, FILE* box_file, STRING* utf8_str, TBOX* bounding_box); // As ReadNextBox above, but get a specific page number. (0-based) // Use -1 to read any page number. Files without page number all // read as if they are page 0. bool ReadNextBox(int target_page, int *line_number, FILE* box_file, STRING* utf8_str, TBOX* bounding_box); // Parses the given box file string into a page_number, utf8_str, and // bounding_box. Returns true on a successful parse. bool ParseBoxFileStr(const char* boxfile_str, int* page_number, STRING* utf8_str, TBOX* bounding_box); // Creates a box file string from a unichar string, TBOX and page number. void MakeBoxFileStr(const char* unichar_str, const TBOX& box, int page_num, STRING* box_str); #endif // TESSERACT_CCUTIL_BOXREAD_H__
1080228-arabicocr11
ccstruct/boxread.h
C++
asf20
3,831
/********************************************************************** * File: ocrblock.h (Formerly block.h) * Description: Page block class definition. * Author: Ray Smith * Created: Thu Mar 14 17:32:01 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef OCRBLOCK_H #define OCRBLOCK_H #include "ocrpara.h" #include "ocrrow.h" #include "pdblock.h" class BLOCK; //forward decl ELISTIZEH (BLOCK) class BLOCK:public ELIST_LINK, public PDBLK //page block { friend class BLOCK_RECT_IT; //block iterator public: BLOCK() : re_rotation_(1.0f, 0.0f), classify_rotation_(1.0f, 0.0f), skew_(1.0f, 0.0f) { right_to_left_ = false; hand_poly = NULL; } BLOCK(const char *name, //< filename BOOL8 prop, //< proportional inT16 kern, //< kerning inT16 space, //< spacing inT16 xmin, //< bottom left inT16 ymin, inT16 xmax, //< top right inT16 ymax); ~BLOCK () { } /** * set space size etc. * @param prop proportional * @param kern inter char size * @param space inter word size * @param ch_pitch pitch if fixed */ void set_stats(BOOL8 prop, inT16 kern, inT16 space, inT16 ch_pitch) { proportional = prop; kerning = (inT8) kern; spacing = space; pitch = ch_pitch; } /// set char size void set_xheight(inT32 height) { xheight = height; } /// set font class void set_font_class(inT16 font) { font_class = font; } /// return proportional BOOL8 prop() const { return proportional; } bool right_to_left() const { return right_to_left_; } void set_right_to_left(bool value) { right_to_left_ = value; } /// return pitch inT32 fixed_pitch() const { return pitch; } /// return kerning inT16 kern() const { return kerning; } /// return font class inT16 font() const { return font_class; } /// return spacing inT16 space() const { return spacing; } /// return filename const char *name() const { return filename.string (); } /// return xheight inT32 x_height() const { return xheight; } float cell_over_xheight() const { return cell_over_xheight_; } void set_cell_over_xheight(float ratio) { cell_over_xheight_ = ratio; } /// get rows ROW_LIST *row_list() { return &rows; } // Compute the margins between the edges of each row and this block's // polyblock, and store the results in the rows. void compute_row_margins(); // get paragraphs PARA_LIST *para_list() { return &paras_; } /// get blobs C_BLOB_LIST *blob_list() { return &c_blobs; } C_BLOB_LIST *reject_blobs() { return &rej_blobs; } FCOORD re_rotation() const { return re_rotation_; // How to transform coords back to image. } void set_re_rotation(const FCOORD& rotation) { re_rotation_ = rotation; } FCOORD classify_rotation() const { return classify_rotation_; // Apply this before classifying. } void set_classify_rotation(const FCOORD& rotation) { classify_rotation_ = rotation; } FCOORD skew() const { return skew_; // Direction of true horizontal. } void set_skew(const FCOORD& skew) { skew_ = skew; } const ICOORD& median_size() const { return median_size_; } void set_median_size(int x, int y) { median_size_.set_x(x); median_size_.set_y(y); } Pix* render_mask() { return PDBLK::render_mask(re_rotation_); } // Reflects the polygon in the y-axis and recomputes the bounding_box. // Does nothing to any contained rows/words/blobs etc. void reflect_polygon_in_y_axis(); void rotate(const FCOORD& rotation); /// decreasing y order void sort_rows(); /// shrink white space void compress(); /// check proportional void check_pitch(); /// shrink white space and move by vector void compress(const ICOORD vec); /// dump whole table void print(FILE *fp, BOOL8 dump); BLOCK& operator=(const BLOCK & source); private: BOOL8 proportional; //< proportional bool right_to_left_; //< major script is right to left. inT8 kerning; //< inter blob gap inT16 spacing; //< inter word gap inT16 pitch; //< pitch of non-props inT16 font_class; //< correct font class inT32 xheight; //< height of chars float cell_over_xheight_; //< Ratio of cell height to xheight. STRING filename; //< name of block ROW_LIST rows; //< rows in block PARA_LIST paras_; //< paragraphs of block C_BLOB_LIST c_blobs; //< before textord C_BLOB_LIST rej_blobs; //< duff stuff FCOORD re_rotation_; //< How to transform coords back to image. FCOORD classify_rotation_; //< Apply this before classifying. FCOORD skew_; //< Direction of true horizontal. ICOORD median_size_; //< Median size of blobs. }; int decreasing_top_order(const void *row1, const void *row2); // A function to print segmentation stats for the given block list. void PrintSegmentationStats(BLOCK_LIST* block_list); // Extracts blobs fromo the given block list and adds them to the output list. // The block list must have been created by performing a page segmentation. void ExtractBlobsFromSegmentation(BLOCK_LIST* blocks, C_BLOB_LIST* output_blob_list); // Refreshes the words in the block_list by using blobs in the // new_blobs list. // Block list must have word segmentation in it. // It consumes the blobs provided in the new_blobs list. The blobs leftover in // the new_blobs list after the call weren't matched to any blobs of the words // in block list. // The output not_found_blobs is a list of blobs from the original segmentation // in the block_list for which no corresponding new blobs were found. void RefreshWordBlobsFromNewBlobs(BLOCK_LIST* block_list, C_BLOB_LIST* new_blobs, C_BLOB_LIST* not_found_blobs); #endif
1080228-arabicocr11
ccstruct/ocrblock.h
C++
asf20
6,871
/********************************************************************** * File: normalis.cpp (Formerly denorm.c) * Description: Code for the DENORM class. * Author: Ray Smith * Created: Thu Apr 23 09:22:43 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "normalis.h" #include <stdlib.h> #include "allheaders.h" #include "blobs.h" #include "helpers.h" #include "matrix.h" #include "ocrblock.h" #include "unicharset.h" #include "werd.h" // Tolerance in pixels used for baseline and xheight on non-upper/lower scripts. const int kSloppyTolerance = 4; // Final tolerance in pixels added to the computed xheight range. const float kFinalPixelTolerance = 0.125f; DENORM::DENORM() { Init(); } DENORM::DENORM(const DENORM &src) { rotation_ = NULL; *this = src; } DENORM & DENORM::operator=(const DENORM & src) { Clear(); inverse_ = src.inverse_; predecessor_ = src.predecessor_; pix_ = src.pix_; block_ = src.block_; if (src.rotation_ == NULL) rotation_ = NULL; else rotation_ = new FCOORD(*src.rotation_); x_origin_ = src.x_origin_; y_origin_ = src.y_origin_; x_scale_ = src.x_scale_; y_scale_ = src.y_scale_; final_xshift_ = src.final_xshift_; final_yshift_ = src.final_yshift_; return *this; } DENORM::~DENORM() { Clear(); } // Initializes the denorm for a transformation. For details see the large // comment in normalis.h. // Arguments: // block: if not NULL, then this is the first transformation, and // block->re_rotation() needs to be used after the Denorm // transformation to get back to the image coords. // rotation: if not NULL, apply this rotation after translation to the // origin and scaling. (Usually a classify rotation.) // predecessor: if not NULL, then predecessor has been applied to the // input space and needs to be undone to complete the inverse. // The above pointers are not owned by this DENORM and are assumed to live // longer than this denorm, except rotation, which is deep copied on input. // // x_origin: The x origin which will be mapped to final_xshift in the result. // y_origin: The y origin which will be mapped to final_yshift in the result. // Added to result of row->baseline(x) if not NULL. // // x_scale: scale factor for the x-coordinate. // y_scale: scale factor for the y-coordinate. Ignored if segs is given. // Note that these scale factors apply to the same x and y system as the // x-origin and y-origin apply, ie after any block rotation, but before // the rotation argument is applied. // // final_xshift: The x component of the final translation. // final_yshift: The y component of the final translation. void DENORM::SetupNormalization(const BLOCK* block, const FCOORD* rotation, const DENORM* predecessor, float x_origin, float y_origin, float x_scale, float y_scale, float final_xshift, float final_yshift) { Clear(); block_ = block; if (rotation == NULL) rotation_ = NULL; else rotation_ = new FCOORD(*rotation); predecessor_ = predecessor; x_origin_ = x_origin; y_origin_ = y_origin; x_scale_ = x_scale; y_scale_ = y_scale; final_xshift_ = final_xshift; final_yshift_ = final_yshift; } // Helper for SetupNonLinear computes an image of shortest run-lengths from // the x/y edges provided. // Based on "A nonlinear normalization method for handprinted Kanji character // recognition -- line density equalization" by Hiromitsu Yamada et al. // Eg below is an O in a 1-pixel margin-ed bounding box and the corresponding // ______________ input x_coords and y_coords. // | _________ | <empty> // | | _ | | 1, 6 // | | | | | | 1, 3, 4, 6 // | | | | | | 1, 3, 4, 6 // | | | | | | 1, 3, 4, 6 // | | |_| | | 1, 3, 4, 6 // | |_________| | 1, 6 // |_____________| <empty> // E 1 1 1 1 1 E // m 7 7 2 7 7 m // p 6 p // t 7 t // y y // The output image contains the min of the x and y run-length (distance // between edges) at each coordinate in the image thus: // ______________ // |7 1_1_1_1_1 7| // |1|5 5 1 5 5|1| // |1|2 2|1|2 2|1| // |1|2 2|1|2 2|1| // |1|2 2|1|2 2|1| // |1|2 2|1|2 2|1| // |1|5_5_1_5_5|1| // |7_1_1_1_1_1_7| // Note that the input coords are all integer, so all partial pixels are dealt // with elsewhere. Although it is nice for outlines to be properly connected // and continuous, there is no requirement that they be as such, so they could // have been derived from a flaky source, such as greyscale. // This function works only within the provided box, and it is assumed that the // input x_coords and y_coords have already been translated to have the bottom- // left of box as the origin. Although an output, the minruns should have been // pre-initialized to be the same size as box. Each element will contain the // minimum of x and y run-length as shown above. static void ComputeRunlengthImage( const TBOX& box, const GenericVector<GenericVector<int> >& x_coords, const GenericVector<GenericVector<int> >& y_coords, GENERIC_2D_ARRAY<int>* minruns) { int width = box.width(); int height = box.height(); ASSERT_HOST(minruns->dim1() == width); ASSERT_HOST(minruns->dim2() == height); // Set a 2-d image array to the run lengths at each pixel. for (int ix = 0; ix < width; ++ix) { int y = 0; for (int i = 0; i < y_coords[ix].size(); ++i) { int y_edge = ClipToRange(y_coords[ix][i], 0, height); int gap = y_edge - y; // Every pixel between the last and current edge get set to the gap. while (y < y_edge) { (*minruns)(ix, y) = gap; ++y; } } // Pretend there is a bounding box of edges all around the image. int gap = height - y; while (y < height) { (*minruns)(ix, y) = gap; ++y; } } // Now set the image pixels the the MIN of the x and y runlengths. for (int iy = 0; iy < height; ++iy) { int x = 0; for (int i = 0; i < x_coords[iy].size(); ++i) { int x_edge = ClipToRange(x_coords[iy][i], 0, width); int gap = x_edge - x; while (x < x_edge) { if (gap < (*minruns)(x, iy)) (*minruns)(x, iy) = gap; ++x; } } int gap = width - x; while (x < width) { if (gap < (*minruns)(x, iy)) (*minruns)(x, iy) = gap; ++x; } } } // Converts the run-length image (see above to the edge density profiles used // for scaling, thus: // ______________ // |7 1_1_1_1_1 7| = 5.28 // |1|5 5 1 5 5|1| = 3.8 // |1|2 2|1|2 2|1| = 5 // |1|2 2|1|2 2|1| = 5 // |1|2 2|1|2 2|1| = 5 // |1|2 2|1|2 2|1| = 5 // |1|5_5_1_5_5|1| = 3.8 // |7_1_1_1_1_1_7| = 5.28 // 6 4 4 8 4 4 6 // . . . . . . . // 2 4 4 0 4 4 2 // 8 8 // Each profile is the sum of the reciprocals of the pixels in the image in // the appropriate row or column, and these are then normalized to sum to 1. // On output hx, hy contain an extra element, which will eventually be used // to guarantee that the top/right edge of the box (and anything beyond) always // gets mapped to the maximum target coordinate. static void ComputeEdgeDensityProfiles(const TBOX& box, const GENERIC_2D_ARRAY<int>& minruns, GenericVector<float>* hx, GenericVector<float>* hy) { int width = box.width(); int height = box.height(); hx->init_to_size(width + 1, 0.0); hy->init_to_size(height + 1, 0.0); double total = 0.0; for (int iy = 0; iy < height; ++iy) { for (int ix = 0; ix < width; ++ix) { int run = minruns(ix, iy); if (run == 0) run = 1; float density = 1.0f / run; (*hx)[ix] += density; (*hy)[iy] += density; } total += (*hy)[iy]; } // Normalize each profile to sum to 1. if (total > 0.0) { for (int ix = 0; ix < width; ++ix) { (*hx)[ix] /= total; } for (int iy = 0; iy < height; ++iy) { (*hy)[iy] /= total; } } // There is an extra element in each array, so initialize to 1. (*hx)[width] = 1.0f; (*hy)[height] = 1.0f; } // Sets up the DENORM to execute a non-linear transformation based on // preserving an even distribution of stroke edges. The transformation // operates only within the given box. // x_coords is a collection of the x-coords of vertical edges for each // y-coord starting at box.bottom(). // y_coords is a collection of the y-coords of horizontal edges for each // x-coord starting at box.left(). // Eg x_coords[0] is a collection of the x-coords of edges at y=bottom. // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1. // The second-level vectors must all be sorted in ascending order. // See comments on the helper functions above for more details. void DENORM::SetupNonLinear( const DENORM* predecessor, const TBOX& box, float target_width, float target_height, float final_xshift, float final_yshift, const GenericVector<GenericVector<int> >& x_coords, const GenericVector<GenericVector<int> >& y_coords) { Clear(); predecessor_ = predecessor; // x_map_ and y_map_ store a mapping from input x and y coordinate to output // x and y coordinate, based on scaling to the supplied target_width and // target_height. x_map_ = new GenericVector<float>; y_map_ = new GenericVector<float>; // Set a 2-d image array to the run lengths at each pixel. int width = box.width(); int height = box.height(); GENERIC_2D_ARRAY<int> minruns(width, height, 0); ComputeRunlengthImage(box, x_coords, y_coords, &minruns); // Edge density is the sum of the inverses of the run lengths. Compute // edge density projection profiles. ComputeEdgeDensityProfiles(box, minruns, x_map_, y_map_); // Convert the edge density profiles to the coordinates by multiplying by // the desired size and accumulating. (*x_map_)[width] = target_width; for (int x = width - 1; x >= 0; --x) { (*x_map_)[x] = (*x_map_)[x + 1] - (*x_map_)[x] * target_width; } (*y_map_)[height] = target_height; for (int y = height - 1; y >= 0; --y) { (*y_map_)[y] = (*y_map_)[y + 1] - (*y_map_)[y] * target_height; } x_origin_ = box.left(); y_origin_ = box.bottom(); final_xshift_ = final_xshift; final_yshift_ = final_yshift; } // Transforms the given coords one step forward to normalized space, without // using any block rotation or predecessor. void DENORM::LocalNormTransform(const TPOINT& pt, TPOINT* transformed) const { FCOORD src_pt(pt.x, pt.y); FCOORD float_result; LocalNormTransform(src_pt, &float_result); transformed->x = IntCastRounded(float_result.x()); transformed->y = IntCastRounded(float_result.y()); } void DENORM::LocalNormTransform(const FCOORD& pt, FCOORD* transformed) const { FCOORD translated(pt.x() - x_origin_, pt.y() - y_origin_); if (x_map_ != NULL && y_map_ != NULL) { int x = ClipToRange(IntCastRounded(translated.x()), 0, x_map_->size()-1); translated.set_x((*x_map_)[x]); int y = ClipToRange(IntCastRounded(translated.y()), 0, y_map_->size()-1); translated.set_y((*y_map_)[y]); } else { translated.set_x(translated.x() * x_scale_); translated.set_y(translated.y() * y_scale_); if (rotation_ != NULL) translated.rotate(*rotation_); } transformed->set_x(translated.x() + final_xshift_); transformed->set_y(translated.y() + final_yshift_); } // Transforms the given coords forward to normalized space using the // full transformation sequence defined by the block rotation, the // predecessors, deepest first, and finally this. If first_norm is not NULL, // then the first and deepest transformation used is first_norm, ending // with this, and the block rotation will not be applied. void DENORM::NormTransform(const DENORM* first_norm, const TPOINT& pt, TPOINT* transformed) const { FCOORD src_pt(pt.x, pt.y); FCOORD float_result; NormTransform(first_norm, src_pt, &float_result); transformed->x = IntCastRounded(float_result.x()); transformed->y = IntCastRounded(float_result.y()); } void DENORM::NormTransform(const DENORM* first_norm, const FCOORD& pt, FCOORD* transformed) const { FCOORD src_pt(pt); if (first_norm != this) { if (predecessor_ != NULL) { predecessor_->NormTransform(first_norm, pt, &src_pt); } else if (block_ != NULL) { FCOORD fwd_rotation(block_->re_rotation().x(), -block_->re_rotation().y()); src_pt.rotate(fwd_rotation); } } LocalNormTransform(src_pt, transformed); } // Transforms the given coords one step back to source space, without // using to any block rotation or predecessor. void DENORM::LocalDenormTransform(const TPOINT& pt, TPOINT* original) const { FCOORD src_pt(pt.x, pt.y); FCOORD float_result; LocalDenormTransform(src_pt, &float_result); original->x = IntCastRounded(float_result.x()); original->y = IntCastRounded(float_result.y()); } void DENORM::LocalDenormTransform(const FCOORD& pt, FCOORD* original) const { FCOORD rotated(pt.x() - final_xshift_, pt.y() - final_yshift_); if (x_map_ != NULL && y_map_ != NULL) { int x = x_map_->binary_search(rotated.x()); original->set_x(x + x_origin_); int y = y_map_->binary_search(rotated.y()); original->set_y(y + y_origin_); } else { if (rotation_ != NULL) { FCOORD inverse_rotation(rotation_->x(), -rotation_->y()); rotated.rotate(inverse_rotation); } original->set_x(rotated.x() / x_scale_ + x_origin_); float y_scale = y_scale_; original->set_y(rotated.y() / y_scale + y_origin_); } } // Transforms the given coords all the way back to source image space using // the full transformation sequence defined by this and its predecesors // recursively, shallowest first, and finally any block re_rotation. // If last_denorm is not NULL, then the last transformation used will // be last_denorm, and the block re_rotation will never be executed. void DENORM::DenormTransform(const DENORM* last_denorm, const TPOINT& pt, TPOINT* original) const { FCOORD src_pt(pt.x, pt.y); FCOORD float_result; DenormTransform(last_denorm, src_pt, &float_result); original->x = IntCastRounded(float_result.x()); original->y = IntCastRounded(float_result.y()); } void DENORM::DenormTransform(const DENORM* last_denorm, const FCOORD& pt, FCOORD* original) const { LocalDenormTransform(pt, original); if (last_denorm != this) { if (predecessor_ != NULL) { predecessor_->DenormTransform(last_denorm, *original, original); } else if (block_ != NULL) { original->rotate(block_->re_rotation()); } } } // Normalize a blob using blob transformations. Less accurate, but // more accurately copies the old way. void DENORM::LocalNormBlob(TBLOB* blob) const { TBOX blob_box = blob->bounding_box(); ICOORD translation(-IntCastRounded(x_origin_), -IntCastRounded(y_origin_)); blob->Move(translation); if (y_scale_ != 1.0f) blob->Scale(y_scale_); if (rotation_ != NULL) blob->Rotate(*rotation_); translation.set_x(IntCastRounded(final_xshift_)); translation.set_y(IntCastRounded(final_yshift_)); blob->Move(translation); } // Fills in the x-height range accepted by the given unichar_id, given its // bounding box in the usual baseline-normalized coordinates, with some // initial crude x-height estimate (such as word size) and this denoting the // transformation that was used. void DENORM::XHeightRange(int unichar_id, const UNICHARSET& unicharset, const TBOX& bbox, float* min_xht, float* max_xht, float* yshift) const { // Default return -- accept anything. *yshift = 0.0f; *min_xht = 0.0f; *max_xht = MAX_FLOAT32; if (!unicharset.top_bottom_useful()) return; // Clip the top and bottom to the limit of normalized feature space. int top = ClipToRange<int>(bbox.top(), 0, kBlnCellHeight - 1); int bottom = ClipToRange<int>(bbox.bottom(), 0, kBlnCellHeight - 1); // A tolerance of yscale corresponds to 1 pixel in the image. double tolerance = y_scale(); // If the script doesn't have upper and lower-case characters, widen the // tolerance to allow sloppy baseline/x-height estimates. if (!unicharset.script_has_upper_lower()) tolerance = y_scale() * kSloppyTolerance; int min_bottom, max_bottom, min_top, max_top; unicharset.get_top_bottom(unichar_id, &min_bottom, &max_bottom, &min_top, &max_top); // Calculate the scale factor we'll use to get to image y-pixels double midx = (bbox.left() + bbox.right()) / 2.0; double ydiff = (bbox.top() - bbox.bottom()) + 2.0; FCOORD mid_bot(midx, bbox.bottom()), tmid_bot; FCOORD mid_high(midx, bbox.bottom() + ydiff), tmid_high; DenormTransform(NULL, mid_bot, &tmid_bot); DenormTransform(NULL, mid_high, &tmid_high); // bln_y_measure * yscale = image_y_measure double yscale = tmid_high.pt_to_pt_dist(tmid_bot) / ydiff; // Calculate y-shift int bln_yshift = 0, bottom_shift = 0, top_shift = 0; if (bottom < min_bottom - tolerance) { bottom_shift = bottom - min_bottom; } else if (bottom > max_bottom + tolerance) { bottom_shift = bottom - max_bottom; } if (top < min_top - tolerance) { top_shift = top - min_top; } else if (top > max_top + tolerance) { top_shift = top - max_top; } if ((top_shift >= 0 && bottom_shift > 0) || (top_shift < 0 && bottom_shift < 0)) { bln_yshift = (top_shift + bottom_shift) / 2; } *yshift = bln_yshift * yscale; // To help very high cap/xheight ratio fonts accept the correct x-height, // and to allow the large caps in small caps to accept the xheight of the // small caps, add kBlnBaselineOffset to chars with a maximum max, and have // a top already at a significantly high position. if (max_top == kBlnCellHeight - 1 && top > kBlnCellHeight - kBlnBaselineOffset / 2) max_top += kBlnBaselineOffset; top -= bln_yshift; int height = top - kBlnBaselineOffset - bottom_shift; double min_height = min_top - kBlnBaselineOffset - tolerance; double max_height = max_top - kBlnBaselineOffset + tolerance; // We shouldn't try calculations if the characters are very short (for example // for punctuation). if (min_height > kBlnXHeight / 8 && height > 0) { float result = height * kBlnXHeight * yscale / min_height; *max_xht = result + kFinalPixelTolerance; result = height * kBlnXHeight * yscale / max_height; *min_xht = result - kFinalPixelTolerance; } } // Prints the content of the DENORM for debug purposes. void DENORM::Print() const { if (pix_ != NULL) { tprintf("Pix dimensions %d x %d x %d\n", pixGetWidth(pix_), pixGetHeight(pix_), pixGetDepth(pix_)); } if (inverse_) tprintf("Inverse\n"); if (block_ && block_->re_rotation().x() != 1.0f) { tprintf("Block rotation %g, %g\n", block_->re_rotation().x(), block_->re_rotation().y()); } tprintf("Input Origin = (%g, %g)\n", x_origin_, y_origin_); if (x_map_ != NULL && y_map_ != NULL) { tprintf("x map:\n"); for (int x = 0; x < x_map_->size(); ++x) { tprintf("%g ", (*x_map_)[x]); } tprintf("\ny map:\n"); for (int y = 0; y < y_map_->size(); ++y) { tprintf("%g ", (*y_map_)[y]); } tprintf("\n"); } else { tprintf("Scale = (%g, %g)\n", x_scale_, y_scale_); if (rotation_ != NULL) tprintf("Rotation = (%g, %g)\n", rotation_->x(), rotation_->y()); } tprintf("Final Origin = (%g, %g)\n", final_xshift_, final_xshift_); if (predecessor_ != NULL) { tprintf("Predecessor:\n"); predecessor_->Print(); } } // ============== Private Code ====================== // Free allocated memory and clear pointers. void DENORM::Clear() { if (x_map_ != NULL) { delete x_map_; x_map_ = NULL; } if (y_map_ != NULL) { delete y_map_; y_map_ = NULL; } if (rotation_ != NULL) { delete rotation_; rotation_ = NULL; } } // Setup default values. void DENORM::Init() { inverse_ = false; pix_ = NULL; block_ = NULL; rotation_ = NULL; predecessor_ = NULL; x_map_ = NULL; y_map_ = NULL; x_origin_ = 0.0f; y_origin_ = 0.0f; x_scale_ = 1.0f; y_scale_ = 1.0f; final_xshift_ = 0.0f; final_yshift_ = static_cast<float>(kBlnBaselineOffset); }
1080228-arabicocr11
ccstruct/normalis.cpp
C++
asf20
21,189
/********************************************************************** * File: ocrblock.cpp (Formerly block.c) * Description: BLOCK member functions and iterator functions. * Author: Ray Smith * Created: Fri Mar 15 09:41:28 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdlib.h> #include "blckerr.h" #include "ocrblock.h" #include "stepblob.h" #include "tprintf.h" #define BLOCK_LABEL_HEIGHT 150 //char height of block id ELISTIZE (BLOCK) /** * BLOCK::BLOCK * * Constructor for a simple rectangular block. */ BLOCK::BLOCK(const char *name, //< filename BOOL8 prop, //< proportional inT16 kern, //< kerning inT16 space, //< spacing inT16 xmin, //< bottom left inT16 ymin, inT16 xmax, //< top right inT16 ymax) : PDBLK (xmin, ymin, xmax, ymax), filename(name), re_rotation_(1.0f, 0.0f), classify_rotation_(1.0f, 0.0f), skew_(1.0f, 0.0f) { ICOORDELT_IT left_it = &leftside; ICOORDELT_IT right_it = &rightside; proportional = prop; right_to_left_ = false; kerning = kern; spacing = space; font_class = -1; //not assigned cell_over_xheight_ = 2.0f; hand_poly = NULL; left_it.set_to_list (&leftside); right_it.set_to_list (&rightside); //make default box left_it.add_to_end (new ICOORDELT (xmin, ymin)); left_it.add_to_end (new ICOORDELT (xmin, ymax)); right_it.add_to_end (new ICOORDELT (xmax, ymin)); right_it.add_to_end (new ICOORDELT (xmax, ymax)); } /** * decreasing_top_order * * Sort Comparator: Return <0 if row1 top < row2 top */ int decreasing_top_order( // const void *row1, const void *row2) { return (*(ROW **) row2)->bounding_box ().top () - (*(ROW **) row1)->bounding_box ().top (); } /** * BLOCK::rotate * * Rotate the polygon by the given rotation and recompute the bounding_box. */ void BLOCK::rotate(const FCOORD& rotation) { poly_block()->rotate(rotation); box = *poly_block()->bounding_box(); } /** * BLOCK::reflect_polygon_in_y_axis * * Reflects the polygon in the y-axis and recompute the bounding_box. * Does nothing to any contained rows/words/blobs etc. */ void BLOCK::reflect_polygon_in_y_axis() { poly_block()->reflect_in_y_axis(); box = *poly_block()->bounding_box(); } /** * BLOCK::sort_rows * * Order rows so that they are in order of decreasing Y coordinate */ void BLOCK::sort_rows() { // order on "top" ROW_IT row_it(&rows); row_it.sort (decreasing_top_order); } /** * BLOCK::compress * * Delete space between the rows. (And maybe one day, compress the rows) * Fill space of block from top down, left aligning rows. */ void BLOCK::compress() { // squash it up #define ROW_SPACING 5 ROW_IT row_it(&rows); ROW *row; ICOORD row_spacing (0, ROW_SPACING); ICOORDELT_IT icoordelt_it; sort_rows(); box = TBOX (box.topleft (), box.topleft ()); box.move_bottom_edge (ROW_SPACING); for (row_it.mark_cycle_pt (); !row_it.cycled_list (); row_it.forward ()) { row = row_it.data (); row->move (box.botleft () - row_spacing - row->bounding_box ().topleft ()); box += row->bounding_box (); } leftside.clear (); icoordelt_it.set_to_list (&leftside); icoordelt_it.add_to_end (new ICOORDELT (box.left (), box.bottom ())); icoordelt_it.add_to_end (new ICOORDELT (box.left (), box.top ())); rightside.clear (); icoordelt_it.set_to_list (&rightside); icoordelt_it.add_to_end (new ICOORDELT (box.right (), box.bottom ())); icoordelt_it.add_to_end (new ICOORDELT (box.right (), box.top ())); } /** * BLOCK::check_pitch * * Check whether the block is fixed or prop, set the flag, and set * the pitch if it is fixed. */ void BLOCK::check_pitch() { // check prop // tprintf("Missing FFT fixed pitch stuff!\n"); pitch = -1; } /** * BLOCK::compress * * Compress and move in a single operation. */ void BLOCK::compress( // squash it up const ICOORD vec // and move ) { box.move (vec); compress(); } /** * BLOCK::print * * Print the info on a block */ void BLOCK::print( //print list of sides FILE *, //< file to print on BOOL8 dump //< print full detail ) { ICOORDELT_IT it = &leftside; //iterator box.print (); tprintf ("Proportional= %s\n", proportional ? "TRUE" : "FALSE"); tprintf ("Kerning= %d\n", kerning); tprintf ("Spacing= %d\n", spacing); tprintf ("Fixed_pitch=%d\n", pitch); tprintf ("Filename= %s\n", filename.string ()); if (dump) { tprintf ("Left side coords are:\n"); for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) tprintf ("(%d,%d) ", it.data ()->x (), it.data ()->y ()); tprintf ("\n"); tprintf ("Right side coords are:\n"); it.set_to_list (&rightside); for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) tprintf ("(%d,%d) ", it.data ()->x (), it.data ()->y ()); tprintf ("\n"); } } /** * BLOCK::operator= * * Assignment - duplicate the block structure, but with an EMPTY row list. */ BLOCK & BLOCK::operator= ( //assignment const BLOCK & source //from this ) { this->ELIST_LINK::operator= (source); this->PDBLK::operator= (source); proportional = source.proportional; kerning = source.kerning; spacing = source.spacing; filename = source.filename; //STRINGs assign ok if (!rows.empty ()) rows.clear (); re_rotation_ = source.re_rotation_; classify_rotation_ = source.classify_rotation_; skew_ = source.skew_; return *this; } // This function is for finding the approximate (horizontal) distance from // the x-coordinate of the left edge of a symbol to the left edge of the // text block which contains it. We are passed: // segments - output of PB_LINE_IT::get_line() which contains x-coordinate // intervals for the scan line going through the symbol's y-coordinate. // Each element of segments is of the form (x()=start_x, y()=length). // x - the x coordinate of the symbol we're interested in. // margin - return value, the distance from x,y to the left margin of the // block containing it. // If all segments were to the right of x, we return false and 0. bool LeftMargin(ICOORDELT_LIST *segments, int x, int *margin) { bool found = false; *margin = 0; if (segments->empty()) return found; ICOORDELT_IT seg_it(segments); for (seg_it.mark_cycle_pt(); !seg_it.cycled_list(); seg_it.forward()) { int cur_margin = x - seg_it.data()->x(); if (cur_margin >= 0) { if (!found) { *margin = cur_margin; } else if (cur_margin < *margin) { *margin = cur_margin; } found = true; } } return found; } // This function is for finding the approximate (horizontal) distance from // the x-coordinate of the right edge of a symbol to the right edge of the // text block which contains it. We are passed: // segments - output of PB_LINE_IT::get_line() which contains x-coordinate // intervals for the scan line going through the symbol's y-coordinate. // Each element of segments is of the form (x()=start_x, y()=length). // x - the x coordinate of the symbol we're interested in. // margin - return value, the distance from x,y to the right margin of the // block containing it. // If all segments were to the left of x, we return false and 0. bool RightMargin(ICOORDELT_LIST *segments, int x, int *margin) { bool found = false; *margin = 0; if (segments->empty()) return found; ICOORDELT_IT seg_it(segments); for (seg_it.mark_cycle_pt(); !seg_it.cycled_list(); seg_it.forward()) { int cur_margin = seg_it.data()->x() + seg_it.data()->y() - x; if (cur_margin >= 0) { if (!found) { *margin = cur_margin; } else if (cur_margin < *margin) { *margin = cur_margin; } found = true; } } return found; } // Compute the distance from the left and right ends of each row to the // left and right edges of the block's polyblock. Illustration: // ____________________________ _______________________ // | Howdy neighbor! | |rectangular blocks look| // | This text is written to| |more like stacked pizza| // |illustrate how useful poly- |boxes. | // |blobs are in ----------- ------ The polyblob| // |dealing with| _________ |for a BLOCK rec-| // |harder layout| /===========\ |ords the possibly| // |issues. | | _ _ | |skewed pseudo-| // | You see this| | |_| \|_| | |rectangular | // |text is flowed| | } | |boundary that| // |around a mid-| \ ____ | |forms the ideal-| // |cloumn portrait._____ \ / __|ized text margin| // | Polyblobs exist| \ / |from which we should| // |to account for insets| | | |measure paragraph| // |which make otherwise| ----- |indentation. | // ----------------------- ---------------------- // // If we identify a drop-cap, we measure the left margin for the lines // below the first line relative to one space past the drop cap. The // first line's margin and those past the drop cap area are measured // relative to the enclosing polyblock. // // TODO(rays): Before this will work well, we'll need to adjust the // polyblob tighter around the text near images, as in: // UNLV_AUTO:mag.3G0 page 2 // UNLV_AUTO:mag.3G4 page 16 void BLOCK::compute_row_margins() { if (row_list()->empty() || row_list()->singleton()) { return; } // If Layout analysis was not called, default to this. POLY_BLOCK rect_block(bounding_box(), PT_FLOWING_TEXT); POLY_BLOCK *pblock = &rect_block; if (poly_block() != NULL) { pblock = poly_block(); } // Step One: Determine if there is a drop-cap. // TODO(eger): Fix up drop cap code for RTL languages. ROW_IT r_it(row_list()); ROW *first_row = r_it.data(); ROW *second_row = r_it.data_relative(1); // initialize the bottom of a fictitious drop cap far above the first line. int drop_cap_bottom = first_row->bounding_box().top() + first_row->bounding_box().height(); int drop_cap_right = first_row->bounding_box().left(); int mid_second_line = second_row->bounding_box().top() - second_row->bounding_box().height() / 2; WERD_IT werd_it(r_it.data()->word_list()); // words of line one if (!werd_it.empty()) { C_BLOB_IT cblob_it(werd_it.data()->cblob_list()); for (cblob_it.mark_cycle_pt(); !cblob_it.cycled_list(); cblob_it.forward()) { TBOX bbox = cblob_it.data()->bounding_box(); if (bbox.bottom() <= mid_second_line) { // we found a real drop cap first_row->set_has_drop_cap(true); if (drop_cap_bottom > bbox.bottom()) drop_cap_bottom = bbox.bottom(); if (drop_cap_right < bbox.right()) drop_cap_right = bbox.right(); } } } // Step Two: Calculate the margin from the text of each row to the block // (or drop-cap) boundaries. PB_LINE_IT lines(pblock); r_it.set_to_list(row_list()); for (r_it.mark_cycle_pt(); !r_it.cycled_list(); r_it.forward()) { ROW *row = r_it.data(); TBOX row_box = row->bounding_box(); int left_y = row->base_line(row_box.left()) + row->x_height(); int left_margin; ICOORDELT_LIST *segments = lines.get_line(left_y); LeftMargin(segments, row_box.left(), &left_margin); delete segments; if (row_box.top() >= drop_cap_bottom) { int drop_cap_distance = row_box.left() - row->space() - drop_cap_right; if (drop_cap_distance < 0) drop_cap_distance = 0; if (drop_cap_distance < left_margin) left_margin = drop_cap_distance; } int right_y = row->base_line(row_box.right()) + row->x_height(); int right_margin; segments = lines.get_line(right_y); RightMargin(segments, row_box.right(), &right_margin); delete segments; row->set_lmargin(left_margin); row->set_rmargin(right_margin); } } /********************************************************************** * PrintSegmentationStats * * Prints segmentation stats for the given block list. **********************************************************************/ void PrintSegmentationStats(BLOCK_LIST* block_list) { int num_blocks = 0; int num_rows = 0; int num_words = 0; int num_blobs = 0; BLOCK_IT block_it(block_list); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { BLOCK* block = block_it.data(); ++num_blocks; ROW_IT row_it(block->row_list()); for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { ++num_rows; ROW* row = row_it.data(); // Iterate over all werds in the row. WERD_IT werd_it(row->word_list()); for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) { WERD* werd = werd_it.data(); ++num_words; num_blobs += werd->cblob_list()->length(); } } } tprintf("Block list stats:\nBlocks = %d\nRows = %d\nWords = %d\nBlobs = %d\n", num_blocks, num_rows, num_words, num_blobs); } /********************************************************************** * ExtractBlobsFromSegmentation * * Extracts blobs from the given block list and adds them to the output list. * The block list must have been created by performing a page segmentation. **********************************************************************/ void ExtractBlobsFromSegmentation(BLOCK_LIST* blocks, C_BLOB_LIST* output_blob_list) { C_BLOB_IT return_list_it(output_blob_list); BLOCK_IT block_it(blocks); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { BLOCK* block = block_it.data(); ROW_IT row_it(block->row_list()); for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { ROW* row = row_it.data(); // Iterate over all werds in the row. WERD_IT werd_it(row->word_list()); for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) { WERD* werd = werd_it.data(); return_list_it.move_to_last(); return_list_it.add_list_after(werd->cblob_list()); return_list_it.move_to_last(); return_list_it.add_list_after(werd->rej_cblob_list()); } } } } /********************************************************************** * RefreshWordBlobsFromNewBlobs() * * Refreshes the words in the block_list by using blobs in the * new_blobs list. * Block list must have word segmentation in it. * It consumes the blobs provided in the new_blobs list. The blobs leftover in * the new_blobs list after the call weren't matched to any blobs of the words * in block list. * The output not_found_blobs is a list of blobs from the original segmentation * in the block_list for which no corresponding new blobs were found. **********************************************************************/ void RefreshWordBlobsFromNewBlobs(BLOCK_LIST* block_list, C_BLOB_LIST* new_blobs, C_BLOB_LIST* not_found_blobs) { // Now iterate over all the blobs in the segmentation_block_list_, and just // replace the corresponding c-blobs inside the werds. BLOCK_IT block_it(block_list); for (block_it.mark_cycle_pt(); !block_it.cycled_list(); block_it.forward()) { BLOCK* block = block_it.data(); if (block->poly_block() != NULL && !block->poly_block()->IsText()) continue; // Don't touch non-text blocks. // Iterate over all rows in the block. ROW_IT row_it(block->row_list()); for (row_it.mark_cycle_pt(); !row_it.cycled_list(); row_it.forward()) { ROW* row = row_it.data(); // Iterate over all werds in the row. WERD_IT werd_it(row->word_list()); WERD_LIST new_words; WERD_IT new_words_it(&new_words); for (werd_it.mark_cycle_pt(); !werd_it.cycled_list(); werd_it.forward()) { WERD* werd = werd_it.extract(); WERD* new_werd = werd->ConstructWerdWithNewBlobs(new_blobs, not_found_blobs); if (new_werd) { // Insert this new werd into the actual row's werd-list. Remove the // existing one. new_words_it.add_after_then_move(new_werd); delete werd; } else { // Reinsert the older word back, for lack of better options. // This is critical since dropping the words messes up segmentation: // eg. 1st word in the row might otherwise have W_FUZZY_NON turned on. new_words_it.add_after_then_move(werd); } } // Get rid of the old word list & replace it with the new one. row->word_list()->clear(); werd_it.move_to_first(); werd_it.add_list_after(&new_words); } } }
1080228-arabicocr11
ccstruct/ocrblock.cpp
C++
asf20
17,904
/********************************************************************** * File: rejctmap.cpp (Formerly rejmap.c) * Description: REJ and REJMAP class functions. * Author: Phil Cheatle * Created: Thu Jun 9 13:46:38 BST 1994 * * (C) Copyright 1994, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "host.h" #include "rejctmap.h" #include "params.h" BOOL8 REJ::perm_rejected() { //Is char perm reject? return (flag (R_TESS_FAILURE) || flag (R_SMALL_XHT) || flag (R_EDGE_CHAR) || flag (R_1IL_CONFLICT) || flag (R_POSTNN_1IL) || flag (R_REJ_CBLOB) || flag (R_BAD_REPETITION) || flag (R_MM_REJECT)); } BOOL8 REJ::rej_before_nn_accept() { return flag (R_POOR_MATCH) || flag (R_NOT_TESS_ACCEPTED) || flag (R_CONTAINS_BLANKS) || flag (R_BAD_PERMUTER); } BOOL8 REJ::rej_between_nn_and_mm() { return flag (R_HYPHEN) || flag (R_DUBIOUS) || flag (R_NO_ALPHANUMS) || flag (R_MOSTLY_REJ) || flag (R_XHT_FIXUP); } BOOL8 REJ::rej_between_mm_and_quality_accept() { return flag (R_BAD_QUALITY); } BOOL8 REJ::rej_between_quality_and_minimal_rej_accept() { return flag (R_DOC_REJ) || flag (R_BLOCK_REJ) || flag (R_ROW_REJ) || flag (R_UNLV_REJ); } BOOL8 REJ::rej_before_mm_accept() { return rej_between_nn_and_mm () || (rej_before_nn_accept () && !flag (R_NN_ACCEPT) && !flag (R_HYPHEN_ACCEPT)); } BOOL8 REJ::rej_before_quality_accept() { return rej_between_mm_and_quality_accept () || (!flag (R_MM_ACCEPT) && rej_before_mm_accept ()); } BOOL8 REJ::rejected() { //Is char rejected? if (flag (R_MINIMAL_REJ_ACCEPT)) return FALSE; else return (perm_rejected () || rej_between_quality_and_minimal_rej_accept () || (!flag (R_QUALITY_ACCEPT) && rej_before_quality_accept ())); } BOOL8 REJ::accept_if_good_quality() { //potential rej? return (rejected () && !perm_rejected () && flag (R_BAD_PERMUTER) && !flag (R_POOR_MATCH) && !flag (R_NOT_TESS_ACCEPTED) && !flag (R_CONTAINS_BLANKS) && (!rej_between_nn_and_mm () && !rej_between_mm_and_quality_accept () && !rej_between_quality_and_minimal_rej_accept ())); } void REJ::setrej_tess_failure() { //Tess generated blank set_flag(R_TESS_FAILURE); } void REJ::setrej_small_xht() { //Small xht char/wd set_flag(R_SMALL_XHT); } void REJ::setrej_edge_char() { //Close to image edge set_flag(R_EDGE_CHAR); } void REJ::setrej_1Il_conflict() { //Initial reject map set_flag(R_1IL_CONFLICT); } void REJ::setrej_postNN_1Il() { //1Il after NN set_flag(R_POSTNN_1IL); } void REJ::setrej_rej_cblob() { //Insert duff blob set_flag(R_REJ_CBLOB); } void REJ::setrej_mm_reject() { //Matrix matcher set_flag(R_MM_REJECT); } void REJ::setrej_bad_repetition() { //Odd repeated char set_flag(R_BAD_REPETITION); } void REJ::setrej_poor_match() { //Failed Rays heuristic set_flag(R_POOR_MATCH); } void REJ::setrej_not_tess_accepted() { //TEMP reject_word set_flag(R_NOT_TESS_ACCEPTED); } void REJ::setrej_contains_blanks() { //TEMP reject_word set_flag(R_CONTAINS_BLANKS); } void REJ::setrej_bad_permuter() { //POTENTIAL reject_word set_flag(R_BAD_PERMUTER); } void REJ::setrej_hyphen() { //PostNN dubious hyphen or . set_flag(R_HYPHEN); } void REJ::setrej_dubious() { //PostNN dubious limit set_flag(R_DUBIOUS); } void REJ::setrej_no_alphanums() { //TEMP reject_word set_flag(R_NO_ALPHANUMS); } void REJ::setrej_mostly_rej() { //TEMP reject_word set_flag(R_MOSTLY_REJ); } void REJ::setrej_xht_fixup() { //xht fixup set_flag(R_XHT_FIXUP); } void REJ::setrej_bad_quality() { //TEMP reject_word set_flag(R_BAD_QUALITY); } void REJ::setrej_doc_rej() { //TEMP reject_word set_flag(R_DOC_REJ); } void REJ::setrej_block_rej() { //TEMP reject_word set_flag(R_BLOCK_REJ); } void REJ::setrej_row_rej() { //TEMP reject_word set_flag(R_ROW_REJ); } void REJ::setrej_unlv_rej() { //TEMP reject_word set_flag(R_UNLV_REJ); } void REJ::setrej_hyphen_accept() { //NN Flipped a char set_flag(R_HYPHEN_ACCEPT); } void REJ::setrej_nn_accept() { //NN Flipped a char set_flag(R_NN_ACCEPT); } void REJ::setrej_mm_accept() { //Matrix matcher set_flag(R_MM_ACCEPT); } void REJ::setrej_quality_accept() { //Quality flip a char set_flag(R_QUALITY_ACCEPT); } void REJ::setrej_minimal_rej_accept() { //Accept all except blank set_flag(R_MINIMAL_REJ_ACCEPT); } void REJ::full_print(FILE *fp) { fprintf (fp, "R_TESS_FAILURE: %s\n", flag (R_TESS_FAILURE) ? "T" : "F"); fprintf (fp, "R_SMALL_XHT: %s\n", flag (R_SMALL_XHT) ? "T" : "F"); fprintf (fp, "R_EDGE_CHAR: %s\n", flag (R_EDGE_CHAR) ? "T" : "F"); fprintf (fp, "R_1IL_CONFLICT: %s\n", flag (R_1IL_CONFLICT) ? "T" : "F"); fprintf (fp, "R_POSTNN_1IL: %s\n", flag (R_POSTNN_1IL) ? "T" : "F"); fprintf (fp, "R_REJ_CBLOB: %s\n", flag (R_REJ_CBLOB) ? "T" : "F"); fprintf (fp, "R_MM_REJECT: %s\n", flag (R_MM_REJECT) ? "T" : "F"); fprintf (fp, "R_BAD_REPETITION: %s\n", flag (R_BAD_REPETITION) ? "T" : "F"); fprintf (fp, "R_POOR_MATCH: %s\n", flag (R_POOR_MATCH) ? "T" : "F"); fprintf (fp, "R_NOT_TESS_ACCEPTED: %s\n", flag (R_NOT_TESS_ACCEPTED) ? "T" : "F"); fprintf (fp, "R_CONTAINS_BLANKS: %s\n", flag (R_CONTAINS_BLANKS) ? "T" : "F"); fprintf (fp, "R_BAD_PERMUTER: %s\n", flag (R_BAD_PERMUTER) ? "T" : "F"); fprintf (fp, "R_HYPHEN: %s\n", flag (R_HYPHEN) ? "T" : "F"); fprintf (fp, "R_DUBIOUS: %s\n", flag (R_DUBIOUS) ? "T" : "F"); fprintf (fp, "R_NO_ALPHANUMS: %s\n", flag (R_NO_ALPHANUMS) ? "T" : "F"); fprintf (fp, "R_MOSTLY_REJ: %s\n", flag (R_MOSTLY_REJ) ? "T" : "F"); fprintf (fp, "R_XHT_FIXUP: %s\n", flag (R_XHT_FIXUP) ? "T" : "F"); fprintf (fp, "R_BAD_QUALITY: %s\n", flag (R_BAD_QUALITY) ? "T" : "F"); fprintf (fp, "R_DOC_REJ: %s\n", flag (R_DOC_REJ) ? "T" : "F"); fprintf (fp, "R_BLOCK_REJ: %s\n", flag (R_BLOCK_REJ) ? "T" : "F"); fprintf (fp, "R_ROW_REJ: %s\n", flag (R_ROW_REJ) ? "T" : "F"); fprintf (fp, "R_UNLV_REJ: %s\n", flag (R_UNLV_REJ) ? "T" : "F"); fprintf (fp, "R_HYPHEN_ACCEPT: %s\n", flag (R_HYPHEN_ACCEPT) ? "T" : "F"); fprintf (fp, "R_NN_ACCEPT: %s\n", flag (R_NN_ACCEPT) ? "T" : "F"); fprintf (fp, "R_MM_ACCEPT: %s\n", flag (R_MM_ACCEPT) ? "T" : "F"); fprintf (fp, "R_QUALITY_ACCEPT: %s\n", flag (R_QUALITY_ACCEPT) ? "T" : "F"); fprintf (fp, "R_MINIMAL_REJ_ACCEPT: %s\n", flag (R_MINIMAL_REJ_ACCEPT) ? "T" : "F"); } //The REJMAP class has been hacked to use alloc_struct instead of new []. //This is to reduce memory fragmentation only as it is rather kludgy. //alloc_struct by-passes the call to the contsructor of REJ on each //array element. Although the constructor is empty, the BITS16 members //do have a constructor which sets all the flags to 0. The memset //replaces this functionality. REJMAP::REJMAP( //classwise copy const REJMAP &source) { REJ *to; REJ *from = source.ptr; int i; len = source.length (); if (len > 0) { ptr = (REJ *) alloc_struct (len * sizeof (REJ), "REJ"); to = ptr; for (i = 0; i < len; i++) { *to = *from; to++; from++; } } else ptr = NULL; } REJMAP & REJMAP::operator= ( //assign REJMAP const REJMAP & source //from this ) { REJ * to; REJ * from = source.ptr; int i; initialise (source.len); to = ptr; for (i = 0; i < len; i++) { *to = *from; to++; from++; } return *this; } void REJMAP::initialise( //Redefine map inT16 length) { if (ptr != NULL) free_struct (ptr, len * sizeof (REJ), "REJ"); len = length; if (len > 0) ptr = (REJ *) memset (alloc_struct (len * sizeof (REJ), "REJ"), 0, len * sizeof (REJ)); else ptr = NULL; } inT16 REJMAP::accept_count() { //How many accepted? int i; inT16 count = 0; for (i = 0; i < len; i++) { if (ptr[i].accepted ()) count++; } return count; } BOOL8 REJMAP::recoverable_rejects() { //Any non perm rejs? int i; for (i = 0; i < len; i++) { if (ptr[i].recoverable ()) return TRUE; } return FALSE; } BOOL8 REJMAP::quality_recoverable_rejects() { //Any potential rejs? int i; for (i = 0; i < len; i++) { if (ptr[i].accept_if_good_quality ()) return TRUE; } return FALSE; } void REJMAP::remove_pos( //Cut out an element inT16 pos //element to remove ) { REJ *new_ptr; //new, smaller map int i; ASSERT_HOST (pos >= 0); ASSERT_HOST (pos < len); ASSERT_HOST (len > 0); len--; if (len > 0) new_ptr = (REJ *) memset (alloc_struct (len * sizeof (REJ), "REJ"), 0, len * sizeof (REJ)); else new_ptr = NULL; for (i = 0; i < pos; i++) new_ptr[i] = ptr[i]; //copy pre pos for (; pos < len; pos++) new_ptr[pos] = ptr[pos + 1]; //copy post pos //delete old map free_struct (ptr, (len + 1) * sizeof (REJ), "REJ"); ptr = new_ptr; } void REJMAP::print(FILE *fp) { int i; char buff[512]; for (i = 0; i < len; i++) { buff[i] = ptr[i].display_char (); } buff[i] = '\0'; fprintf (fp, "\"%s\"", buff); } void REJMAP::full_print(FILE *fp) { int i; for (i = 0; i < len; i++) { ptr[i].full_print (fp); fprintf (fp, "\n"); } } void REJMAP::rej_word_small_xht() { //Reject whole word int i; for (i = 0; i < len; i++) { ptr[i].setrej_small_xht (); } } void REJMAP::rej_word_tess_failure() { //Reject whole word int i; for (i = 0; i < len; i++) { ptr[i].setrej_tess_failure (); } } void REJMAP::rej_word_not_tess_accepted() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_not_tess_accepted(); } } void REJMAP::rej_word_contains_blanks() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_contains_blanks(); } } void REJMAP::rej_word_bad_permuter() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_bad_permuter (); } } void REJMAP::rej_word_xht_fixup() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_xht_fixup(); } } void REJMAP::rej_word_no_alphanums() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_no_alphanums(); } } void REJMAP::rej_word_mostly_rej() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_mostly_rej(); } } void REJMAP::rej_word_bad_quality() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_bad_quality(); } } void REJMAP::rej_word_doc_rej() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_doc_rej(); } } void REJMAP::rej_word_block_rej() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_block_rej(); } } void REJMAP::rej_word_row_rej() { //Reject whole word int i; for (i = 0; i < len; i++) { if (ptr[i].accepted()) ptr[i].setrej_row_rej(); } }
1080228-arabicocr11
ccstruct/rejctmap.cpp
C++
asf20
11,983
/********************************************************************** * File: points.c (Formerly coords.c) * Description: Member functions for coordinate classes. * Author: Ray Smith * Created: Fri Mar 15 08:58:17 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifdef _MSC_VER #define _USE_MATH_DEFINES #endif // _MSC_VER #include <stdlib.h> #include "helpers.h" #include "ndminx.h" #include "serialis.h" #include "points.h" ELISTIZE (ICOORDELT) //turn to list bool FCOORD::normalise() { //Convert to unit vec float len = length (); if (len < 0.0000000001) { return false; } xcoord /= len; ycoord /= len; return true; } // Set from the given x,y, shrinking the vector to fit if needed. void ICOORD::set_with_shrink(int x, int y) { // Fit the vector into an ICOORD, which is 16 bit. int factor = 1; int max_extent = MAX(abs(x), abs(y)); if (max_extent > MAX_INT16) factor = max_extent / MAX_INT16 + 1; xcoord = x / factor; ycoord = y / factor; } // The fortran/basic sgn function returns -1, 0, 1 if x < 0, x == 0, x > 0 // respectively. static int sign(int x) { if (x < 0) return -1; else return x > 0 ? 1 : 0; } // Writes to the given file. Returns false in case of error. bool ICOORD::Serialize(FILE* fp) const { if (fwrite(&xcoord, sizeof(xcoord), 1, fp) != 1) return false; if (fwrite(&ycoord, sizeof(ycoord), 1, fp) != 1) return false; return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool ICOORD::DeSerialize(bool swap, FILE* fp) { if (fread(&xcoord, sizeof(xcoord), 1, fp) != 1) return false; if (fread(&ycoord, sizeof(ycoord), 1, fp) != 1) return false; if (swap) { ReverseN(&xcoord, sizeof(xcoord)); ReverseN(&ycoord, sizeof(ycoord)); } return true; } // Setup for iterating over the pixels in a vector by the well-known // Bresenham rendering algorithm. // Starting with major/2 in the accumulator, on each step add major_step, // and then add minor to the accumulator. When the accumulator >= major // subtract major and step a minor step. void ICOORD::setup_render(ICOORD* major_step, ICOORD* minor_step, int* major, int* minor) const { int abs_x = abs(xcoord); int abs_y = abs(ycoord); if (abs_x >= abs_y) { // X-direction is major. major_step->xcoord = sign(xcoord); major_step->ycoord = 0; minor_step->xcoord = 0; minor_step->ycoord = sign(ycoord); *major = abs_x; *minor = abs_y; } else { // Y-direction is major. major_step->xcoord = 0; major_step->ycoord = sign(ycoord); minor_step->xcoord = sign(xcoord); minor_step->ycoord = 0; *major = abs_y; *minor = abs_x; } } // Returns the standard feature direction corresponding to this. // See binary_angle_plus_pi below for a description of the direction. uinT8 FCOORD::to_direction() const { return binary_angle_plus_pi(angle()); } // Sets this with a unit vector in the given standard feature direction. void FCOORD::from_direction(uinT8 direction) { double radians = angle_from_direction(direction); xcoord = cos(radians); ycoord = sin(radians); } // Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a // standard feature direction as an unsigned angle in 256ths of a circle // measured anticlockwise from (-1, 0). uinT8 FCOORD::binary_angle_plus_pi(double radians) { return Modulo(IntCastRounded((radians + M_PI) * 128.0 / M_PI), 256); } // Inverse of binary_angle_plus_pi returns an angle in radians for the // given standard feature direction. double FCOORD::angle_from_direction(uinT8 direction) { return direction * M_PI / 128.0 - M_PI; } // Returns the point on the given line nearest to this, ie the point such // that the vector point->this is perpendicular to the line. // The line is defined as a line_point and a dir_vector for its direction. FCOORD FCOORD::nearest_pt_on_line(const FCOORD& line_point, const FCOORD& dir_vector) const { FCOORD point_vector(*this - line_point); // The dot product (%) is |dir_vector||point_vector|cos theta, so dividing by // the square of the length of dir_vector gives us the fraction of dir_vector // to add to line1 to get the appropriate point, so // result = line1 + lambda dir_vector. double lambda = point_vector % dir_vector / dir_vector.sqlength(); return line_point + (dir_vector * lambda); }
1080228-arabicocr11
ccstruct/points.cpp
C++
asf20
5,177
/////////////////////////////////////////////////////////////////////// // File: boxword.h // Description: Class to represent the bounding boxes of the output. // Author: Ray Smith // Created: Tue May 25 14:18:14 PDT 2010 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CSTRUCT_BOXWORD_H__ #define TESSERACT_CSTRUCT_BOXWORD_H__ #include "genericvector.h" #include "rect.h" #include "unichar.h" class BLOCK; class DENORM; struct TWERD; class UNICHARSET; class WERD; class WERD_CHOICE; class WERD_RES; namespace tesseract { // Class to hold an array of bounding boxes for an output word and // the bounding box of the whole word. class BoxWord { public: BoxWord(); explicit BoxWord(const BoxWord& src); ~BoxWord(); BoxWord& operator=(const BoxWord& src); void CopyFrom(const BoxWord& src); // Factory to build a BoxWord from a TWERD using the DENORMs on each blob to // switch back to original image coordinates. static BoxWord* CopyFromNormalized(TWERD* tessword); // Clean up the bounding boxes from the polygonal approximation by // expanding slightly, then clipping to the blobs from the original_word // that overlap. If not null, the block provides the inverse rotation. void ClipToOriginalWord(const BLOCK* block, WERD* original_word); // Merges the boxes from start to end, not including end, and deletes // the boxes between start and end. void MergeBoxes(int start, int end); // Inserts a new box before the given index. // Recomputes the bounding box. void InsertBox(int index, const TBOX& box); // Changes the box at the given index to the new box. // Recomputes the bounding box. void ChangeBox(int index, const TBOX& box); // Deletes the box with the given index, and shuffles up the rest. // Recomputes the bounding box. void DeleteBox(int index); // Deletes all the boxes stored in BoxWord. void DeleteAllBoxes(); // This and other putatively are the same, so call the (permanent) callback // for each blob index where the bounding boxes match. // The callback is deleted on completion. void ProcessMatchedBlobs(const TWERD& other, TessCallback1<int>* cb) const; const TBOX& bounding_box() const { return bbox_; } const int length() const { return length_; } const TBOX& BlobBox(int index) const { return boxes_[index]; } private: void ComputeBoundingBox(); TBOX bbox_; int length_; GenericVector<TBOX> boxes_; }; } // namespace tesseract. #endif // TESSERACT_CSTRUCT_BOXWORD_H__
1080228-arabicocr11
ccstruct/boxword.h
C++
asf20
3,155
/////////////////////////////////////////////////////////////////////// // File: params_training_featdef.cpp // Description: Utility functions for params training features. // Author: David Eger // Created: Mon Jun 11 11:26:42 PDT 2012 // // (C) Copyright 2012, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include <string.h> #include "params_training_featdef.h" namespace tesseract { int ParamsTrainingFeatureByName(const char *name) { if (name == NULL) return -1; int array_size = sizeof(kParamsTrainingFeatureTypeName) / sizeof(kParamsTrainingFeatureTypeName[0]); for (int i = 0; i < array_size; i++) { if (kParamsTrainingFeatureTypeName[i] == NULL) continue; if (strcmp(name, kParamsTrainingFeatureTypeName[i]) == 0) return i; } return -1; } } // namespace tesseract
1080228-arabicocr11
ccstruct/params_training_featdef.cpp
C++
asf20
1,419
AM_CPPFLAGS += \ -I$(top_srcdir)/ccutil -I$(top_srcdir)/cutil \ -I$(top_srcdir)/viewer \ -I$(top_srcdir)/opencl if USE_OPENCL AM_CPPFLAGS += -I$(OPENCL_HDR_PATH) endif if VISIBILITY AM_CPPFLAGS += -DTESS_EXPORTS \ -fvisibility=hidden -fvisibility-inlines-hidden endif include_HEADERS = publictypes.h noinst_HEADERS = \ blamer.h blckerr.h blobbox.h blobs.h blread.h boxread.h boxword.h ccstruct.h coutln.h crakedge.h \ detlinefit.h dppoint.h fontinfo.h genblob.h hpdsizes.h \ ## imagedata.h \ ipoints.h \ linlsq.h matrix.h mod128.h normalis.h \ ocrblock.h ocrpara.h ocrrow.h otsuthr.h \ pageres.h params_training_featdef.h \ pdblock.h points.h polyaprx.h polyblk.h \ quadlsq.h quadratc.h quspline.h ratngs.h rect.h rejctmap.h \ seam.h split.h statistc.h stepblob.h vecfuncs.h werd.h if !USING_MULTIPLELIBS noinst_LTLIBRARIES = libtesseract_ccstruct.la else lib_LTLIBRARIES = libtesseract_ccstruct.la libtesseract_ccstruct_la_LDFLAGS = -version-info $(GENERIC_LIBRARY_VERSION) libtesseract_ccstruct_la_LIBADD = \ ../ccutil/libtesseract_ccutil.la \ ../cutil/libtesseract_cutil.la \ ../viewer/libtesseract_viewer.la \ ../opencl/libtesseract_opencl.la endif libtesseract_ccstruct_la_SOURCES = \ blamer.cpp blobbox.cpp blobs.cpp blread.cpp boxread.cpp boxword.cpp ccstruct.cpp coutln.cpp \ detlinefit.cpp dppoint.cpp fontinfo.cpp genblob.cpp \ ## imagedata.cpp \ linlsq.cpp matrix.cpp mod128.cpp normalis.cpp \ ocrblock.cpp ocrpara.cpp ocrrow.cpp otsuthr.cpp \ pageres.cpp pdblock.cpp points.cpp polyaprx.cpp polyblk.cpp \ params_training_featdef.cpp publictypes.cpp \ quadlsq.cpp quspline.cpp ratngs.cpp rect.cpp rejctmap.cpp \ seam.cpp split.cpp statistc.cpp stepblob.cpp \ vecfuncs.cpp werd.cpp
1080228-arabicocr11
ccstruct/Makefile.am
Makefile
asf20
1,812
/////////////////////////////////////////////////////////////////////// // File: detlinefit.h // Description: Deterministic least upper-quartile squares line fitting. // Author: Ray Smith // Created: Thu Feb 28 14:35:01 PDT 2008 // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCSTRUCT_DETLINEFIT_H_ #define TESSERACT_CCSTRUCT_DETLINEFIT_H_ #include "genericvector.h" #include "kdpair.h" #include "points.h" namespace tesseract { // This class fits a line to a set of ICOORD points. // There is no restriction on the direction of the line, as it // uses a vector method, ie no concern over infinite gradients. // The fitted line has the least upper quartile of squares of perpendicular // distances of all source points from the line, subject to the constraint // that the line is made from one of the pairs of [{p1,p2,p3},{pn-2, pn-1, pn}] // i.e. the 9 combinations of one of the first 3 and last 3 points. // A fundamental assumption of this algorithm is that one of the first 3 and // one of the last 3 points are near the best line fit. // The points must be Added in line order for the algorithm to work properly. // No floating point calculations are needed* to make an accurate fit, // and no random numbers are needed** so the algorithm is deterministic, // architecture-stable, and compiler-stable as well as stable to minor // changes in the input. // *A single floating point division is used to compute each line's distance. // This is unlikely to result in choice of a different line, but if it does, // it would be easy to replace with a 64 bit integer calculation. // **Random numbers are used in the nth_item function, but the worst // non-determinism that can result is picking a different result among equals, // and that wouldn't make any difference to the end-result distance, so the // randomness does not affect the determinism of the algorithm. The random // numbers are only there to guarantee average linear time. // Fitting time is linear, but with a high constant, as it tries 9 different // lines and computes the distance of all points each time. // This class is aimed at replacing the LLSQ (linear least squares) and // LMS (least median of squares) classes that are currently used for most // of the line fitting in Tesseract. class DetLineFit { public: DetLineFit(); ~DetLineFit(); // Delete all Added points. void Clear(); // Adds a new point. Takes a copy - the pt doesn't need to stay in scope. // Add must be called on points in sequence along the line. void Add(const ICOORD& pt); // Associates a half-width with the given point if a point overlaps the // previous point by more than half the width, and its distance is further // than the previous point, then the more distant point is ignored in the // distance calculation. Useful for ignoring i dots and other diacritics. void Add(const ICOORD& pt, int halfwidth); // Fits a line to the points, returning the fitted line as a pair of // points, and the upper quartile error. double Fit(ICOORD* pt1, ICOORD* pt2) { return Fit(0, 0, pt1, pt2); } // Fits a line to the points, ignoring the skip_first initial points and the // skip_last final points, returning the fitted line as a pair of points, // and the upper quartile error. double Fit(int skip_first, int skip_last, ICOORD* pt1, ICOORD* pt2); // Constrained fit with a supplied direction vector. Finds the best line_pt, // that is one of the supplied points having the median cross product with // direction, ignoring points that have a cross product outside of the range // [min_dist, max_dist]. Returns the resulting error metric using the same // reduced set of points. // *Makes use of floating point arithmetic* double ConstrainedFit(const FCOORD& direction, double min_dist, double max_dist, bool debug, ICOORD* line_pt); // Returns true if there were enough points at the last call to Fit or // ConstrainedFit for the fitted points to be used on a badly fitted line. bool SufficientPointsForIndependentFit() const; // Backwards compatible fit returning a gradient and constant. // Deprecated. Prefer Fit(ICOORD*, ICOORD*) where possible, but use this // function in preference to the LMS class. double Fit(float* m, float* c); // Backwards compatible constrained fit with a supplied gradient. // Deprecated. Use ConstrainedFit(const FCOORD& direction) where possible // to avoid potential difficulties with infinite gradients. double ConstrainedFit(double m, float* c); private: // Simple struct to hold an ICOORD point and a halfwidth representing half // the "width" (supposedly approximately parallel to the direction of the // line) of each point, such that distant points can be discarded when they // overlap nearer points. (Think i dot and other diacritics or noise.) struct PointWidth { PointWidth() : pt(ICOORD(0, 0)), halfwidth(0) {} PointWidth(const ICOORD& pt0, int halfwidth0) : pt(pt0), halfwidth(halfwidth0) {} ICOORD pt; int halfwidth; }; // Type holds the distance of each point from the fitted line and the point // itself. Use of double allows integer distances from ICOORDs to be stored // exactly, and also the floating point results from ConstrainedFit. typedef KDPairInc<double, ICOORD> DistPointPair; // Computes and returns the squared evaluation metric for a line fit. double EvaluateLineFit(); // Computes the absolute values of the precomputed distances_, // and returns the squared upper-quartile error distance. double ComputeUpperQuartileError(); // Returns the number of sample points that have an error more than threshold. int NumberOfMisfittedPoints(double threshold) const; // Computes all the cross product distances of the points from the line, // storing the actual (signed) cross products in distances_. // Ignores distances of points that are further away than the previous point, // and overlaps the previous point by at least half. void ComputeDistances(const ICOORD& start, const ICOORD& end); // Computes all the cross product distances of the points perpendicular to // the given direction, ignoring distances outside of the give distance range, // storing the actual (signed) cross products in distances_. void ComputeConstrainedDistances(const FCOORD& direction, double min_dist, double max_dist); // Stores all the source points in the order they were given and their // halfwidths, if any. GenericVector<PointWidth> pts_; // Stores the computed perpendicular distances of (some of) the pts_ from a // given vector (assuming it goes through the origin, making it a line). // Since the distances may be a subset of the input points, and get // re-ordered by the nth_item function, the original point is stored // along side the distance. GenericVector<DistPointPair> distances_; // Distances of points. // The squared length of the vector used to compute distances_. double square_length_; }; } // namespace tesseract. #endif // TESSERACT_CCSTRUCT_DETLINEFIT_H_
1080228-arabicocr11
ccstruct/detlinefit.h
C++
asf20
7,795
/********************************************************************** * File: dppoint.h * Description: Simple generic dynamic programming class. * Author: Ray Smith * Created: Wed Mar 25 18:57:01 PDT 2009 * * (C) Copyright 2009, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef TESSERACT_CCSTRUCT_DPPOINT_H__ #define TESSERACT_CCSTRUCT_DPPOINT_H__ #include "host.h" namespace tesseract { // A simple class to provide a dynamic programming solution to a class of // 1st-order problems in which the cost is dependent only on the current // step and the best cost to that step, with a possible special case // of using the variance of the steps, and only the top choice is required. // Useful for problems such as finding the optimal cut points in a fixed-pitch // (vertical or horizontal) situation. // Skeletal Example: // DPPoint* array = new DPPoint[width]; // for (int i = 0; i < width; i++) { // array[i].AddLocalCost(cost_at_i) // } // DPPoint* best_end = DPPoint::Solve(..., array); // while (best_end != NULL) { // int cut_index = best_end - array; // best_end = best_end->best_prev(); // } // delete [] array; class DPPoint { public: // The cost function evaluates the total cost at this (excluding this's // local_cost) and if it beats this's total_cost, then // replace the appropriate values in this. typedef inT64 (DPPoint::*CostFunc)(const DPPoint* prev); DPPoint() : local_cost_(0), total_cost_(MAX_INT32), total_steps_(1), best_prev_(NULL), n_(0), sig_x_(0), sig_xsq_(0) { } // Solve the dynamic programming problem for the given array of points, with // the given size and cost function. // Steps backwards are limited to being between min_step and max_step // inclusive. // The return value is the tail of the best path. static DPPoint* Solve(int min_step, int max_step, bool debug, CostFunc cost_func, int size, DPPoint* points); // A CostFunc that takes the variance of step into account in the cost. inT64 CostWithVariance(const DPPoint* prev); // Accessors. int total_cost() const { return total_cost_; } int Pathlength() const { return total_steps_; } const DPPoint* best_prev() const { return best_prev_; } void AddLocalCost(int new_cost) { local_cost_ += new_cost; } private: // Code common to different cost functions. // Update the other members if the cost is lower. void UpdateIfBetter(inT64 cost, inT32 steps, const DPPoint* prev, inT32 n, inT32 sig_x, inT64 sig_xsq); inT32 local_cost_; // Cost of this point on its own. inT32 total_cost_; // Sum of all costs in best path to here. // During cost calculations local_cost is excluded. inT32 total_steps_; // Number of steps in best path to here. const DPPoint* best_prev_; // Pointer to prev point in best path from here. // Information for computing the variance part of the cost. inT32 n_; // Number of steps in best path to here for variance. inT32 sig_x_; // Sum of step sizes for computing variance. inT64 sig_xsq_; // Sum of squares of steps for computing variance. }; } // namespace tesseract. #endif // TESSERACT_CCSTRUCT_DPPOINT_H__
1080228-arabicocr11
ccstruct/dppoint.h
C++
asf20
3,868
/********************************************************************** * File: coutln.c (Formerly coutline.c) * Description: Code for the C_OUTLINE class. * Author: Ray Smith * Created: Mon Oct 07 16:01:57 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <string.h> #ifdef __UNIX__ #include <assert.h> #endif #include "coutln.h" #include "allheaders.h" #include "blobs.h" #include "normalis.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif ELISTIZE (C_OUTLINE) ICOORD C_OUTLINE::step_coords[4] = { ICOORD (-1, 0), ICOORD (0, -1), ICOORD (1, 0), ICOORD (0, 1) }; /********************************************************************** * C_OUTLINE::C_OUTLINE * * Constructor to build a C_OUTLINE from a CRACKEDGE LOOP. **********************************************************************/ C_OUTLINE::C_OUTLINE ( //constructor CRACKEDGE * startpt, //outline to convert ICOORD bot_left, //bounding box ICOORD top_right, inT16 length //length of loop ):box (bot_left, top_right), start (startpt->pos), offsets(NULL) { inT16 stepindex; //index to step CRACKEDGE *edgept; //current point stepcount = length; //no of steps if (length == 0) { steps = NULL; return; } //get memory steps = (uinT8 *) alloc_mem (step_mem()); memset(steps, 0, step_mem()); edgept = startpt; for (stepindex = 0; stepindex < length; stepindex++) { //set compact step set_step (stepindex, edgept->stepdir); edgept = edgept->next; } } /********************************************************************** * C_OUTLINE::C_OUTLINE * * Constructor to build a C_OUTLINE from a C_OUTLINE_FRAG. **********************************************************************/ C_OUTLINE::C_OUTLINE ( //constructor //steps to copy ICOORD startpt, DIR128 * new_steps, inT16 length //length of loop ):start (startpt), offsets(NULL) { inT8 dirdiff; //direction difference DIR128 prevdir; //previous direction DIR128 dir; //current direction DIR128 lastdir; //dir of last step TBOX new_box; //easy bounding inT16 stepindex; //index to step inT16 srcindex; //source steps ICOORD pos; //current position pos = startpt; stepcount = length; // No. of steps. ASSERT_HOST(length >= 0); steps = reinterpret_cast<uinT8*>(alloc_mem(step_mem())); // Get memory. memset(steps, 0, step_mem()); lastdir = new_steps[length - 1]; prevdir = lastdir; for (stepindex = 0, srcindex = 0; srcindex < length; stepindex++, srcindex++) { new_box = TBOX (pos, pos); box += new_box; //copy steps dir = new_steps[srcindex]; set_step(stepindex, dir); dirdiff = dir - prevdir; pos += step (stepindex); if ((dirdiff == 64 || dirdiff == -64) && stepindex > 0) { stepindex -= 2; //cancel there-and-back prevdir = stepindex >= 0 ? step_dir (stepindex) : lastdir; } else prevdir = dir; } ASSERT_HOST (pos.x () == startpt.x () && pos.y () == startpt.y ()); do { dirdiff = step_dir (stepindex - 1) - step_dir (0); if (dirdiff == 64 || dirdiff == -64) { start += step (0); stepindex -= 2; //cancel there-and-back for (int i = 0; i < stepindex; ++i) set_step(i, step_dir(i + 1)); } } while (stepindex > 1 && (dirdiff == 64 || dirdiff == -64)); stepcount = stepindex; ASSERT_HOST (stepcount >= 4); } /********************************************************************** * C_OUTLINE::C_OUTLINE * * Constructor to build a C_OUTLINE from a rotation of a C_OUTLINE. **********************************************************************/ C_OUTLINE::C_OUTLINE( //constructor C_OUTLINE *srcline, //outline to FCOORD rotation //rotate ) : offsets(NULL) { TBOX new_box; //easy bounding inT16 stepindex; //index to step inT16 dirdiff; //direction change ICOORD pos; //current position ICOORD prevpos; //previous dest point ICOORD destpos; //destination point inT16 destindex; //index to step DIR128 dir; //coded direction uinT8 new_step; stepcount = srcline->stepcount * 2; if (stepcount == 0) { steps = NULL; box = srcline->box; box.rotate(rotation); return; } //get memory steps = (uinT8 *) alloc_mem (step_mem()); memset(steps, 0, step_mem()); for (int iteration = 0; iteration < 2; ++iteration) { DIR128 round1 = iteration == 0 ? 32 : 0; DIR128 round2 = iteration != 0 ? 32 : 0; pos = srcline->start; prevpos = pos; prevpos.rotate (rotation); start = prevpos; box = TBOX (start, start); destindex = 0; for (stepindex = 0; stepindex < srcline->stepcount; stepindex++) { pos += srcline->step (stepindex); destpos = pos; destpos.rotate (rotation); // tprintf("%i %i %i %i ", destpos.x(), destpos.y(), pos.x(), pos.y()); while (destpos.x () != prevpos.x () || destpos.y () != prevpos.y ()) { dir = DIR128 (FCOORD (destpos - prevpos)); dir += 64; //turn to step style new_step = dir.get_dir (); // tprintf(" %i\n", new_step); if (new_step & 31) { set_step(destindex++, dir + round1); prevpos += step(destindex - 1); if (destindex < 2 || ((dirdiff = step_dir (destindex - 1) - step_dir (destindex - 2)) != -64 && dirdiff != 64)) { set_step(destindex++, dir + round2); prevpos += step(destindex - 1); } else { prevpos -= step(destindex - 1); destindex--; prevpos -= step(destindex - 1); set_step(destindex - 1, dir + round2); prevpos += step(destindex - 1); } } else { set_step(destindex++, dir); prevpos += step(destindex - 1); } while (destindex >= 2 && ((dirdiff = step_dir (destindex - 1) - step_dir (destindex - 2)) == -64 || dirdiff == 64)) { prevpos -= step(destindex - 1); prevpos -= step(destindex - 2); destindex -= 2; // Forget u turn } //ASSERT_HOST(prevpos.x() == destpos.x() && prevpos.y() == destpos.y()); new_box = TBOX (destpos, destpos); box += new_box; } } ASSERT_HOST (destpos.x () == start.x () && destpos.y () == start.y ()); dirdiff = step_dir (destindex - 1) - step_dir (0); while ((dirdiff == 64 || dirdiff == -64) && destindex > 1) { start += step (0); destindex -= 2; for (int i = 0; i < destindex; ++i) set_step(i, step_dir(i + 1)); dirdiff = step_dir (destindex - 1) - step_dir (0); } if (destindex >= 4) break; } ASSERT_HOST(destindex <= stepcount); stepcount = destindex; destpos = start; for (stepindex = 0; stepindex < stepcount; stepindex++) { destpos += step (stepindex); } ASSERT_HOST (destpos.x () == start.x () && destpos.y () == start.y ()); } // Build a fake outline, given just a bounding box and append to the list. void C_OUTLINE::FakeOutline(const TBOX& box, C_OUTLINE_LIST* outlines) { C_OUTLINE_IT ol_it(outlines); // Make a C_OUTLINE from the bounds. This is a bit of a hack, // as there is no outline, just a bounding box, but it works nicely. CRACKEDGE start; start.pos = box.topleft(); C_OUTLINE* outline = new C_OUTLINE(&start, box.topleft(), box.botright(), 0); ol_it.add_to_end(outline); } /********************************************************************** * C_OUTLINE::area * * Compute the area of the outline. **********************************************************************/ inT32 C_OUTLINE::area() const { int stepindex; //current step inT32 total_steps; //steps to do inT32 total; //total area ICOORD pos; //position of point ICOORD next_step; //step to next pix // We aren't going to modify the list, or its contents, but there is // no const iterator. C_OUTLINE_IT it(const_cast<C_OUTLINE_LIST*>(&children)); pos = start_pos (); total_steps = pathlength (); total = 0; for (stepindex = 0; stepindex < total_steps; stepindex++) { //all intersected next_step = step (stepindex); if (next_step.x () < 0) total += pos.y (); else if (next_step.x () > 0) total -= pos.y (); pos += next_step; } for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) total += it.data ()->area ();//add areas of children return total; } /********************************************************************** * C_OUTLINE::perimeter * * Compute the perimeter of the outline and its first level children. **********************************************************************/ inT32 C_OUTLINE::perimeter() const { inT32 total_steps; // Return value. // We aren't going to modify the list, or its contents, but there is // no const iterator. C_OUTLINE_IT it(const_cast<C_OUTLINE_LIST*>(&children)); total_steps = pathlength(); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) total_steps += it.data()->pathlength(); // Add perimeters of children. return total_steps; } /********************************************************************** * C_OUTLINE::outer_area * * Compute the area of the outline. **********************************************************************/ inT32 C_OUTLINE::outer_area() const { int stepindex; //current step inT32 total_steps; //steps to do inT32 total; //total area ICOORD pos; //position of point ICOORD next_step; //step to next pix pos = start_pos (); total_steps = pathlength (); if (total_steps == 0) return box.area(); total = 0; for (stepindex = 0; stepindex < total_steps; stepindex++) { //all intersected next_step = step (stepindex); if (next_step.x () < 0) total += pos.y (); else if (next_step.x () > 0) total -= pos.y (); pos += next_step; } return total; } /********************************************************************** * C_OUTLINE::count_transitions * * Compute the number of x and y maxes and mins in the outline. **********************************************************************/ inT32 C_OUTLINE::count_transitions( //winding number inT32 threshold //on size ) { BOOL8 first_was_max_x; //what was first BOOL8 first_was_max_y; BOOL8 looking_for_max_x; //what is next BOOL8 looking_for_min_x; BOOL8 looking_for_max_y; //what is next BOOL8 looking_for_min_y; int stepindex; //current step inT32 total_steps; //steps to do //current limits inT32 max_x, min_x, max_y, min_y; inT32 initial_x, initial_y; //initial limits inT32 total; //total changes ICOORD pos; //position of point ICOORD next_step; //step to next pix pos = start_pos (); total_steps = pathlength (); total = 0; max_x = min_x = pos.x (); max_y = min_y = pos.y (); looking_for_max_x = TRUE; looking_for_min_x = TRUE; looking_for_max_y = TRUE; looking_for_min_y = TRUE; first_was_max_x = FALSE; first_was_max_y = FALSE; initial_x = pos.x (); initial_y = pos.y (); //stop uninit warning for (stepindex = 0; stepindex < total_steps; stepindex++) { //all intersected next_step = step (stepindex); pos += next_step; if (next_step.x () < 0) { if (looking_for_max_x && pos.x () < min_x) min_x = pos.x (); if (looking_for_min_x && max_x - pos.x () > threshold) { if (looking_for_max_x) { initial_x = max_x; first_was_max_x = FALSE; } total++; looking_for_max_x = TRUE; looking_for_min_x = FALSE; min_x = pos.x (); //reset min } } else if (next_step.x () > 0) { if (looking_for_min_x && pos.x () > max_x) max_x = pos.x (); if (looking_for_max_x && pos.x () - min_x > threshold) { if (looking_for_min_x) { initial_x = min_x; //remember first min first_was_max_x = TRUE; } total++; looking_for_max_x = FALSE; looking_for_min_x = TRUE; max_x = pos.x (); } } else if (next_step.y () < 0) { if (looking_for_max_y && pos.y () < min_y) min_y = pos.y (); if (looking_for_min_y && max_y - pos.y () > threshold) { if (looking_for_max_y) { initial_y = max_y; //remember first max first_was_max_y = FALSE; } total++; looking_for_max_y = TRUE; looking_for_min_y = FALSE; min_y = pos.y (); //reset min } } else { if (looking_for_min_y && pos.y () > max_y) max_y = pos.y (); if (looking_for_max_y && pos.y () - min_y > threshold) { if (looking_for_min_y) { initial_y = min_y; //remember first min first_was_max_y = TRUE; } total++; looking_for_max_y = FALSE; looking_for_min_y = TRUE; max_y = pos.y (); } } } if (first_was_max_x && looking_for_min_x) { if (max_x - initial_x > threshold) total++; else total--; } else if (!first_was_max_x && looking_for_max_x) { if (initial_x - min_x > threshold) total++; else total--; } if (first_was_max_y && looking_for_min_y) { if (max_y - initial_y > threshold) total++; else total--; } else if (!first_was_max_y && looking_for_max_y) { if (initial_y - min_y > threshold) total++; else total--; } return total; } /********************************************************************** * C_OUTLINE::operator< * * Return TRUE if the left operand is inside the right one. **********************************************************************/ BOOL8 C_OUTLINE::operator< ( //winding number const C_OUTLINE & other //other outline ) const { inT16 count = 0; //winding count ICOORD pos; //position of point inT32 stepindex; //index to cstep if (!box.overlap (other.box)) return FALSE; //can't be contained if (stepcount == 0) return other.box.contains(this->box); pos = start; for (stepindex = 0; stepindex < stepcount && (count = other.winding_number (pos)) == INTERSECTING; stepindex++) pos += step (stepindex); //try all points if (count == INTERSECTING) { //all intersected pos = other.start; for (stepindex = 0; stepindex < other.stepcount && (count = winding_number (pos)) == INTERSECTING; stepindex++) //try other way round pos += other.step (stepindex); return count == INTERSECTING || count == 0; } return count != 0; } /********************************************************************** * C_OUTLINE::winding_number * * Return the winding number of the outline around the given point. **********************************************************************/ inT16 C_OUTLINE::winding_number( //winding number ICOORD point //point to wind around ) const { inT16 stepindex; //index to cstep inT16 count; //winding count ICOORD vec; //to current point ICOORD stepvec; //step vector inT32 cross; //cross product vec = start - point; //vector to it count = 0; for (stepindex = 0; stepindex < stepcount; stepindex++) { stepvec = step (stepindex); //get the step //crossing the line if (vec.y () <= 0 && vec.y () + stepvec.y () > 0) { cross = vec * stepvec; //cross product if (cross > 0) count++; //crossing right half else if (cross == 0) return INTERSECTING; //going through point } else if (vec.y () > 0 && vec.y () + stepvec.y () <= 0) { cross = vec * stepvec; if (cross < 0) count--; //crossing back else if (cross == 0) return INTERSECTING; //illegal } vec += stepvec; //sum vectors } return count; //winding number } /********************************************************************** * C_OUTLINE::turn_direction * * Return the sum direction delta of the outline. **********************************************************************/ inT16 C_OUTLINE::turn_direction() const { //winding number DIR128 prevdir; //previous direction DIR128 dir; //current direction inT16 stepindex; //index to cstep inT8 dirdiff; //direction difference inT16 count; //winding count if (stepcount == 0) return 128; count = 0; prevdir = step_dir (stepcount - 1); for (stepindex = 0; stepindex < stepcount; stepindex++) { dir = step_dir (stepindex); dirdiff = dir - prevdir; ASSERT_HOST (dirdiff == 0 || dirdiff == 32 || dirdiff == -32); count += dirdiff; prevdir = dir; } ASSERT_HOST (count == 128 || count == -128); return count; //winding number } /********************************************************************** * C_OUTLINE::reverse * * Reverse the direction of an outline. **********************************************************************/ void C_OUTLINE::reverse() { //reverse drection DIR128 halfturn = MODULUS / 2; //amount to shift DIR128 stepdir; //direction of step inT16 stepindex; //index to cstep inT16 farindex; //index to other side inT16 halfsteps; //half of stepcount halfsteps = (stepcount + 1) / 2; for (stepindex = 0; stepindex < halfsteps; stepindex++) { farindex = stepcount - stepindex - 1; stepdir = step_dir (stepindex); set_step (stepindex, step_dir (farindex) + halfturn); set_step (farindex, stepdir + halfturn); } } /********************************************************************** * C_OUTLINE::move * * Move C_OUTLINE by vector **********************************************************************/ void C_OUTLINE::move( // reposition OUTLINE const ICOORD vec // by vector ) { C_OUTLINE_IT it(&children); // iterator box.move (vec); start += vec; for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) it.data ()->move (vec); // move child outlines } // Returns true if *this and its children are legally nested. // The outer area of a child should have the opposite sign to the // parent. If not, it means we have discarded an outline in between // (probably due to excessive length). bool C_OUTLINE::IsLegallyNested() const { if (stepcount == 0) return true; int parent_area = outer_area(); // We aren't going to modify the list, or its contents, but there is // no const iterator. C_OUTLINE_IT child_it(const_cast<C_OUTLINE_LIST*>(&children)); for (child_it.mark_cycle_pt(); !child_it.cycled_list(); child_it.forward()) { const C_OUTLINE* child = child_it.data(); if (child->outer_area() * parent_area > 0 || !child->IsLegallyNested()) return false; } return true; } // If this outline is smaller than the given min_size, delete this and // remove from its list, via *it, after checking that *it points to this. // Otherwise, if any children of this are too small, delete them. // On entry, *it must be an iterator pointing to this. If this gets deleted // then this is extracted from *it, so an iteration can continue. void C_OUTLINE::RemoveSmallRecursive(int min_size, C_OUTLINE_IT* it) { if (box.width() < min_size || box.height() < min_size) { ASSERT_HOST(this == it->data()); delete it->extract(); // Too small so get rid of it and any children. } else if (!children.empty()) { // Search the children of this, deleting any that are too small. C_OUTLINE_IT child_it(&children); for (child_it.mark_cycle_pt(); !child_it.cycled_list(); child_it.forward()) { C_OUTLINE* child = child_it.data(); child->RemoveSmallRecursive(min_size, &child_it); } } } // Factored out helpers below are used only by ComputeEdgeOffsets to operate // on data from an 8-bit Pix, and assume that any input x and/or y are already // constrained to be legal Pix coordinates. // Helper computes the local 2-D gradient (dx, dy) from the 2x2 cell centered // on the given (x,y). If the cell would go outside the image, it is padded // with white. static void ComputeGradient(const l_uint32* data, int wpl, int x, int y, int width, int height, ICOORD* gradient) { const l_uint32* line = data + y * wpl; int pix_x_y = x < width && y < height ? GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x) : 255; int pix_x_prevy = x < width && y > 0 ? GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line - wpl)), x) : 255; int pix_prevx_prevy = x > 0 && y > 0 ? GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<void const*>(line - wpl)), x - 1) : 255; int pix_prevx_y = x > 0 && y < height ? GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x - 1) : 255; gradient->set_x(pix_x_y + pix_x_prevy - (pix_prevx_y + pix_prevx_prevy)); gradient->set_y(pix_x_prevy + pix_prevx_prevy - (pix_x_y + pix_prevx_y)); } // Helper evaluates a vertical difference, (x,y) - (x,y-1), returning true if // the difference, matches diff_sign and updating the best_diff, best_sum, // best_y if a new max. static bool EvaluateVerticalDiff(const l_uint32* data, int wpl, int diff_sign, int x, int y, int height, int* best_diff, int* best_sum, int* best_y) { if (y <= 0 || y >= height) return false; const l_uint32* line = data + y * wpl; int pixel1 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line - wpl)), x); int pixel2 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x); int diff = (pixel2 - pixel1) * diff_sign; if (diff > *best_diff) { *best_diff = diff; *best_sum = pixel1 + pixel2; *best_y = y; } return diff > 0; } // Helper evaluates a horizontal difference, (x,y) - (x-1,y), where y is implied // by the input image line, returning true if the difference matches diff_sign // and updating the best_diff, best_sum, best_x if a new max. static bool EvaluateHorizontalDiff(const l_uint32* line, int diff_sign, int x, int width, int* best_diff, int* best_sum, int* best_x) { if (x <= 0 || x >= width) return false; int pixel1 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x - 1); int pixel2 = GET_DATA_BYTE(const_cast<void*> (reinterpret_cast<const void *>(line)), x); int diff = (pixel2 - pixel1) * diff_sign; if (diff > *best_diff) { *best_diff = diff; *best_sum = pixel1 + pixel2; *best_x = x; } return diff > 0; } // Adds sub-pixel resolution EdgeOffsets for the outline if the supplied // pix is 8-bit. Does nothing otherwise. // Operation: Consider the following near-horizontal line: // _________ // |________ // |________ // At *every* position along this line, the gradient direction will be close // to vertical. Extrapoaltion/interpolation of the position of the threshold // that was used to binarize the image gives a more precise vertical position // for each horizontal step, and the conflict in step direction and gradient // direction can be used to ignore the vertical steps. void C_OUTLINE::ComputeEdgeOffsets(int threshold, Pix* pix) { if (pixGetDepth(pix) != 8) return; const l_uint32* data = pixGetData(pix); int wpl = pixGetWpl(pix); int width = pixGetWidth(pix); int height = pixGetHeight(pix); bool negative = flag(COUT_INVERSE); delete [] offsets; offsets = new EdgeOffset[stepcount]; ICOORD pos = start; ICOORD prev_gradient; ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height, &prev_gradient); for (int s = 0; s < stepcount; ++s) { ICOORD step_vec = step(s); TPOINT pt1(pos); pos += step_vec; TPOINT pt2(pos); ICOORD next_gradient; ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height, &next_gradient); // Use the sum of the prev and next as the working gradient. ICOORD gradient = prev_gradient + next_gradient; // best_diff will be manipulated to be always positive. int best_diff = 0; // offset will be the extrapolation of the location of the greyscale // threshold from the edge with the largest difference, relative to the // location of the binary edge. int offset = 0; if (pt1.y == pt2.y && abs(gradient.y()) * 2 >= abs(gradient.x())) { // Horizontal step. diff_sign == 1 indicates black above. int diff_sign = (pt1.x > pt2.x) == negative ? 1 : -1; int x = MIN(pt1.x, pt2.x); int y = height - pt1.y; int best_sum = 0; int best_y = y; EvaluateVerticalDiff(data, wpl, diff_sign, x, y, height, &best_diff, &best_sum, &best_y); // Find the strongest edge. int test_y = y; do { ++test_y; } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height, &best_diff, &best_sum, &best_y)); test_y = y; do { --test_y; } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height, &best_diff, &best_sum, &best_y)); offset = diff_sign * (best_sum / 2 - threshold) + (y - best_y) * best_diff; } else if (pt1.x == pt2.x && abs(gradient.x()) * 2 >= abs(gradient.y())) { // Vertical step. diff_sign == 1 indicates black on the left. int diff_sign = (pt1.y > pt2.y) == negative ? 1 : -1; int x = pt1.x; int y = height - MAX(pt1.y, pt2.y); const l_uint32* line = pixGetData(pix) + y * wpl; int best_sum = 0; int best_x = x; EvaluateHorizontalDiff(line, diff_sign, x, width, &best_diff, &best_sum, &best_x); // Find the strongest edge. int test_x = x; do { ++test_x; } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width, &best_diff, &best_sum, &best_x)); test_x = x; do { --test_x; } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width, &best_diff, &best_sum, &best_x)); offset = diff_sign * (threshold - best_sum / 2) + (best_x - x) * best_diff; } offsets[s].offset_numerator = static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8)); offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 , MAX_UINT8)); if (negative) gradient = -gradient; // Compute gradient angle quantized to 256 directions, rotated by 64 (pi/2) // to convert from gradient direction to edge direction. offsets[s].direction = Modulo(FCOORD::binary_angle_plus_pi(gradient.angle()) + 64, 256); prev_gradient = next_gradient; } } // Adds sub-pixel resolution EdgeOffsets for the outline using only // a binary image source. // Runs a sliding window of 5 edge steps over the outline, maintaining a count // of the number of steps in each of the 4 directions in the window, and a // sum of the x or y position of each step (as appropriate to its direction.) // Ignores single-count steps EXCEPT the sharp U-turn and smoothes out the // perpendicular direction. Eg // ___ ___ Chain code from the left: // |___ ___ ___| 222122212223221232223000 // |___| |_| Corresponding counts of each direction: // 0 00000000000000000123 // 1 11121111001111100000 // 2 44434443443333343321 // 3 00000001111111112111 // Count of direction at center 41434143413313143313 // Step gets used? YNYYYNYYYNYYNYNYYYyY (y= U-turn exception) // Path redrawn showing only the used points: // ___ ___ // ___ ___ ___| // ___ _ // Sub-pixel edge position cannot be shown well with ASCII-art, but each // horizontal step's y position is the mean of the y positions of the steps // in the same direction in the sliding window, which makes a much smoother // outline, without losing important detail. void C_OUTLINE::ComputeBinaryOffsets() { delete [] offsets; offsets = new EdgeOffset[stepcount]; // Count of the number of steps in each direction in the sliding window. int dir_counts[4]; // Sum of the positions (y for a horizontal step, x for vertical) in each // direction in the sliding window. int pos_totals[4]; memset(dir_counts, 0, sizeof(dir_counts)); memset(pos_totals, 0, sizeof(pos_totals)); ICOORD pos = start; ICOORD tail_pos = pos; // tail_pos is the trailing position, with the next point to be lost from // the window. tail_pos -= step(stepcount - 1); tail_pos -= step(stepcount - 2); // head_pos is the leading position, with the next point to be added to the // window. ICOORD head_pos = tail_pos; // Set up the initial window with 4 points in [-2, 2) for (int s = -2; s < 2; ++s) { increment_step(s, 1, &head_pos, dir_counts, pos_totals); } for (int s = 0; s < stepcount; pos += step(s++)) { // At step s, s in in the middle of [s-2, s+2]. increment_step(s + 2, 1, &head_pos, dir_counts, pos_totals); int dir_index = chain_code(s); ICOORD step_vec = step(s); int best_diff = 0; int offset = 0; // Use only steps that have a count of >=2 OR the strong U-turn with a // single d and 2 at d-1 and 2 at d+1 (mod 4). if (dir_counts[dir_index] >= 2 || (dir_counts[dir_index] == 1 && dir_counts[Modulo(dir_index - 1, 4)] == 2 && dir_counts[Modulo(dir_index + 1, 4)] == 2)) { // Valid step direction. best_diff = dir_counts[dir_index]; int edge_pos = step_vec.x() == 0 ? pos.x() : pos.y(); // The offset proposes that the actual step should be positioned at // the mean position of the steps in the window of the same direction. // See ASCII art above. offset = pos_totals[dir_index] - best_diff * edge_pos; } offsets[s].offset_numerator = static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8)); offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 , MAX_UINT8)); // The direction is just the vector from start to end of the window. FCOORD direction(head_pos.x() - tail_pos.x(), head_pos.y() - tail_pos.y()); offsets[s].direction = direction.to_direction(); increment_step(s - 2, -1, &tail_pos, dir_counts, pos_totals); } } // Renders the outline to the given pix, with left and top being // the coords of the upper-left corner of the pix. void C_OUTLINE::render(int left, int top, Pix* pix) const { ICOORD pos = start; for (int stepindex = 0; stepindex < stepcount; ++stepindex) { ICOORD next_step = step(stepindex); if (next_step.y() < 0) { pixRasterop(pix, 0, top - pos.y(), pos.x() - left, 1, PIX_NOT(PIX_DST), NULL, 0, 0); } else if (next_step.y() > 0) { pixRasterop(pix, 0, top - pos.y() - 1, pos.x() - left, 1, PIX_NOT(PIX_DST), NULL, 0, 0); } pos += next_step; } } // Renders just the outline to the given pix (no fill), with left and top // being the coords of the upper-left corner of the pix. void C_OUTLINE::render_outline(int left, int top, Pix* pix) const { ICOORD pos = start; for (int stepindex = 0; stepindex < stepcount; ++stepindex) { ICOORD next_step = step(stepindex); if (next_step.y() < 0) { pixSetPixel(pix, pos.x() - left, top - pos.y(), 1); } else if (next_step.y() > 0) { pixSetPixel(pix, pos.x() - left - 1, top - pos.y() - 1, 1); } else if (next_step.x() < 0) { pixSetPixel(pix, pos.x() - left - 1, top - pos.y(), 1); } else if (next_step.x() > 0) { pixSetPixel(pix, pos.x() - left, top - pos.y() - 1, 1); } pos += next_step; } } /********************************************************************** * C_OUTLINE::plot * * Draw the outline in the given colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED void C_OUTLINE::plot( //draw it ScrollView* window, // window to draw in ScrollView::Color colour // colour to draw in ) const { inT16 stepindex; // index to cstep ICOORD pos; // current position DIR128 stepdir; // direction of step pos = start; // current position window->Pen(colour); if (stepcount == 0) { window->Rectangle(box.left(), box.top(), box.right(), box.bottom()); return; } window->SetCursor(pos.x(), pos.y()); stepindex = 0; while (stepindex < stepcount) { pos += step(stepindex); // step to next stepdir = step_dir(stepindex); stepindex++; // count steps // merge straight lines while (stepindex < stepcount && stepdir.get_dir() == step_dir(stepindex).get_dir()) { pos += step(stepindex); stepindex++; } window->DrawTo(pos.x(), pos.y()); } } // Draws the outline in the given colour, normalized using the given denorm, // making use of sub-pixel accurate information if available. void C_OUTLINE::plot_normed(const DENORM& denorm, ScrollView::Color colour, ScrollView* window) const { window->Pen(colour); if (stepcount == 0) { window->Rectangle(box.left(), box.top(), box.right(), box.bottom()); return; } const DENORM* root_denorm = denorm.RootDenorm(); ICOORD pos = start; // current position FCOORD f_pos = sub_pixel_pos_at_index(pos, 0); FCOORD pos_normed; denorm.NormTransform(root_denorm, f_pos, &pos_normed); window->SetCursor(IntCastRounded(pos_normed.x()), IntCastRounded(pos_normed.y())); for (int s = 0; s < stepcount; pos += step(s++)) { int edge_weight = edge_strength_at_index(s); if (edge_weight == 0) { // This point has conflicting gradient and step direction, so ignore it. continue; } FCOORD f_pos = sub_pixel_pos_at_index(pos, s); FCOORD pos_normed; denorm.NormTransform(root_denorm, f_pos, &pos_normed); window->DrawTo(IntCastRounded(pos_normed.x()), IntCastRounded(pos_normed.y())); } } #endif /********************************************************************** * C_OUTLINE::operator= * * Assignment - deep copy data **********************************************************************/ //assignment C_OUTLINE & C_OUTLINE::operator= ( const C_OUTLINE & source //from this ) { box = source.box; start = source.start; if (steps != NULL) free_mem(steps); stepcount = source.stepcount; steps = (uinT8 *) alloc_mem (step_mem()); memmove (steps, source.steps, step_mem()); if (!children.empty ()) children.clear (); children.deep_copy(&source.children, &deep_copy); delete [] offsets; if (source.offsets != NULL) { offsets = new EdgeOffset[stepcount]; memcpy(offsets, source.offsets, stepcount * sizeof(*offsets)); } else { offsets = NULL; } return *this; } // Helper for ComputeBinaryOffsets. Increments pos, dir_counts, pos_totals // by the step, increment, and vertical step ? x : y position * increment // at step s Mod stepcount respectively. Used to add or subtract the // direction and position to/from accumulators of a small neighbourhood. void C_OUTLINE::increment_step(int s, int increment, ICOORD* pos, int* dir_counts, int* pos_totals) const { int step_index = Modulo(s, stepcount); int dir_index = chain_code(step_index); dir_counts[dir_index] += increment; ICOORD step_vec = step(step_index); if (step_vec.x() == 0) pos_totals[dir_index] += pos->x() * increment; else pos_totals[dir_index] += pos->y() * increment; *pos += step_vec; } ICOORD C_OUTLINE::chain_step(int chaindir) { return step_coords[chaindir % 4]; }
1080228-arabicocr11
ccstruct/coutln.cpp
C++
asf20
38,534
/********************************************************************** * File: word.c * Description: Code for the WERD class. * Author: Ray Smith * Created: Tue Oct 08 14:32:12 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef WERD_H #define WERD_H #include "params.h" #include "bits16.h" #include "elst2.h" #include "strngs.h" #include "blckerr.h" #include "stepblob.h" enum WERD_FLAGS { W_SEGMENTED, //< correctly segmented W_ITALIC, //< italic text W_BOLD, //< bold text W_BOL, //< start of line W_EOL, //< end of line W_NORMALIZED, //< flags W_SCRIPT_HAS_XHEIGHT, //< x-height concept makes sense. W_SCRIPT_IS_LATIN, //< Special case latin for y. splitting. W_DONT_CHOP, //< fixed pitch chopped W_REP_CHAR, //< repeated character W_FUZZY_SP, //< fuzzy space W_FUZZY_NON, //< fuzzy nonspace W_INVERSE //< white on black }; enum DISPLAY_FLAGS { /* Display flags bit number allocations */ DF_BOX, //< Bounding box DF_TEXT, //< Correct ascii DF_POLYGONAL, //< Polyg approx DF_EDGE_STEP, //< Edge steps DF_BN_POLYGONAL, //< BL normalisd polyapx DF_BLAMER //< Blamer information }; class ROW; //forward decl class WERD : public ELIST2_LINK { public: WERD() {} // WERD constructed with: // blob_list - blobs of the word (we take this list's contents) // blanks - number of blanks before the word // text - correct text (outlives WERD) WERD(C_BLOB_LIST *blob_list, uinT8 blanks, const char *text); // WERD constructed from: // blob_list - blobs in the word // clone - werd to clone flags, etc from. WERD(C_BLOB_LIST *blob_list, WERD *clone); // Construct a WERD from a single_blob and clone the flags from this. // W_BOL and W_EOL flags are set according to the given values. WERD* ConstructFromSingleBlob(bool bol, bool eol, C_BLOB* blob); ~WERD() { } // assignment WERD & operator= (const WERD &source); // This method returns a new werd constructed using the blobs in the input // all_blobs list, which correspond to the blobs in this werd object. The // blobs used to construct the new word are consumed and removed from the // input all_blobs list. // Returns NULL if the word couldn't be constructed. // Returns original blobs for which no matches were found in the output list // orphan_blobs (appends). WERD *ConstructWerdWithNewBlobs(C_BLOB_LIST *all_blobs, C_BLOB_LIST *orphan_blobs); // Accessors for reject / DUFF blobs in various formats C_BLOB_LIST *rej_cblob_list() { // compact format return &rej_cblobs; } // Accessors for good blobs in various formats. C_BLOB_LIST *cblob_list() { // get compact blobs return &cblobs; } uinT8 space() { // access function return blanks; } void set_blanks(uinT8 new_blanks) { blanks = new_blanks; } int script_id() const { return script_id_; } void set_script_id(int id) { script_id_ = id; } TBOX bounding_box(); // compute bounding box const char *text() const { return correct.string(); } void set_text(const char *new_text) { correct = new_text; } BOOL8 flag(WERD_FLAGS mask) const { return flags.bit(mask); } void set_flag(WERD_FLAGS mask, BOOL8 value) { flags.set_bit(mask, value); } BOOL8 display_flag(uinT8 flag) const { return disp_flags.bit(flag); } void set_display_flag(uinT8 flag, BOOL8 value) { disp_flags.set_bit(flag, value); } WERD *shallow_copy(); // shallow copy word // reposition word by vector void move(const ICOORD vec); // join other's blobs onto this werd, emptying out other. void join_on(WERD* other); // copy other's blobs onto this word, leaving other intact. void copy_on(WERD* other); // tprintf word metadata (but not blob innards) void print(); #ifndef GRAPHICS_DISABLED // plot word on window in a uniform colour void plot(ScrollView *window, ScrollView::Color colour); // Get the next color in the (looping) rainbow. static ScrollView::Color NextColor(ScrollView::Color colour); // plot word on window in a rainbow of colours void plot(ScrollView *window); // plot rejected blobs in a rainbow of colours void plot_rej_blobs(ScrollView *window); #endif // GRAPHICS_DISABLED private: uinT8 blanks; // no of blanks uinT8 dummy; // padding BITS16 flags; // flags about word BITS16 disp_flags; // display flags inT16 script_id_; // From unicharset. STRING correct; // correct text C_BLOB_LIST cblobs; // compacted blobs C_BLOB_LIST rej_cblobs; // DUFF blobs }; ELIST2IZEH (WERD) #include "ocrrow.h" // placed here due to // compare words by increasing order of left edge, suitable for qsort(3) int word_comparator(const void *word1p, const void *word2p); #endif
1080228-arabicocr11
ccstruct/werd.h
C++
asf20
6,113
/********************************************************************** * File: otsuthr.cpp * Description: Simple Otsu thresholding for binarizing images. * Author: Ray Smith * Created: Fri Mar 07 12:31:01 PST 2008 * * (C) Copyright 2008, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "otsuthr.h" #include <string.h> #include "allheaders.h" #include "helpers.h" #include "openclwrapper.h" namespace tesseract { // Computes the Otsu threshold(s) for the given image rectangle, making one // for each channel. Each channel is always one byte per pixel. // Returns an array of threshold values and an array of hi_values, such // that a pixel value >threshold[channel] is considered foreground if // hi_values[channel] is 0 or background if 1. A hi_value of -1 indicates // that there is no apparent foreground. At least one hi_value will not be -1. // Delete thresholds and hi_values with delete [] after use. // The return value is the number of channels in the input image, being // the size of the output thresholds and hi_values arrays. int OtsuThreshold(Pix* src_pix, int left, int top, int width, int height, int** thresholds, int** hi_values) { int num_channels = pixGetDepth(src_pix) / 8; // Of all channels with no good hi_value, keep the best so we can always // produce at least one answer. PERF_COUNT_START("OtsuThreshold") int best_hi_value = 1; int best_hi_index = 0; bool any_good_hivalue = false; double best_hi_dist = 0.0; *thresholds = new int[num_channels]; *hi_values = new int[num_channels]; // all of channel 0 then all of channel 1... int *histogramAllChannels = new int[kHistogramSize * num_channels]; // only use opencl if compiled w/ OpenCL and selected device is opencl #ifdef USE_OPENCL // Calculate Histogram on GPU OpenclDevice od; if (od.selectedDeviceIsOpenCL() && (num_channels == 1 || num_channels == 4) && top == 0 && left == 0 ) { od.HistogramRectOCL( (const unsigned char*)pixGetData(src_pix), num_channels, pixGetWpl(src_pix) * 4, left, top, width, height, kHistogramSize, histogramAllChannels); // Calculate Threshold from Histogram on cpu for (int ch = 0; ch < num_channels; ++ch) { (*thresholds)[ch] = -1; (*hi_values)[ch] = -1; int *histogram = &histogramAllChannels[kHistogramSize * ch]; int H; int best_omega_0; int best_t = OtsuStats(histogram, &H, &best_omega_0); if (best_omega_0 == 0 || best_omega_0 == H) { // This channel is empty. continue; } // To be a convincing foreground we must have a small fraction of H // or to be a convincing background we must have a large fraction of H. // In between we assume this channel contains no thresholding information. int hi_value = best_omega_0 < H * 0.5; (*thresholds)[ch] = best_t; if (best_omega_0 > H * 0.75) { any_good_hivalue = true; (*hi_values)[ch] = 0; } else if (best_omega_0 < H * 0.25) { any_good_hivalue = true; (*hi_values)[ch] = 1; } else { // In case all channels are like this, keep the best of the bad lot. double hi_dist = hi_value ? (H - best_omega_0) : best_omega_0; if (hi_dist > best_hi_dist) { best_hi_dist = hi_dist; best_hi_value = hi_value; best_hi_index = ch; } } } } else { #endif for (int ch = 0; ch < num_channels; ++ch) { (*thresholds)[ch] = -1; (*hi_values)[ch] = -1; // Compute the histogram of the image rectangle. int histogram[kHistogramSize]; HistogramRect(src_pix, ch, left, top, width, height, histogram); int H; int best_omega_0; int best_t = OtsuStats(histogram, &H, &best_omega_0); if (best_omega_0 == 0 || best_omega_0 == H) { // This channel is empty. continue; } // To be a convincing foreground we must have a small fraction of H // or to be a convincing background we must have a large fraction of H. // In between we assume this channel contains no thresholding information. int hi_value = best_omega_0 < H * 0.5; (*thresholds)[ch] = best_t; if (best_omega_0 > H * 0.75) { any_good_hivalue = true; (*hi_values)[ch] = 0; } else if (best_omega_0 < H * 0.25) { any_good_hivalue = true; (*hi_values)[ch] = 1; } else { // In case all channels are like this, keep the best of the bad lot. double hi_dist = hi_value ? (H - best_omega_0) : best_omega_0; if (hi_dist > best_hi_dist) { best_hi_dist = hi_dist; best_hi_value = hi_value; best_hi_index = ch; } } } #ifdef USE_OPENCL } #endif // USE_OPENCL delete[] histogramAllChannels; if (!any_good_hivalue) { // Use the best of the ones that were not good enough. (*hi_values)[best_hi_index] = best_hi_value; } PERF_COUNT_END return num_channels; } // Computes the histogram for the given image rectangle, and the given // single channel. Each channel is always one byte per pixel. // Histogram is always a kHistogramSize(256) element array to count // occurrences of each pixel value. void HistogramRect(Pix* src_pix, int channel, int left, int top, int width, int height, int* histogram) { PERF_COUNT_START("HistogramRect") int num_channels = pixGetDepth(src_pix) / 8; channel = ClipToRange(channel, 0, num_channels - 1); int bottom = top + height; memset(histogram, 0, sizeof(*histogram) * kHistogramSize); int src_wpl = pixGetWpl(src_pix); l_uint32* srcdata = pixGetData(src_pix); for (int y = top; y < bottom; ++y) { const l_uint32* linedata = srcdata + y * src_wpl; for (int x = 0; x < width; ++x) { int pixel = GET_DATA_BYTE(const_cast<void*>( reinterpret_cast<const void *>(linedata)), (x + left) * num_channels + channel); ++histogram[pixel]; } } PERF_COUNT_END } // Computes the Otsu threshold(s) for the given histogram. // Also returns H = total count in histogram, and // omega0 = count of histogram below threshold. int OtsuStats(const int* histogram, int* H_out, int* omega0_out) { int H = 0; double mu_T = 0.0; for (int i = 0; i < kHistogramSize; ++i) { H += histogram[i]; mu_T += static_cast<double>(i) * histogram[i]; } // Now maximize sig_sq_B over t. // http://www.ctie.monash.edu.au/hargreave/Cornall_Terry_328.pdf int best_t = -1; int omega_0, omega_1; int best_omega_0 = 0; double best_sig_sq_B = 0.0; double mu_0, mu_1, mu_t; omega_0 = 0; mu_t = 0.0; for (int t = 0; t < kHistogramSize - 1; ++t) { omega_0 += histogram[t]; mu_t += t * static_cast<double>(histogram[t]); if (omega_0 == 0) continue; omega_1 = H - omega_0; if (omega_1 == 0) break; mu_0 = mu_t / omega_0; mu_1 = (mu_T - mu_t) / omega_1; double sig_sq_B = mu_1 - mu_0; sig_sq_B *= sig_sq_B * omega_0 * omega_1; if (best_t < 0 || sig_sq_B > best_sig_sq_B) { best_sig_sq_B = sig_sq_B; best_t = t; best_omega_0 = omega_0; } } if (H_out != NULL) *H_out = H; if (omega0_out != NULL) *omega0_out = best_omega_0; return best_t; } } // namespace tesseract.
1080228-arabicocr11
ccstruct/otsuthr.cpp
C++
asf20
8,019
/********************************************************************** * File: points.h (Formerly coords.h) * Description: Coordinate class definitions. * Author: Ray Smith * Created: Fri Mar 15 08:32:45 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef POINTS_H #define POINTS_H #include <stdio.h> #include <math.h> #include "elst.h" class FCOORD; ///integer coordinate class ICOORD { friend class FCOORD; public: ///empty constructor ICOORD() { xcoord = ycoord = 0; //default zero } ///constructor ///@param xin x value ///@param yin y value ICOORD(inT16 xin, inT16 yin) { xcoord = xin; ycoord = yin; } ///destructor ~ICOORD () { } ///access function inT16 x() const { return xcoord; } ///access_function inT16 y() const { return ycoord; } ///rewrite function void set_x(inT16 xin) { xcoord = xin; //write new value } ///rewrite function void set_y(inT16 yin) { //value to set ycoord = yin; } /// Set from the given x,y, shrinking the vector to fit if needed. void set_with_shrink(int x, int y); ///find sq length float sqlength() const { return (float) (xcoord * xcoord + ycoord * ycoord); } ///find length float length() const { return (float) sqrt (sqlength ()); } ///sq dist between pts float pt_to_pt_sqdist(const ICOORD &pt) const { ICOORD gap; gap.xcoord = xcoord - pt.xcoord; gap.ycoord = ycoord - pt.ycoord; return gap.sqlength (); } ///Distance between pts float pt_to_pt_dist(const ICOORD &pt) const { return (float) sqrt (pt_to_pt_sqdist (pt)); } ///find angle float angle() const { return (float) atan2 ((double) ycoord, (double) xcoord); } ///test equality BOOL8 operator== (const ICOORD & other) const { return xcoord == other.xcoord && ycoord == other.ycoord; } ///test inequality BOOL8 operator!= (const ICOORD & other) const { return xcoord != other.xcoord || ycoord != other.ycoord; } ///rotate 90 deg anti friend ICOORD operator! (const ICOORD &); ///unary minus friend ICOORD operator- (const ICOORD &); ///add friend ICOORD operator+ (const ICOORD &, const ICOORD &); ///add friend ICOORD & operator+= (ICOORD &, const ICOORD &); ///subtract friend ICOORD operator- (const ICOORD &, const ICOORD &); ///subtract friend ICOORD & operator-= (ICOORD &, const ICOORD &); ///scalar product friend inT32 operator% (const ICOORD &, const ICOORD &); ///cross product friend inT32 operator *(const ICOORD &, const ICOORD &); ///multiply friend ICOORD operator *(const ICOORD &, inT16); ///multiply friend ICOORD operator *(inT16, const ICOORD &); ///multiply friend ICOORD & operator*= (ICOORD &, inT16); ///divide friend ICOORD operator/ (const ICOORD &, inT16); ///divide friend ICOORD & operator/= (ICOORD &, inT16); ///rotate ///@param vec by vector void rotate(const FCOORD& vec); /// Setup for iterating over the pixels in a vector by the well-known /// Bresenham rendering algorithm. /// Starting with major/2 in the accumulator, on each step move by /// major_step, and then add minor to the accumulator. When /// accumulator >= major subtract major and also move by minor_step. void setup_render(ICOORD* major_step, ICOORD* minor_step, int* major, int* minor) const; // Writes to the given file. Returns false in case of error. bool Serialize(FILE* fp) const; // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool DeSerialize(bool swap, FILE* fp); protected: inT16 xcoord; //< x value inT16 ycoord; //< y value }; class DLLSYM ICOORDELT:public ELIST_LINK, public ICOORD //embedded coord list { public: ///empty constructor ICOORDELT() { } ///constructor from ICOORD ICOORDELT (ICOORD icoord):ICOORD (icoord) { } ///constructor ///@param xin x value ///@param yin y value ICOORDELT(inT16 xin, inT16 yin) { xcoord = xin; ycoord = yin; } static ICOORDELT* deep_copy(const ICOORDELT* src) { ICOORDELT* elt = new ICOORDELT; *elt = *src; return elt; } }; ELISTIZEH (ICOORDELT) class DLLSYM FCOORD { public: ///empty constructor FCOORD() { } ///constructor ///@param xvalue x value ///@param yvalue y value FCOORD(float xvalue, float yvalue) { xcoord = xvalue; //set coords ycoord = yvalue; } FCOORD( //make from ICOORD ICOORD icoord) { //coords to set xcoord = icoord.xcoord; ycoord = icoord.ycoord; } float x() const { //get coords return xcoord; } float y() const { return ycoord; } ///rewrite function void set_x(float xin) { xcoord = xin; //write new value } ///rewrite function void set_y(float yin) { //value to set ycoord = yin; } ///find sq length float sqlength() const { return xcoord * xcoord + ycoord * ycoord; } ///find length float length() const { return (float) sqrt (sqlength ()); } ///sq dist between pts float pt_to_pt_sqdist(const FCOORD &pt) const { FCOORD gap; gap.xcoord = xcoord - pt.xcoord; gap.ycoord = ycoord - pt.ycoord; return gap.sqlength (); } ///Distance between pts float pt_to_pt_dist(const FCOORD &pt) const { return (float) sqrt (pt_to_pt_sqdist (pt)); } ///find angle float angle() const { return (float) atan2 (ycoord, xcoord); } // Returns the standard feature direction corresponding to this. // See binary_angle_plus_pi below for a description of the direction. uinT8 to_direction() const; // Sets this with a unit vector in the given standard feature direction. void from_direction(uinT8 direction); // Converts an angle in radians (from ICOORD::angle or FCOORD::angle) to a // standard feature direction as an unsigned angle in 256ths of a circle // measured anticlockwise from (-1, 0). static uinT8 binary_angle_plus_pi(double angle); // Inverse of binary_angle_plus_pi returns an angle in radians for the // given standard feature direction. static double angle_from_direction(uinT8 direction); // Returns the point on the given line nearest to this, ie the point such // that the vector point->this is perpendicular to the line. // The line is defined as a line_point and a dir_vector for its direction. // dir_vector need not be a unit vector. FCOORD nearest_pt_on_line(const FCOORD& line_point, const FCOORD& dir_vector) const; ///Convert to unit vec bool normalise(); ///test equality BOOL8 operator== (const FCOORD & other) { return xcoord == other.xcoord && ycoord == other.ycoord; } ///test inequality BOOL8 operator!= (const FCOORD & other) { return xcoord != other.xcoord || ycoord != other.ycoord; } ///rotate 90 deg anti friend FCOORD operator! (const FCOORD &); ///unary minus friend FCOORD operator- (const FCOORD &); ///add friend FCOORD operator+ (const FCOORD &, const FCOORD &); ///add friend FCOORD & operator+= (FCOORD &, const FCOORD &); ///subtract friend FCOORD operator- (const FCOORD &, const FCOORD &); ///subtract friend FCOORD & operator-= (FCOORD &, const FCOORD &); ///scalar product friend float operator% (const FCOORD &, const FCOORD &); ///cross product friend float operator *(const FCOORD &, const FCOORD &); ///multiply friend FCOORD operator *(const FCOORD &, float); ///multiply friend FCOORD operator *(float, const FCOORD &); ///multiply friend FCOORD & operator*= (FCOORD &, float); ///divide friend FCOORD operator/ (const FCOORD &, float); ///rotate ///@param vec by vector void rotate(const FCOORD vec); // unrotate - undo a rotate(vec) // @param vec by vector void unrotate(const FCOORD &vec); ///divide friend FCOORD & operator/= (FCOORD &, float); private: float xcoord; //2 floating coords float ycoord; }; #include "ipoints.h" /*do inline funcs */ #endif
1080228-arabicocr11
ccstruct/points.h
C++
asf20
9,464
/********************************************************************** * File: linlsq.cpp (Formerly llsq.c) * Description: Linear Least squares fitting code. * Author: Ray Smith * Created: Thu Sep 12 08:44:51 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdio.h> #include <math.h> #include "errcode.h" #include "linlsq.h" const ERRCODE EMPTY_LLSQ = "Can't delete from an empty LLSQ"; /********************************************************************** * LLSQ::clear * * Function to initialize a LLSQ. **********************************************************************/ void LLSQ::clear() { // initialize total_weight = 0.0; // no elements sigx = 0.0; // update accumulators sigy = 0.0; sigxx = 0.0; sigxy = 0.0; sigyy = 0.0; } /********************************************************************** * LLSQ::add * * Add an element to the accumulator. **********************************************************************/ void LLSQ::add(double x, double y) { // add an element total_weight++; // count elements sigx += x; // update accumulators sigy += y; sigxx += x * x; sigxy += x * y; sigyy += y * y; } // Adds an element with a specified weight. void LLSQ::add(double x, double y, double weight) { total_weight += weight; sigx += x * weight; // update accumulators sigy += y * weight; sigxx += x * x * weight; sigxy += x * y * weight; sigyy += y * y * weight; } // Adds a whole LLSQ. void LLSQ::add(const LLSQ& other) { total_weight += other.total_weight; sigx += other.sigx; // update accumulators sigy += other.sigy; sigxx += other.sigxx; sigxy += other.sigxy; sigyy += other.sigyy; } /********************************************************************** * LLSQ::remove * * Delete an element from the acculuator. **********************************************************************/ void LLSQ::remove(double x, double y) { // delete an element if (total_weight <= 0.0) // illegal EMPTY_LLSQ.error("LLSQ::remove", ABORT, NULL); total_weight--; // count elements sigx -= x; // update accumulators sigy -= y; sigxx -= x * x; sigxy -= x * y; sigyy -= y * y; } /********************************************************************** * LLSQ::m * * Return the gradient of the line fit. **********************************************************************/ double LLSQ::m() const { // get gradient double covar = covariance(); double x_var = x_variance(); if (x_var != 0.0) return covar / x_var; else return 0.0; // too little } /********************************************************************** * LLSQ::c * * Return the constant of the line fit. **********************************************************************/ double LLSQ::c(double m) const { // get constant if (total_weight > 0.0) return (sigy - m * sigx) / total_weight; else return 0; // too little } /********************************************************************** * LLSQ::rms * * Return the rms error of the fit. **********************************************************************/ double LLSQ::rms(double m, double c) const { // get error double error; // total error if (total_weight > 0) { error = sigyy + m * (m * sigxx + 2 * (c * sigx - sigxy)) + c * (total_weight * c - 2 * sigy); if (error >= 0) error = sqrt(error / total_weight); // sqrt of mean else error = 0; } else { error = 0; // too little } return error; } /********************************************************************** * LLSQ::pearson * * Return the pearson product moment correlation coefficient. **********************************************************************/ double LLSQ::pearson() const { // get correlation double r = 0.0; // Correlation is 0 if insufficent data. double covar = covariance(); if (covar != 0.0) { double var_product = x_variance() * y_variance(); if (var_product > 0.0) r = covar / sqrt(var_product); } return r; } // Returns the x,y means as an FCOORD. FCOORD LLSQ::mean_point() const { if (total_weight > 0.0) { return FCOORD(sigx / total_weight, sigy / total_weight); } else { return FCOORD(0.0f, 0.0f); } } // Returns the sqrt of the mean squared error measured perpendicular from the // line through mean_point() in the direction dir. // // Derivation: // Lemma: Let v and x_i (i=1..N) be a k-dimensional vectors (1xk matrices). // Let % be dot product and ' be transpose. Note that: // Sum[i=1..N] (v % x_i)^2 // = v * [x_1' x_2' ... x_N'] * [x_1' x_2' .. x_N']' * v' // If x_i have average 0 we have: // = v * (N * COVARIANCE_MATRIX(X)) * v' // Expanded for the case that k = 2, where we treat the dimensions // as x_i and y_i, this is: // = v * (N * [VAR(X), COV(X,Y); COV(X,Y) VAR(Y)]) * v' // Now, we are trying to calculate the mean squared error, where v is // perpendicular to our line of interest: // Mean squared error // = E [ (v % (x_i - x_avg))) ^2 ] // = Sum (v % (x_i - x_avg))^2 / N // = v * N * [VAR(X) COV(X,Y); COV(X,Y) VAR(Y)] / N * v' // = v * [VAR(X) COV(X,Y); COV(X,Y) VAR(Y)] * v' // = code below double LLSQ::rms_orth(const FCOORD &dir) const { FCOORD v = !dir; v.normalise(); return sqrt(v.x() * v.x() * x_variance() + 2 * v.x() * v.y() * covariance() + v.y() * v.y() * y_variance()); } // Returns the direction of the fitted line as a unit vector, using the // least mean squared perpendicular distance. The line runs through the // mean_point, i.e. a point p on the line is given by: // p = mean_point() + lambda * vector_fit() for some real number lambda. // Note that the result (0<=x<=1, -1<=y<=-1) is directionally ambiguous // and may be negated without changing its meaning. // Fitting a line m + 𝜆v to a set of N points Pi = (xi, yi), where // m is the mean point (𝝁, 𝝂) and // v is the direction vector (cos𝜃, sin𝜃) // The perpendicular distance of each Pi from the line is: // (Pi - m) x v, where x is the scalar cross product. // Total squared error is thus: // E = ∑((xi - 𝝁)sin𝜃 - (yi - 𝝂)cos𝜃)² // = ∑(xi - 𝝁)²sin²𝜃 - 2∑(xi - 𝝁)(yi - 𝝂)sin𝜃 cos𝜃 + ∑(yi - 𝝂)²cos²𝜃 // = NVar(xi)sin²𝜃 - 2NCovar(xi, yi)sin𝜃 cos𝜃 + NVar(yi)cos²𝜃 (Eq 1) // where Var(xi) is the variance of xi, // and Covar(xi, yi) is the covariance of xi, yi. // Taking the derivative wrt 𝜃 and setting to 0 to obtain the min/max: // 0 = 2NVar(xi)sin𝜃 cos𝜃 -2NCovar(xi, yi)(cos²𝜃 - sin²𝜃) -2NVar(yi)sin𝜃 cos𝜃 // => Covar(xi, yi)(cos²𝜃 - sin²𝜃) = (Var(xi) - Var(yi))sin𝜃 cos𝜃 // Using double angles: // 2Covar(xi, yi)cos2𝜃 = (Var(xi) - Var(yi))sin2𝜃 (Eq 2) // So 𝜃 = 0.5 atan2(2Covar(xi, yi), Var(xi) - Var(yi)) (Eq 3) // Because it involves 2𝜃 , Eq 2 has 2 solutions 90 degrees apart, but which // is the min and which is the max? From Eq1: // E/N = Var(xi)sin²𝜃 - 2Covar(xi, yi)sin𝜃 cos𝜃 + Var(yi)cos²𝜃 // and 90 degrees away, using sin/cos equivalences: // E'/N = Var(xi)cos²𝜃 + 2Covar(xi, yi)sin𝜃 cos𝜃 + Var(yi)sin²𝜃 // The second error is smaller (making it the minimum) iff // E'/N < E/N ie: // (Var(xi) - Var(yi))(cos²𝜃 - sin²𝜃) < -4Covar(xi, yi)sin𝜃 cos𝜃 // Using double angles: // (Var(xi) - Var(yi))cos2𝜃 < -2Covar(xi, yi)sin2𝜃 (InEq 1) // But atan2(2Covar(xi, yi), Var(xi) - Var(yi)) picks 2𝜃 such that: // sgn(cos2𝜃) = sgn(Var(xi) - Var(yi)) and sgn(sin2𝜃) = sgn(Covar(xi, yi)) // so InEq1 can *never* be true, making the atan2 result *always* the min! // In the degenerate case, where Covar(xi, yi) = 0 AND Var(xi) = Var(yi), // the 2 solutions have equal error and the inequality is still false. // Therefore the solution really is as trivial as Eq 3. // This is equivalent to returning the Principal Component in PCA, or the // eigenvector corresponding to the largest eigenvalue in the covariance // matrix. However, atan2 is much simpler! The one reference I found that // uses this formula is http://web.mit.edu/18.06/www/Essays/tlsfit.pdf but // that is still a much more complex derivation. It seems Pearson had already // found this simple solution in 1901. // http://books.google.com/books?id=WXwvAQAAIAAJ&pg=PA559 FCOORD LLSQ::vector_fit() const { double x_var = x_variance(); double y_var = y_variance(); double covar = covariance(); double theta = 0.5 * atan2(2.0 * covar, x_var - y_var); FCOORD result(cos(theta), sin(theta)); return result; }
1080228-arabicocr11
ccstruct/linlsq.cpp
C++
asf20
9,671
/********************************************************************** * File: polyblk.c (Formerly poly_block.c) * Description: Polygonal blocks * Author: Sheelagh Lloyd? * Created: * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <ctype.h> #include <math.h> #include <stdio.h> #include "elst.h" #include "polyblk.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif #define PBLOCK_LABEL_SIZE 150 #define INTERSECTING MAX_INT16 int lessthan(const void *first, const void *second); POLY_BLOCK::POLY_BLOCK(ICOORDELT_LIST *points, PolyBlockType t) { ICOORDELT_IT v = &vertices; vertices.clear(); v.move_to_first(); v.add_list_before(points); compute_bb(); type = t; } // Initialize from box coordinates. POLY_BLOCK::POLY_BLOCK(const TBOX& box, PolyBlockType t) { vertices.clear(); ICOORDELT_IT v = &vertices; v.move_to_first(); v.add_to_end(new ICOORDELT(box.left(), box.top())); v.add_to_end(new ICOORDELT(box.left(), box.bottom())); v.add_to_end(new ICOORDELT(box.right(), box.bottom())); v.add_to_end(new ICOORDELT(box.right(), box.top())); compute_bb(); type = t; } /** * @name POLY_BLOCK::compute_bb * * Compute the bounding box from the outline points. */ void POLY_BLOCK::compute_bb() { //constructor ICOORD ibl, itr; //integer bb ICOORD botleft; //bounding box ICOORD topright; ICOORD pos; //current pos; ICOORDELT_IT pts = &vertices; //iterator botleft = *pts.data (); topright = botleft; do { pos = *pts.data (); if (pos.x () < botleft.x ()) //get bounding box botleft = ICOORD (pos.x (), botleft.y ()); if (pos.y () < botleft.y ()) botleft = ICOORD (botleft.x (), pos.y ()); if (pos.x () > topright.x ()) topright = ICOORD (pos.x (), topright.y ()); if (pos.y () > topright.y ()) topright = ICOORD (topright.x (), pos.y ()); pts.forward (); } while (!pts.at_first ()); ibl = ICOORD (botleft.x (), botleft.y ()); itr = ICOORD (topright.x (), topright.y ()); box = TBOX (ibl, itr); } /** * @name POLY_BLOCK::winding_number * * Return the winding number of the outline around the given point. * @param point point to wind around */ inT16 POLY_BLOCK::winding_number(const ICOORD &point) { inT16 count; //winding count ICOORD pt; //current point ICOORD vec; //point to current point ICOORD vvec; //current point to next point inT32 cross; //cross product ICOORDELT_IT it = &vertices; //iterator count = 0; do { pt = *it.data (); vec = pt - point; vvec = *it.data_relative (1) - pt; //crossing the line if (vec.y () <= 0 && vec.y () + vvec.y () > 0) { cross = vec * vvec; //cross product if (cross > 0) count++; //crossing right half else if (cross == 0) return INTERSECTING; //going through point } else if (vec.y () > 0 && vec.y () + vvec.y () <= 0) { cross = vec * vvec; if (cross < 0) count--; //crossing back else if (cross == 0) return INTERSECTING; //illegal } else if (vec.y () == 0 && vec.x () == 0) return INTERSECTING; it.forward (); } while (!it.at_first ()); return count; //winding number } /// @return true if other is inside this. bool POLY_BLOCK::contains(POLY_BLOCK *other) { inT16 count; // winding count ICOORDELT_IT it = &vertices; // iterator ICOORD vertex; if (!box.overlap (*(other->bounding_box ()))) return false; // can't be contained /* check that no vertex of this is inside other */ do { vertex = *it.data (); // get winding number count = other->winding_number (vertex); if (count != INTERSECTING) if (count != 0) return false; it.forward (); } while (!it.at_first ()); /* check that all vertices of other are inside this */ //switch lists it.set_to_list (other->points ()); do { vertex = *it.data (); //try other way round count = winding_number (vertex); if (count != INTERSECTING) if (count == 0) return false; it.forward (); } while (!it.at_first ()); return true; } /** * @name POLY_BLOCK::rotate * * Rotate the POLY_BLOCK. * @param rotation cos, sin of angle */ void POLY_BLOCK::rotate(FCOORD rotation) { FCOORD pos; //current pos; ICOORDELT *pt; //current point ICOORDELT_IT pts = &vertices; //iterator do { pt = pts.data (); pos.set_x (pt->x ()); pos.set_y (pt->y ()); pos.rotate (rotation); pt->set_x ((inT16) (floor (pos.x () + 0.5))); pt->set_y ((inT16) (floor (pos.y () + 0.5))); pts.forward (); } while (!pts.at_first ()); compute_bb(); } /** * @name POLY_BLOCK::reflect_in_y_axis * * Reflect the coords of the polygon in the y-axis. (Flip the sign of x.) */ void POLY_BLOCK::reflect_in_y_axis() { ICOORDELT *pt; // current point ICOORDELT_IT pts = &vertices; // Iterator. do { pt = pts.data(); pt->set_x(-pt->x()); pts.forward(); } while (!pts.at_first()); compute_bb(); } /** * POLY_BLOCK::move * * Move the POLY_BLOCK. * @param shift x,y translation vector */ void POLY_BLOCK::move(ICOORD shift) { ICOORDELT *pt; //current point ICOORDELT_IT pts = &vertices; //iterator do { pt = pts.data (); *pt += shift; pts.forward (); } while (!pts.at_first ()); compute_bb(); } #ifndef GRAPHICS_DISABLED void POLY_BLOCK::plot(ScrollView* window, inT32 num) { ICOORDELT_IT v = &vertices; window->Pen(ColorForPolyBlockType(type)); v.move_to_first (); if (num > 0) { window->TextAttributes("Times", 80, false, false, false); char temp_buff[34]; #if defined(__UNIX__) || defined(MINGW) sprintf(temp_buff, INT32FORMAT, num); #else ltoa (num, temp_buff, 10); #endif window->Text(v.data ()->x (), v.data ()->y (), temp_buff); } window->SetCursor(v.data ()->x (), v.data ()->y ()); for (v.mark_cycle_pt (); !v.cycled_list (); v.forward ()) { window->DrawTo(v.data ()->x (), v.data ()->y ()); } v.move_to_first (); window->DrawTo(v.data ()->x (), v.data ()->y ()); } void POLY_BLOCK::fill(ScrollView* window, ScrollView::Color colour) { inT16 y; inT16 width; PB_LINE_IT *lines; ICOORDELT_LIST *segments; ICOORDELT_IT s_it; lines = new PB_LINE_IT (this); window->Pen(colour); for (y = this->bounding_box ()->bottom (); y <= this->bounding_box ()->top (); y++) { segments = lines->get_line (y); if (!segments->empty ()) { s_it.set_to_list (segments); for (s_it.mark_cycle_pt (); !s_it.cycled_list (); s_it.forward ()) { // Note different use of ICOORDELT, x coord is x coord of pixel // at the start of line segment, y coord is length of line segment // Last pixel is start pixel + length. width = s_it.data ()->y (); window->SetCursor(s_it.data ()->x (), y); window->DrawTo(s_it.data ()->x () + (float) width, y); } } } } #endif /// @return true if the polygons of other and this overlap. bool POLY_BLOCK::overlap(POLY_BLOCK *other) { inT16 count; // winding count ICOORDELT_IT it = &vertices; // iterator ICOORD vertex; if (!box.overlap(*(other->bounding_box()))) return false; // can't be any overlap. /* see if a vertex of this is inside other */ do { vertex = *it.data (); // get winding number count = other->winding_number (vertex); if (count != INTERSECTING) if (count != 0) return true; it.forward (); } while (!it.at_first ()); /* see if a vertex of other is inside this */ // switch lists it.set_to_list (other->points ()); do { vertex = *it.data(); // try other way round count = winding_number (vertex); if (count != INTERSECTING) if (count != 0) return true; it.forward (); } while (!it.at_first ()); return false; } ICOORDELT_LIST *PB_LINE_IT::get_line(inT16 y) { ICOORDELT_IT v, r; ICOORDELT_LIST *result; ICOORDELT *x, *current, *previous; float fy, fx; fy = (float) (y + 0.5); result = new ICOORDELT_LIST (); r.set_to_list (result); v.set_to_list (block->points ()); for (v.mark_cycle_pt (); !v.cycled_list (); v.forward ()) { if (((v.data_relative (-1)->y () > y) && (v.data ()->y () <= y)) || ((v.data_relative (-1)->y () <= y) && (v.data ()->y () > y))) { previous = v.data_relative (-1); current = v.data (); fx = (float) (0.5 + previous->x () + (current->x () - previous->x ()) * (fy - previous->y ()) / (current->y () - previous->y ())); x = new ICOORDELT ((inT16) fx, 0); r.add_to_end (x); } } if (!r.empty ()) { r.sort (lessthan); for (r.mark_cycle_pt (); !r.cycled_list (); r.forward ()) x = r.data (); for (r.mark_cycle_pt (); !r.cycled_list (); r.forward ()) { r.data ()->set_y (r.data_relative (1)->x () - r.data ()->x ()); r.forward (); delete (r.extract ()); } } return result; } int lessthan(const void *first, const void *second) { ICOORDELT *p1 = (*(ICOORDELT **) first); ICOORDELT *p2 = (*(ICOORDELT **) second); if (p1->x () < p2->x ()) return (-1); else if (p1->x () > p2->x ()) return (1); else return (0); } #ifndef GRAPHICS_DISABLED /// Returns a color to draw the given type. ScrollView::Color POLY_BLOCK::ColorForPolyBlockType(PolyBlockType type) { // Keep kPBColors in sync with PolyBlockType. const ScrollView::Color kPBColors[PT_COUNT] = { ScrollView::WHITE, // Type is not yet known. Keep as the 1st element. ScrollView::BLUE, // Text that lives inside a column. ScrollView::CYAN, // Text that spans more than one column. ScrollView::MEDIUM_BLUE, // Text that is in a cross-column pull-out region. ScrollView::AQUAMARINE, // Partition belonging to an equation region. ScrollView::SKY_BLUE, // Partition belonging to an inline equation region. ScrollView::MAGENTA, // Partition belonging to a table region. ScrollView::GREEN, // Text-line runs vertically. ScrollView::LIGHT_BLUE, // Text that belongs to an image. ScrollView::RED, // Image that lives inside a column. ScrollView::YELLOW, // Image that spans more than one column. ScrollView::ORANGE, // Image in a cross-column pull-out region. ScrollView::BROWN, // Horizontal Line. ScrollView::DARK_GREEN, // Vertical Line. ScrollView::GREY // Lies outside of any column. }; if (type >= 0 && type < PT_COUNT) { return kPBColors[type]; } return ScrollView::WHITE; } #endif // GRAPHICS_DISABLED
1080228-arabicocr11
ccstruct/polyblk.cpp
C++
asf20
11,922
/********************************************************************** * File: polyaprx.cpp (Formerly polygon.c) * Description: Code for polygonal approximation from old edgeprog. * Author: Ray Smith * Created: Thu Nov 25 11:42:04 GMT 1993 * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdio.h> #ifdef __UNIX__ #include <assert.h> #endif #define FASTEDGELENGTH 256 #include "polyaprx.h" #include "params.h" #include "tprintf.h" #define EXTERN EXTERN BOOL_VAR(poly_debug, FALSE, "Debug old poly"); EXTERN BOOL_VAR(poly_wide_objects_better, TRUE, "More accurate approx on wide things"); #define FIXED 4 /*OUTLINE point is fixed */ #define RUNLENGTH 1 /*length of run */ #define DIR 2 /*direction of run */ #define FLAGS 0 #define fixed_dist 20 //really an int_variable #define approx_dist 15 //really an int_variable const int par1 = 4500 / (approx_dist * approx_dist); const int par2 = 6750 / (approx_dist * approx_dist); /********************************************************************** * tesspoly_outline * * Approximate an outline from chain codes form using the old tess algorithm. * If allow_detailed_fx is true, the EDGEPTs in the returned TBLOB * contain pointers to the input C_OUTLINEs that enable higher-resolution * feature extraction that does not use the polygonal approximation. **********************************************************************/ TESSLINE* ApproximateOutline(bool allow_detailed_fx, C_OUTLINE* c_outline) { TBOX loop_box; // bounding box inT32 area; // loop area EDGEPT stack_edgepts[FASTEDGELENGTH]; // converted path EDGEPT* edgepts = stack_edgepts; // Use heap memory if the stack buffer is not big enough. if (c_outline->pathlength() > FASTEDGELENGTH) edgepts = new EDGEPT[c_outline->pathlength()]; loop_box = c_outline->bounding_box(); area = loop_box.height(); if (!poly_wide_objects_better && loop_box.width() > area) area = loop_box.width(); area *= area; edgesteps_to_edgepts(c_outline, edgepts); fix2(edgepts, area); EDGEPT* edgept = poly2(edgepts, area); // 2nd approximation. EDGEPT* startpt = edgept; EDGEPT* result = NULL; EDGEPT* prev_result = NULL; do { EDGEPT* new_pt = new EDGEPT; new_pt->pos = edgept->pos; new_pt->prev = prev_result; if (prev_result == NULL) { result = new_pt; } else { prev_result->next = new_pt; new_pt->prev = prev_result; } if (allow_detailed_fx) { new_pt->src_outline = edgept->src_outline; new_pt->start_step = edgept->start_step; new_pt->step_count = edgept->step_count; } prev_result = new_pt; edgept = edgept->next; } while (edgept != startpt); prev_result->next = result; result->prev = prev_result; if (edgepts != stack_edgepts) delete [] edgepts; return TESSLINE::BuildFromOutlineList(result); } /********************************************************************** * edgesteps_to_edgepts * * Convert a C_OUTLINE to EDGEPTs. **********************************************************************/ EDGEPT * edgesteps_to_edgepts ( //convert outline C_OUTLINE * c_outline, //input EDGEPT edgepts[] //output is array ) { inT32 length; //steps in path ICOORD pos; //current coords inT32 stepindex; //current step inT32 stepinc; //increment inT32 epindex; //current EDGEPT inT32 count; //repeated steps ICOORD vec; //for this 8 step ICOORD prev_vec; inT8 epdir; //of this step DIR128 prevdir; //prvious dir DIR128 dir; //of this step pos = c_outline->start_pos (); //start of loop length = c_outline->pathlength (); stepindex = 0; epindex = 0; prevdir = -1; count = 0; int prev_stepindex = 0; do { dir = c_outline->step_dir (stepindex); vec = c_outline->step (stepindex); if (stepindex < length - 1 && c_outline->step_dir (stepindex + 1) - dir == -32) { dir += 128 - 16; vec += c_outline->step (stepindex + 1); stepinc = 2; } else stepinc = 1; if (count == 0) { prevdir = dir; prev_vec = vec; } if (prevdir.get_dir () != dir.get_dir ()) { edgepts[epindex].pos.x = pos.x (); edgepts[epindex].pos.y = pos.y (); prev_vec *= count; edgepts[epindex].vec.x = prev_vec.x (); edgepts[epindex].vec.y = prev_vec.y (); pos += prev_vec; edgepts[epindex].flags[RUNLENGTH] = count; edgepts[epindex].prev = &edgepts[epindex - 1]; edgepts[epindex].flags[FLAGS] = 0; edgepts[epindex].next = &edgepts[epindex + 1]; prevdir += 64; epdir = (DIR128) 0 - prevdir; epdir >>= 4; epdir &= 7; edgepts[epindex].flags[DIR] = epdir; edgepts[epindex].src_outline = c_outline; edgepts[epindex].start_step = prev_stepindex; edgepts[epindex].step_count = stepindex - prev_stepindex; epindex++; prevdir = dir; prev_vec = vec; count = 1; prev_stepindex = stepindex; } else count++; stepindex += stepinc; } while (stepindex < length); edgepts[epindex].pos.x = pos.x (); edgepts[epindex].pos.y = pos.y (); prev_vec *= count; edgepts[epindex].vec.x = prev_vec.x (); edgepts[epindex].vec.y = prev_vec.y (); pos += prev_vec; edgepts[epindex].flags[RUNLENGTH] = count; edgepts[epindex].flags[FLAGS] = 0; edgepts[epindex].src_outline = c_outline; edgepts[epindex].start_step = prev_stepindex; edgepts[epindex].step_count = stepindex - prev_stepindex; edgepts[epindex].prev = &edgepts[epindex - 1]; edgepts[epindex].next = &edgepts[0]; prevdir += 64; epdir = (DIR128) 0 - prevdir; epdir >>= 4; epdir &= 7; edgepts[epindex].flags[DIR] = epdir; edgepts[0].prev = &edgepts[epindex]; ASSERT_HOST (pos.x () == c_outline->start_pos ().x () && pos.y () == c_outline->start_pos ().y ()); return &edgepts[0]; } /********************************************************************** *fix2(start,area) fixes points on the outline according to a trial method* **********************************************************************/ //#pragma OPT_LEVEL 1 /*stop compiler bugs*/ void fix2( //polygonal approx EDGEPT *start, /*loop to approimate */ int area) { register EDGEPT *edgept; /*current point */ register EDGEPT *edgept1; register EDGEPT *loopstart; /*modified start of loop */ register EDGEPT *linestart; /*start of line segment */ register int dir1, dir2; /*directions of line */ register int sum1, sum2; /*lengths in dir1,dir2 */ int stopped; /*completed flag */ int fixed_count; //no of fixed points int d01, d12, d23, gapmin; TPOINT d01vec, d12vec, d23vec; register EDGEPT *edgefix, *startfix; register EDGEPT *edgefix0, *edgefix1, *edgefix2, *edgefix3; edgept = start; /*start of loop */ while (((edgept->flags[DIR] - edgept->prev->flags[DIR] + 1) & 7) < 3 && (dir1 = (edgept->prev->flags[DIR] - edgept->next->flags[DIR]) & 7) != 2 && dir1 != 6) edgept = edgept->next; /*find suitable start */ loopstart = edgept; /*remember start */ stopped = 0; /*not finished yet */ edgept->flags[FLAGS] |= FIXED; /*fix it */ do { linestart = edgept; /*possible start of line */ dir1 = edgept->flags[DIR]; /*first direction */ /*length of dir1 */ sum1 = edgept->flags[RUNLENGTH]; edgept = edgept->next; dir2 = edgept->flags[DIR]; /*2nd direction */ /*length in dir2 */ sum2 = edgept->flags[RUNLENGTH]; if (((dir1 - dir2 + 1) & 7) < 3) { while (edgept->prev->flags[DIR] == edgept->next->flags[DIR]) { edgept = edgept->next; /*look at next */ if (edgept->flags[DIR] == dir1) /*sum lengths */ sum1 += edgept->flags[RUNLENGTH]; else sum2 += edgept->flags[RUNLENGTH]; } if (edgept == loopstart) stopped = 1; /*finished */ if (sum2 + sum1 > 2 && linestart->prev->flags[DIR] == dir2 && (linestart->prev->flags[RUNLENGTH] > linestart->flags[RUNLENGTH] || sum2 > sum1)) { /*start is back one */ linestart = linestart->prev; linestart->flags[FLAGS] |= FIXED; } if (((edgept->next->flags[DIR] - edgept->flags[DIR] + 1) & 7) >= 3 || (edgept->flags[DIR] == dir1 && sum1 >= sum2) || ((edgept->prev->flags[RUNLENGTH] < edgept->flags[RUNLENGTH] || (edgept->flags[DIR] == dir2 && sum2 >= sum1)) && linestart->next != edgept)) edgept = edgept->next; } /*sharp bend */ edgept->flags[FLAGS] |= FIXED; } /*do whole loop */ while (edgept != loopstart && !stopped); edgept = start; do { if (((edgept->flags[RUNLENGTH] >= 8) && (edgept->flags[DIR] != 2) && (edgept->flags[DIR] != 6)) || ((edgept->flags[RUNLENGTH] >= 8) && ((edgept->flags[DIR] == 2) || (edgept->flags[DIR] == 6)))) { edgept->flags[FLAGS] |= FIXED; edgept1 = edgept->next; edgept1->flags[FLAGS] |= FIXED; } edgept = edgept->next; } while (edgept != start); edgept = start; do { /*single fixed step */ if (edgept->flags[FLAGS] & FIXED && edgept->flags[RUNLENGTH] == 1 /*and neighours free */ && edgept->next->flags[FLAGS] & FIXED && (edgept->prev->flags[FLAGS] & FIXED) == 0 /*same pair of dirs */ && (edgept->next->next->flags[FLAGS] & FIXED) == 0 && edgept->prev->flags[DIR] == edgept->next->flags[DIR] && edgept->prev->prev->flags[DIR] == edgept->next->next->flags[DIR] && ((edgept->prev->flags[DIR] - edgept->flags[DIR] + 1) & 7) < 3) { /*unfix it */ edgept->flags[FLAGS] &= ~FIXED; edgept->next->flags[FLAGS] &= ~FIXED; } edgept = edgept->next; /*do all points */ } while (edgept != start); /*until finished */ stopped = 0; if (area < 450) area = 450; gapmin = area * fixed_dist * fixed_dist / 44000; edgept = start; fixed_count = 0; do { if (edgept->flags[FLAGS] & FIXED) fixed_count++; edgept = edgept->next; } while (edgept != start); while ((edgept->flags[FLAGS] & FIXED) == 0) edgept = edgept->next; edgefix0 = edgept; edgept = edgept->next; while ((edgept->flags[FLAGS] & FIXED) == 0) edgept = edgept->next; edgefix1 = edgept; edgept = edgept->next; while ((edgept->flags[FLAGS] & FIXED) == 0) edgept = edgept->next; edgefix2 = edgept; edgept = edgept->next; while ((edgept->flags[FLAGS] & FIXED) == 0) edgept = edgept->next; edgefix3 = edgept; startfix = edgefix2; do { if (fixed_count <= 3) break; //already too few point_diff (d12vec, edgefix1->pos, edgefix2->pos); d12 = LENGTH (d12vec); // TODO(rays) investigate this change: // Only unfix a point if it is part of a low-curvature section // of outline and the total angle change of the outlines is // less than 90 degrees, ie the scalar product is positive. // if (d12 <= gapmin && SCALAR(edgefix0->vec, edgefix2->vec) > 0) { if (d12 <= gapmin) { point_diff (d01vec, edgefix0->pos, edgefix1->pos); d01 = LENGTH (d01vec); point_diff (d23vec, edgefix2->pos, edgefix3->pos); d23 = LENGTH (d23vec); if (d01 > d23) { edgefix2->flags[FLAGS] &= ~FIXED; fixed_count--; } else { edgefix1->flags[FLAGS] &= ~FIXED; fixed_count--; edgefix1 = edgefix2; } } else { edgefix0 = edgefix1; edgefix1 = edgefix2; } edgefix2 = edgefix3; edgept = edgept->next; while ((edgept->flags[FLAGS] & FIXED) == 0) { if (edgept == startfix) stopped = 1; edgept = edgept->next; } edgefix3 = edgept; edgefix = edgefix2; } while ((edgefix != startfix) && (!stopped)); } //#pragma OPT_LEVEL 2 /*stop compiler bugs*/ /********************************************************************** *poly2(startpt,area,path) applies a second approximation to the outline *using the points which have been fixed by the first approximation* **********************************************************************/ EDGEPT *poly2( //second poly EDGEPT *startpt, /*start of loop */ int area /*area of blob box */ ) { register EDGEPT *edgept; /*current outline point */ EDGEPT *loopstart; /*starting point */ register EDGEPT *linestart; /*start of line */ register int edgesum; /*correction count */ if (area < 1200) area = 1200; /*minimum value */ loopstart = NULL; /*not found it yet */ edgept = startpt; /*start of loop */ do { /*current point fixed */ if (edgept->flags[FLAGS] & FIXED /*and next not */ && (edgept->next->flags[FLAGS] & FIXED) == 0) { loopstart = edgept; /*start of repoly */ break; } edgept = edgept->next; /*next point */ } while (edgept != startpt); /*until found or finished */ if (loopstart == NULL && (startpt->flags[FLAGS] & FIXED) == 0) { /*fixed start of loop */ startpt->flags[FLAGS] |= FIXED; loopstart = startpt; /*or start of loop */ } if (loopstart) { do { edgept = loopstart; /*first to do */ do { linestart = edgept; edgesum = 0; /*sum of lengths */ do { /*sum lengths */ edgesum += edgept->flags[RUNLENGTH]; edgept = edgept->next; /*move on */ } while ((edgept->flags[FLAGS] & FIXED) == 0 && edgept != loopstart && edgesum < 126); if (poly_debug) tprintf ("Poly2:starting at (%d,%d)+%d=(%d,%d),%d to (%d,%d)\n", linestart->pos.x, linestart->pos.y, linestart->flags[DIR], linestart->vec.x, linestart->vec.y, edgesum, edgept->pos.x, edgept->pos.y); /*reapproximate */ cutline(linestart, edgept, area); while ((edgept->next->flags[FLAGS] & FIXED) && edgept != loopstart) edgept = edgept->next; /*look for next non-fixed */ } /*do all the loop */ while (edgept != loopstart); edgesum = 0; do { if (edgept->flags[FLAGS] & FIXED) edgesum++; edgept = edgept->next; } //count fixed pts while (edgept != loopstart); if (edgesum < 3) area /= 2; //must have 3 pts } while (edgesum < 3); do { linestart = edgept; do { edgept = edgept->next; } while ((edgept->flags[FLAGS] & FIXED) == 0); linestart->next = edgept; edgept->prev = linestart; linestart->vec.x = edgept->pos.x - linestart->pos.x; linestart->vec.y = edgept->pos.y - linestart->pos.y; } while (edgept != loopstart); } else edgept = startpt; /*start of loop */ loopstart = edgept; /*new start */ return loopstart; /*correct exit */ } /********************************************************************** *cutline(first,last,area) straightens out a line by partitioning *and joining the ends by a straight line* **********************************************************************/ void cutline( //recursive refine EDGEPT *first, /*ends of line */ EDGEPT *last, int area /*area of object */ ) { register EDGEPT *edge; /*current edge */ TPOINT vecsum; /*vector sum */ int vlen; /*approx length of vecsum */ TPOINT vec; /*accumulated vector */ EDGEPT *maxpoint; /*worst point */ int maxperp; /*max deviation */ register int perp; /*perp distance */ int ptcount; /*no of points */ int squaresum; /*sum of perps */ edge = first; /*start of line */ if (edge->next == last) return; /*simple line */ /*vector sum */ vecsum.x = last->pos.x - edge->pos.x; vecsum.y = last->pos.y - edge->pos.y; if (vecsum.x == 0 && vecsum.y == 0) { /*special case */ vecsum.x = -edge->prev->vec.x; vecsum.y = -edge->prev->vec.y; } /*absolute value */ vlen = vecsum.x > 0 ? vecsum.x : -vecsum.x; if (vecsum.y > vlen) vlen = vecsum.y; /*maximum */ else if (-vecsum.y > vlen) vlen = -vecsum.y; /*absolute value */ vec.x = edge->vec.x; /*accumulated vector */ vec.y = edge->vec.y; maxperp = 0; /*none yet */ squaresum = ptcount = 0; edge = edge->next; /*move to actual point */ maxpoint = edge; /*in case there isn't one */ do { perp = CROSS (vec, vecsum); /*get perp distance */ if (perp != 0) { perp *= perp; /*squared deviation */ } squaresum += perp; /*sum squares */ ptcount++; /*count points */ if (poly_debug) tprintf ("Cutline:Final perp=%d\n", perp); if (perp > maxperp) { maxperp = perp; maxpoint = edge; /*find greatest deviation */ } vec.x += edge->vec.x; /*accumulate vectors */ vec.y += edge->vec.y; edge = edge->next; } while (edge != last); /*test all line */ perp = LENGTH (vecsum); ASSERT_HOST (perp != 0); if (maxperp < 256 * MAX_INT16) { maxperp <<= 8; maxperp /= perp; /*true max perp */ } else { maxperp /= perp; maxperp <<= 8; /*avoid overflow */ } if (squaresum < 256 * MAX_INT16) /*mean squared perp */ perp = (squaresum << 8) / (perp * ptcount); else /*avoid overflow */ perp = (squaresum / perp << 8) / ptcount; if (poly_debug) tprintf ("Cutline:A=%d, max=%.2f(%.2f%%), msd=%.2f(%.2f%%)\n", area, maxperp / 256.0, maxperp * 200.0 / area, perp / 256.0, perp * 300.0 / area); if (maxperp * par1 >= 10 * area || perp * par2 >= 10 * area || vlen >= 126) { maxpoint->flags[FLAGS] |= FIXED; /*partitions */ cutline(first, maxpoint, area); cutline(maxpoint, last, area); } }
1080228-arabicocr11
ccstruct/polyaprx.cpp
C++
asf20
20,149
/********************************************************************** * File: quadlsq.cpp (Formerly qlsq.c) * Description: Code for least squares approximation of quadratics. * Author: Ray Smith * Created: Wed Oct 6 15:14:23 BST 1993 * * (C) Copyright 1993, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include <stdio.h> #include <math.h> #include "quadlsq.h" #include "tprintf.h" // Minimum variance in least squares before backing off to a lower degree. const double kMinVariance = 1.0 / 1024; /********************************************************************** * QLSQ::clear * * Function to initialize a QLSQ. **********************************************************************/ void QLSQ::clear() { // initialize a = 0.0; b = 0.0; c = 0.0; n = 0; // No elements. sigx = 0.0; // Zero accumulators. sigy = 0.0; sigxx = 0.0; sigxy = 0.0; sigyy = 0.0; sigxxx = 0.0; sigxxy = 0.0; sigxxxx = 0.0; } /********************************************************************** * QLSQ::add * * Add an element to the accumulator. **********************************************************************/ void QLSQ::add(double x, double y) { n++; // Count elements. sigx += x; // Update accumulators. sigy += y; sigxx += x * x; sigxy += x * y; sigyy += y * y; sigxxx += static_cast<long double>(x) * x * x; sigxxy += static_cast<long double>(x) * x * y; sigxxxx += static_cast<long double>(x) * x * x * x; } /********************************************************************** * QLSQ::remove * * Delete an element from the accumulator. **********************************************************************/ void QLSQ::remove(double x, double y) { if (n <= 0) { tprintf("Can't remove an element from an empty QLSQ accumulator!\n"); return; } n--; // Count elements. sigx -= x; // Update accumulators. sigy -= y; sigxx -= x * x; sigxy -= x * y; sigyy -= y * y; sigxxx -= static_cast<long double>(x) * x * x; sigxxy -= static_cast<long double>(x) * x * y; sigxxxx -= static_cast<long double>(x) * x * x * x; } /********************************************************************** * QLSQ::fit * * Fit the given degree of polynomial and store the result. * This creates a quadratic of the form axx + bx + c, but limited to * the given degree. **********************************************************************/ void QLSQ::fit(int degree) { long double x_variance = static_cast<long double>(sigxx) * n - static_cast<long double>(sigx) * sigx; // Note: for computational efficiency, we do not normalize the variance, // covariance and cube variance here as they are in the same order in both // nominators and denominators. However, we need be careful in value range // check. if (x_variance < kMinVariance * n * n || degree < 1 || n < 2) { // We cannot calculate b reliably so forget a and b, and just work on c. a = b = 0.0; if (n >= 1 && degree >= 0) { c = sigy / n; } else { c = 0.0; } return; } long double top96 = 0.0; // Accurate top. long double bottom96 = 0.0; // Accurate bottom. long double cubevar = sigxxx * n - static_cast<long double>(sigxx) * sigx; long double covariance = static_cast<long double>(sigxy) * n - static_cast<long double>(sigx) * sigy; if (n >= 4 && degree >= 2) { top96 = cubevar * covariance; top96 += x_variance * (static_cast<long double>(sigxx) * sigy - sigxxy * n); bottom96 = cubevar * cubevar; bottom96 -= x_variance * (sigxxxx * n - static_cast<long double>(sigxx) * sigxx); } if (bottom96 >= kMinVariance * n * n * n * n) { // Denominators looking good a = top96 / bottom96; top96 = covariance - cubevar * a; b = top96 / x_variance; } else { // Forget a, and concentrate on b. a = 0.0; b = covariance / x_variance; } c = (sigy - a * sigxx - b * sigx) / n; }
1080228-arabicocr11
ccstruct/quadlsq.cpp
C++
asf20
4,711
/********************************************************************** * File: ratngs.h (Formerly ratings.h) * Description: Definition of the WERD_CHOICE and BLOB_CHOICE classes. * Author: Ray Smith * Created: Thu Apr 23 11:40:38 BST 1992 * * (C) Copyright 1992, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef RATNGS_H #define RATNGS_H #include <assert.h> #include "clst.h" #include "elst.h" #include "genericvector.h" #include "matrix.h" #include "unichar.h" #include "unicharset.h" #include "werd.h" class MATRIX; struct TBLOB; struct TWERD; // Enum to describe the source of a BLOB_CHOICE to make it possible to determine // whether a blob has been classified by inspecting the BLOB_CHOICEs. enum BlobChoiceClassifier { BCC_STATIC_CLASSIFIER, // From the char_norm classifier. BCC_ADAPTED_CLASSIFIER, // From the adaptive classifier. BCC_SPECKLE_CLASSIFIER, // Backup for failed classification. BCC_AMBIG, // Generated by ambiguity detection. BCC_FAKE, // From some other process. }; class BLOB_CHOICE: public ELIST_LINK { public: BLOB_CHOICE() { unichar_id_ = UNICHAR_SPACE; fontinfo_id_ = -1; fontinfo_id2_ = -1; rating_ = 10.0; certainty_ = -1.0; script_id_ = -1; xgap_before_ = 0; xgap_after_ = 0; min_xheight_ = 0.0f; max_xheight_ = 0.0f; yshift_ = 0.0f; classifier_ = BCC_FAKE; } BLOB_CHOICE(UNICHAR_ID src_unichar_id, // character id float src_rating, // rating float src_cert, // certainty inT16 src_fontinfo_id, // font inT16 src_fontinfo_id2, // 2nd choice font int script_id, // script float min_xheight, // min xheight in image pixel units float max_xheight, // max xheight allowed by this char float yshift, // the larger of y shift (top or bottom) BlobChoiceClassifier c); // adapted match or other BLOB_CHOICE(const BLOB_CHOICE &other); ~BLOB_CHOICE() {} UNICHAR_ID unichar_id() const { return unichar_id_; } float rating() const { return rating_; } float certainty() const { return certainty_; } inT16 fontinfo_id() const { return fontinfo_id_; } inT16 fontinfo_id2() const { return fontinfo_id2_; } int script_id() const { return script_id_; } const MATRIX_COORD& matrix_cell() { return matrix_cell_; } inT16 xgap_before() const { return xgap_before_; } inT16 xgap_after() const { return xgap_after_; } float min_xheight() const { return min_xheight_; } float max_xheight() const { return max_xheight_; } float yshift() const { return yshift_; } BlobChoiceClassifier classifier() const { return classifier_; } bool IsAdapted() const { return classifier_ == BCC_ADAPTED_CLASSIFIER; } bool IsClassified() const { return classifier_ == BCC_STATIC_CLASSIFIER || classifier_ == BCC_ADAPTED_CLASSIFIER || classifier_ == BCC_SPECKLE_CLASSIFIER; } void set_unichar_id(UNICHAR_ID newunichar_id) { unichar_id_ = newunichar_id; } void set_rating(float newrat) { rating_ = newrat; } void set_certainty(float newrat) { certainty_ = newrat; } void set_fontinfo_id(inT16 newfont) { fontinfo_id_ = newfont; } void set_fontinfo_id2(inT16 newfont) { fontinfo_id2_ = newfont; } void set_script(int newscript_id) { script_id_ = newscript_id; } void set_matrix_cell(int col, int row) { matrix_cell_.col = col; matrix_cell_.row = row; } void set_xgap_before(inT16 gap) { xgap_before_ = gap; } void set_xgap_after(inT16 gap) { xgap_after_ = gap; } void set_classifier(BlobChoiceClassifier classifier) { classifier_ = classifier; } static BLOB_CHOICE* deep_copy(const BLOB_CHOICE* src) { BLOB_CHOICE* choice = new BLOB_CHOICE; *choice = *src; return choice; } // Returns true if *this and other agree on the baseline and x-height // to within some tolerance based on a given estimate of the x-height. bool PosAndSizeAgree(const BLOB_CHOICE& other, float x_height, bool debug) const; void print(const UNICHARSET *unicharset) const { tprintf("r%.2f c%.2f x[%g,%g]: %d %s", rating_, certainty_, min_xheight_, max_xheight_, unichar_id_, (unicharset == NULL) ? "" : unicharset->debug_str(unichar_id_).string()); } void print_full() const { print(NULL); tprintf(" script=%d, font1=%d, font2=%d, yshift=%g, classifier=%d\n", script_id_, fontinfo_id_, fontinfo_id2_, yshift_, classifier_); } // Sort function for sorting BLOB_CHOICEs in increasing order of rating. static int SortByRating(const void *p1, const void *p2) { const BLOB_CHOICE *bc1 = *reinterpret_cast<const BLOB_CHOICE * const *>(p1); const BLOB_CHOICE *bc2 = *reinterpret_cast<const BLOB_CHOICE * const *>(p2); return (bc1->rating_ < bc2->rating_) ? -1 : 1; } private: UNICHAR_ID unichar_id_; // unichar id inT16 fontinfo_id_; // char font information inT16 fontinfo_id2_; // 2nd choice font information // Rating is the classifier distance weighted by the length of the outline // in the blob. In terms of probability, classifier distance is -klog p such // that the resulting distance is in the range [0, 1] and then // rating = w (-k log p) where w is the weight for the length of the outline. // Sums of ratings may be compared meaningfully for words of different // segmentation. float rating_; // size related // Certainty is a number in [-20, 0] indicating the classifier certainty // of the choice. In terms of probability, certainty = 20 (k log p) where // k is defined as above to normalize -klog p to the range [0, 1]. float certainty_; // absolute int script_id_; // Holds the position of this choice in the ratings matrix. // Used to location position in the matrix during path backtracking. MATRIX_COORD matrix_cell_; inT16 xgap_before_; inT16 xgap_after_; // X-height range (in image pixels) that this classification supports. float min_xheight_; float max_xheight_; // yshift_ - The vertical distance (in image pixels) the character is // shifted (up or down) from an acceptable y position. float yshift_; BlobChoiceClassifier classifier_; // What generated *this. }; // Make BLOB_CHOICE listable. ELISTIZEH(BLOB_CHOICE) // Return the BLOB_CHOICE in bc_list matching a given unichar_id, // or NULL if there is no match. BLOB_CHOICE *FindMatchingChoice(UNICHAR_ID char_id, BLOB_CHOICE_LIST *bc_list); // Permuter codes used in WERD_CHOICEs. enum PermuterType { NO_PERM, // 0 PUNC_PERM, // 1 TOP_CHOICE_PERM, // 2 LOWER_CASE_PERM, // 3 UPPER_CASE_PERM, // 4 NGRAM_PERM, // 5 NUMBER_PERM, // 6 USER_PATTERN_PERM, // 7 SYSTEM_DAWG_PERM, // 8 DOC_DAWG_PERM, // 9 USER_DAWG_PERM, // 10 FREQ_DAWG_PERM, // 11 COMPOUND_PERM, // 12 NUM_PERMUTER_TYPES }; namespace tesseract { // ScriptPos tells whether a character is subscript, superscript or normal. enum ScriptPos { SP_NORMAL, SP_SUBSCRIPT, SP_SUPERSCRIPT, SP_DROPCAP }; const char *ScriptPosToString(tesseract::ScriptPos script_pos); } // namespace tesseract. class WERD_CHOICE : public ELIST_LINK { public: static const float kBadRating; static const char *permuter_name(uinT8 permuter); WERD_CHOICE(const UNICHARSET *unicharset) : unicharset_(unicharset) { this->init(8); } WERD_CHOICE(const UNICHARSET *unicharset, int reserved) : unicharset_(unicharset) { this->init(reserved); } WERD_CHOICE(const char *src_string, const char *src_lengths, float src_rating, float src_certainty, uinT8 src_permuter, const UNICHARSET &unicharset) : unicharset_(&unicharset) { this->init(src_string, src_lengths, src_rating, src_certainty, src_permuter); } WERD_CHOICE(const char *src_string, const UNICHARSET &unicharset); WERD_CHOICE(const WERD_CHOICE &word) : unicharset_(word.unicharset_) { this->init(word.length()); this->operator=(word); } ~WERD_CHOICE(); const UNICHARSET *unicharset() const { return unicharset_; } inline int length() const { return length_; } float adjust_factor() const { return adjust_factor_; } void set_adjust_factor(float factor) { adjust_factor_ = factor; } inline const UNICHAR_ID *unichar_ids() const { return unichar_ids_; } inline const UNICHAR_ID unichar_id(int index) const { assert(index < length_); return unichar_ids_[index]; } inline int state(int index) const { return state_[index]; } tesseract::ScriptPos BlobPosition(int index) const { if (index < 0 || index >= length_) return tesseract::SP_NORMAL; return script_pos_[index]; } inline float rating() const { return rating_; } inline float certainty() const { return certainty_; } inline float certainty(int index) const { return certainties_[index]; } inline float min_x_height() const { return min_x_height_; } inline float max_x_height() const { return max_x_height_; } inline void set_x_heights(float min_height, float max_height) { min_x_height_ = min_height; max_x_height_ = max_height; } inline uinT8 permuter() const { return permuter_; } const char *permuter_name() const; // Returns the BLOB_CHOICE_LIST corresponding to the given index in the word, // taken from the appropriate cell in the ratings MATRIX. // Borrowed pointer, so do not delete. BLOB_CHOICE_LIST* blob_choices(int index, MATRIX* ratings) const; // Returns the MATRIX_COORD corresponding to the location in the ratings // MATRIX for the given index into the word. MATRIX_COORD MatrixCoord(int index) const; inline void set_unichar_id(UNICHAR_ID unichar_id, int index) { assert(index < length_); unichar_ids_[index] = unichar_id; } bool dangerous_ambig_found() const { return dangerous_ambig_found_; } void set_dangerous_ambig_found_(bool value) { dangerous_ambig_found_ = value; } inline void set_rating(float new_val) { rating_ = new_val; } inline void set_certainty(float new_val) { certainty_ = new_val; } inline void set_permuter(uinT8 perm) { permuter_ = perm; } // Note: this function should only be used if all the fields // are populated manually with set_* functions (rather than // (copy)constructors and append_* functions). inline void set_length(int len) { ASSERT_HOST(reserved_ >= len); length_ = len; } /// Make more space in unichar_id_ and fragment_lengths_ arrays. inline void double_the_size() { if (reserved_ > 0) { unichar_ids_ = GenericVector<UNICHAR_ID>::double_the_size_memcpy( reserved_, unichar_ids_); script_pos_ = GenericVector<tesseract::ScriptPos>::double_the_size_memcpy( reserved_, script_pos_); state_ = GenericVector<int>::double_the_size_memcpy( reserved_, state_); certainties_ = GenericVector<float>::double_the_size_memcpy( reserved_, certainties_); reserved_ *= 2; } else { unichar_ids_ = new UNICHAR_ID[1]; script_pos_ = new tesseract::ScriptPos[1]; state_ = new int[1]; certainties_ = new float[1]; reserved_ = 1; } } /// Initializes WERD_CHOICE - reserves length slots in unichar_ids_ and /// fragment_length_ arrays. Sets other values to default (blank) values. inline void init(int reserved) { reserved_ = reserved; if (reserved > 0) { unichar_ids_ = new UNICHAR_ID[reserved]; script_pos_ = new tesseract::ScriptPos[reserved]; state_ = new int[reserved]; certainties_ = new float[reserved]; } else { unichar_ids_ = NULL; script_pos_ = NULL; state_ = NULL; certainties_ = NULL; } length_ = 0; adjust_factor_ = 1.0f; rating_ = 0.0; certainty_ = MAX_FLOAT32; min_x_height_ = 0.0f; max_x_height_ = MAX_FLOAT32; permuter_ = NO_PERM; unichars_in_script_order_ = false; // Tesseract is strict left-to-right. dangerous_ambig_found_ = false; } /// Helper function to build a WERD_CHOICE from the given string, /// fragment lengths, rating, certainty and permuter. /// The function assumes that src_string is not NULL. /// src_lengths argument could be NULL, in which case the unichars /// in src_string are assumed to all be of length 1. void init(const char *src_string, const char *src_lengths, float src_rating, float src_certainty, uinT8 src_permuter); /// Set the fields in this choice to be default (bad) values. inline void make_bad() { length_ = 0; rating_ = kBadRating; certainty_ = -MAX_FLOAT32; } /// This function assumes that there is enough space reserved /// in the WERD_CHOICE for adding another unichar. /// This is an efficient alternative to append_unichar_id(). inline void append_unichar_id_space_allocated( UNICHAR_ID unichar_id, int blob_count, float rating, float certainty) { assert(reserved_ > length_); length_++; this->set_unichar_id(unichar_id, blob_count, rating, certainty, length_-1); } void append_unichar_id(UNICHAR_ID unichar_id, int blob_count, float rating, float certainty); inline void set_unichar_id(UNICHAR_ID unichar_id, int blob_count, float rating, float certainty, int index) { assert(index < length_); unichar_ids_[index] = unichar_id; state_[index] = blob_count; certainties_[index] = certainty; script_pos_[index] = tesseract::SP_NORMAL; rating_ += rating; if (certainty < certainty_) { certainty_ = certainty; } } // Sets the entries for the given index from the BLOB_CHOICE, assuming // unit fragment lengths, but setting the state for this index to blob_count. void set_blob_choice(int index, int blob_count, const BLOB_CHOICE* blob_choice); bool contains_unichar_id(UNICHAR_ID unichar_id) const; void remove_unichar_ids(int index, int num); inline void remove_last_unichar_id() { --length_; } inline void remove_unichar_id(int index) { this->remove_unichar_ids(index, 1); } bool has_rtl_unichar_id() const; void reverse_and_mirror_unichar_ids(); // Returns the half-open interval of unichar_id indices [start, end) which // enclose the core portion of this word -- the part after stripping // punctuation from the left and right. void punct_stripped(int *start_core, int *end_core) const; // Returns the indices [start, end) containing the core of the word, stripped // of any superscript digits on either side. (i.e., the non-footnote part // of the word). There is no guarantee that the output range is non-empty. void GetNonSuperscriptSpan(int *start, int *end) const; // Return a copy of this WERD_CHOICE with the choices [start, end). // The result is useful only for checking against a dictionary. WERD_CHOICE shallow_copy(int start, int end) const; void string_and_lengths(STRING *word_str, STRING *word_lengths_str) const; const STRING debug_string() const { STRING word_str; for (int i = 0; i < length_; ++i) { word_str += unicharset_->debug_str(unichar_ids_[i]); word_str += " "; } return word_str; } // Call this to override the default (strict left to right graphemes) // with the fact that some engine produces a "reading order" set of // Graphemes for each word. bool set_unichars_in_script_order(bool in_script_order) { return unichars_in_script_order_ = in_script_order; } bool unichars_in_script_order() const { return unichars_in_script_order_; } // Returns a UTF-8 string equivalent to the current choice // of UNICHAR IDs. const STRING &unichar_string() const { this->string_and_lengths(&unichar_string_, &unichar_lengths_); return unichar_string_; } // Returns the lengths, one byte each, representing the number of bytes // required in the unichar_string for each UNICHAR_ID. const STRING &unichar_lengths() const { this->string_and_lengths(&unichar_string_, &unichar_lengths_); return unichar_lengths_; } // Sets up the script_pos_ member using the blobs_list to get the bln // bounding boxes, *this to get the unichars, and this->unicharset // to get the target positions. If small_caps is true, sub/super are not // considered, but dropcaps are. // NOTE: blobs_list should be the chopped_word blobs. (Fully segemented.) void SetScriptPositions(bool small_caps, TWERD* word); // Sets the script_pos_ member from some source positions with a given length. void SetScriptPositions(const tesseract::ScriptPos* positions, int length); // Sets all the script_pos_ positions to the given position. void SetAllScriptPositions(tesseract::ScriptPos position); static tesseract::ScriptPos ScriptPositionOf(bool print_debug, const UNICHARSET& unicharset, const TBOX& blob_box, UNICHAR_ID unichar_id); // Returns the "dominant" script ID for the word. By "dominant", the script // must account for at least half the characters. Otherwise, it returns 0. // Note that for Japanese, Hiragana and Katakana are simply treated as Han. int GetTopScriptID() const; // Fixes the state_ for a chop at the given blob_posiiton. void UpdateStateForSplit(int blob_position); // Returns the sum of all the state elements, being the total number of blobs. int TotalOfStates() const; void print() const { this->print(""); } void print(const char *msg) const; // Prints the segmentation state with an introductory message. void print_state(const char *msg) const; // Displays the segmentation state of *this (if not the same as the last // one displayed) and waits for a click in the window. void DisplaySegmentation(TWERD* word); WERD_CHOICE& operator+= ( // concatanate const WERD_CHOICE & second);// second on first WERD_CHOICE& operator= (const WERD_CHOICE& source); private: const UNICHARSET *unicharset_; // TODO(rays) Perhaps replace the multiple arrays with an array of structs? // unichar_ids_ is an array of classifier "results" that make up a word. // For each unichar_ids_[i], script_pos_[i] has the sub/super/normal position // of each unichar_id. // state_[i] indicates the number of blobs in WERD_RES::chopped_word that // were put together to make the classification results in the ith position // in unichar_ids_, and certainties_[i] is the certainty of the choice that // was used in this word. // == Change from before == // Previously there was fragment_lengths_ that allowed a word to be // artificially composed of multiple fragment results. Since the new // segmentation search doesn't do fragments, treatment of fragments has // been moved to a lower level, augmenting the ratings matrix with the // combined fragments, and allowing the language-model/segmentation-search // to deal with only the combined unichar_ids. UNICHAR_ID *unichar_ids_; // unichar ids that represent the text of the word tesseract::ScriptPos* script_pos_; // Normal/Sub/Superscript of each unichar. int* state_; // Number of blobs in each unichar. float* certainties_; // Certainty of each unichar. int reserved_; // size of the above arrays int length_; // word length // Factor that was used to adjust the rating. float adjust_factor_; // Rating is the sum of the ratings of the individual blobs in the word. float rating_; // size related // certainty is the min (worst) certainty of the individual blobs in the word. float certainty_; // absolute // xheight computed from the result, or 0 if inconsistent. float min_x_height_; float max_x_height_; uinT8 permuter_; // permuter code // Normally, the ratings_ matrix represents the recognition results in order // from left-to-right. However, some engines (say Cube) may return // recognition results in the order of the script's major reading direction // (for Arabic, that is right-to-left). bool unichars_in_script_order_; // True if NoDangerousAmbig found an ambiguity. bool dangerous_ambig_found_; // The following variables are populated and passed by reference any // time unichar_string() or unichar_lengths() are called. mutable STRING unichar_string_; mutable STRING unichar_lengths_; }; // Make WERD_CHOICE listable. ELISTIZEH(WERD_CHOICE) typedef GenericVector<BLOB_CHOICE_LIST *> BLOB_CHOICE_LIST_VECTOR; // Utilities for comparing WERD_CHOICEs bool EqualIgnoringCaseAndTerminalPunct(const WERD_CHOICE &word1, const WERD_CHOICE &word2); // Utilities for debug printing. void print_ratings_list( const char *msg, // intro message BLOB_CHOICE_LIST *ratings, // list of results const UNICHARSET &current_unicharset // unicharset that can be used // for id-to-unichar conversion ); #endif
1080228-arabicocr11
ccstruct/ratngs.h
C++
asf20
22,550
/********************************************************************** * File: blread.h (Formerly pdread.h) * Description: Friend function of BLOCK to read the uscan pd file. * Author: Ray Smith * Created: Mon Mar 18 14:39:00 GMT 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef BLREAD_H #define BLREAD_H #include "params.h" #include "ocrblock.h" bool read_unlv_file( //print list of sides STRING name, //basename of file inT32 xsize, //image size inT32 ysize, //image size BLOCK_LIST *blocks //output list ); void FullPageBlock(int width, int height, BLOCK_LIST *blocks); #endif
1080228-arabicocr11
ccstruct/blread.h
C
asf20
1,422
/* -*-C-*- ******************************************************************************** * * File: seam.c (Formerly seam.c) * Description: * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri May 17 16:30:13 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "seam.h" #include "blobs.h" #include "freelist.h" #include "tprintf.h" #ifdef __UNIX__ #include <assert.h> #endif /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ #define NUM_STARTING_SEAMS 20 /*---------------------------------------------------------------------- Public Function Code ----------------------------------------------------------------------*/ /** * @name point_in_split * * Check to see if either of these points are present in the current * split. * @returns TRUE if one of them is split. */ bool point_in_split(SPLIT *split, EDGEPT *point1, EDGEPT *point2) { return ((split) ? ((exact_point (split->point1, point1) || exact_point (split->point1, point2) || exact_point (split->point2, point1) || exact_point (split->point2, point2)) ? TRUE : FALSE) : FALSE); } /** * @name point_in_seam * * Check to see if either of these points are present in the current * seam. * @returns TRUE if one of them is. */ bool point_in_seam(const SEAM *seam, SPLIT *split) { return (point_in_split(seam->split1, split->point1, split->point2) || point_in_split(seam->split2, split->point1, split->point2) || point_in_split(seam->split3, split->point1, split->point2)); } /** * @name point_used_by_split * * Return whether this particular EDGEPT * is used in a given split. * @returns TRUE if the edgept is used by the split. */ bool point_used_by_split(SPLIT *split, EDGEPT *point) { if (split == NULL) return false; return point == split->point1 || point == split->point2; } /** * @name point_used_by_seam * * Return whether this particular EDGEPT * is used in a given seam. * @returns TRUE if the edgept is used by the seam. */ bool point_used_by_seam(SEAM *seam, EDGEPT *point) { if (seam == NULL) return false; return point_used_by_split(seam->split1, point) || point_used_by_split(seam->split2, point) || point_used_by_split(seam->split3, point); } /** * @name combine_seam * * Combine two seam records into a single seam. Move the split * references from the second seam to the first one. The argument * convention is patterned after strcpy. */ void combine_seams(SEAM *dest_seam, SEAM *source_seam) { dest_seam->priority += source_seam->priority; dest_seam->location += source_seam->location; dest_seam->location /= 2; if (source_seam->split1) { if (!dest_seam->split1) dest_seam->split1 = source_seam->split1; else if (!dest_seam->split2) dest_seam->split2 = source_seam->split1; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split1; else delete source_seam->split1; // Wouldn't have fitted. source_seam->split1 = NULL; } if (source_seam->split2) { if (!dest_seam->split2) dest_seam->split2 = source_seam->split2; else if (!dest_seam->split3) dest_seam->split3 = source_seam->split2; else delete source_seam->split2; // Wouldn't have fitted. source_seam->split2 = NULL; } if (source_seam->split3) { if (!dest_seam->split3) dest_seam->split3 = source_seam->split3; else delete source_seam->split3; // Wouldn't have fitted. source_seam->split3 = NULL; } delete source_seam; } /** * @name start_seam_list * * Initialize a list of seams that match the original number of blobs * present in the starting segmentation. Each of the seams created * by this routine have location information only. */ void start_seam_list(TWERD *word, GenericVector<SEAM*>* seam_array) { seam_array->truncate(0); TPOINT location; for (int b = 1; b < word->NumBlobs(); ++b) { TBOX bbox = word->blobs[b - 1]->bounding_box(); TBOX nbox = word->blobs[b]->bounding_box(); location.x = (bbox.right() + nbox.left()) / 2; location.y = (bbox.bottom() + bbox.top() + nbox.bottom() + nbox.top()) / 4; seam_array->push_back(new SEAM(0.0f, location, NULL, NULL, NULL)); } } /** * @name test_insert_seam * * @returns true if insert_seam will succeed. */ bool test_insert_seam(const GenericVector<SEAM*>& seam_array, TWERD *word, int index) { SEAM *test_seam; int list_length = seam_array.size(); for (int test_index = 0; test_index < index; ++test_index) { test_seam = seam_array[test_index]; if (test_index + test_seam->widthp < index && test_seam->widthp + test_index == index - 1 && account_splits(test_seam, word, test_index + 1, 1) < 0) return false; } for (int test_index = index; test_index < list_length; test_index++) { test_seam = seam_array[test_index]; if (test_index - test_seam->widthn >= index && test_index - test_seam->widthn == index && account_splits(test_seam, word, test_index + 1, -1) < 0) return false; } return true; } /** * @name insert_seam * * Add another seam to a collection of seams at a particular location * in the seam array. */ void insert_seam(const TWERD* word, int index, SEAM *seam, GenericVector<SEAM*>* seam_array) { SEAM *test_seam; int list_length = seam_array->size(); for (int test_index = 0; test_index < index; ++test_index) { test_seam = seam_array->get(test_index); if (test_index + test_seam->widthp >= index) { test_seam->widthp++; /*got in the way */ } else if (test_seam->widthp + test_index == index - 1) { test_seam->widthp = account_splits(test_seam, word, test_index + 1, 1); if (test_seam->widthp < 0) { tprintf("Failed to find any right blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } for (int test_index = index; test_index < list_length; test_index++) { test_seam = seam_array->get(test_index); if (test_index - test_seam->widthn < index) { test_seam->widthn++; /*got in the way */ } else if (test_index - test_seam->widthn == index) { test_seam->widthn = account_splits(test_seam, word, test_index + 1, -1); if (test_seam->widthn < 0) { tprintf("Failed to find any left blob for a split!\n"); print_seam("New dud seam", seam); print_seam("Failed seam", test_seam); } } } seam_array->insert(seam, index); } /** * @name account_splits * * Account for all the splits by looking to the right (blob_direction == 1), * or to the left (blob_direction == -1) in the word. */ int account_splits(const SEAM *seam, const TWERD *word, int blob_index, int blob_direction) { inT8 found_em[3]; inT8 width; found_em[0] = seam->split1 == NULL; found_em[1] = seam->split2 == NULL; found_em[2] = seam->split3 == NULL; if (found_em[0] && found_em[1] && found_em[2]) return 0; width = 0; do { TBLOB* blob = word->blobs[blob_index]; if (!found_em[0]) found_em[0] = find_split_in_blob(seam->split1, blob); if (!found_em[1]) found_em[1] = find_split_in_blob(seam->split2, blob); if (!found_em[2]) found_em[2] = find_split_in_blob(seam->split3, blob); if (found_em[0] && found_em[1] && found_em[2]) { return width; } width++; blob_index += blob_direction; } while (0 <= blob_index && blob_index < word->NumBlobs()); return -1; } /** * @name find_split_in_blob * * @returns TRUE if the split is somewhere in this blob. */ bool find_split_in_blob(SPLIT *split, TBLOB *blob) { TESSLINE *outline; for (outline = blob->outlines; outline != NULL; outline = outline->next) if (outline->Contains(split->point1->pos)) break; if (outline == NULL) return FALSE; for (outline = blob->outlines; outline != NULL; outline = outline->next) if (outline->Contains(split->point2->pos)) return TRUE; return FALSE; } /** * @name join_two_seams * * Merge these two seams into a new seam. Duplicate the split records * in both of the input seams. Return the resultant seam. */ SEAM *join_two_seams(const SEAM *seam1, const SEAM *seam2) { SEAM *result = NULL; SEAM *temp; assert(seam1 &&seam2); if (((seam1->split3 == NULL && seam2->split2 == NULL) || (seam1->split2 == NULL && seam2->split3 == NULL) || seam1->split1 == NULL || seam2->split1 == NULL) && (!shared_split_points(seam1, seam2))) { result = new SEAM(*seam1); temp = new SEAM(*seam2); combine_seams(result, temp); } return (result); } /** * @name print_seam * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seam(const char *label, SEAM *seam) { if (seam) { tprintf(label); tprintf(" %6.2f @ (%d,%d), p=%d, n=%d ", seam->priority, seam->location.x, seam->location.y, seam->widthp, seam->widthn); print_split(seam->split1); if (seam->split2) { tprintf(", "); print_split (seam->split2); if (seam->split3) { tprintf(", "); print_split (seam->split3); } } tprintf("\n"); } } /** * @name print_seams * * Print a list of splits. Show the coordinates of both points in * each split. */ void print_seams(const char *label, const GenericVector<SEAM*>& seams) { char number[CHARS_PER_LINE]; if (!seams.empty()) { tprintf("%s\n", label); for (int x = 0; x < seams.size(); ++x) { sprintf(number, "%2d: ", x); print_seam(number, seams[x]); } tprintf("\n"); } } /** * @name shared_split_points * * Check these two seams to make sure that neither of them have two * points in common. Return TRUE if any of the same points are present * in any of the splits of both seams. */ int shared_split_points(const SEAM *seam1, const SEAM *seam2) { if (seam1 == NULL || seam2 == NULL) return (FALSE); if (seam2->split1 == NULL) return (FALSE); if (point_in_seam(seam1, seam2->split1)) return (TRUE); if (seam2->split2 == NULL) return (FALSE); if (point_in_seam(seam1, seam2->split2)) return (TRUE); if (seam2->split3 == NULL) return (FALSE); if (point_in_seam(seam1, seam2->split3)) return (TRUE); return (FALSE); } /********************************************************************** * break_pieces * * Break up the blobs in this chain so that they are all independent. * This operation should undo the affect of join_pieces. **********************************************************************/ void break_pieces(const GenericVector<SEAM*>& seams, int first, int last, TWERD *word) { for (int x = first; x < last; ++x) reveal_seam(seams[x]); TESSLINE *outline = word->blobs[first]->outlines; int next_blob = first + 1; while (outline != NULL && next_blob <= last) { if (outline->next == word->blobs[next_blob]->outlines) { outline->next = NULL; outline = word->blobs[next_blob]->outlines; ++next_blob; } else { outline = outline->next; } } } /********************************************************************** * join_pieces * * Join a group of base level pieces into a single blob that can then * be classified. **********************************************************************/ void join_pieces(const GenericVector<SEAM*>& seams, int first, int last, TWERD *word) { TESSLINE *outline = word->blobs[first]->outlines; if (!outline) return; for (int x = first; x < last; ++x) { SEAM *seam = seams[x]; if (x - seam->widthn >= first && x + seam->widthp < last) hide_seam(seam); while (outline->next) outline = outline->next; outline->next = word->blobs[x + 1]->outlines; } } /********************************************************************** * hide_seam * * Change the edge points that are referenced by this seam to make * them hidden edges. **********************************************************************/ void hide_seam(SEAM *seam) { if (seam == NULL || seam->split1 == NULL) return; hide_edge_pair (seam->split1->point1, seam->split1->point2); if (seam->split2 == NULL) return; hide_edge_pair (seam->split2->point1, seam->split2->point2); if (seam->split3 == NULL) return; hide_edge_pair (seam->split3->point1, seam->split3->point2); } /********************************************************************** * hide_edge_pair * * Change the edge points that are referenced by this seam to make * them hidden edges. **********************************************************************/ void hide_edge_pair(EDGEPT *pt1, EDGEPT *pt2) { EDGEPT *edgept; edgept = pt1; do { edgept->Hide(); edgept = edgept->next; } while (!exact_point (edgept, pt2) && edgept != pt1); if (edgept == pt1) { /* tprintf("Hid entire outline at (%d,%d)!!\n", edgept->pos.x,edgept->pos.y); */ } edgept = pt2; do { edgept->Hide(); edgept = edgept->next; } while (!exact_point (edgept, pt1) && edgept != pt2); if (edgept == pt2) { /* tprintf("Hid entire outline at (%d,%d)!!\n", edgept->pos.x,edgept->pos.y); */ } } /********************************************************************** * reveal_seam * * Change the edge points that are referenced by this seam to make * them hidden edges. **********************************************************************/ void reveal_seam(SEAM *seam) { if (seam == NULL || seam->split1 == NULL) return; reveal_edge_pair (seam->split1->point1, seam->split1->point2); if (seam->split2 == NULL) return; reveal_edge_pair (seam->split2->point1, seam->split2->point2); if (seam->split3 == NULL) return; reveal_edge_pair (seam->split3->point1, seam->split3->point2); } /********************************************************************** * reveal_edge_pair * * Change the edge points that are referenced by this seam to make * them hidden edges. **********************************************************************/ void reveal_edge_pair(EDGEPT *pt1, EDGEPT *pt2) { EDGEPT *edgept; edgept = pt1; do { edgept->Reveal(); edgept = edgept->next; } while (!exact_point (edgept, pt2) && edgept != pt1); if (edgept == pt1) { /* tprintf("Hid entire outline at (%d,%d)!!\n", edgept->pos.x,edgept->pos.y); */ } edgept = pt2; do { edgept->Reveal(); edgept = edgept->next; } while (!exact_point (edgept, pt1) && edgept != pt2); if (edgept == pt2) { /* tprintf("Hid entire outline at (%d,%d)!!\n", edgept->pos.x,edgept->pos.y); */ } }
1080228-arabicocr11
ccstruct/seam.cpp
C
asf20
16,144
/********************************************************************** * File: ocrrow.cpp (Formerly row.c) * Description: Code for the ROW class. * Author: Ray Smith * Created: Tue Oct 08 15:58:04 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "ocrrow.h" #include "blobbox.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif ELISTIZE (ROW) /********************************************************************** * ROW::ROW * * Constructor to build a ROW. Only the stats stuff are given here. * The words are added directly. **********************************************************************/ ROW::ROW ( //constructor inT32 spline_size, //no of segments inT32 * xstarts, //segment boundaries double *coeffs, //coefficients float x_height, //line height float ascenders, //ascender size float descenders, //descender drop inT16 kern, //char gap inT16 space //word gap ) : baseline(spline_size, xstarts, coeffs), para_(NULL) { kerning = kern; //just store stuff spacing = space; xheight = x_height; ascrise = ascenders; bodysize = 0.0f; descdrop = descenders; has_drop_cap_ = false; lmargin_ = 0; rmargin_ = 0; } /********************************************************************** * ROW::ROW * * Constructor to build a ROW. Only the stats stuff are given here. * The words are added directly. **********************************************************************/ ROW::ROW( //constructor TO_ROW *to_row, //source row inT16 kern, //char gap inT16 space //word gap ) : para_(NULL) { kerning = kern; //just store stuff spacing = space; xheight = to_row->xheight; bodysize = to_row->body_size; ascrise = to_row->ascrise; descdrop = to_row->descdrop; baseline = to_row->baseline; has_drop_cap_ = false; lmargin_ = 0; rmargin_ = 0; } /********************************************************************** * ROW::recalc_bounding_box * * Set the bounding box correctly **********************************************************************/ void ROW::recalc_bounding_box() { //recalculate BB WERD *word; //current word WERD_IT it = &words; //words of ROW inT16 left; //of word inT16 prev_left; //old left if (!it.empty ()) { word = it.data (); prev_left = word->bounding_box ().left (); it.forward (); while (!it.at_first ()) { word = it.data (); left = word->bounding_box ().left (); if (left < prev_left) { it.move_to_first (); //words in BB order it.sort (word_comparator); break; } prev_left = left; it.forward (); } } for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { word = it.data (); if (it.at_first ()) word->set_flag (W_BOL, TRUE); else //not start of line word->set_flag (W_BOL, FALSE); if (it.at_last ()) word->set_flag (W_EOL, TRUE); else //not end of line word->set_flag (W_EOL, FALSE); //extend BB as reqd bound_box += word->bounding_box (); } } /********************************************************************** * ROW::move * * Reposition row by vector **********************************************************************/ void ROW::move( // reposition row const ICOORD vec // by vector ) { WERD_IT it(&words); // word iterator for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) it.data ()->move (vec); bound_box.move (vec); baseline.move (vec); } /********************************************************************** * ROW::print * * Display members **********************************************************************/ void ROW::print( //print FILE *fp //file to print on ) { tprintf("Kerning= %d\n", kerning); tprintf("Spacing= %d\n", spacing); bound_box.print(); tprintf("Xheight= %f\n", xheight); tprintf("Ascrise= %f\n", ascrise); tprintf("Descdrop= %f\n", descdrop); tprintf("has_drop_cap= %d\n", has_drop_cap_); tprintf("lmargin= %d, rmargin= %d\n", lmargin_, rmargin_); } /********************************************************************** * ROW::plot * * Draw the ROW in the given colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED void ROW::plot( //draw it ScrollView* window, //window to draw in ScrollView::Color colour //colour to draw in ) { WERD *word; //current word WERD_IT it = &words; //words of ROW for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { word = it.data (); word->plot (window, colour); //all in one colour } } /********************************************************************** * ROW::plot * * Draw the ROW in rainbow colours. **********************************************************************/ void ROW::plot( //draw it ScrollView* window //window to draw in ) { WERD *word; //current word WERD_IT it = &words; //words of ROW for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { word = it.data (); word->plot (window); //in rainbow colours } } #endif // GRAPHICS_DISABLED /********************************************************************** * ROW::operator= * * Assign rows by duplicating the row structure but NOT the WERDLIST **********************************************************************/ ROW & ROW::operator= (const ROW & source) { this->ELIST_LINK::operator= (source); kerning = source.kerning; spacing = source.spacing; xheight = source.xheight; bodysize = source.bodysize; ascrise = source.ascrise; descdrop = source.descdrop; if (!words.empty ()) words.clear (); baseline = source.baseline; //QSPLINES must do = bound_box = source.bound_box; has_drop_cap_ = source.has_drop_cap_; lmargin_ = source.lmargin_; rmargin_ = source.rmargin_; para_ = source.para_; return *this; }
1080228-arabicocr11
ccstruct/ocrrow.cpp
C++
asf20
7,289
/********************************************************************** * File: stepblob.cpp (Formerly cblob.c) * Description: Code for C_BLOB class. * Author: Ray Smith * Created: Tue Oct 08 10:41:13 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "stepblob.h" #include "allheaders.h" // Include automatically generated configuration file if running autoconf. #ifdef HAVE_CONFIG_H #include "config_auto.h" #endif // Max perimeter to width ratio for a baseline position above box bottom. const double kMaxPerimeterWidthRatio = 8.0; ELISTIZE (C_BLOB) /********************************************************************** * position_outline * * Position the outline in the given list at the relevant place * according to its nesting. **********************************************************************/ static void position_outline( //put in place C_OUTLINE *outline, //thing to place C_OUTLINE_LIST *destlist //desstination list ) { C_OUTLINE *dest_outline; //outline from dest list C_OUTLINE_IT it = destlist; //iterator //iterator on children C_OUTLINE_IT child_it = outline->child (); if (!it.empty ()) { do { dest_outline = it.data (); //get destination //encloses dest if (*dest_outline < *outline) { //take off list dest_outline = it.extract (); //put this in place it.add_after_then_move (outline); //make it a child child_it.add_to_end (dest_outline); while (!it.at_last ()) { it.forward (); //do rest of list //check for other children dest_outline = it.data (); if (*dest_outline < *outline) { //take off list dest_outline = it.extract (); child_it.add_to_end (dest_outline); //make it a child if (it.empty ()) break; } } return; //finished } //enclosed by dest else if (*outline < *dest_outline) { position_outline (outline, dest_outline->child ()); //place in child list return; //finished } it.forward (); } while (!it.at_first ()); } it.add_to_end (outline); //at outer level } /********************************************************************** * plot_outline_list * * Draw a list of outlines in the given colour and their children * in the child colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED static void plot_outline_list( //draw outlines C_OUTLINE_LIST *list, //outline to draw ScrollView* window, //window to draw in ScrollView::Color colour, //colour to use ScrollView::Color child_colour //colour of children ) { C_OUTLINE *outline; //current outline C_OUTLINE_IT it = list; //iterator for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { outline = it.data (); //draw it outline->plot (window, colour); if (!outline->child ()->empty ()) plot_outline_list (outline->child (), window, child_colour, child_colour); } } // Draws the outlines in the given colour, and child_colour, normalized // using the given denorm, making use of sub-pixel accurate information // if available. static void plot_normed_outline_list(const DENORM& denorm, C_OUTLINE_LIST *list, ScrollView::Color colour, ScrollView::Color child_colour, ScrollView* window) { C_OUTLINE_IT it(list); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); outline->plot_normed(denorm, colour, window); if (!outline->child()->empty()) plot_normed_outline_list(denorm, outline->child(), child_colour, child_colour, window); } } #endif /********************************************************************** * reverse_outline_list * * Reverse a list of outlines and their children. **********************************************************************/ static void reverse_outline_list(C_OUTLINE_LIST *list) { C_OUTLINE_IT it = list; // iterator for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); outline->reverse(); // reverse it outline->set_flag(COUT_INVERSE, TRUE); if (!outline->child()->empty()) reverse_outline_list(outline->child()); } } /********************************************************************** * C_BLOB::C_BLOB * * Constructor to build a C_BLOB from a list of C_OUTLINEs. * The C_OUTLINEs are not copied so the source list is emptied. * The C_OUTLINEs are nested correctly in the blob. **********************************************************************/ C_BLOB::C_BLOB(C_OUTLINE_LIST *outline_list) { for (C_OUTLINE_IT ol_it(outline_list); !ol_it.empty(); ol_it.forward()) { C_OUTLINE* outline = ol_it.extract(); // Position this outline in appropriate position in the hierarchy. position_outline(outline, &outlines); } CheckInverseFlagAndDirection(); } // Simpler constructor to build a blob from a single outline that has // already been fully initialized. C_BLOB::C_BLOB(C_OUTLINE* outline) { C_OUTLINE_IT it(&outlines); it.add_to_end(outline); } // Builds a set of one or more blobs from a list of outlines. // Input: one outline on outline_list contains all the others, but the // nesting and order are undefined. // If good_blob is true, the blob is added to good_blobs_it, unless // an illegal (generation-skipping) parent-child relationship is found. // If so, the parent blob goes to bad_blobs_it, and the immediate children // are promoted to the top level, recursively being sent to good_blobs_it. // If good_blob is false, all created blobs will go to the bad_blobs_it. // Output: outline_list is empty. One or more blobs are added to // good_blobs_it and/or bad_blobs_it. void C_BLOB::ConstructBlobsFromOutlines(bool good_blob, C_OUTLINE_LIST* outline_list, C_BLOB_IT* good_blobs_it, C_BLOB_IT* bad_blobs_it) { // List of top-level outlines with correctly nested children. C_OUTLINE_LIST nested_outlines; for (C_OUTLINE_IT ol_it(outline_list); !ol_it.empty(); ol_it.forward()) { C_OUTLINE* outline = ol_it.extract(); // Position this outline in appropriate position in the hierarchy. position_outline(outline, &nested_outlines); } // Check for legal nesting and reassign as required. for (C_OUTLINE_IT ol_it(&nested_outlines); !ol_it.empty(); ol_it.forward()) { C_OUTLINE* outline = ol_it.extract(); bool blob_is_good = good_blob; if (!outline->IsLegallyNested()) { // The blob is illegally nested. // Mark it bad, and add all its children to the top-level list. blob_is_good = false; ol_it.add_list_after(outline->child()); } C_BLOB* blob = new C_BLOB(outline); // Set inverse flag and reverse if needed. blob->CheckInverseFlagAndDirection(); // Put on appropriate list. if (!blob_is_good && bad_blobs_it != NULL) bad_blobs_it->add_after_then_move(blob); else good_blobs_it->add_after_then_move(blob); } } // Sets the COUT_INVERSE flag appropriately on the outlines and their // children recursively, reversing the outlines if needed so that // everything has an anticlockwise top-level. void C_BLOB::CheckInverseFlagAndDirection() { C_OUTLINE_IT ol_it(&outlines); for (ol_it.mark_cycle_pt(); !ol_it.cycled_list(); ol_it.forward()) { C_OUTLINE* outline = ol_it.data(); if (outline->turn_direction() < 0) { outline->reverse(); reverse_outline_list(outline->child()); outline->set_flag(COUT_INVERSE, TRUE); } else { outline->set_flag(COUT_INVERSE, FALSE); } } } // Build and return a fake blob containing a single fake outline with no // steps. C_BLOB* C_BLOB::FakeBlob(const TBOX& box) { C_OUTLINE_LIST outlines; C_OUTLINE::FakeOutline(box, &outlines); return new C_BLOB(&outlines); } /********************************************************************** * C_BLOB::bounding_box * * Return the bounding box of the blob. **********************************************************************/ TBOX C_BLOB::bounding_box() const { // bounding box C_OUTLINE *outline; // current outline // This is a read-only iteration of the outlines. C_OUTLINE_IT it = const_cast<C_OUTLINE_LIST*>(&outlines); TBOX box; // bounding box for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { outline = it.data (); box += outline->bounding_box (); } return box; } /********************************************************************** * C_BLOB::area * * Return the area of the blob. **********************************************************************/ inT32 C_BLOB::area() { //area C_OUTLINE *outline; //current outline C_OUTLINE_IT it = &outlines; //outlines of blob inT32 total; //total area total = 0; for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { outline = it.data (); total += outline->area (); } return total; } /********************************************************************** * C_BLOB::perimeter * * Return the perimeter of the top and 2nd level outlines. **********************************************************************/ inT32 C_BLOB::perimeter() { C_OUTLINE *outline; // current outline C_OUTLINE_IT it = &outlines; // outlines of blob inT32 total; // total perimeter total = 0; for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { outline = it.data(); total += outline->perimeter(); } return total; } /********************************************************************** * C_BLOB::outer_area * * Return the area of the blob. **********************************************************************/ inT32 C_BLOB::outer_area() { //area C_OUTLINE *outline; //current outline C_OUTLINE_IT it = &outlines; //outlines of blob inT32 total; //total area total = 0; for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { outline = it.data (); total += outline->outer_area (); } return total; } /********************************************************************** * C_BLOB::count_transitions * * Return the total x and y maxes and mins in the blob. * Chlid outlines are not counted. **********************************************************************/ inT32 C_BLOB::count_transitions( //area inT32 threshold //on size ) { C_OUTLINE *outline; //current outline C_OUTLINE_IT it = &outlines; //outlines of blob inT32 total; //total area total = 0; for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) { outline = it.data (); total += outline->count_transitions (threshold); } return total; } /********************************************************************** * C_BLOB::move * * Move C_BLOB by vector **********************************************************************/ void C_BLOB::move( // reposition blob const ICOORD vec // by vector ) { C_OUTLINE_IT it(&outlines); // iterator for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) it.data ()->move (vec); // move each outline } // Static helper for C_BLOB::rotate to allow recursion of child outlines. void RotateOutlineList(const FCOORD& rotation, C_OUTLINE_LIST* outlines) { C_OUTLINE_LIST new_outlines; C_OUTLINE_IT src_it(outlines); C_OUTLINE_IT dest_it(&new_outlines); while (!src_it.empty()) { C_OUTLINE* old_outline = src_it.extract(); src_it.forward(); C_OUTLINE* new_outline = new C_OUTLINE(old_outline, rotation); if (!old_outline->child()->empty()) { RotateOutlineList(rotation, old_outline->child()); C_OUTLINE_IT child_it(new_outline->child()); child_it.add_list_after(old_outline->child()); } delete old_outline; dest_it.add_to_end(new_outline); } src_it.add_list_after(&new_outlines); } /********************************************************************** * C_BLOB::rotate * * Rotate C_BLOB by rotation. * Warning! has to rebuild all the C_OUTLINEs. **********************************************************************/ void C_BLOB::rotate(const FCOORD& rotation) { RotateOutlineList(rotation, &outlines); } // Helper calls ComputeEdgeOffsets or ComputeBinaryOffsets recursively on the // outline list and its children. static void ComputeEdgeOffsetsOutlineList(int threshold, Pix* pix, C_OUTLINE_LIST *list) { C_OUTLINE_IT it(list); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); if (pix != NULL && pixGetDepth(pix) == 8) outline->ComputeEdgeOffsets(threshold, pix); else outline->ComputeBinaryOffsets(); if (!outline->child()->empty()) ComputeEdgeOffsetsOutlineList(threshold, pix, outline->child()); } } // Adds sub-pixel resolution EdgeOffsets for the outlines using greyscale // if the supplied pix is 8-bit or the binary edges if NULL. void C_BLOB::ComputeEdgeOffsets(int threshold, Pix* pix) { ComputeEdgeOffsetsOutlineList(threshold, pix, &outlines); } // Estimates and returns the baseline position based on the shape of the // outlines. // We first find the minimum y-coord (y_mins) at each x-coord within the blob. // If there is a run of some y or y+1 in y_mins that is longer than the total // number of positions at bottom or bottom+1, subject to the additional // condition that at least one side of the y/y+1 run is higher than y+1, so it // is not a local minimum, then y, not the bottom, makes a good candidate // baseline position for this blob. Eg // | ---| // | | // |- -----------| <= Good candidate baseline position. // |- -| // | -| // |---| <= Bottom of blob inT16 C_BLOB::EstimateBaselinePosition() { TBOX box = bounding_box(); int left = box.left(); int width = box.width(); int bottom = box.bottom(); if (outlines.empty() || perimeter() > width * kMaxPerimeterWidthRatio) return bottom; // This is only for non-CJK blobs. // Get the minimum y coordinate at each x-coordinate. GenericVector<int> y_mins; y_mins.init_to_size(width + 1, box.top()); C_OUTLINE_IT it(&outlines); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); ICOORD pos = outline->start_pos(); for (int s = 0; s < outline->pathlength(); ++s) { if (pos.y() < y_mins[pos.x() - left]) y_mins[pos.x() - left] = pos.y(); pos += outline->step(s); } } // Find the total extent of the bottom or bottom + 1. int bottom_extent = 0; for (int x = 0; x <= width; ++x) { if (y_mins[x] == bottom || y_mins[x] == bottom + 1) ++bottom_extent; } // Find the lowest run longer than the bottom extent that is not the bottom. int best_min = box.top(); int prev_run = 0; int prev_y = box.top(); int prev_prev_y = box.top(); for (int x = 0; x < width; x += prev_run) { // Find the length of the current run. int y_at_x = y_mins[x]; int run = 1; while (x + run <= width && y_mins[x + run] == y_at_x) ++run; if (y_at_x > bottom + 1) { // Possible contender. int total_run = run; // Find extent of current value or +1 to the right of x. while (x + total_run <= width && (y_mins[x + total_run] == y_at_x || y_mins[x + total_run] == y_at_x + 1)) ++total_run; // At least one end has to be higher so it is not a local max. if (prev_prev_y > y_at_x + 1 || x + total_run > width || y_mins[x + total_run] > y_at_x + 1) { // If the prev_run is at y + 1, then we can add that too. There cannot // be a suitable run at y before that or we would have found it already. if (prev_run > 0 && prev_y == y_at_x + 1) total_run += prev_run; if (total_run > bottom_extent && y_at_x < best_min) { best_min = y_at_x; } } } prev_run = run; prev_prev_y = prev_y; prev_y = y_at_x; } return best_min == box.top() ? bottom : best_min; } static void render_outline_list(C_OUTLINE_LIST *list, int left, int top, Pix* pix) { C_OUTLINE_IT it(list); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); outline->render(left, top, pix); if (!outline->child()->empty()) render_outline_list(outline->child(), left, top, pix); } } static void render_outline_list_outline(C_OUTLINE_LIST *list, int left, int top, Pix* pix) { C_OUTLINE_IT it(list); for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { C_OUTLINE* outline = it.data(); outline->render_outline(left, top, pix); } } // Returns a Pix rendering of the blob. pixDestroy after use. Pix* C_BLOB::render() { TBOX box = bounding_box(); Pix* pix = pixCreate(box.width(), box.height(), 1); render_outline_list(&outlines, box.left(), box.top(), pix); return pix; } // Returns a Pix rendering of the outline of the blob. (no fill). // pixDestroy after use. Pix* C_BLOB::render_outline() { TBOX box = bounding_box(); Pix* pix = pixCreate(box.width(), box.height(), 1); render_outline_list_outline(&outlines, box.left(), box.top(), pix); return pix; } /********************************************************************** * C_BLOB::plot * * Draw the C_BLOB in the given colour. **********************************************************************/ #ifndef GRAPHICS_DISABLED void C_BLOB::plot(ScrollView* window, // window to draw in ScrollView::Color blob_colour, // main colour ScrollView::Color child_colour) { // for holes plot_outline_list(&outlines, window, blob_colour, child_colour); } // Draws the blob in the given colour, and child_colour, normalized // using the given denorm, making use of sub-pixel accurate information // if available. void C_BLOB::plot_normed(const DENORM& denorm, ScrollView::Color blob_colour, ScrollView::Color child_colour, ScrollView* window) { plot_normed_outline_list(denorm, &outlines, blob_colour, child_colour, window); } #endif
1080228-arabicocr11
ccstruct/stepblob.cpp
C++
asf20
20,168
/////////////////////////////////////////////////////////////////////// // File: ccstruct.cpp // Description: ccstruct class. // Author: Samuel Charron // // (C) Copyright 2006, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "ccstruct.h" namespace tesseract { // APPROXIMATIONS of the fractions of the character cell taken by // the descenders, ascenders, and x-height. const double CCStruct::kDescenderFraction = 0.25; const double CCStruct::kXHeightFraction = 0.5; const double CCStruct::kAscenderFraction = 0.25; const double CCStruct::kXHeightCapRatio = CCStruct::kXHeightFraction / (CCStruct::kXHeightFraction + CCStruct::kAscenderFraction); CCStruct::CCStruct() {} CCStruct::~CCStruct() { } }
1080228-arabicocr11
ccstruct/ccstruct.cpp
C++
asf20
1,316
/* -*-C-*- ******************************************************************************** * * File: split.c (Formerly split.c) * Description: * Author: Mark Seaman, OCR Technology * Created: Fri Oct 16 14:37:00 1987 * Modified: Fri May 17 16:27:49 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Reusable Software Component * * (c) Copyright 1987, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "split.h" #include "coutln.h" #include "tprintf.h" #ifdef __UNIX__ #include <assert.h> #endif /*---------------------------------------------------------------------- V a r i a b l e s ----------------------------------------------------------------------*/ BOOL_VAR(wordrec_display_splits, 0, "Display splits"); /*---------------------------------------------------------------------- F u n c t i o n s ----------------------------------------------------------------------*/ /********************************************************************** * delete_split * * Remove this split from existence. **********************************************************************/ void delete_split(SPLIT *split) { if (split) { delete split; } } /********************************************************************** * make_edgept * * Create an EDGEPT and hook it into an existing list of edge points. **********************************************************************/ EDGEPT *make_edgept(int x, int y, EDGEPT *next, EDGEPT *prev) { EDGEPT *this_edgept; /* Create point */ this_edgept = new EDGEPT; this_edgept->pos.x = x; this_edgept->pos.y = y; // Now deal with the src_outline steps. C_OUTLINE* prev_ol = prev->src_outline; if (prev_ol != NULL && prev->next == next) { // Compute the fraction of the segment that is being cut. FCOORD segment_vec(next->pos.x - prev->pos.x, next->pos.y - prev->pos.y); FCOORD target_vec(x - prev->pos.x, y - prev->pos.y); double cut_fraction = target_vec.length() / segment_vec.length(); // Get the start and end at the step level. ICOORD step_start = prev_ol->position_at_index(prev->start_step); int end_step = prev->start_step + prev->step_count; int step_length = prev_ol->pathlength(); ICOORD step_end = prev_ol->position_at_index(end_step % step_length); ICOORD step_vec = step_end - step_start; double target_length = step_vec.length() * cut_fraction; // Find the point on the segment that gives the length nearest to target. int best_step = prev->start_step; ICOORD total_step(0, 0); double best_dist = target_length; for (int s = prev->start_step; s < end_step; ++s) { total_step += prev_ol->step(s % step_length); double dist = fabs(target_length - total_step.length()); if (dist < best_dist) { best_dist = dist; best_step = s + 1; } } // The new point is an intermediate point. this_edgept->src_outline = prev_ol; this_edgept->step_count = end_step - best_step; this_edgept->start_step = best_step % step_length; prev->step_count = best_step - prev->start_step; } else { // The new point is poly only. this_edgept->src_outline = NULL; this_edgept->step_count = 0; this_edgept->start_step = 0; } /* Hook it up */ this_edgept->next = next; this_edgept->prev = prev; prev->next = this_edgept; next->prev = this_edgept; /* Set up vec entries */ this_edgept->vec.x = this_edgept->next->pos.x - x; this_edgept->vec.y = this_edgept->next->pos.y - y; this_edgept->prev->vec.x = x - this_edgept->prev->pos.x; this_edgept->prev->vec.y = y - this_edgept->prev->pos.y; return this_edgept; } /********************************************************************** * remove_edgept * * Remove a given EDGEPT from its list and delete it. **********************************************************************/ void remove_edgept(EDGEPT *point) { EDGEPT *prev = point->prev; EDGEPT *next = point->next; // Add point's steps onto prev's steps if they are from the same outline. if (prev->src_outline == point->src_outline && prev->src_outline != NULL) { prev->step_count += point->step_count; } prev->next = next; next->prev = prev; prev->vec.x = next->pos.x - prev->pos.x; prev->vec.y = next->pos.y - prev->pos.y; delete point; } /********************************************************************** * new_split * * Create a new split record and initialize it. Put it on the display * list. **********************************************************************/ SPLIT *new_split(EDGEPT *point1, EDGEPT *point2) { SPLIT *s = new SPLIT; s->point1 = point1; s->point2 = point2; return (s); } /********************************************************************** * print_split * * Print a list of splits. Show the coordinates of both points in * each split. **********************************************************************/ void print_split(SPLIT *split) { if (split) { tprintf("(%d,%d)--(%d,%d)", split->point1->pos.x, split->point1->pos.y, split->point2->pos.x, split->point2->pos.y); } } /********************************************************************** * split_outline * * Split between these two edge points. **********************************************************************/ void split_outline(EDGEPT *join_point1, EDGEPT *join_point2) { assert(join_point1 != join_point2); EDGEPT* temp2 = join_point2->next; EDGEPT* temp1 = join_point1->next; /* Create two new points */ EDGEPT* new_point1 = make_edgept(join_point1->pos.x, join_point1->pos.y, temp1, join_point2); EDGEPT* new_point2 = make_edgept(join_point2->pos.x, join_point2->pos.y, temp2, join_point1); // Join_point1 and 2 are now cross-over points, so they must have NULL // src_outlines and give their src_outline information their new // replacements. new_point1->src_outline = join_point1->src_outline; new_point1->start_step = join_point1->start_step; new_point1->step_count = join_point1->step_count; new_point2->src_outline = join_point2->src_outline; new_point2->start_step = join_point2->start_step; new_point2->step_count = join_point2->step_count; join_point1->src_outline = NULL; join_point1->start_step = 0; join_point1->step_count = 0; join_point2->src_outline = NULL; join_point2->start_step = 0; join_point2->step_count = 0; join_point1->MarkChop(); join_point2->MarkChop(); } /********************************************************************** * unsplit_outlines * * Remove the split that was put between these two points. **********************************************************************/ void unsplit_outlines(EDGEPT *p1, EDGEPT *p2) { EDGEPT *tmp1 = p1->next; EDGEPT *tmp2 = p2->next; assert (p1 != p2); tmp1->next->prev = p2; tmp2->next->prev = p1; // tmp2 is coincident with p1. p1 takes tmp2's place as tmp2 is deleted. p1->next = tmp2->next; p1->src_outline = tmp2->src_outline; p1->start_step = tmp2->start_step; p1->step_count = tmp2->step_count; // Likewise p2 takes tmp1's place. p2->next = tmp1->next; p2->src_outline = tmp1->src_outline; p2->start_step = tmp1->start_step; p2->step_count = tmp1->step_count; p1->UnmarkChop(); p2->UnmarkChop(); delete tmp1; delete tmp2; p1->vec.x = p1->next->pos.x - p1->pos.x; p1->vec.y = p1->next->pos.y - p1->pos.y; p2->vec.x = p2->next->pos.x - p2->pos.x; p2->vec.y = p2->next->pos.y - p2->pos.y; }
1080228-arabicocr11
ccstruct/split.cpp
C
asf20
8,457
/********************************************************************** * File: stepblob.h (Formerly cblob.h) * Description: Code for C_BLOB class. * Author: Ray Smith * Created: Tue Oct 08 10:41:13 BST 1991 * * (C) Copyright 1991, Hewlett-Packard Ltd. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #ifndef STEPBLOB_H #define STEPBLOB_H #include "coutln.h" #include "rect.h" class C_BLOB; struct Pix; ELISTIZEH(C_BLOB) class C_BLOB:public ELIST_LINK { public: C_BLOB() { } explicit C_BLOB(C_OUTLINE_LIST *outline_list); // Simpler constructor to build a blob from a single outline that has // already been fully initialized. explicit C_BLOB(C_OUTLINE* outline); // Builds a set of one or more blobs from a list of outlines. // Input: one outline on outline_list contains all the others, but the // nesting and order are undefined. // If good_blob is true, the blob is added to good_blobs_it, unless // an illegal (generation-skipping) parent-child relationship is found. // If so, the parent blob goes to bad_blobs_it, and the immediate children // are promoted to the top level, recursively being sent to good_blobs_it. // If good_blob is false, all created blobs will go to the bad_blobs_it. // Output: outline_list is empty. One or more blobs are added to // good_blobs_it and/or bad_blobs_it. static void ConstructBlobsFromOutlines(bool good_blob, C_OUTLINE_LIST* outline_list, C_BLOB_IT* good_blobs_it, C_BLOB_IT* bad_blobs_it); // Sets the COUT_INVERSE flag appropriately on the outlines and their // children recursively, reversing the outlines if needed so that // everything has an anticlockwise top-level. void CheckInverseFlagAndDirection(); // Build and return a fake blob containing a single fake outline with no // steps. static C_BLOB* FakeBlob(const TBOX& box); C_OUTLINE_LIST *out_list() { //get outline list return &outlines; } TBOX bounding_box() const; // compute bounding box inT32 area(); //compute area inT32 perimeter(); // Total perimeter of outlines and 1st level children. inT32 outer_area(); //compute area inT32 count_transitions( //count maxima inT32 threshold); //size threshold void move(const ICOORD vec); // repostion blob by vector void rotate(const FCOORD& rotation); // Rotate by given vector. // Adds sub-pixel resolution EdgeOffsets for the outlines using greyscale // if the supplied pix is 8-bit or the binary edges if NULL. void ComputeEdgeOffsets(int threshold, Pix* pix); // Estimates and returns the baseline position based on the shape of the // outlines. inT16 EstimateBaselinePosition(); // Returns a Pix rendering of the blob. pixDestroy after use. Pix* render(); // Returns a Pix rendering of the outline of the blob. (no fill). // pixDestroy after use. Pix* render_outline(); #ifndef GRAPHICS_DISABLED void plot( //draw one ScrollView* window, //window to draw in ScrollView::Color blob_colour, //for outer bits ScrollView::Color child_colour); //for holes // Draws the blob in the given colour, and child_colour, normalized // using the given denorm, making use of sub-pixel accurate information // if available. void plot_normed(const DENORM& denorm, ScrollView::Color blob_colour, ScrollView::Color child_colour, ScrollView* window); #endif // GRAPHICS_DISABLED C_BLOB& operator= (const C_BLOB & source) { if (!outlines.empty ()) outlines.clear(); outlines.deep_copy(&source.outlines, &C_OUTLINE::deep_copy); return *this; } static C_BLOB* deep_copy(const C_BLOB* src) { C_BLOB* blob = new C_BLOB; *blob = *src; return blob; } static int SortByXMiddle(const void *v1, const void *v2) { const C_BLOB* blob1 = *reinterpret_cast<const C_BLOB* const *>(v1); const C_BLOB* blob2 = *reinterpret_cast<const C_BLOB* const *>(v2); return blob1->bounding_box().x_middle() - blob2->bounding_box().x_middle(); } private: C_OUTLINE_LIST outlines; //master elements }; #endif
1080228-arabicocr11
ccstruct/stepblob.h
C++
asf20
5,118
/********************************************************************** * File: dppoint.cpp * Description: Simple generic dynamic programming class. * Author: Ray Smith * Created: Wed Mar 25 19:08:01 PDT 2009 * * (C) Copyright 2009, Google Inc. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * **********************************************************************/ #include "dppoint.h" #include "tprintf.h" namespace tesseract { // Solve the dynamic programming problem for the given array of points, with // the given size and cost function. // Steps backwards are limited to being between min_step and max_step // inclusive. // The return value is the tail of the best path. DPPoint* DPPoint::Solve(int min_step, int max_step, bool debug, CostFunc cost_func, int size, DPPoint* points) { if (size <= 0 || max_step < min_step || min_step >= size) return NULL; // Degenerate, but not necessarily an error. ASSERT_HOST(min_step > 0); // Infinite loop possible if this is not true. if (debug) tprintf("min = %d, max=%d\n", min_step, max_step); // Evaluate the total cost at each point. for (int i = 0; i < size; ++i) { for (int offset = min_step; offset <= max_step; ++offset) { DPPoint* prev = offset <= i ? points + i - offset : NULL; inT64 new_cost = (points[i].*cost_func)(prev); if (points[i].best_prev_ != NULL && offset > min_step * 2 && new_cost > points[i].total_cost_) break; // Find only the first minimum if going over twice the min. } points[i].total_cost_ += points[i].local_cost_; if (debug) { tprintf("At point %d, local cost=%d, total_cost=%d, steps=%d\n", i, points[i].local_cost_, points[i].total_cost_, points[i].total_steps_); } } // Now find the end of the best path and return it. int best_cost = points[size - 1].total_cost_; int best_end = size - 1; for (int end = best_end - 1; end >= size - min_step; --end) { int cost = points[end].total_cost_; if (cost < best_cost) { best_cost = cost; best_end = end; } } return points + best_end; } // A CostFunc that takes the variance of step into account in the cost. inT64 DPPoint::CostWithVariance(const DPPoint* prev) { if (prev == NULL || prev == this) { UpdateIfBetter(0, 1, NULL, 0, 0, 0); return 0; } int delta = this - prev; inT32 n = prev->n_ + 1; inT32 sig_x = prev->sig_x_ + delta; inT64 sig_xsq = prev->sig_xsq_ + delta * delta; inT64 cost = (sig_xsq - sig_x * sig_x / n) / n; cost += prev->total_cost_; UpdateIfBetter(cost, prev->total_steps_ + 1, prev, n, sig_x, sig_xsq); return cost; } // Update the other members if the cost is lower. void DPPoint::UpdateIfBetter(inT64 cost, inT32 steps, const DPPoint* prev, inT32 n, inT32 sig_x, inT64 sig_xsq) { if (cost < total_cost_) { total_cost_ = cost; total_steps_ = steps; best_prev_ = prev; n_ = n; sig_x_ = sig_x; sig_xsq_ = sig_xsq; } } } // namespace tesseract.
1080228-arabicocr11
ccstruct/dppoint.cpp
C++
asf20
3,603
/////////////////////////////////////////////////////////////////////// // File: otsuthr.h // Description: Simple Otsu thresholding for binarizing images. // Author: Ray Smith // Created: Fri Mar 07 12:14:01 PST 2008 // // (C) Copyright 2008, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #ifndef TESSERACT_CCMAIN_OTSUTHR_H__ #define TESSERACT_CCMAIN_OTSUTHR_H__ struct Pix; namespace tesseract { const int kHistogramSize = 256; // The size of a histogram of pixel values. // Computes the Otsu threshold(s) for the given image rectangle, making one // for each channel. Each channel is always one byte per pixel. // Returns an array of threshold values and an array of hi_values, such // that a pixel value >threshold[channel] is considered foreground if // hi_values[channel] is 0 or background if 1. A hi_value of -1 indicates // that there is no apparent foreground. At least one hi_value will not be -1. // Delete thresholds and hi_values with delete [] after use. // The return value is the number of channels in the input image, being // the size of the output thresholds and hi_values arrays. int OtsuThreshold(Pix* src_pix, int left, int top, int width, int height, int** thresholds, int** hi_values); // Computes the histogram for the given image rectangle, and the given // single channel. Each channel is always one byte per pixel. // Histogram is always a kHistogramSize(256) element array to count // occurrences of each pixel value. void HistogramRect(Pix* src_pix, int channel, int left, int top, int width, int height, int* histogram); // Computes the Otsu threshold(s) for the given histogram. // Also returns H = total count in histogram, and // omega0 = count of histogram below threshold. int OtsuStats(const int* histogram, int* H_out, int* omega0_out); } // namespace tesseract. #endif // TESSERACT_CCMAIN_OTSUTHR_H__
1080228-arabicocr11
ccstruct/otsuthr.h
C++
asf20
2,510
/////////////////////////////////////////////////////////////////////// // File: boxword.h // Description: Class to represent the bounding boxes of the output. // Author: Ray Smith // Created: Tue May 25 14:18:14 PDT 2010 // // (C) Copyright 2010, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////// #include "blobs.h" #include "boxword.h" #include "normalis.h" #include "ocrblock.h" #include "pageres.h" namespace tesseract { // Clip output boxes to input blob boxes for bounds that are within this // tolerance. Otherwise, the blob may be chopped and we have to just use // the word bounding box. const int kBoxClipTolerance = 2; BoxWord::BoxWord() : length_(0) { } BoxWord::BoxWord(const BoxWord& src) { CopyFrom(src); } BoxWord::~BoxWord() { } BoxWord& BoxWord::operator=(const BoxWord& src) { CopyFrom(src); return *this; } void BoxWord::CopyFrom(const BoxWord& src) { bbox_ = src.bbox_; length_ = src.length_; boxes_.clear(); boxes_.reserve(length_); for (int i = 0; i < length_; ++i) boxes_.push_back(src.boxes_[i]); } // Factory to build a BoxWord from a TWERD using the DENORMs on each blob to // switch back to original image coordinates. BoxWord* BoxWord::CopyFromNormalized(TWERD* tessword) { BoxWord* boxword = new BoxWord(); // Count the blobs. boxword->length_ = tessword->NumBlobs(); // Allocate memory. boxword->boxes_.reserve(boxword->length_); for (int b = 0; b < boxword->length_; ++b) { TBLOB* tblob = tessword->blobs[b]; TBOX blob_box; for (TESSLINE* outline = tblob->outlines; outline != NULL; outline = outline->next) { EDGEPT* edgept = outline->loop; // Iterate over the edges. do { if (!edgept->IsHidden() || !edgept->prev->IsHidden()) { ICOORD pos(edgept->pos.x, edgept->pos.y); TPOINT denormed; tblob->denorm().DenormTransform(NULL, edgept->pos, &denormed); pos.set_x(denormed.x); pos.set_y(denormed.y); TBOX pt_box(pos, pos); blob_box += pt_box; } edgept = edgept->next; } while (edgept != outline->loop); } boxword->boxes_.push_back(blob_box); } boxword->ComputeBoundingBox(); return boxword; } // Clean up the bounding boxes from the polygonal approximation by // expanding slightly, then clipping to the blobs from the original_word // that overlap. If not null, the block provides the inverse rotation. void BoxWord::ClipToOriginalWord(const BLOCK* block, WERD* original_word) { for (int i = 0; i < length_; ++i) { TBOX box = boxes_[i]; // Expand by a single pixel, as the poly approximation error is 1 pixel. box = TBOX(box.left() - 1, box.bottom() - 1, box.right() + 1, box.top() + 1); // Now find the original box that matches. TBOX original_box; C_BLOB_IT b_it(original_word->cblob_list()); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { TBOX blob_box = b_it.data()->bounding_box(); if (block != NULL) blob_box.rotate(block->re_rotation()); if (blob_box.major_overlap(box)) { original_box += blob_box; } } if (!original_box.null_box()) { if (NearlyEqual<int>(original_box.left(), box.left(), kBoxClipTolerance)) box.set_left(original_box.left()); if (NearlyEqual<int>(original_box.right(), box.right(), kBoxClipTolerance)) box.set_right(original_box.right()); if (NearlyEqual<int>(original_box.top(), box.top(), kBoxClipTolerance)) box.set_top(original_box.top()); if (NearlyEqual<int>(original_box.bottom(), box.bottom(), kBoxClipTolerance)) box.set_bottom(original_box.bottom()); } original_box = original_word->bounding_box(); if (block != NULL) original_box.rotate(block->re_rotation()); boxes_[i] = box.intersection(original_box); } ComputeBoundingBox(); } // Merges the boxes from start to end, not including end, and deletes // the boxes between start and end. void BoxWord::MergeBoxes(int start, int end) { start = ClipToRange(start, 0, length_); end = ClipToRange(end, 0, length_); if (end <= start + 1) return; for (int i = start + 1; i < end; ++i) { boxes_[start] += boxes_[i]; } int shrinkage = end - 1 - start; length_ -= shrinkage; for (int i = start + 1; i < length_; ++i) boxes_[i] = boxes_[i + shrinkage]; boxes_.truncate(length_); } // Inserts a new box before the given index. // Recomputes the bounding box. void BoxWord::InsertBox(int index, const TBOX& box) { if (index < length_) boxes_.insert(box, index); else boxes_.push_back(box); length_ = boxes_.size(); ComputeBoundingBox(); } // Changes the box at the given index to the new box. // Recomputes the bounding box. void BoxWord::ChangeBox(int index, const TBOX& box) { boxes_[index] = box; ComputeBoundingBox(); } // Deletes the box with the given index, and shuffles up the rest. // Recomputes the bounding box. void BoxWord::DeleteBox(int index) { ASSERT_HOST(0 <= index && index < length_); boxes_.remove(index); --length_; ComputeBoundingBox(); } // Deletes all the boxes stored in BoxWord. void BoxWord::DeleteAllBoxes() { length_ = 0; boxes_.clear(); bbox_ = TBOX(); } // Computes the bounding box of the word. void BoxWord::ComputeBoundingBox() { bbox_ = TBOX(); for (int i = 0; i < length_; ++i) bbox_ += boxes_[i]; } // This and other putatively are the same, so call the (permanent) callback // for each blob index where the bounding boxes match. // The callback is deleted on completion. void BoxWord::ProcessMatchedBlobs(const TWERD& other, TessCallback1<int>* cb) const { for (int i = 0; i < length_ && i < other.NumBlobs(); ++i) { TBOX blob_box = other.blobs[i]->bounding_box(); if (blob_box == boxes_[i]) cb->Run(i); } delete cb; } } // namespace tesseract.
1080228-arabicocr11
ccstruct/boxword.cpp
C++
asf20
6,563
/* -*-C-*- ******************************************************************************** * * File: matrix.c (Formerly matrix.c) * Description: Ratings matrix code. (Used by associator) * Author: Mark Seaman, OCR Technology * Created: Wed May 16 13:18:47 1990 * Modified: Wed Mar 20 09:44:47 1991 (Mark Seaman) marks@hpgrlt * Language: C * Package: N/A * Status: Experimental (Do Not Distribute) * * (c) Copyright 1990, Hewlett-Packard Company. ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. * *********************************************************************************/ /*---------------------------------------------------------------------- I n c l u d e s ----------------------------------------------------------------------*/ #include "matrix.h" #include "callcpp.h" #include "ratngs.h" #include "tprintf.h" #include "unicharset.h" // Returns true if there are any real classification results. bool MATRIX::Classified(int col, int row, int wildcard_id) const { if (get(col, row) == NOT_CLASSIFIED) return false; BLOB_CHOICE_IT b_it(get(col, row)); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { BLOB_CHOICE* choice = b_it.data(); if (choice->IsClassified()) return true; } return false; } // Expands the existing matrix in-place to make the band wider, without // losing any existing data. void MATRIX::IncreaseBandSize(int bandwidth) { ResizeWithCopy(dimension(), bandwidth); } // Returns a bigger MATRIX with a new column and row in the matrix in order // to split the blob at the given (ind,ind) diagonal location. // Entries are relocated to the new MATRIX using the transformation defined // by MATRIX_COORD::MapForSplit. // Transfers the pointer data to the new MATRIX and deletes *this. MATRIX* MATRIX::ConsumeAndMakeBigger(int ind) { int dim = dimension(); int band_width = bandwidth(); // Check to see if bandwidth needs expanding. for (int col = ind; col >= 0 && col > ind - band_width; --col) { if (array_[col * band_width + band_width - 1] != empty_) { ++band_width; break; } } MATRIX* result = new MATRIX(dim + 1, band_width); for (int col = 0; col < dim; ++col) { for (int row = col; row < dim && row < col + bandwidth(); ++row) { MATRIX_COORD coord(col, row); coord.MapForSplit(ind); BLOB_CHOICE_LIST* choices = get(col, row); if (choices != NULL) { // Correct matrix location on each choice. BLOB_CHOICE_IT bc_it(choices); for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) { BLOB_CHOICE* choice = bc_it.data(); choice->set_matrix_cell(coord.col, coord.row); } ASSERT_HOST(coord.Valid(*result)); result->put(coord.col, coord.row, choices); } } } delete this; return result; } // Makes and returns a deep copy of *this, including all the BLOB_CHOICEs // on the lists, but not any LanguageModelState that may be attached to the // BLOB_CHOICEs. MATRIX* MATRIX::DeepCopy() const { int dim = dimension(); int band_width = bandwidth(); MATRIX* result = new MATRIX(dim, band_width); for (int col = 0; col < dim; ++col) { for (int row = col; row < col + band_width; ++row) { BLOB_CHOICE_LIST* choices = get(col, row); if (choices != NULL) { BLOB_CHOICE_LIST* copy_choices = new BLOB_CHOICE_LIST; choices->deep_copy(copy_choices, &BLOB_CHOICE::deep_copy); result->put(col, row, copy_choices); } } } return result; } // Print the best guesses out of the match rating matrix. void MATRIX::print(const UNICHARSET &unicharset) const { tprintf("Ratings Matrix (top 3 choices)\n"); int dim = dimension(); int band_width = bandwidth(); int row, col; for (col = 0; col < dim; ++col) { for (row = col; row < dim && row < col + band_width; ++row) { BLOB_CHOICE_LIST *rating = this->get(col, row); if (rating == NOT_CLASSIFIED) continue; BLOB_CHOICE_IT b_it(rating); tprintf("col=%d row=%d ", col, row); for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { tprintf("%s rat=%g cert=%g " , unicharset.id_to_unichar(b_it.data()->unichar_id()), b_it.data()->rating(), b_it.data()->certainty()); } tprintf("\n"); } tprintf("\n"); } tprintf("\n"); for (col = 0; col < dim; ++col) tprintf("\t%d", col); tprintf("\n"); for (row = 0; row < dim; ++row) { for (col = 0; col <= row; ++col) { if (col == 0) tprintf("%d\t", row); if (row >= col + band_width) { tprintf(" \t"); continue; } BLOB_CHOICE_LIST *rating = this->get(col, row); if (rating != NOT_CLASSIFIED) { BLOB_CHOICE_IT b_it(rating); int counter = 0; for (b_it.mark_cycle_pt(); !b_it.cycled_list(); b_it.forward()) { tprintf("%s ", unicharset.id_to_unichar(b_it.data()->unichar_id())); ++counter; if (counter == 3) break; } tprintf("\t"); } else { tprintf(" \t"); } } tprintf("\n"); } }
1080228-arabicocr11
ccstruct/matrix.cpp
C
asf20
5,694