RU2718571C1 - Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries - Google Patents

Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries Download PDF

Info

Publication number
RU2718571C1
RU2718571C1 RU2019134234A RU2019134234A RU2718571C1 RU 2718571 C1 RU2718571 C1 RU 2718571C1 RU 2019134234 A RU2019134234 A RU 2019134234A RU 2019134234 A RU2019134234 A RU 2019134234A RU 2718571 C1 RU2718571 C1 RU 2718571C1
Authority
RU
Russia
Prior art keywords
brightness
length
threshold
pixel
image
Prior art date
Application number
RU2019134234A
Other languages
Russian (ru)
Inventor
Петр Валерьевич Минин
Дмитрий Геннадиевич Письменный
Original Assignee
Общество С Ограниченной Ответственностью "Конструкторское Бюро "Дорс" (Ооо "Кб "Дорс")
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Общество С Ограниченной Ответственностью "Конструкторское Бюро "Дорс" (Ооо "Кб "Дорс") filed Critical Общество С Ограниченной Ответственностью "Конструкторское Бюро "Дорс" (Ооо "Кб "Дорс")
Priority to RU2019134234A priority Critical patent/RU2718571C1/en
Application granted granted Critical
Publication of RU2718571C1 publication Critical patent/RU2718571C1/en

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06TIMAGE DATA PROCESSING OR GENERATION, IN GENERAL
    • G06T7/00Image analysis
    • G06T7/10Segmentation; Edge detection
    • G06T7/11Region-based segmentation
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06VIMAGE OR VIDEO RECOGNITION OR UNDERSTANDING
    • G06V30/00Character recognition; Recognising digital ink; Document-oriented image-based pattern recognition
    • G06V30/40Document-oriented image-based pattern recognition

Abstract

FIELD: data processing.SUBSTANCE: invention relates to a method of binarisation of images of symbols on banknotes and can be used during authentication. To a halftone image of a symbol in a portion of a banknote to be binarized, a pixel of which is characterized by a brightness level, applying a threshold procedure using a process of forming a two-level image having one of two possible brightness levels with a predetermined binarisation threshold, plotting a histogram of the boundaries of said image, for which an ordered set of increasing brightness values, which are possible in a halftone image, is set, and for all values of brightness in the specified set, starting from the value following the least, the value of the corresponding cell of the histogram of the length of boundaries is set as an increment of the length of boundaries of the two-level image. Length of boundaries of the two-level image is counted as the sum of the lengths of the segments, each of which is a boundary segment of two adjacent pixels with different brightness levels, adding a component to account for the length of those sides of the pixels, which are located on the edge of the image, analyzing said histogram of the length of boundaries to find the final threshold of binarisation, when using which the result of binarisation contains continuous lines contained in the gray-scale image of the banknote area.EFFECT: faster recognition of banknote symbols.7 cl, 6 dwg

Description

Изобретение относится к способу бинаризации изображений символов на банкнотах и может быть использовано при проверке подлинности. Банкнота представляет собой защищенный документ, содержащий как изобразительную, так и текстовую информацию. Текстовая информация состоит из символов, представляющих собой буквы, цифры и некоторые знаки, такие как прямые и наклонные черты. В данном описании мы не будем относить к текстовой информации те символы, которые художественным образом встроены в рисунок на банкноте и, таким образом, являются неотъемлемой частью изобразительной информации.The invention relates to a method for binarizing symbol images on banknotes and can be used in authentication. A banknote is a secure document containing both pictorial and textual information. Textual information consists of characters that are letters, numbers, and some characters, such as forward and backward lines. In this description, we will not refer to textual information those characters that are artistically embedded in the drawing on the banknote and, thus, are an integral part of the pictorial information.

Часть текстовой информации неизменно наносится на каждую банкноту определенного номинала и версии ее выпуска. К такой информации относятся, например, указание версии выпуска банкноты и места ее эмиссии, а также имя казначея национального банка. Кроме того, каждый экземпляр помечен уникальной строкой символов, которую принято называть серийным номером. Контроль неизменной текстовой информации важен для проверки подлинности банкнот. Однако, более важно обеспечить распознавание переменной текстовой информации. В современной технологии обработки банкнот необходимо вести учет движения индивидуальных экземпляров банкнот по цепочкам денежного оборота. Таким образом, для обработки банкнот необходимо оборудование, которое может распознавать символы на банкноте, находящиеся в серийном номере, а также в местах размещения неизменной текстовой информации. Распознавание символов на банкнотах представляет собой особую задачу, которая отличается от широко распространенных способов распознавания текстов, применяемых в офисной и библиотечной практике. Документы и печатные издания, за исключением небольшого числа особых видов документов (исторические документы, древняя литература), имеют высокое качество печати. Как правило, они напечатаны черным цветом на белом фоне, а загрязнения бумаги и повреждения красочного слоя практически отсутствуют. При сканировании таких документов получается контрастное и целостное изображение каждого символа. Разрешение сканирования, используемое для документов и печатных изданий, как правило, составляет 300 точек на дюйм или больше.Part of the textual information is invariably applied to each banknote of a certain denomination and version of its issue. Such information includes, for example, an indication of the version of the issue of the banknote and the place of its issue, as well as the name of the treasurer of the national bank. In addition, each instance is marked with a unique character string, which is usually called a serial number. Controlling unchanged textual information is important for banknote authentication. However, it is more important to provide recognition of variable textual information. In modern technology for processing banknotes, it is necessary to keep track of the movement of individual copies of banknotes along chains of money circulation. Thus, for the processing of banknotes, equipment is needed that can recognize the characters on the banknote located in the serial number, as well as in the locations of invariable text information. Character recognition on banknotes is a special task, which differs from the widely used text recognition methods used in office and library practice. Documents and print media, with the exception of a small number of special types of documents (historical documents, ancient literature), have high print quality. As a rule, they are printed in black on a white background, and paper pollution and damage to the paint layer are practically absent. When scanning such documents, a contrasting and complete image of each character is obtained. The scan resolution used for documents and prints is typically 300 dpi or more.

В отличие от документов и печатных изданий, банкноты постоянно находятся в обращении, что приводит к постепенному истиранию красочного слоя, запятныванию и общему загрязнению бумаги. В результате, контрастность и целостность изображения символа на банкнотах могут очень ощутимо снижаться. Ситуация также осложняется тем, что серийный номер или неизменный текст далеко не всегда печатается на белом участке банкноты. Во многих случаях, он наносится на ранее запечатанную область бумаги. Поэтому, даже на новых банкнотах, фон символа часто уже содержит дополнительное изображение, мешающее распознаванию.Unlike documents and print media, banknotes are constantly in circulation, which leads to the gradual abrasion of the paint layer, staining and general pollution of the paper. As a result, the contrast and image integrity of the symbol on banknotes can be very noticeably reduced. The situation is also complicated by the fact that the serial number or unchanged text is not always printed on the white section of the banknote. In many cases, it is applied to a previously sealed area of paper. Therefore, even on new banknotes, the background of the symbol often already contains an additional image that interferes with recognition.

Качество сканирования банкнот в машинах для обработки наличности значительно уступает качеству сканирования обычных документов, поскольку банкнота перемещается в машине на высокой скорости (до 10 километров в час). Это приводит к необходимости использовать невысокое разрешение сканирования, не превышающее 200 точек на дюйм.The quality of scanning banknotes in cash processing machines is significantly inferior to the quality of scanning conventional documents, since the banknote moves in the machine at high speed (up to 10 kilometers per hour). This leads to the need to use a low resolution scan, not exceeding 200 dpi.

За счет высокой скорости перемещения банкноты в машине, к быстродействию распознавания символов на банкноте предъявляются высокие требования. Обычно, допустимым является время распознавания строки серийного номера в пределах нескольких миллисекунд. Это время примерно сопоставимо с временем распознавания напечатанного слова той же длины в современных способах распознавания обычных документов, выполняемых на высокопроизводительных процессорах. Однако, применение высокопроизводительных процессоров в большинстве машин для обработки банкнот невозможно по экономическим причинам. Те же виды процессоров, которые экономически оправданы для применения в машинах для обработки банкнот, имеют в 10 и более раз низкую производительность, чем производительность процессора рабочей станции с архитектурой IBM PC. В связи с этим, вычислительная сложность распознавания символов на банкноте должна быть снижена в сравнении со способами распознавания, применяемыми для распознавания обычных документов.Due to the high speed of movement of the banknote in the machine, high demands are placed on the speed of character recognition on the banknote. Typically, it can take a few milliseconds to recognize a serial number string. This time is approximately comparable with the recognition time of a printed word of the same length in modern methods of recognition of ordinary documents, executed on high-performance processors. However, the use of high-performance processors in most banknote processing machines is not possible for economic reasons. The same types of processors that are economically viable for use in banknote processing machines have 10 or more times lower performance than the processor performance of a workstation with an IBM PC architecture. In this regard, the computational complexity of recognizing characters on a banknote should be reduced in comparison with the recognition methods used to recognize ordinary documents.

Способы распознавания символов на банкнотах можно условно разделить на те, в которых используется предварительная бинаризация полутонового изображения, и те, где алгоритм распознавания напрямую обращается к полутоновому изображению. Примером алгоритма распознавания, не требующего бинаризации, можно назвать метод сверточной нейронной сети, а также метод гистограммы градиентов. В способах с бинаризацией сначала отделяют пиксели, принадлежащие значимому объекту на изображении, от пикселей фона. Бинаризация представляет собой метод выделения значимого объекта в полутоновом изображении, такого, как символ, основываясь на яркости пикселей. Обычно, результат бинаризации представляется как изображение с двумя градациями яркости, где пиксели фона представляются белыми, а пиксели объекта имеют черный цвет. Алгоритм распознавания работает с бинаризованным изображением. К таким алгоритмам распознавания относятся, например, морфологические алгоритмы. Эти алгоритмы анализируют бинаризованное изображение символа на предмет наличия и расположения определенных формных элементов символа, таких, как прямые линии, дуги, перекрестья символа, а также элементов фона в виде «островов» и «полуостровов».Character recognition methods on banknotes can be divided into those that use pre-binarization of a grayscale image and those where the recognition algorithm directly refers to a grayscale image. An example of a recognition algorithm that does not require binarization is the convolutional neural network method, as well as the gradient histogram method. In binarization methods, pixels belonging to a significant object in the image are first separated from background pixels. Binarization is a method of highlighting a significant object in a grayscale image, such as a symbol, based on the brightness of the pixels. Usually, the result of binarization is presented as an image with two gradations of brightness, where the background pixels appear white and the object pixels are black. The recognition algorithm works with a binarized image. Such recognition algorithms include, for example, morphological algorithms. These algorithms analyze the binarized symbol image for the presence and location of certain formal symbol elements, such as straight lines, arcs, symbol crosses, as well as background elements in the form of “islands” and “peninsulas”.

Пиксели объекта часто называют пикселями переднего плана изображения. В рамках данного описания, в качестве объекта рассматривается символ, поэтому, пиксели переднего плана изображения называются пикселями, отнесенными к символу. Необходимо учитывать, что качество бинаризации может быть различным. При плохом качестве, к пикселям символа, в ходе бинаризации, могут ошибочно быть отнесены пиксели, которые, в действительности, не принадлежат символу и являются частью фона либо постороннего объекта на изображении. Аналогично, пиксели, которые, в действительности, относятся к символу, могут быть ошибочно отнесены к фону. Как показывает опыт, невозможно создать совершенно безошибочный способ бинаризации, поэтому указанные ошибки, так или иначе, всегда имеют место.The pixels of an object are often called the foreground pixels of the image. In the framework of this description, a symbol is considered as an object, therefore, the foreground pixels of an image are called pixels assigned to a symbol. Keep in mind that the quality of binarization can be different. If the quality is poor, the pixels of a symbol during binarization may mistakenly include pixels that, in reality, do not belong to the symbol and are part of the background or an extraneous object in the image. Similarly, pixels that actually refer to a character may be erroneously assigned to the background. As experience shows, it is impossible to create a completely error-free method of binarization, therefore, these errors, one way or another, always take place.

В целом, алгоритмы, работающие с бинаризованным изображением, требуют меньших вычислительных ресурсов и выполняются быстрее алгоритмов, которые напрямую обращаются к полутоновому изображению. Поэтому, бинаризацию часто используют в машинах для обработки банкнот. В то же время, бинаризация, сама по себе, требует дополнительных затрат процессорного времени. При неудачном выполнении, бинаризация может ухудшить качество изображения символа до такой степени, что его распознавание становится невозможным. В таких случаях, изображение символа состоит из отдельных разделенных сегментов с потерей определенных частей символа, либо же, наоборот, фрагменты фона соединяются с символом и нарушают структуру его составных частей. Еще один вид ошибки, вносимой при бинаризации, состоит в проявлении изолированных фрагментов фона в виде точек и линий, которые ошибочно воспринимаются алгоритмом распознавания как элементы символа.In general, binarized image algorithms require less computational resources and are faster than algorithms that directly access a grayscale image. Therefore, binarization is often used in banknote processing machines. At the same time, binarization, in itself, requires additional processor time. If it fails, binarization can degrade the image quality of the symbol to such an extent that its recognition becomes impossible. In such cases, the image of the symbol consists of separate divided segments with the loss of certain parts of the symbol, or, conversely, background fragments are connected to the symbol and violate the structure of its component parts. Another type of error introduced during binarization is the manifestation of isolated background fragments in the form of points and lines that are mistakenly recognized by the recognition algorithm as elements of a symbol.

Таким образом, способ бинаризации для применения в машинах для обработки банкнот должен обладать определенным набором свойств. Во-первых, он должен быстро выполняться, так чтобы позволить всему процессу распознавания уложиться в отведенное под него короткое время. Во-вторых, символ должен передаваться в бинаризованное изображение без потерь частей и разрывов линий. В-третьих, способ бинаризации должен надежно блокировать проявление пикселей фона в бинаризованном изображении в качестве пикселей символа, несмотря на то, что сам фон может быть высококонтрастным изображением, а яркость отдельных пикселей фона может вплотную приближаться к яркости пикселей символа.Thus, the binarization method for use in banknote processing machines must have a certain set of properties. Firstly, it must be executed quickly, so as to allow the entire recognition process to fit into the short time allotted for it. Secondly, the symbol must be transmitted to the binarized image without loss of parts and line breaks. Thirdly, the binarization method should reliably block the appearance of background pixels in the binarized image as pixel symbols, despite the fact that the background itself can be a high-contrast image, and the brightness of individual background pixels can come close to the brightness of the pixel pixels.

Полутоновый цифровой образ банкноты, получаемый в результате сканирования в машине для обработки банкнот, обладает некоторыми особенностями, которые несколько облегчают задачу бинаризации. При сканировании, засветка поверхности банкноты в машине для обработки банкнот является весьма равномерной, поэтому в цифровом образе не возникает совместного изменения яркости частей символа и частей фона, обуславливаемого неравномерностью засветки. При бинаризации изображения символа нет необходимости проводить компенсацию неравномерности засветки, которая создает существенные сложности в ходе решения родственных технических задач, таких, как распознавание номерных знаков автомобилей.The grayscale digital image of a banknote obtained by scanning in a banknote processing machine has some features that make the binarization task somewhat easier. When scanning, the illumination of the surface of the banknote in the banknote processing machine is very uniform, therefore, in the digital image, there is no joint change in the brightness of parts of the symbol and parts of the background, due to the uneven illumination. When binarizing a symbol image, there is no need to compensate for uneven illumination, which creates significant difficulties in solving related technical problems, such as recognition of license plates of cars.

Кроме того, за редчайшими исключениями, интервал яркостей пикселей фона на банкноте в окрестности символа не перекрывается с интервалом яркостей пикселей символа. В большинстве случаев, эти интервалы соприкасаются в разделяющей точке на шкале яркостей, по одну сторону которой находятся значения яркости пикселей символа, а по другую располагаются яркости пикселей фона. Это позволяет разделять пиксели фона и пиксели символа при помощи единого, так называемого глобального, порога бинаризации, который равняется яркости в указанной разделяющей точке. Все пиксели, яркость которых меньше яркости порога бинаризации, относят к символу, а остальные пиксели относят к фону. Возможность применения глобального порога бинаризации значительно ускоряет процесс бинаризации, поскольку порог должен быть вычислен только один раз и далее многократно применяется к пикселям участка цифрового образа банкноты, где расположен символ. В то же время, выбор порога бинаризации является ответственной задачей, от которой, главным образом, зависит качество бинаризации символов на банкноте.In addition, with rare exceptions, the interval of the brightness of the pixels on the banknote in the vicinity of the symbol does not overlap with the interval of the brightness of the pixels of the symbol. In most cases, these intervals are in contact at a separating point on the brightness scale, on one side of which are the pixel pixel brightness values, and on the other are the background pixel brightness. This allows you to separate the background pixels and the pixels of the symbol using a single, so-called global, binarization threshold, which is equal to the brightness at the specified dividing point. All pixels whose brightness is less than the brightness of the binarization threshold are assigned to the symbol, and the remaining pixels are assigned to the background. The possibility of using the global binarization threshold significantly accelerates the binarization process, since the threshold must be calculated only once and then repeatedly applied to the pixels of the digital image of the banknote where the symbol is located. At the same time, the choice of the binarization threshold is a crucial task, on which, mainly, the quality of binarization of symbols on the banknote depends.

Для минимизации вычислительных затрат, бинаризацию и распознавание проводят для заранее известного участка цифрового образа банкноты, на котором находится требуемый символ или группа символов. Как правило, перед распознаванием символов, цифровой образ анализируется для определения валюты, номинала, версии выпуска банкноты и ее ориентации при прохождении через машину для обработки банкнот. Способы, применяемые на практике для подобного анализа, хорошо известны специалистам. По результатам этого анализа, на основе известного изобразительного дизайна банкноты, можно с высокой точностью выделить участок цифрового образа для распознавания символа или символов.To minimize computational costs, binarization and recognition is carried out for a previously known portion of the digital image of the banknote, on which the desired symbol or group of symbols is located. As a rule, before character recognition, the digital image is analyzed to determine the currency, face value, version of the banknote issue and its orientation when passing through the banknote processing machine. The methods used in practice for such an analysis are well known in the art. According to the results of this analysis, based on the well-known graphic design of a banknote, it is possible to select a portion of a digital image for recognition of a symbol or symbols with high accuracy.

Печатные символы на банкноте, как правило, обладают высокой оптической плотностью красочного слоя и четкими границами. За счет местной нестабильности краскопередачи в печатном процессе, оптическая плотность в пределах символа изменяется, как правило, на небольшую величину, не превышающую нескольких процентов. Кроме того, по мере износа банкноты, оптическая плотность красочного слоя становится различной в различных точках символа. Указанные различия передаются в цифровой образ банкноты в виде неизбежного разброса яркости пикселей, относящихся к символу.Printed characters on a banknote, as a rule, have a high optical density of the ink layer and clear boundaries. Due to the local instability of the ink transfer in the printing process, the optical density within the symbol changes, as a rule, by a small amount, not exceeding several percent. In addition, as the banknote wears out, the optical density of the ink layer becomes different at different points of the symbol. These differences are transmitted in a digital image of a banknote in the form of an inevitable spread of brightness of pixels related to a symbol.

Фон, на котором напечатан символ, может быть незапечатанной поверхностью бумаги либо печатным рисунком. Для банкнот на полимерной основе фон часто выполняют в виде сплошной запечатки белой краской. Яркость пикселей фона в цифровом образе непостоянна, даже в том случае, когда в фоне отсутствует печатный рисунок. Локальная отражающая способность поверхности бумаги непостоянна и определяется ее волокнистой структурой. Сплошная запечатка белой краской также дает неравномерность яркости из-за локальной неравномерности толщины красочного слоя. Дополнительный вклад в неоднородность яркости как печатного символа, так и фона, вносят шумы фотоприемного датчика и электронной аппаратуры, используемой для регистрации цифрового образа.The background on which the symbol is printed may be an unprinted surface of the paper or a printed pattern. For polymer-based banknotes, the background is often made as a solid seal with white paint. The brightness of the background pixels in a digital image is inconsistent, even if there is no printed pattern in the background. The local reflectivity of the paper surface is inconsistent and is determined by its fibrous structure. Continuous white paint also produces uneven brightness due to local unevenness in the thickness of the ink layer. An additional contribution to the brightness inhomogeneity of both the printed symbol and the background is made by the noise of the photodetector and electronic equipment used to register the digital image.

За счет размытия в оптической системе фотоприемного датчика, применяемого для получения цифрового образа, на цифровом образе банкноты образуется полоса неопределенности, окружающая линии каждого символа. Пиксели в полосе неопределенности имеют яркость, которая складывается из яркости пограничной части символа и яркости фона. Важно, что вклад каждой из этих яркостей зависит от массы случайных факторов, таких, как смещение поверхности банкноты из точки наилучшей фокусировки оптической системы фотоприемного датчика, а также расстояние между границей пикселя и ближайшей к нему границей символа. Поэтому, для пикселей в полосе неопределенности, соотношение между вкладами яркости символа и яркости фона не может быть достоверно определено. Это создает трудно разрешаемую задачу отнесения каждого пикселя в зоне неопределенности к пикселям символа или к пикселям фона.Due to the blur in the optical system of the photodetector sensor used to obtain the digital image, an uncertainty band is formed on the digital image of the banknote surrounding the lines of each symbol. The pixels in the uncertainty band have a brightness that is the sum of the brightness of the border of the symbol and the brightness of the background. It is important that the contribution of each of these brightnesses depends on a mass of random factors, such as the displacement of the surface of the banknote from the point of best focus of the optical system of the photodetector, as well as the distance between the pixel border and the nearest symbol border. Therefore, for pixels in the uncertainty band, the ratio between the contributions of the symbol brightness and the background brightness cannot be reliably determined. This creates a difficult problem to assign each pixel in the uncertainty zone to the pixels of the symbol or to the pixels of the background.

Рассмотрим, как поэтапно изменяется бинаризованное изображение при последовательном увеличении глобального порога бинаризации. На первом этапе, при очень низком значении глобального порога, яркость практически всех пикселей в цифровом образе оказывается выше значения порога. В результате, бинаризованное изображение состоит почти исключительно из белых пикселей. По мере роста порога, он оказывается выше наиболее темных пикселей символа. На этом, втором этапе, в бинаризованном изображении начинают проявляться разрозненные черные пиксели, относящиеся к символу. В ходе дальнейшего увеличения порога, на третьем этапе, разрозненные черные пиксели объединяются в кластеры, которые представляют собой части символа, разделенные разрывами, состоящими из белых пикселей. Далее, эти разрывы сокращаются, и при определенном значении порога, которое мы будем называть минимально допустимым, разрывы исчезают практически полностью. Как на втором, так и на третьем этапе не происходит одномоментного проявления символа в бинаризованном изображении, так как пиксели символа имеют различные уровни яркости и начинают передаваться в бинаризованное изображение при различных значениях порога.Let us consider how the binarized image changes in stages with a sequential increase in the global binarization threshold. At the first stage, at a very low value of the global threshold, the brightness of almost all the pixels in the digital image is higher than the threshold value. As a result, the binarized image consists almost exclusively of white pixels. As the threshold grows, it is higher than the darkest pixels of the symbol. In this second stage, scattered black pixels related to the symbol begin to appear in the binarized image. During a further increase in the threshold, in the third stage, disparate black pixels are combined into clusters, which are parts of a symbol separated by gaps consisting of white pixels. Further, these gaps are reduced, and at a certain threshold value, which we will call the minimum acceptable, the gaps disappear almost completely. Both in the second and in the third stage, the symbol does not appear simultaneously in the binarized image, since the pixels of the symbol have different brightness levels and begin to be transmitted to the binarized image at different threshold values.

В момент практически полного исчезновения разрывов, при так называемом минимально допустимом значении порога, символ в бинаризованном изображении состоит из непрерывных линий, соответствующих линиям исходного символа на банкноте. Возможные случайные единичные разрывы не нарушают возможности распознавания символов. Начертание символа в бинаризованном изображении, в целом, соответствует исходному, но толщина линий оказывается существенно меньше.At the moment of almost complete disappearance of gaps, with the so-called minimum acceptable threshold value, the symbol in the binarized image consists of continuous lines corresponding to the lines of the original symbol on the banknote. Possible random single gaps do not violate character recognition capabilities. The outline of the symbol in the binarized image, in general, corresponds to the original, but the thickness of the lines is significantly less.

В ходе четвертого этапа, последующее увеличение порога ведет к тому, что пиксели в полосе неопределенности постепенно переходят из фона в символ, что сопровождается ростом толщины линий с сохранением начертания. Имеется значение порога, которое мы будем называть наилучшим, при котором средняя толщина линий символа в бинаризованном изображении равна средней толщине линий исходного символа. При увеличении порога сверх наилучшего продолжается увеличение толщины линий с сохранением начертания. Существует максимально допустимое значение порога, при котором начертание символа еще сохраняется, несмотря на то, что толщина линий символа в бинаризованном изображении превосходит толщину линий исходного символа. На пятом этапе, при увеличении порога сверх максимально допустимого, некоторые пиксели фона в цифровом образе оказываются ниже порога и проявляются в бинаризованном изображении как черные пиксели. В результате, нарушается начертание символа и возникают шумовые кластеры черных пикселей в местах пробелов. На шестом этапе, при очень больших значениях порога шумовые кластеры сливаются с линиями символа. На седьмом этапе шумовые кластеры и линии символа сливаются друг с другом, образуя сплошное черное заполнение бинаризованного изображения с белыми включениями. На восьмом этапе, при наибольшем значении порога, белые включения исчезают, и все бинаризованное изображение состоит из черных пикселей. На этапах с пятого по седьмой не происходит одномоментного перехода всех пикселей фона в пиксели символа, поскольку пиксели фона, даже при отсутствии рисунка фона, имеют различные уровни яркости и переходят в пиксели символа в бинаризованном изображении при различных значениях порога.During the fourth stage, a subsequent increase in the threshold leads to the fact that the pixels in the uncertainty band gradually change from the background to the symbol, which is accompanied by an increase in the thickness of the lines while maintaining the style. There is a threshold value, which we will call best, at which the average thickness of the lines of the symbol in the binarized image is equal to the average thickness of the lines of the original symbol. With an increase in the threshold in excess of the best, an increase in the thickness of the lines continues, while maintaining the style. There is a maximum threshold value at which the character design is still preserved, despite the fact that the thickness of the symbol lines in the binarized image exceeds the thickness of the lines of the original symbol. At the fifth stage, when the threshold is increased above the maximum allowed, some background pixels in the digital image appear below the threshold and appear in the binarized image as black pixels. As a result, the style of the character is broken and noise clusters of black pixels appear in the spaces. At the sixth stage, at very large threshold values, the noise clusters merge with the symbol lines. At the seventh stage, noise clusters and symbol lines merge with each other, forming a solid black filling of the binarized image with white inclusions. At the eighth stage, at the highest threshold value, white inclusions disappear, and the entire binarized image consists of black pixels. At the fifth through seventh stages, all background pixels do not simultaneously transition to symbol pixels, since background pixels, even in the absence of a background image, have different brightness levels and turn into symbol pixels in a binarized image at different threshold values.

Для специалиста очевидно, что для гарантированного распознавания символа, в ходе бинаризации требуется сохранить его начертание. Это возможно, когда порог бинаризации находится между минимально допустимым и максимально допустимым значениями, что соответствует четвертому этапу увеличения порога.It is obvious to a specialist that for guaranteed character recognition, during the binarization it is required to preserve its mark. This is possible when the binarization threshold is between the minimum allowable and maximum allowable values, which corresponds to the fourth stage of increasing the threshold.

Чтобы получить наилучшие условия распознавания символа нужно, чтобы порог бинаризации был равен наилучшему значению. Тогда, в бинаризованном изображении черные пиксели наиболее точно отражают изображение исходного символа на банкноте, с сохранением всех формных элементов символа и толщины его линий. Если выбран порог между минимально допустимым и наилучшим значениями, то пиксели в полосе неопределенности, которые фактически относятся к символу, могут быть ошибочно отнесены к фону. Если выбран порог между наилучшим и максимально допустимым значениями, то, наоборот, пиксели в полосе неопределенности, относящиеся к фону, могут быть ошибочно отнесены к символу. Неправильный выбор порога приводит к утонению или, наоборот, к утолщению линий символа, а также к искажению мелких формных элементов, таких, как засечки на концах линий. В некоторых шрифтах, линии очень близко подходят друг к другу, образуя узкий зазор. Вблизи максимально допустимого порога, за счет избыточного увеличения толщины линий, линии могут сомкнуться, так что зазор может исчезнуть. Перечисленные искажения создают сложности для работы алгоритма распознавания, использующего бинаризованное изображение.In order to obtain the best conditions for character recognition, it is necessary that the binarization threshold is equal to the best value. Then, in the binarized image, black pixels most accurately reflect the image of the original symbol on the banknote, while preserving all the form elements of the symbol and the thickness of its lines. If the threshold between the minimum acceptable and the best values is selected, then the pixels in the uncertainty band that actually refer to the symbol may be mistakenly assigned to the background. If the threshold between the best and the maximum allowable values is selected, then, on the contrary, the pixels in the uncertainty band related to the background may be erroneously assigned to a symbol. Wrong choice of the threshold leads to thinning or, conversely, to thickening of the lines of the symbol, as well as to distortion of small shaped elements, such as serifs at the ends of the lines. In some fonts, the lines come very close to each other, forming a narrow gap. Near the maximum allowable threshold, due to an excess increase in the thickness of the lines, the lines can close, so that the gap can disappear. The listed distortions create difficulties for the recognition algorithm using a binarized image.

Таким образом, выбор глобального порога является ответственной задачей. Можно говорить о грубом выборе порога, когда обеспечивается его значение в интервале между минимально допустимым и максимально допустимым. Однако, для наилучшего качества распознавания символа, требуется точный выбор порога, когда порог получает значение, близкое к наилучшему.Thus, the choice of a global threshold is a crucial task. We can talk about a rough choice of a threshold when its value is ensured in the interval between the minimum allowable and the maximum allowable. However, for the best character recognition quality, accurate threshold selection is required when the threshold receives a value close to the best.

Широко известным способом выбора глобального порога бинаризации является так называемый метод Отсу (в литературе также встречается написание Otsu или Отцу). В этом методе, глобальный порог определяется исключительно на основе анализа гистограммы яркостей изображения. Метод Отсу основан на предположении, что гистограмма яркости представляет собой бимодальное статистическое распределение, в котором одна мода относится к символу, а другая мода относится к фону. В таком предположении, оптимальный порог бинаризации должен располагаться на границе этих мод. В статистических терминах, метод Отсу разделяет гистограмму яркости изображения значением глобального порога на две части, называемые классами, таким образом, что межклассовая дисперсия оказывается максимальной. Метод Отсу использует перебор всех значений яркости в гистограмме и, в исходной реализации, требует существенных затрат процессорного времени. Однако, для него известны усовершенствования, которые используют рекуррентные формулы и уменьшают общее количество вычислений. Поэтому, общепринятая реализация метода Отсу обладает умеренной вычислительной сложностью.A well-known way of choosing a global binarization threshold is the so-called Otsu method (Otsu or Father is also written in the literature). In this method, the global threshold is determined solely on the basis of the analysis of the histogram of image brightness. The Otsu method is based on the assumption that the luminance histogram is a bimodal statistical distribution in which one mode refers to a symbol and another mode refers to a background. Under this assumption, the optimal binarization threshold should be located at the boundary of these modes. In statistical terms, the Otsu method divides the image brightness histogram by the global threshold value into two parts, called classes, so that interclass dispersion is maximal. The Otsu method uses enumeration of all brightness values in a histogram and, in the initial implementation, requires significant processor time. However, improvements are known for him that use recurrence formulas and reduce the total number of calculations. Therefore, the generally accepted implementation of the Otsu method has moderate computational complexity.

В применении к символам на банкнотах, метод Отсу успешно обеспечивает грубый выбор порога, если фон символа является светлым и равномерным либо слабоконтрастным. В таких случаях, гистограмма полутонового участка цифрового образа, подлежащего распознаванию, имеет явный бимодальный характер. Поэтому, глобальный порог бинаризации, находимый по методу Отсу, устойчиво разделяет интервалы яркостей пикселей, относящихся к символу и относящихся к фону. Однако, когда фон является высококонтрастным изображением, бимодальный характер гистограммы нарушается. Для такой гистограммы, метод Отсу очень часто находит неверный порог бинаризации, который лежит вне интервала между наименьшим и наибольшим допустимыми значениями. Часто гистограмма оказывается многомодальной, с числом мод более двух. В случае многомодальной гистограммы, фону может соответствовать две или большее количество мод гистограммы. В этом случае, найденный порог зачастую разделяет пиксели символа и часть пикселей фона от другой части пикселей фона вблизи точки, где моды фона граничат друг с другом. Это приводит к слиянию символа с частью пикселей фона.As applied to symbols on banknotes, the Otsu method successfully provides a rough choice of the threshold if the background of the symbol is bright and uniform or low contrast. In such cases, the histogram of the grayscale portion of the digital image to be recognized has an explicit bimodal character. Therefore, the global binarization threshold, found by the Otsu method, stably divides the intervals of brightness of pixels related to the symbol and related to the background. However, when the background is a high-contrast image, the bimodal nature of the histogram is violated. For such a histogram, the Otsu method very often finds an incorrect binarization threshold that lies outside the interval between the smallest and largest acceptable values. Often, the histogram is multimodal, with more than two modes. In the case of a multimodal histogram, the background may correspond to two or more modes of the histogram. In this case, the found threshold often separates the pixels of the symbol and part of the background pixels from another part of the background pixels near the point where the background modes border each other. This merges the character with part of the background pixels.

В более сложном случае гистограмма имеет одну моду, где реальная разделяющая точка, отделяющая интервалы яркостей символа и фона, находится в пределах одной моды. Как правило, это происходит, если статистические плотности распределения как пикселей символа, так и пикселей фона в гистограмме вблизи разделяющей точки оказываются достаточно высокими. Кроме того, возможен случай, когда гистограмма, за счет бимодального распределения яркости пикселей фона, также является бимодальной, но разделяющая точка находится в пределах одной моды. Для такого распределения, метод Отсу не всегда гарантирует даже грубый выбор порога.In a more complex case, the histogram has one mode, where the real dividing point, separating the intervals of the brightness of the symbol and background, is within the same mode. As a rule, this happens if the statistical distribution densities of both the symbol pixels and the background pixels in the histogram near the dividing point turn out to be quite high. In addition, it is possible that the histogram, due to the bimodal distribution of the brightness of the background pixels, is also bimodal, but the dividing point is within the same mode. For such a distribution, the Otsu method does not always guarantee even a rough choice of the threshold.

Известен патент US 5956421 (опубл. 21.09.1999, МПК G06K 9/38), далее называемый в этом описании методом Танаки. В методе Танаки, для нахождения глобального порога, как и в методе Отсу, используются только данные гистограммы яркости. Для поиска порога используется процесс последовательного приближения, на каждом шаге которого вычисляют новое положение рабочего отрезка уровней гистограммы. Первоначально, рабочий отрезок охватывает всю гистограмму. На первом шаге, вычисляют математическое ожидание и параметр асимметрии распределения на этом отрезке. Параметр асимметрии представляет собой отношение третьего и второго центральных статистических моментов. Если параметр асимметрии отрицателен, то верхний конец отрезка устанавливают в ранее вычисленную точку математического ожидания. Если параметр асимметрии положителен, то нижний конец отрезка устанавливают в ранее вычисленную точку математического ожидания. Далее, шаг повторяют. На каждом шаге, происходит уменьшение длины отрезка. Процесс останавливают, как только модуль параметра асимметрии становится меньше единицы. Математическое ожидание, полученное на последнем отрезке, используют в качестве глобального порога бинаризации. В случае близкого уровня яркости символа и фона, а, также, при контрастном фоне, метод Танаки находит значительно лучшее положение разделяющей точки, чем метод Отсу. Он гарантирует грубое определение порога практически при любом фоне. Однако, метод Танаки обладает высокой вычислительной сложностью, так как на каждом шаге приходится вычислять, по всем уровням на рабочем отрезке, не только математическое ожидание, но также суммы квадратов и кубов отклонения от этого математического ожидания. В известном патенте описывается аппаратный ускоритель для реализации метода Танаки, призванный обеспечить приемлемое быстродействие.Known patent US 5956421 (publ. 09/21/1999, IPC G06K 9/38), hereinafter referred to in this description as the Tanaki method. In the Tanaki method, only the brightness histogram data is used to find the global threshold, as in the Otsu method. To search for a threshold, a sequential approximation process is used, at each step of which a new position of the working segment of the histogram levels is calculated. Initially, the working segment covers the entire histogram. At the first step, the mathematical expectation and the asymmetry parameter of the distribution on this segment are calculated. The asymmetry parameter is the ratio of the third and second central statistical moments. If the asymmetry parameter is negative, then the upper end of the segment is set to the previously calculated point of mathematical expectation. If the asymmetry parameter is positive, then the lower end of the segment is set to the previously calculated point of mathematical expectation. Next, the step is repeated. At each step, there is a decrease in the length of the segment. The process is stopped as soon as the module of the asymmetry parameter becomes less than unity. The mathematical expectation obtained in the last segment is used as the global binarization threshold. In the case of a close brightness level of the symbol and background, and also with a contrasting background, the Tanaki method finds a significantly better position of the dividing point than the Otsu method. It guarantees a rough determination of the threshold in almost any background. However, the Tanaki method has high computational complexity, since at each step it is necessary to calculate, at all levels on the working interval, not only the mathematical expectation, but also the sum of the squares and cubes of the deviation from this mathematical expectation. A well-known patent describes a hardware accelerator for implementing the Tanaki method, designed to provide acceptable performance.

К сожалению, ни метод Отсу, ни метод Танаки не позволяют провести точное определение глобального порога. В целом, эта проблема характерна для тех способов, где, в качестве данных для нахождения глобального порога, используется исключительно гистограмма яркости. Поскольку для пикселей в полосе неопределенности соотношение между вкладами яркости символа и яркости фона не известно достоверно, то отсутствует возможность выработать критерий, по которому можно разделить в гистограмме яркости те уровни, которые в этой полосе относятся к пикселям фона и пикселям символа. Различия в яркости соседних участков фона создают дополнительные сложности в разделении полосы неопределенности. Чаще всего, указанная проблема приводит к неконтролируемому изменению толщины линий символа в бинаризованном изображении в зависимости от яркости и контрастности фона и состояния сканирующего механизма в конкретный момент сканирования, а также иных случайных факторов.Unfortunately, neither the Otsu method nor the Tanaki method allow an accurate determination of the global threshold. In general, this problem is characteristic of those methods where, exclusively, a luminance histogram is used as data for finding the global threshold. Since for the pixels in the uncertainty band the relation between the contributions of the symbol brightness and the background brightness is not known reliably, it is not possible to develop a criterion by which to divide the levels in the histogram that correspond to background pixels and symbol pixels. Differences in the brightness of neighboring background regions create additional difficulties in dividing the uncertainty band. Most often, this problem leads to an uncontrolled change in the thickness of the symbol lines in the binarized image depending on the brightness and contrast of the background and the state of the scanning mechanism at a particular moment of scanning, as well as other random factors.

Таким образом, использование одной только гистограммы яркости участка цифрового изображения не позволяет надежно находить наилучшее значение глобального порога бинаризации для многих случаев практического применения.Thus, the use of only a histogram of the brightness of a portion of a digital image does not make it possible to reliably find the best value of the global binarization threshold for many practical applications.

В научной литературе известны так называемые адаптивные методы бинаризации, в которых вместо использования глобального порога применяется индивидуальное значение порога, отдельно вычисляемое для каждого пикселя. В качестве примеров можно назвать адаптивный метод Отсу, методы Брэдли, Ниблэка, а также Сауволы. В целом, адаптивный метод анализирует окрестность для каждого пиксела, и по значениям яркости пикселей в этой окрестности определяет требуемый индивидуальный порог. В адаптивном методе Отсу строится гистограмма яркости в заданной окрестности пикселя, и по ней, аналогично обычному методу Отсу, определяется разделяющая точка. Эта разделяющая точка используется в качестве индивидуального порога для пикселя. В методе Брэдли вычисляется средний уровень яркости в пределах окрестности пикселя, и далее этот средний уровень домножается на некоторый настроечный коэффициент. Значение настроечного коэффициента выбирается несколько меньшим единицы. В результате домножения, получают индивидуальный порог для пикселя. В методе Ниблэка, для получения индивидуального порога, из среднего уровня яркости вычитается дисперсия яркости в окрестности пикселя, домноженная на настроечный коэффициент. В методе Сауволы, средний уровень яркости домножается на переменный коэффициент, который линейно зависит от дисперсии яркости в окрестности пикселя. Специалистам известны дальнейшие развития методов Сауволы и Ниблэка, использующие более сложные функциональные зависимости для вычисления индивидуального порога.In the scientific literature, the so-called adaptive binarization methods are known, in which instead of using a global threshold, an individual threshold value is used, separately calculated for each pixel. Examples include the Otsu adaptive method, the Bradley, Niblack, and Sauvola methods. In general, the adaptive method analyzes the neighborhood for each pixel, and determines the required individual threshold from the brightness values of pixels in this neighborhood. In the adaptive Otsu method, a luminance histogram is constructed in a given neighborhood of the pixel, and using it, similarly to the usual Otsu method, a dividing point is determined. This dividing point is used as an individual threshold for the pixel. In the Bradley method, the average brightness level is calculated within the vicinity of the pixel, and then this average level is multiplied by some tuning factor. The value of the tuning factor is selected slightly less than one. As a result of multiplication, an individual threshold for the pixel is obtained. In the Niblack method, to obtain an individual threshold, the variance of brightness in the vicinity of the pixel, multiplied by the tuning factor, is subtracted from the average brightness level. In the Sauvola method, the average brightness level is multiplied by a variable coefficient, which linearly depends on the brightness variance in the vicinity of the pixel. Specialists are aware of the further development of the Sauvola and Niblack methods, using more complex functional dependencies to calculate an individual threshold.

Методы адаптивной бинаризации учитывают состояние ближайших пикселей фона вокруг символа и, в определенной мере, снижают влияние яркости и контрастности фона на выделение пикселей символа в полосе неопределенности. Главным недостатком всех адаптивных методов бинаризации является их повышенная вычислительная сложность. Из перечисленных здесь, только метод Брэдли обладает вычислительной сложностью и быстродействием, приемлемыми для применения в машинах для обработки банкнот. Все остальные адаптивные методы оказываются во много раз медленнее метода Брэдли. По качеству отделения высококонтрастного фона от символа, метод Сауволы показывает достаточно хорошие результаты. К сожалению, он же оказывается и наиболее медленным. Метод Брэдли разрешает часть сложностей, вызываемых наличием высококонтрастного фона. Однако, при его использовании, в результате бинаризации, на больших областях фона появляются случайно расположенные кластеры черных пикселей, а толщина линий символа уменьшается в местах их пересечений. Таким образом, известные адаптивные алгоритмы оказываются малопригодными для бинаризации символов на банкноте.Adaptive binarization methods take into account the state of the nearest background pixels around the symbol and, to a certain extent, reduce the influence of the brightness and contrast of the background on the allocation of the symbol pixels in the uncertainty band. The main disadvantage of all adaptive binarization methods is their increased computational complexity. Of those listed here, only the Bradley method has the computational complexity and speed acceptable for use in banknote processing machines. All other adaptive methods are many times slower than the Bradley method. In terms of the quality of separation of a high-contrast background from a symbol, the Sauvola method shows fairly good results. Unfortunately, it also turns out to be the slowest. The Bradley method resolves some of the difficulties caused by the presence of a high-contrast background. However, when using it, as a result of binarization, randomly located clusters of black pixels appear on large areas of the background, and the thickness of the symbol lines decreases at their intersections. Thus, well-known adaptive algorithms are of little use for binarizing symbols on a banknote.

Полутоновые изображения символов характеризуются тем, что пиксели символа имеют схожие и низкие значения яркости. Символы как европейских, так и азиатских алфавитов состоят из линий, длина которых во много раз превосходит толщину. Поэтому, пиксели символа соседствуют друг с другом, образуя вытянутые кластеры. Эти вытянутые кластеры содержат значительное количество пикселей и соответствуют линиям символа. Наличие крупных вытянутых кластеров соседствующих пикселей, имеющих близкие и невысокие значения яркости, отличает символы от других элементов изображения. Фон образует кластеры высокой яркости. Шумовые элементы, вызванные волокнистой структурой и загрязнениями поверхности бумаги, образуют темные кластеры небольшого размера. Графические элементы, не состоящие из линий, образуют темные кластеры, не имеющие вытянутой формы. Перечисленные здесь свойства кластеризации пикселей, образующих символы, используют в качестве дополнительной информации для нахождения оптимального глобального порога. Так, известен патент США US 9367899 (опубл. 14.06.2016, МПК G06K 9/00), в котором проводят пробную бинаризацию цифрового образа при различных значениях порога, и анализируют полученный результат бинаризации. В каждом из полученных бинарных образов, проводят поиск кластеров черных пикселей, измеряют их геометрические параметры, и на основе этих параметров относят кластеры либо к символам, либо к шумовым элементам. Для каждого пробного значения порога, вычисляют отношение между количеством шумовых кластеров и кластеров символов. Оптимальным считают порог, при котором это отношение минимально.Halftone images of symbols are characterized in that the pixels of the symbol have similar and low brightness values. Symbols of both European and Asian alphabets consist of lines whose length is many times greater than the thickness. Therefore, the pixels of the symbol are adjacent to each other, forming elongated clusters. These elongated clusters contain a significant number of pixels and correspond to the lines of the symbol. The presence of large elongated clusters of neighboring pixels having close and low brightness values distinguishes characters from other image elements. The background forms clusters of high brightness. Noise elements caused by the fibrous structure and surface contamination of the paper form small dark clusters. Graphic elements that do not consist of lines form dark clusters that do not have an elongated shape. The clustering properties of the pixels forming the symbols listed here are used as additional information to find the optimal global threshold. Thus, US patent US 9367899 (published on 06/14/2016, IPC G06K 9/00) is known, in which test binarization of a digital image is performed at various threshold values, and the result of binarization is analyzed. In each of the obtained binary images, clusters of black pixels are searched for, their geometric parameters are measured, and based on these parameters, clusters are assigned either to symbols or to noise elements. For each trial threshold value, the ratio between the number of noise clusters and symbol clusters is calculated. The threshold at which this ratio is minimal is considered optimal.

В соответствии с ранее описанными этапами изменения бинаризованного изображения, шумовые кластеры в большом количестве присутствуют в этом изображении на втором, третьем, и пятом этапах. На четвертом этапе, соответствующем грубому определению порога, шумовые кластеры отсутствуют или же их количество минимально. Таким образом, оптимальный порог, определяемый в известном патенте, соответствует четвертому этапу.In accordance with the previously described steps for changing a binarized image, noise clusters are present in large numbers in this image in the second, third, and fifth stages. At the fourth stage, corresponding to a rough definition of the threshold, noise clusters are absent or their number is minimal. Thus, the optimal threshold determined in the known patent corresponds to the fourth stage.

Известный способ отличается большой вычислительной сложностью за счет многократного повторения бинаризации и выполнения процедур поиска и оценки кластеров на многочисленных пробных бинарных изображениях. Так, в практической реализации способа создается 16 бинарных изображений, по одному для 16 пробных значений порога. В связи с высокой вычислительной сложностью, он мало пригоден для распознавания символов на банкнотах. Находимый им порог гарантированно находится в интервале между наименьшим и наибольшим допустимыми значениями. Однако, указанный способ не выполняет точного определения порога, по крайней мере, в реализациях, описанных в патенте. В этом отношении он показывает результат, сходный с результатом метода Танаки.The known method is very computationally complex due to the repeated repetition of binarization and the search and evaluation of clusters in numerous trial binary images. So, in the practical implementation of the method, 16 binary images are created, one for 16 trial threshold values. Due to the high computational complexity, it is not suitable for character recognition on banknotes. The threshold he finds is guaranteed to be in the interval between the smallest and largest acceptable values. However, this method does not accurately determine the threshold, at least in the implementations described in the patent. In this regard, he shows a result similar to that of the Tanaki method.

Известен ряд способов бинаризации изображений символов, основанных на сравнении яркостей соседних пикселей и исследовании так называемых связанных компонентов в исходном цифровом образе, состоящих из соседствующих пикселей, близких по яркости.A number of methods are known for binarizing symbol images based on comparing the brightnesses of neighboring pixels and examining the so-called related components in the original digital image, consisting of neighboring pixels of similar brightness.

В патенте США US 10049291 (опубл. 15.02.2018, МПК G06K 9/34) изображение разбивают на связанные компоненты, состоящие из соседствующих пикселей одного и того же уровня яркости. Далее, строят иерархический граф соединения связанных компонентов друг с другом по принципу касания пикселей, относящихся к различным связанным компонентам. Затем, анализируют соотношения площадей соединенных связанных компонентов и получают так называемый параметр резкости. Параметр резкости, а также параметры контраста и площади, позволяют отличить связанные компоненты, которые вместе составляют символ, от шумовых и фоновых связанных компонентов. В результате, выбирается порог бинаризации, обеспечивающий полную передачу символа в бинарное изображение. За счет использования иерархического графа связи, в бинарное изображение передаются только связанные компоненты, отнесенные к символу, не передаются шумовые кластеры, не связанные с символом. Описанный способ обеспечивает надежное отделение символа от фона, но обладает повышенной вычислительной сложностью. Эта сложность связана, прежде всего, с затратами на прослеживание цепочек соседствующих пикселей в отдельных связанных компонентах, на построение иерархического графа соединения связанных компонентов, и на обсчет характеристик соединения между связанными компонентами. Чем сложнее оказывается граф связи и чем больше связанных компонентов в изображении, тем дольше длится бинаризация. Это не позволяет удовлетворить жесткие требования к быстродействию при обработке банкнот. Сказанное можно отнести в целом к способам, в которых используют построение иерархических графов связанных компонентов.In US patent US 10049291 (publ. 02.15.2018, IPC G06K 9/34) the image is divided into related components consisting of adjacent pixels of the same brightness level. Next, build a hierarchical graph of the connection of related components to each other on the principle of touching pixels related to various related components. Then, analyze the ratio of the areas of the connected related components and get the so-called sharpness parameter. The sharpness parameter, as well as the parameters of contrast and area, make it possible to distinguish the related components that together make up the symbol from the noise and background related components. As a result, the binarization threshold is selected, which ensures the complete transmission of the symbol to the binary image. Due to the use of a hierarchical communication graph, only related components assigned to the symbol are transferred to the binary image, no noise clusters that are not associated with the symbol are not transferred. The described method provides reliable separation of the symbol from the background, but has increased computational complexity. This complexity is associated primarily with the costs of tracking chains of adjacent pixels in separate related components, constructing a hierarchical graph of the connection of related components, and computing the characteristics of the connection between related components. The more complex the communication graph is and the more connected components in the image, the longer binarization lasts. This does not allow to meet the stringent requirements for speed when processing banknotes. The aforesaid can be attributed as a whole to methods that use the construction of hierarchical graphs of related components.

Как и все другие способы, описанные ранее, этот способ не содержит критерия, по которому можно выбрать порог, который наилучшим образом разделяет пиксели, находящиеся в полосе неопределенности. Параметр резкости позволяет определить принадлежность к линии, но не толщину этой линии. Таким образом, при бинаризации не гарантируется точная передача мелких формных элементов и толщины линий исходного символа.Like all other methods described earlier, this method does not contain a criterion by which you can choose the threshold that best separates the pixels in the uncertainty band. The sharpness parameter allows you to determine the line, but not the thickness of the line. Thus, with binarization, the exact transfer of small shaped elements and the thickness of the lines of the original symbol is not guaranteed.

В случае символов на банкнотах, всегда известен шрифт, которым напечатаны символы, а, следовательно, заранее известна средняя толщина линий символов. Это дает возможность провести поиск наилучшего порога бинаризации, обеспечивающего заранее известную среднюю толщину символов. Это позволяет исключить, либо существенно уменьшить влияние зоны неопределенности на точность воспроизведения символа в бинаризованном изображении.In the case of symbols on banknotes, the font with which the symbols are printed is always known, and therefore the average thickness of the symbol lines is known in advance. This makes it possible to search for the best binarization threshold, providing a previously known average symbol thickness. This allows us to eliminate or significantly reduce the influence of the zone of uncertainty on the accuracy of reproduction of the symbol in the binarized image.

Для нахождения наилучшего порога можно было бы оценивать толщину линий, получаемую при использовании того или иного порога бинаризации. В качестве наилучшего значения следовало бы выбирать тот порог бинаризации, при котором средняя толщина линий в бинаризованном изображении соответствует заранее известной. Это можно было бы сделать, например, с использованием способа, описанного в упомянутом ранее патенте US 9367899. Для этого, нужно было бы обеспечить измерение толщины линий в кластерах на пробных бинаризованных образах, и сравнение измеренной толщины с заранее известной величиной. Тот порог, при котором почти все кластеры бинаризованного изображения имеют заранее известную среднюю толщину линий, был бы близок к наилучшему. К сожалению, за счет вычислительной сложности, указанной ранее, подобное решение не подходит для распознавания символов на банкнотах.To find the best threshold, one could estimate the thickness of the lines obtained by using one or another binarization threshold. The binarization threshold should be chosen as the best value at which the average line thickness in the binarized image corresponds to a previously known one. This could be done, for example, using the method described in the aforementioned US Pat. No. 3,967,899. To do this, it would be necessary to measure the thickness of the lines in the clusters on trial binarized images and compare the measured thickness with a predetermined value. The threshold at which almost all binarized image clusters have a predetermined average line thickness would be close to the best. Unfortunately, due to the computational complexity indicated earlier, such a solution is not suitable for recognizing characters on banknotes.

Патент US 9367899 был выбран в качестве прототипа заявленного изобретения. Техническим результатом заявленного изобретения является повышение быстродействия распознавания символов банкноты.US patent 9367899 was selected as a prototype of the claimed invention. The technical result of the claimed invention is to increase the speed of recognition of banknote characters.

Этот результат достигается в способе бинаризации изображений символов на банкноте, в котором получают полутоновое изображение участка банкноты, содержащего, по меньшей мере, один символ, подлежащий бинаризации, в котором каждый пиксель характеризуется уровнем яркости, и определяют итоговый порог бинаризации и формируют итоговый результат бинаризации, для чего применяют пороговую процедуру с использованием итогового порога бинаризации где пороговая процедура является процессом формирования двухуровневого изображения, в котором каждый пиксель соответствует пикселю полутонового изображения, и имеет один из двух возможных уровней яркости, назначаемый на основе сравнения яркости соответствующего пикселя полутонового изображения с заданным порогом бинаризации, при этом для определения итогового порога бинаризации строят гистограмму длины границ указанного полутонового изображения для чего задают упорядоченный набор возрастающих значений яркости, возможных в полутоновом изображении, и, для всех значений яркости в указанном наборе, начиная со значения, следующего за наименьшим, задают значение соответствующей ячейки гистограммы длины границ как приращение длины границ двухуровневого изображения, получаемого в результате выполнения пороговой процедуры, соответствующее приращению порога, применяемого в пороговой процедуре, до рассматриваемого значения яркости от предшествующего ему значения яркости в указанном наборе, причем длина границ двухуровневого изображения подсчитывается как сумма длин отрезков, каждый из которых представляет собой границу двух граничащих пикселей с различными уровнями яркости, плюс дополнительная составляющая для учета длины тех сторон пикселей, которые находятся на краю изображения, и по заданному критерию анализируют указанную гистограмму длины границ для нахождения итогового порога бинаризации, при использовании которого результат бинаризации содержит непрерывные линии, содержащиеся в полутоновом изображении участка банкноты.This result is achieved in a method for binarizing symbol images on a banknote, in which a grayscale image of a section of a banknote containing at least one symbol to be binarized in which each pixel is characterized by a brightness level is obtained, and a final binarization threshold is determined and a final binarization result is generated, why apply the threshold procedure using the final binarization threshold where the threshold procedure is the process of forming a two-level image in which each the second pixel corresponds to a grayscale image pixel, and has one of two possible brightness levels, assigned based on a comparison of the brightness of the corresponding grayscale image pixel with a given binarization threshold, and a histogram of the boundaries of the specified grayscale image is constructed to determine the final binarization threshold, for which an ordered set of increasing luminance values possible in a grayscale image, and, for all luminance values in a specified set, starting from the value following for the smallest, specify the value of the corresponding cell of the histogram of the length of the boundaries as an increment of the length of the boundaries of the two-level image obtained as a result of the threshold procedure, corresponding to the increment of the threshold used in the threshold procedure to the brightness value considered from the previous brightness value in the specified set, and the length of the boundaries of the two-level image is calculated as the sum of the lengths of the segments, each of which is the border of two adjacent pixels with different levels brightness, plus an additional component to take into account the length of those sides of the pixels that are on the edge of the image, and according to a specified criterion, analyze the specified histogram of the border lengths to find the final binarization threshold, when using which the binarization result contains continuous lines contained in the grayscale image of the banknote section.

Получение полутонового изображения участка банкноты, содержащего символ, является типовой операцией обработки банкнот и хорошо известно специалистам. Применение пороговой процедуры с использованием заданного глобального порога для получения итогового результата бинаризации, также является типовой операцией, применяемой в способах бинаризации, опирающихся на глобальный порог. Новизна и изобретательский уровень заявленного изобретения обеспечиваются признаками, характеризующими то, каким образом в нем определяется итоговый порог бинаризации.Obtaining a grayscale image of a portion of a banknote containing a symbol is a typical banknote processing operation and is well known in the art. The application of a threshold procedure using a given global threshold to obtain the final result of binarization is also a typical operation used in binarization methods based on the global threshold. The novelty and inventive step of the claimed invention are provided with features characterizing how the final binarization threshold is determined in it.

В прототипе, для определения итогового порога бинаризации, производят множество пробных бинаризаций с пробными значениями порога, анализируют результаты пробных бинаризаций, и, по результатам анализа выбирают итоговый порог. В заявленном изобретении также рассматривается набор возможных значений для порога, однако, для выбора из них итогового порога не требуется выполнять множество пробных бинаризаций. Вместо этого, для анализа качества бинаризации и выбора подходящего итогового порога используют гистограмму длины границ. Рассмотрим гистограмму длины границ более подробно.In the prototype, in order to determine the final binarization threshold, a lot of trial binarizations with trial threshold values are produced, the results of trial binarizations are analyzed, and the final threshold is selected according to the analysis results. The claimed invention also considers a set of possible values for a threshold, however, to select the final threshold from them, it is not necessary to perform many test binarizations. Instead, a histogram of the length of the borders is used to analyze the quality of binarization and select the appropriate final threshold. Consider the histogram of the length of the borders in more detail.

Длина границ в двухуровневом бинаризованном изображении есть сумма длин отрезков, каждый из которых представляет собой границу двух граничащих пикселей с различными уровнями яркости. Если два граничащих пикселя в бинаризованном изображении имеют одинаковое значение яркости, то их пограничный отрезок не входит в длину границ. Гистограмма длины границ показывает, каким образом изменяется длина границ при пошаговом нарастании порога бинаризации, который используется для получения бинаризованного изображения.The length of the borders in a two-level binarized image is the sum of the lengths of the segments, each of which represents the border of two adjacent pixels with different levels of brightness. If two bordering pixels in a binarized image have the same brightness value, then their boundary segment is not included in the length of the borders. The histogram of the length of the borders shows how the length of the borders changes with a stepwise increase in the binarization threshold, which is used to obtain a binarized image.

При рассмотрении двух соседних пикселей полутонового изображения, имеется простой способ определить, при каких значениях порога бинаризации пограничный отрезок между этими пикселями будет включен в длину границ бинаризованного изображения. Для каждого из пограничных отрезков между двумя пикселями полутонового изображения, если порог бинаризации находится в интервале между значениями яркостей этих пикселей, то в результате бинаризации будут получены пиксели с разными уровнями яркости. В этом случае, их пограничный отрезок входит в длину границ. Если порог бинаризации имеет значение ниже указанного интервала либо выше указанного интервала, то в результате бинаризации будут получены пиксели с одинаковыми уровнями яркости. В этом случае, их пограничный отрезок не входит в длину границ.When examining two adjacent pixels of a grayscale image, there is a simple way to determine at what values of the binarization threshold the boundary segment between these pixels will be included in the length of the borders of the binarized image. For each of the boundary segments between two pixels of a grayscale image, if the binarization threshold is in the range between the brightness values of these pixels, then binarization will produce pixels with different brightness levels. In this case, their boundary segment is included in the length of the boundaries. If the binarization threshold is lower than the specified interval or higher than the specified interval, then binarization will produce pixels with the same brightness levels. In this case, their boundary segment is not included in the length of the boundaries.

Включение концов интервала или их исключение зависит от того, как именно определена операция сравнения в конкретной реализации пороговой процедуры.The inclusion of the ends of the interval or their exclusion depends on how exactly the comparison operation is defined in a particular implementation of the threshold procedure.

Когда некоторые стороны части пикселей символа оказываются на границе участка банкноты, они должны быть рассмотрены в особом порядке. Они не являются пограничными отрезками между пикселями изображения участка банкноты. Для учета вклада этих сторон в длину границ в заявленном способе предусматривается дополнительная составляющая длины границ. В частности, для темных пикселей символа и светлых пикселей фона, дополнительная составляющая длины границ двухуровневого изображения представляет собой сумму длин тех сторон пикселей двухуровневого изображения с низшим уровнем яркости, которые находятся на краю изображения.When some sides of the pixel part of the symbol appear on the border of the banknote section, they must be considered in a special order. They are not boundary segments between the pixels of the image section of the banknote. To account for the contribution of these parties to the length of the borders in the claimed method provides an additional component of the length of the borders. In particular, for dark symbol pixels and light background pixels, the additional component of the length of the borders of a two-level image is the sum of the lengths of those sides of the pixels of a two-level image with a lower brightness level that are located on the edge of the image.

Рассмотрим, в самом общем виде, каким образом может быть построена гистограмма длины границ. В ходе последовательного нарастания порога, пограничный отрезок пары граничащих пикселей будет включен в длину границ бинаризованного изображения при прохождении наименьшего значения яркости в рассматриваемой паре граничащих пикселей в полутоновом изображении. Затем, он будет исключен из длины границ при прохождении наибольшего значения яркости в рассматриваемой паре. В гистограмме длины границ, этим значениям яркости пикселей соответствуют две ячейки, в одной из которых рассматриваемая пара пикселей обеспечивает прибавление длины отрезка, а в другой - вычитание длины отрезка. Таким образом, рассмотрев все пограничные отрезки между граничащими пикселями и проведя увеличение и уменьшение соответствующих им ячеек, можно построить гистограмму длины границ, не выполняя пробную бинаризацию.Let us consider, in the most general form, how a histogram of the length of borders can be constructed. During the successive increase in the threshold, the boundary segment of a pair of bordering pixels will be included in the length of the boundaries of the binarized image when passing the lowest brightness value in the considered pair of bordering pixels in a grayscale image. Then, it will be excluded from the length of the boundaries when passing the highest brightness value in the pair under consideration. In the histogram of the border length, these pixel brightness values correspond to two cells, in one of which the pair of pixels in question provides the addition of the length of the segment, and in the other, the subtraction of the length of the segment. Thus, having examined all the boundary segments between adjacent pixels and having increased and decreased their corresponding cells, we can construct a histogram of the length of the boundaries without performing trial binarization.

Можно легко увидеть, что количество пограничных отрезков между граничащими пикселями в двухуровневом изображении, подлежащих анализу, несколько меньше удвоенного числа пикселей. Для определения наибольшего и наименьшего значения яркости в паре пикселей нужно лишь несколько простых арифметических операций. Более того, в большинстве современных процессоров, операции вычисления минимума и максимума являются атомарными процессорными командами. Все это обуславливает низкую вычислительную сложность и быстроту построения гистограммы длины границ. Как будет показано далее, ее можно построить, например, сравнивая яркость каждого пикселя участка банкноты с яркостями четырех соседних граничащих с ним пикселей, хотя, возможно, существуют и другие способы с еще более низкими вычислительными затратами. Таким образом, построение гистограммы длины границ требует четырех операций сравнения на каждый пиксель. Вполне возможно, что существует еще более быстрый, но пока неизвестный, способ построения гистограммы длины границ.You can easily see that the number of boundary segments between adjacent pixels in a two-level image to be analyzed is slightly less than twice the number of pixels. To determine the highest and lowest brightness values in a pair of pixels, you need only a few simple arithmetic operations. Moreover, in most modern processors, the operations of calculating the minimum and maximum are atomic processor instructions. All this leads to low computational complexity and speed of building a histogram of the length of the borders. As will be shown below, it can be constructed, for example, by comparing the brightness of each pixel in a section of a banknote with the brightnesses of four neighboring pixels adjacent to it, although there may be other methods with even lower computational costs. Thus, building a histogram of the length of the borders requires four comparison operations per pixel. It is possible that there is an even faster, but still unknown, way to construct a histogram of the length of the borders.

Дальнейшая обработка данных в заявленном изобретении производится на основе гистограммы длины границ результата бинаризации. Сложность этой обработки не зависит от числа пикселей и определяется только количеством уровней гистограммы. В соответствии с критериями анализа гистограммы длины границ, приведенными далее, для каждого уровня гистограммы необходимо всего лишь несколько простых арифметических операций. Практически необходимое количество уровней гистограммы не превышает 256 и, как показывает практика, может быть уменьшено до 64. Поэтому, вычислительная сложность критерия анализа гистограммы длины границ оказывается ниже, чем вычислительная сложность построения этой гистограммы.Further data processing in the claimed invention is based on a histogram of the length of the boundaries of the binarization result. The complexity of this processing does not depend on the number of pixels and is determined only by the number of histogram levels. In accordance with the criteria for analyzing the histogram of the border length given below, for each level of the histogram, only a few simple arithmetic operations are necessary. The practically necessary number of histogram levels does not exceed 256 and, as practice shows, can be reduced to 64. Therefore, the computational complexity of the criterion for analyzing the histogram of the border length is lower than the computational complexity of constructing this histogram.

В прототипе при пробной бинаризации для каждого пробного значения порога нужно произвести сравнение яркости каждого пикселя с значением пробного порога. Кроме того, в прототипе для поиска кластеров в каждом пробном бинаризованном изображении необходимо сравнивать значение яркости каждого пикселя с, как минимум, четырьмя соседними. Таким образом, в прототипе на каждый пиксель приходится количество сравнений, равное числу пробных значений порога, помноженному, как минимум, на 5. На практике, рекомендуется не менее 16 пробных значений порога, из-за чего в прототипе требуется количество сравнений на один пиксель, которое на порядок превосходит количество сравнений, требуемое в заявленном изобретении. К этому нужно добавить процедуры анализа кластеров, сложность которых достаточно тяжело оценить, но которые дополнительно увеличивают вычислительную сложность прототипа.In the prototype, during trial binarization, for each trial threshold value, it is necessary to compare the brightness of each pixel with the value of the trial threshold. In addition, in the prototype for searching for clusters in each test binarized image, it is necessary to compare the brightness value of each pixel with at least four neighboring ones. Thus, in the prototype, for each pixel, the number of comparisons is equal to the number of trial threshold values multiplied by at least 5. In practice, at least 16 trial threshold values are recommended, which is why the prototype requires the number of comparisons per pixel, which is an order of magnitude greater than the number of comparisons required in the claimed invention. To this we must add the cluster analysis procedures, the complexity of which is rather difficult to assess, but which additionally increase the computational complexity of the prototype.

Таким образом, вычислительная сложность заявленного изобретения оказывается существенно ниже вычислительной сложности прототипа. Это обеспечивает достижение технического результата.Thus, the computational complexity of the claimed invention is significantly lower than the computational complexity of the prototype. This ensures the achievement of a technical result.

В то же время, заявленное изобретение обеспечивает, по меньшей мере, такую же точность определения итогового порога бинаризации, какую обеспечивает прототип. В наиболее общем виде, как заявленное изобретение, так и прототип гарантируют, что итоговый порог бинаризации будет находиться между минимальным и максимальным допустимыми порогами. В заявленном изобретении, для этого используется критерий анализа гистограммы длины границ.At the same time, the claimed invention provides at least the same accuracy in determining the final binarization threshold as that provided by the prototype. In the most general form, both the claimed invention and the prototype guarantee that the final binarization threshold will be between the minimum and maximum allowable thresholds. In the claimed invention, the criterion for analyzing the histogram of the border length is used for this.

Для пояснения использования гистограммы длины границ при нахождении итогового порога бинаризации рассмотрим поэтапное изменение длины границ бинаризованного изображения по мере последовательного увеличения порога бинаризации. На первом этапе, черные пиксели в бинаризованном изображении отсутствуют, так что длина их границ оказывается равной нулю. При появлении разрозненных пикселей на втором этапе, длина границ начинает резко расти. Без нарушения общности, мы будем рассматривать квадратные пиксели, а в качестве единиц длины границы будем использовать длину стороны пикселя. У каждого квадратного пикселя четыре равные стороны, поэтому, при его проявлении в бинаризованном изображении длина границ изображения вырастает сразу на 4 единицы. На третьем этапе, разрозненные пиксели объединяются в мелкие кластеры. Прибавление нового пикселя к кластеру увеличивает длину границ менее чем на 4 единицы, однако, в целом темп роста длины границ остается высоким.To explain the use of the histogram of the length of the boundaries when finding the final binarization threshold, we consider a phased change in the length of the boundaries of the binarized image as the binarization threshold increases sequentially. At the first stage, there are no black pixels in the binarized image, so the length of their borders is zero. When disparate pixels appear in the second stage, the length of the borders begins to increase sharply. Without loss of generality, we will consider square pixels, and as units of the length of the border we will use the side length of the pixel. Each square pixel has four equal sides, therefore, when it appears in a binarized image, the length of the image borders grows immediately by 4 units. In the third stage, disparate pixels are combined into small clusters. Adding a new pixel to the cluster increases the length of the borders by less than 4 units, however, in general, the growth rate of the length of the borders remains high.

Ситуация меняется на четвертом этапе, на котором символ в бинаризованном изображении состоит из безразрывных линий. С ростом порога растет толщина линий. Однако, длина границ линий растет только за счет их концов. На протяженных участках линий длина границ практически не меняется. Соответственно, на четвертом этапе рост границ бинаризованного изображения очень мал. Для замкнутых символов, где линии не имеют концов, рост границ практически отсутствует. На пятом этапе, с проявлением шумовых разрозненных пикселей фона в бинаризованном изображении, вновь начинается резкий рост длины границ с темпом до 4 единиц на один пиксель.The situation changes in the fourth stage, in which the symbol in the binarized image consists of continuous lines. As the threshold increases, the thickness of the lines increases. However, the length of the boundaries of the lines grows only due to their ends. On extended sections of lines, the length of the boundaries remains practically unchanged. Accordingly, at the fourth stage, the growth of the boundaries of the binarized image is very small. For closed symbols, where the lines have no ends, the growth of borders is practically absent. At the fifth stage, with the manifestation of noise scattered pixels of the background in the binarized image, a sharp increase in the length of the borders begins again at a rate of up to 4 units per pixel.

Суммируя описанное здесь, можно сказать, что на втором, третьем и пятом этапах, по крайней мере часть ячеек гистограммы длины границ содержит значительные положительные значения, связанные с появлением разрозненных пикселей и ростом небольших кластеров. Напротив, средние значения ячеек гистограммы длины границ на четвертом этапе очень малы, поскольку рост границ мал или практически отсутствует. Это явное противопоставление позволяет реализовать различные критерии, находящие порог бинаризации на допустимом отрезке уровней гистограммы от минимально допустимого до максимально допустимого, соответствующие четвертому этапу. Любое значение порога бинаризации в пределах допустимого отрезка обеспечивает передачу символа в бинаризованное изображение с сохранением его формы. Конкретное значение порога бинаризации может быть найдено внутри допустимого отрезка с использованием дополнительных соображений. Самым простым решением может быть выбор порога в середине допустимого отрезка. Основную разницу между прототипом и заявленным изобретением можно описать следующим образом. В прототипе, проводится многократная пробная бинаризация с различными значениями порога, результаты ее анализируется и по результатам анализа выбирается итоговый порог бинаризации. При анализе производится выделение и сравнение геометрических признаков кластеров, с целью определения того порога бинаризации, при котором кластеры, почти исключительно, будут представлять собой бинаризованные изображения символов. В заявленном изобретении, гистограмма длины границ применяется для анализа результата бинаризации, проводимого с той же целью, что и в прототипе, но без необходимости проведения самой бинаризации. Отсутствием пробной бинаризации, в конечном счете, объясняется сниженная вычислительная сложность и повышенное быстродействие заявленного способа в сравнении с прототипом.Summarizing what is described here, we can say that in the second, third and fifth stages, at least part of the cells of the histogram of the border length contains significant positive values associated with the appearance of disparate pixels and the growth of small clusters. In contrast, the average values of the histogram cells of the border length at the fourth stage are very small, since the border growth is small or practically absent. This explicit contrast makes it possible to implement various criteria that find the binarization threshold on an acceptable range of histogram levels from the minimum to the maximum allowable, corresponding to the fourth stage. Any value of the binarization threshold within the allowable range ensures the transmission of the symbol in the binarized image while maintaining its shape. The specific value of the binarization threshold can be found within an acceptable range using additional considerations. The simplest solution may be to select a threshold in the middle of an acceptable interval. The main difference between the prototype and the claimed invention can be described as follows. In the prototype, multiple trial binarization with different threshold values is carried out, its results are analyzed and the final binarization threshold is selected based on the results of the analysis. In the analysis, the geometric features of the clusters are extracted and compared to determine the binarization threshold at which the clusters will almost exclusively be binarized images of symbols. In the claimed invention, a histogram of the length of the boundaries is used to analyze the result of binarization, carried out for the same purpose as in the prototype, but without the need for binarization itself. The lack of trial binarization, ultimately, explains the reduced computational complexity and increased speed of the claimed method in comparison with the prototype.

Пороговая процедура может быть определена различным образом. В наиболее общепринятом определении порога бинаризации и пороговой процедуры, пиксели, яркость которых меньше яркости порога бинаризации, относят к символу, а остальные пиксели относят к фону. Для пороговой процедуры, определенной таким образом, переходный уровень пикселя оказывается на единицу больше значения яркости пикселя. При ином определении порога бинаризации и пороговой процедуры, когда пиксели, яркость которых меньше либо равна яркости порога бинаризации, относят к символу, переходный уровень пикселя равен яркости этого пикселя. Для заявленного способа, разница в определениях порога бинаризации и пороговой процедуры не играет существенной роли. Так как переходный уровень отличается от уровня яркости пикселя на постоянную величину, то соотношения «больше», «меньше» и «равно» для уровня яркости между соседними пикселями совпадают с соотношениями «больше», «меньше» и «равно» для переходного уровня соседних пикселей. Понятие переходного уровня позволяет единым образом рассматривать различные реализации пороговой процедуры.The threshold procedure can be defined in various ways. In the most common definition of a binarization threshold and a threshold procedure, pixels whose brightness is less than the brightness of the binarization threshold are assigned to a symbol, and the remaining pixels are assigned to the background. For the threshold procedure defined in this way, the transition level of the pixel is one more than the pixel brightness value. With a different definition of the binarization threshold and the threshold procedure, when pixels whose brightness is less than or equal to the brightness of the binarization threshold are assigned to a symbol, the transition level of the pixel is equal to the brightness of this pixel. For the claimed method, the difference in the definitions of the binarization threshold and the threshold procedure does not play a significant role. Since the transition level differs from the pixel brightness level by a constant value, the ratios “greater”, “less” and “equal” for the brightness level between adjacent pixels coincide with the ratios “greater”, “less” and “equal” for the transition level of neighboring pixels. The concept of a transitional level allows a single way to consider various implementations of a threshold procedure.

Для построения гистограммы длины границ в соответствии с приведенным ранее общим подходом, первоначально присваивают всем ячейкам гистограммы длины границ нулевые значения, а затем анализируют границы между граничащими пикселями, для чего для каждой пары граничащих пикселей полутонового изображения, разделенных пограничным отрезком, проводят сравнение яркости пикселей и определяют менее яркий и более яркий пиксель в паре, после чего увеличивают значение ячейки, соответствующей переходному уровню менее яркого пикселя в паре, на длину пограничного отрезка, и уменьшают значение ячейки, соответствующей переходному уровню более яркого пикселя в паре, на длину пограничного отрезка, где переходный уровень пикселя представляет собой такой уровень из упорядоченного набора возрастающих значений яркости, при котором значение соответствующего пикселя в двухуровневом изображении, формируемом пороговой процедура, изменяется при изменении порога, применяемого в пороговой процедуре, до переходного уровня от предшествующего ему уровня в упомянутом упорядоченном наборе, и, для учета дополнительной составляющей длины границ, для каждого пикселя, находящегося на краю изображения, увеличивают значение ячейки гистограммы длины границ, соответствующей переходному уровню этого пикселя, на длину стороны пикселя, находящейся на краю изображения.To construct a histogram of the border length in accordance with the general approach given above, initially assign all the histogram cells of the border length to zero values, and then analyze the boundaries between the bordering pixels, for which, for each pair of bordering pixels of a grayscale image separated by a border line, the brightness of the pixels is compared and determine a less bright and brighter pixel in the pair, and then increase the value of the cell corresponding to the transition level of the less bright pixel in the pair, by the length boundary segment, and reduce the value of the cell corresponding to the transition level of the brighter pixel in the pair by the length of the boundary segment, where the transition level of the pixel is such a level from an ordered set of increasing brightness values at which the value of the corresponding pixel in the two-level image formed by the threshold procedure, changes when the threshold used in the threshold procedure changes to a transitional level from the previous level in the said ordered set, and, for taking into account the additional component of the border length, for each pixel located on the edge of the image, the value of the histogram cell of the border length corresponding to the transition level of this pixel is increased by the length of the pixel side located on the edge of the image.

Для простоты рассуждения, мы будем говорить о черных пикселях символа и белых пикселях фона в бинаризованном изображении. Длина границ в бинаризованном изображении определяется суммарной длиной пограничных отрезков между соседними граничащими пикселями, один из которых является черным, а другой является белым.For simplicity of reasoning, we will talk about black pixels of the symbol and white pixels of the background in the binarized image. The length of the borders in the binarized image is determined by the total length of the boundary segments between adjacent bordering pixels, one of which is black and the other is white.

Для формирования гистограммы длины границ, по отдельности рассматриваются все пары граничащих пикселей полутонового изображения. При нарастании порога бинаризации, результат пороговой процедуры для пикселя в паре изменяется в тот момент, когда порог бинаризации достигает переходного уровня этого пикселя. Такое изменение, называемое здесь переходом, вносит свой вклад в значение ячейки гистограммы длины границ, которая соответствует переходному уровню. Когда переход приводит к тому, что пиксели в двухуровневом бинаризованном изображении, соответствующие рассматриваемой паре, получают различающиеся значения, длина границ в бинаризованном изображении увеличивается на длину пограничного отрезка. Для отражения этого в гистограмме длины границ, длина пограничного отрезка должна быть добавлена к ячейке, соответствующей переходному уровню изменившегося пикселя. Напротив, если в результате перехода, значения пикселей в двухуровневом бинаризованном изображении становятся одинаковыми, то длина границ уменьшается и длина пограничного отрезка должна быть вычтена из ячейки, соответствующей переходному уровню изменившегося пикселя. При одинаковых переходных уровнях, в результате синхронного перехода пикселей, длина границ не меняется, и модифицировать ячейки гистограммы длины границ нет необходимости.To form a histogram of the length of the boundaries, separately considered are all pairs of adjacent pixels of a grayscale image. As the binarization threshold increases, the result of the threshold procedure for a pixel in a pair changes at the moment when the binarization threshold reaches the transition level of this pixel. Such a change, referred to here as a transition, contributes to the value of the histogram cell of the border length, which corresponds to the transition level. When the transition causes the pixels in the two-level binarized image corresponding to the pair under consideration to receive different values, the length of the borders in the binarized image increases by the length of the boundary segment. To reflect this in the histogram of the length of the borders, the length of the boundary segment should be added to the cell corresponding to the transitional level of the changed pixel. On the contrary, if, as a result of the transition, the pixel values in the two-level binarized image become the same, then the length of the boundaries decreases and the length of the boundary segment must be subtracted from the cell corresponding to the transition level of the changed pixel. At the same transition levels, as a result of a synchronous transition of pixels, the length of the borders does not change, and there is no need to modify the histogram cells of the border length.

Чтобы реализовать описанную логику модификации значения ячеек гистограммы длины границ, проводится сравнение яркости пикселей, составляющих пару граничащих пикселей. На основе результатов сравнения, когда уровни яркости граничащих пикселей различаются, то обеспечивают изменение значения двух ячеек гистограммы, соответствующих переходным уровням пикселей, на длину пограничного отрезка с использованием соответствующего знака. При равенстве уровней яркости пикселей и, соответственно, их переходных уровней, не изменяют ни одной ячейки гистограммы.In order to implement the described logic of modifying the value of the cells of the histogram of the border length, the brightness of the pixels composing a pair of adjacent pixels is compared. Based on the comparison results, when the brightness levels of the bordering pixels are different, then the value of two histogram cells corresponding to the transitional pixel levels is changed by the length of the boundary segment using the corresponding sign. With the equality of the brightness levels of pixels and, accordingly, their transition levels, do not change a single cell of the histogram.

С целью учета дополнительной составляющей длины границ, для каждого пикселя, находящегося на краю изображения, увеличивают значение ячейки гистограммы длины границ, соответствующей переходному уровню этого пикселя, на длину стороны пикселя, находящейся на краю изображения. Подобная реализация учета основывается на предположении, что вне рассматриваемого участка находятся пиксели заведомо более высокой яркости, чем любой пиксель участка изображения, содержащего символ. За счет этого, граница темного символа, находящаяся на границе участка, рассматривается совершенно аналогично границе данного символа с более ярким фоном. А именно, сторона пикселя, находящаяся на границе рассматриваемого участка, по мере роста порога включается в общую длину границ, как только указанный пиксель, при бинаризации, переходит из высокого уровня яркости в низкий.In order to take into account the additional component of the border length, for each pixel located on the edge of the image, the value of the histogram cell of the border length corresponding to the transition level of this pixel is increased by the length of the pixel side located on the edge of the image. Such an implementation of accounting is based on the assumption that outside the region in question there are pixels of obviously higher brightness than any pixel in the region of the image containing the symbol. Due to this, the border of the dark symbol, located on the border of the site, is considered in exactly the same way as the border of this symbol with a brighter background. Namely, the side of the pixel located on the border of the considered area, as the threshold grows, is included in the total length of the borders, as soon as the specified pixel, with binarization, goes from a high level of brightness to low.

Для ускорения формирования гистограммы длины границ, сравнение уровней яркостей пикселей и соответствующая модификация гистограммы длины границ могут быть сгруппированы наиболее эффективным образом. В одной из реализаций способа, сначала устанавливают накопительную сумму в нулевое значение, а затем если имеется граничащий пиксель, расположенный в строке с меньшим номером, и яркость рассматриваемого пикселя больше либо равна яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка, если имеется граничащий пиксель с меньшим номером, расположенный в той же строке, и яркость рассматриваемого пикселя больше либо равна яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка, если имеется граничащий пиксель, расположенный в строке с большим номером, и яркость рассматриваемого пикселя больше яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка, если имеется граничащий пиксель с большим номером, расположенный в той же строке, и яркость рассматриваемого пикселя больше яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка, после чего изменяют ячейку гистограммы приращения длины границ, соответствующую переходному уровню рассматриваемого пикселя, на число 4, из которого предварительно вычитается удвоенная накопительная сумма.To speed up the formation of a histogram of the length of the borders, a comparison of the brightness levels of the pixels and the corresponding modification of the histogram of the length of the borders can be grouped in the most efficient way. In one implementation of the method, first set the cumulative amount to zero, and then if there is a bordering pixel located in the line with a lower number, and the brightness of the pixel in question is greater than or equal to the brightness of the bordering pixel, then the cumulative amount is increased by the length of the boundary segment, if any bordering pixel with a lower number, located on the same line, and the brightness of the pixel in question is greater than or equal to the brightness of the bordering pixel, then the cumulative amount is increased by the length of the border segment, if there is a bordering pixel located in the line with a large number, and the brightness of the considered pixel is greater than the brightness of the bordering pixel, then the cumulative sum is increased by the length of the boundary segment, if there is a bordering pixel with a large number located on the same line, and the brightness of the considered the pixel is greater than the brightness of the bordering pixel, then the cumulative amount is increased by the length of the boundary segment, after which the cell of the histogram of the increment of the border length corresponding to the transition an equal considered pixel, by the number 4, from which is subtracted twice previously accumulated amount.

Рассмотрение каждого пикселя представляет собой анализ влияния его границ с другими граничащими пикселями на значение в ячейке гистограммы приращения границ, соответствующей переходному уровню рассматриваемого пикселя. Накопительная сумма М соответствует числу пограничных отрезков рассматриваемого пикселя с менее яркими граничащими пикселями. При нарастании порога бинаризации переход менее ярких граничащих пикселей происходит сначала, и лишь потом происходит переход рассматриваемого пикселя. Поэтому, переход рассматриваемого пикселя уменьшает длину границ бинаризованного изображения в соответствии со значением накопительной суммы. В случае более ярких граничащих пикселей, переход рассматриваемого пикселя происходит до перехода более ярких граничащих пикселей, и увеличивает длину границ. Суммарное число граничащих пикселей, вне зависимости от их яркости, равно 4. Поэтому, отрицательный вклад пограничного отрезка с более темным пикселем не только напрямую уменьшает значение ячейки гистограммы приращения границ, соответствующей переходному уровню рассматриваемого пикселя, но также и сокращает количество более светлых граничащих пикселей, увеличивающих значение ячейки. Таким образом, отрицательный вклад накопительной суммы М в ячейку гистограммы длины границ нужно учитывать дважды. В результате, значение 4-2М характеризует полный вклад рассматриваемого пикселя в указанную ячейку.An examination of each pixel is an analysis of the influence of its boundaries with other adjacent pixels on the value in the histogram cell of the increment of boundaries corresponding to the transitional level of the considered pixel. The cumulative sum M corresponds to the number of boundary segments of the considered pixel with less bright bordering pixels. When the binarization threshold increases, the transition of less bright bordering pixels occurs first, and only then does the transition of the considered pixel occur. Therefore, the transition of the considered pixel reduces the length of the boundaries of the binarized image in accordance with the value of the cumulative sum. In the case of brighter bordering pixels, the transition of the considered pixel occurs before the transition of brighter bordering pixels, and increases the length of the borders. The total number of bordering pixels, regardless of their brightness, is 4. Therefore, the negative contribution of the border segment with a darker pixel not only directly reduces the value of the cell of the histogram of the border increment corresponding to the transition level of the pixel in question, but also reduces the number of brighter bordering pixels, increasing the value of the cell. Thus, the negative contribution of the cumulative sum M to the histogram cell of the boundary length must be taken into account twice. As a result, a value of 4-2M characterizes the full contribution of the pixel in question to the specified cell.

Для пикселей, находящихся на краю участка, отсутствие граничащего пикселя не приводит к увеличению накопительной суммы М и, за счет этого, всегда учитывается как пограничный отрезок с более ярким пикселем за пределом участка.For pixels located on the edge of the plot, the absence of a bordering pixel does not increase the cumulative sum M and, due to this, is always taken into account as a boundary segment with a brighter pixel beyond the boundary of the plot.

В двух из четырех условий, применяемых для изменения накопительной суммы М, для яркости используется условие «больше либо равна», а в оставшихся двух применяется условие «больше». Благодаря этому, случай равенства яркости двух граничащих пикселей рассматривается таким образом, что длина пограничного отрезка между двумя указанными пикселями учитывается дважды и приводит, один раз, к увеличению соответствующей ячейки гистограммы длины границ, а другой раз к ее уменьшению. За счет этого, граница между двумя пикселями равной яркости вовсе не учитывается в гистограмме длины границ, поскольку она ни при каком пороге бинаризации не входит в длину границ бинаризованного изображения.In two of the four conditions used to change the cumulative sum M, the condition "greater than or equal to" is used for brightness, and the condition "greater than" is used in the remaining two. Due to this, the case of equality of brightness of two adjacent pixels is considered in such a way that the length of the boundary segment between the two specified pixels is taken into account twice and leads, once, to an increase in the corresponding histogram cell of the border length, and another time to its reduction. Due to this, the border between two pixels of equal brightness is not taken into account in the histogram of the border length, since at any binarization threshold it does not enter the border length of the binarized image.

Описанная здесь группировка действий не изменяет описанного ранее общего подхода, основанного на выборе наибольшего и наименьшего уровня яркости в паре граничащих пикселей. Изменяется порядок действий, но не их результат. Однако, группировка действий уменьшает общее количество арифметических операций и, без дополнительных операций, учитывает вклад пикселей, находящихся на границах участка.The grouping of actions described here does not change the previously described general approach based on the choice of the highest and lowest brightness level in a pair of adjacent pixels. The order of actions is changing, but not their result. However, grouping actions reduces the total number of arithmetic operations and, without additional operations, takes into account the contribution of pixels located at the boundaries of the plot.

Для нахождения итогового порога бинаризации, при использовании которого бинаризованное изображение содержит непрерывные линии, анализируют гистограмму длины границ на предмет нахождения интервала непосредственно следующих друг за другом значений яркости, таких, что значения ячеек гистограммы, соответствующих значениям яркости на указанном интервале, по модулю не превышают заранее заданного предела, и определяют итоговый порог бинаризации на основе значений конечных точек указанного интервала в соответствии с заранее заданным правилом.In order to find the final binarization threshold, when using which the binarized image contains continuous lines, the histogram of the border length is analyzed to find the interval of immediately following luminance values, such that the values of the histogram cells corresponding to the brightness values at the indicated interval do not exceed in advance a predetermined limit, and determine the final binarization threshold based on the values of the endpoints of the specified interval in accordance with a predetermined right silt.

Указанный способ позволяет установить итоговый порог в пределах между минимально допустимым и максимально допустимым значением, опираясь на тот ранее описанный факт, что рост границ бинаризованного изображения на четвертом этапе оказывается очень малым.The specified method allows you to set the final threshold between the minimum acceptable and maximum acceptable values, based on the previously described fact that the growth of the boundaries of the binarized image in the fourth stage is very small.

Однако, существенное дополнительное преимущество дает предпочтительная реализация способа, в которой дополнительно формируют гистограмму яркости полутонового изображения, где ячейки соответствуют значениям яркости из упорядоченного набора, используемого при построении гистограммы длины границ, и, для каждого значения яркости в упорядоченном наборе, задают значение соответствующей ему ячейки как количество пикселей полутонового изображения, переходный уровень которых равен названному значению яркости, а для оценки усредненной толщины линии при пробном значении порога используют параметр толщины, равный отношению суммы всех ячеек гистограммы длины границ на интервале от минимального уровня яркости в наборе до пробного порога к сумме всех ячеек гистограммы яркости на интервале от минимального уровня яркости в наборе до пробного порога, и, по заданному правилу, в качестве итогового порога бинаризации выбирают такой пробный порог, при котором параметр толщины близок к целевому значению, причем, указанное значение заранее выбирают для уменьшения погрешности воспроизведения символа в итоговом результате бинаризации, на основе известных начертаний тех символов, которые могут располагаться в пределах участка банкноты.However, a significant additional advantage is provided by the preferred implementation of the method in which a luminance histogram of a grayscale image is additionally generated, where the cells correspond to the luminance values from the ordered set used to construct the histogram of the border length, and, for each luminance value in the ordered set, the corresponding cell value is set as the number of pixels of a grayscale image, the transition level of which is equal to the named value of brightness, and to estimate the average thickness the line widths at the test threshold value use a thickness parameter equal to the ratio of the sum of all cells of the histogram of the border length in the interval from the minimum brightness level in the set to the test threshold to the sum of all cells of the brightness histogram in the interval from the minimum brightness level in the set to the test threshold, and, by to a given rule, as a final binarization threshold, a trial threshold is chosen at which the thickness parameter is close to the target value, and the specified value is pre-selected to reduce the reproducibility error Institution symbol in the final result of binarization based on known tracings those characters which may be located within the area of the banknote.

Для каждого значения пробного порога сумма всех ячеек гистограммы длины границ на интервале от минимального уровня яркости в наборе до значения пробного порога есть площадь темных частей бинарного изображения, полученного в результате бинаризации с пробным порогом. Площадь выражается числом пикселей. Параметр толщины вычисляется как отношение суммы всех ячеек гистограммы длины границ на интервале от минимального уровня яркости в наборе до пробного порога к сумме всех ячеек гистограммы яркости на интервале от минимального уровня яркости в наборе до пробного порога. То есть, параметр толщины есть отношение длины границ бинаризованного изображения к площади его темных частей.For each value of the test threshold, the sum of all cells of the histogram of the length of the boundaries in the interval from the minimum brightness level in the set to the value of the test threshold is the area of the dark parts of the binary image obtained as a result of binarization with a test threshold. The area is expressed by the number of pixels. The thickness parameter is calculated as the ratio of the sum of all cells of the histogram of the length of the borders in the interval from the minimum brightness level in the set to the test threshold to the sum of all the cells of the histogram of brightness in the interval from the minimum brightness level in the set to the test threshold. That is, the thickness parameter is the ratio of the length of the boundaries of the binarized image to the area of its dark parts.

Символы состоят из линий, для которых характерно существенное превышение длины над шириной. Прежде всего, рассмотрим отдельную длинную прямую линию постоянной толщины, расположенную в участке, подвергаемом бинаризации. При этом рассмотрении, для упрощения, первоначально мы не будем учитывать дискретную пиксельную структуру изображения. Указанная прямая линия, по сути, представляет собой прямоугольник, одна из сторон которого соответствует длине линии, а другая соответствует ее ширине. Для такой линии, из очевидных геометрических соображений, площадь равна произведению длины на толщину.Symbols consist of lines, which are characterized by a significant excess of length over width. First of all, we consider a separate long straight line of constant thickness located in the area subjected to binarization. In this consideration, for simplicity, initially we will not take into account the discrete pixel structure of the image. The specified straight line, in fact, is a rectangle, one side of which corresponds to the length of the line, and the other corresponds to its width. For such a line, from obvious geometric considerations, the area is equal to the product of length and thickness.

Длина границ такой линии есть периметр соответствующего ей прямоугольника. Этот периметр почти точно равен удвоенной длине линии, так как ширина линии мала в сравнении с длиной, и вкладом сторон прямоугольника, соответствующим ширине, можно пренебречь. Таким образом, длина линии почти равна половине длины границ линии. Соответственно, площадь линии S почти равна половине произведения длины границ В на ширину линии W.The length of the borders of such a line is the perimeter of the corresponding rectangle. This perimeter is almost exactly equal to twice the line length, since the line width is small in comparison with the length, and the contribution of the sides of the rectangle corresponding to the width can be neglected. Thus, the line length is almost equal to half the length of the line borders. Accordingly, the area of the line S is almost equal to half the product of the length of the boundaries B and the width of the line W.

Если дополнительно брать в рассмотрение пиксельную структуру изображения, то каждую из сторон прямоугольника нужно заменить на ломаную линию, состоящую из горизонтальных и вертикальных отрезков, соответствующих сторонам пикселей. Поэтому, длина границ представляет собой сумму длин горизонтальных и вертикальных отрезков в составе ломаных линий, соответствующих сторонам прямоугольника. Из-за этого, длина границ линии с учетом дискретной пиксельной структуры изображения отличается от идеальной геометрической длины границ, рассматриваемой без учета дискретности, на коэффициент дискретности, примерно равный 1,2±17% и зависящий от угла наклона линии. Минимальное значение коэффициента дискретности получается в случае вертикальной и горизонтальной ориентации линии, а максимальное достигается при наклоне 45°. Эти соображения непосредственно подтверждаются теоремой Пифагора. При наклоне 45° длина границы с учетом дискретности формируется суммой одинаковых вертикальных и горизонтальных катетов прямоугольных треугольников, образуемых сторонами пикселей. Эта сумма примерно в 1,41 раз превышает длину границы линии без учета дискретизации, вычисляемую как сумма гипотенуз указанных треугольников. Для любых других углов разница между суммой катетов и гипотенузой оказывается меньше названной, и вовсе отсутствует при углах 0° и 90°.If we additionally take into account the pixel structure of the image, then each of the sides of the rectangle must be replaced by a broken line consisting of horizontal and vertical segments corresponding to the sides of the pixels. Therefore, the length of the borders is the sum of the lengths of the horizontal and vertical segments in the composition of the broken lines corresponding to the sides of the rectangle. Because of this, the length of the line borders, taking into account the discrete pixel structure of the image, differs from the ideal geometric length of the borders, considered without taking into account the discreteness, by a discreteness coefficient of approximately 1.2 ± 17% and depending on the angle of the line. The minimum value of the discreteness coefficient is obtained in the case of vertical and horizontal orientation of the line, and the maximum is achieved with an inclination of 45 °. These considerations are directly supported by the Pythagorean theorem. When inclined at 45 °, the length of the border, taking into account the discreteness, is formed by the sum of the same vertical and horizontal legs of rectangular triangles formed by the sides of the pixels. This sum is approximately 1.41 times greater than the length of the line boundary without discretization, calculated as the sum of the hypotenuses of these triangles. For any other angles, the difference between the sum of the legs and the hypotenuse is less than named, and is completely absent at angles of 0 ° and 90 °.

Таким образом, с учетом дискретности, площадь линии S почти равна (0,6±17%)BW. За счет этого, параметр толщины Р, определяемый как отношение длины границ к площади, оказывается обратно пропорциональным толщине линии:

Figure 00000001
. Указанное соотношение, с небольшой потерей точности, сохраняется и для изогнутых линий. Пренебрегая малым вкладом в границы и площадь в местах пересечения линий, это соотношение можно далее распространить на единичный символ либо несколько символов, выполненных одним шрифтом, расположенных в участке изображения, подлежащем бинаризации. Точное значение коэффициента обратной пропорциональности будет варьироваться для различных символов либо их наборов, в зависимости от конкретной формы и ориентации линий в символе либо символах.Thus, taking into account the discreteness, the area of the line S is almost equal to (0.6 ± 17%) BW. Due to this, the thickness parameter P, defined as the ratio of the length of the borders to the area, is inversely proportional to the line thickness:
Figure 00000001
. The indicated ratio, with a slight loss of accuracy, is also preserved for curved lines. Neglecting the small contribution to the boundaries and the area at the intersection of lines, this ratio can be further extended to a single character or several characters made in one font, located in the area of the image to be binarized. The exact value of the coefficient of inverse proportionality will vary for different characters or their sets, depending on the specific shape and orientation of the lines in the character or characters.

Существуют шрифты сложного начертания, в которых толщина линии может меняться от одного конца линии к другому. Для таких шрифтов параметр толщины обратно пропорционален среднему значению толщины линий. В целом, параметр толщины соответствует художественной характеристике, называемой насыщенностью шрифта, которая изменяется по шкале «светлый - жирный». Более светлый шрифт имеет меньшую толщину линий и, соответственно, больший параметр толщины символа, в то время как более жирный имеет большую толщину линий и меньший параметр толщины символа. При составлении начертаний различных символов одного и того же шрифта, дизайнер старается обеспечить постоянство насыщенности для всех символов, поскольку это обеспечивает гармоничное восприятие текста, набранного шрифтом. Этим объясняются близкие значения параметра толщины для символов, составляющих один шрифт.There are complex type fonts in which the line thickness can vary from one end of the line to the other. For such fonts, the thickness parameter is inversely proportional to the average line thickness. In general, the thickness parameter corresponds to an artistic characteristic called font saturation, which changes on a light to bold scale. A lighter font has a smaller line thickness and, accordingly, a larger symbol thickness parameter, while a bold font has a larger line thickness and a smaller symbol thickness parameter. When composing the styles of various characters of the same font, the designer tries to ensure the constancy of saturation for all characters, as this provides a harmonious perception of the text typed in the font. This explains the close values of the thickness parameter for characters that make up one font.

В предпочтительной реализации, по заданному правилу, в качестве итогового порога бинаризации выбирают такой пробный порог, при котором параметр толщины близок к заранее выбранному целевому значению. Указанное целевое значение выбирают для уменьшения погрешности воспроизведения символа в итоговом результате бинаризации, и делают этот выбор на основе известных начертаний тех символов, которые могут располагаться в пределах участка банкноты. Целевое значение параметра толщины, которое обеспечивает уменьшение погрешности воспроизведения, может быть задано путем теоретического анализа эталонных изображений символов известного шрифта либо пробной бинаризации изображений символов этого шрифта.In a preferred embodiment, according to a given rule, a trial threshold is selected as the final binarization threshold at which the thickness parameter is close to a predetermined target value. The specified target value is chosen to reduce the error in the reproduction of the symbol in the final result of binarization, and this choice is made on the basis of the known styles of those symbols that can be located within the banknote section. The target value of the thickness parameter, which provides a reduction in the error of reproduction, can be set by theoretical analysis of reference images of characters of a known font or trial binarization of images of characters of this font.

Теоретический анализ позволяет вычислить площадь и длину границ для известного эталонного бинарного изображения каждого символа в шрифте. По вычисленным значениям следует найти обобщенное значение параметра толщины, которое, в целом, соответствует символам шрифта. Использование такого обобщенного значения параметра толщины в качестве целевого, в свою очередь, обеспечит близость итогового результата бинаризации к соответствующему эталонному изображению.Theoretical analysis allows you to calculate the area and length of the borders for a known reference binary image of each character in the font. From the calculated values, a generalized value of the thickness parameter should be found, which, in general, corresponds to the characters of the font. Using such a generalized thickness parameter as the target, in turn, will ensure that the final result of binarization is close to the corresponding reference image.

При пробной бинаризации следует получить несколько сканированных изображений каждого из символов известного шрифта! Далее, каждое сканированное изображение нужно бинаризовать множество раз с использованием различных порогов бинаризации, и, по полученным бинарным изображениям, найти соответствующие им значения параметра толщины. Из различных значений параметра толщины нужно выбрать и усреднить те, которые обеспечивает наиболее точное воспроизведение символов в бинарном изображении. Усредненное значение параметра толщины следует использовать в качестве целевого.With trial binarization, you should get several scanned images of each of the characters in a known font! Next, each scanned image must be binarized many times using different binarization thresholds, and, using the obtained binary images, find the corresponding thickness parameter values. From various values of the thickness parameter, it is necessary to select and average those that provide the most accurate reproduction of characters in the binary image. The average value of the thickness parameter should be used as the target.

Предпочтительная реализация позволяет найти итоговый порог, близкий к наилучшему. При таком итоговом пороге, в бинаризованном изображении, с точностью до примерно ±17%, будет достигнута средняя толщина линий, характерная для известного шрифта, которым выполнен символ либо символы. За счет сохранения характерной толщины линий повышается сходство между итоговыми результатами бинаризации одного и того же символа, расположенного на различных банкнотах, и снижается влияние различий в загрязнении при износе банкнот. Повышение сходства, выражающееся, в частности, в уменьшении разброса расстояний между характерными точками символа, позволяет проводить распознавание с уменьшенным уровнем ошибок. Важно отметить, что для итогового результата бинаризации изображения разных экземпляров символа одного и того же начертания, различие средней толщины линий между экземплярами оказывается существенно меньше ±17%. Так происходит, поскольку коэффициент дискретности зависит от формы линий и мало изменяется при одинаковой форме линий в символе. Поэтому, хотя искажение толщины линий определенного символа, в сравнении с символами других начертаний, будет находиться в пределах примерно ±17%, но оно будет мало изменяться от одного экземпляра символа к другому экземпляру символа того же начертания. Иначе говоря, предпочтительный способ обеспечивает повышенную повторяемость средней толщины линий в итоговом результате бинаризации для символов одного и того же начертания. Нужно учитывать, что повышенной повторяемости не удается достичь, когда в участке изображения располагается более чем один символ, поскольку коэффициент дискретности будет различаться в зависимости от набора символов.The preferred implementation allows you to find the final threshold, close to the best. With such a final threshold, in a binarized image, with an accuracy of approximately ± 17%, the average thickness of the lines characteristic of the known font with which the character or characters is made will be achieved. By preserving the characteristic thickness of the lines, the similarity between the final binarization results of the same symbol located on different banknotes is increased, and the effect of differences in pollution during banknote wear is reduced. The increase in similarity, expressed, in particular, in reducing the spread of distances between the characteristic points of the symbol, allows recognition with a reduced level of errors. It is important to note that for the final result of binarizing images of different instances of a symbol of the same style, the difference in the average line thickness between the instances is significantly less than ± 17%. This happens because the discreteness coefficient depends on the shape of the lines and changes little with the same line shape in the symbol. Therefore, although the distortion of the thickness of the lines of a certain symbol, in comparison with symbols of other styles, will be within approximately ± 17%, but it will vary little from one instance of the symbol to another instance of the symbol of the same style. In other words, the preferred method provides increased repeatability of the average line thickness in the final binarization result for symbols of the same style. It should be borne in mind that increased repeatability cannot be achieved when more than one character is located in the image area, since the resolution coefficient will vary depending on the character set.

На Фиг. 1 приведено полутоновое изображение серийного номера банкноты, подлежащего бинаризации (А) и результаты его бинаризации с использованием различных значений порога (В - Н).In FIG. 1 shows a grayscale image of the serial number of the banknote to be binarized (A) and the results of its binarization using various threshold values (B - H).

На Фиг. 2 показаны гистограмма длины границ (А) и гистограмма яркостей (В) полутонового изображения серийного номера. Там же, как функции примененного порога бинаризации, приведены зависимости длины границ и параметра толщины (А), а также площади черных пикселей (В) бинаризованного изображения.In FIG. Figure 2 shows a histogram of the length of the borders (A) and a histogram of the brightness (B) of the grayscale image of the serial number. In the same place, as a function of the applied binarization threshold, the dependences of the length of the boundaries and thickness parameter (A), as well as the area of black pixels (B) of the binarized image are given.

На Фиг. 3 показан вклад границы между двумя пикселями в общую длину границ при различных значениях порога бинаризации, и вклад этих пикселей в гистограмму длины границ.In FIG. Figure 3 shows the contribution of the boundary between two pixels to the total length of the boundaries at different values of the binarization threshold, and the contribution of these pixels to the histogram of the length of the boundaries.

На Фиг. 4 дана блок-схема вычисления гистограммы длины границ.In FIG. 4 is a flow chart for calculating a histogram of border lengths.

На Фиг. 5 показаны различные варианты формирования вклада пикселя в общую длину границ при различных соотношениях яркости этого пикселя по отношению к яркости граничащих пикселей.In FIG. 5 shows various options for the formation of the contribution of a pixel to the total length of the borders at various brightness ratios of this pixel with respect to the brightness of the adjacent pixels.

На Фиг. 6 приведена блок-схема применения заявленного способа в устройстве для обработки банкнот.In FIG. 6 shows a block diagram of the application of the claimed method in a device for processing banknotes.

В примере реализации заявленного способа, проводится бинаризация изображения серийного номера банкноты. Для иллюстрации, выбрано полутоновое изображение серийного номера банкноты номиналом 200 израильских шекелей, показанное на Фиг. 1А. Это изображение содержит номер, содержащий 10 символов цифр, а также фон в окрестности номера. Каждый пиксель изображения представлен значением яркости в интервале от 0 (самый темный) до 255 (самый светлый).In an example implementation of the claimed method, binarization of the image of the serial number of the banknote is carried out. To illustrate, a grayscale image of a serial number of a banknote of 200 Israeli shekels, shown in FIG. 1A. This image contains a number containing 10 digits, as well as a background in the vicinity of the number. Each image pixel is represented by a brightness value in the range from 0 (darkest) to 255 (lightest).

Гистограмма 3 яркости этого изображения показана на Фиг. 2 и является трехмодовой. Фон изображения имеет высокую оптическую плотность, сильно различающуюся в разных частях изображения. Две правые моды на гистограмме 3 яркости относятся к фону и разделены глубоким провалом, что затрудняет правильный выбор порога исключительно на основе гистограммы. При использовании алгоритма Отцу, за разделяющую точку на подобных банкнотах часто принимается не раздел между фоном и символом, а провал, разделяющий две моды фона. Это часто приводит к неправильной бинаризации и невозможности распознавания серийного номера.A luminance histogram 3 of this image is shown in FIG. 2 and is three-mode. The background image has a high optical density, which varies greatly in different parts of the image. The two right modes on the histogram 3 brightness relate to the background and are separated by a deep dip, which makes it difficult to choose the threshold based solely on the histogram. When using the Father’s algorithm, the separating point on such banknotes is often taken not as a section between the background and the symbol, but as a gap separating the two background modes. This often leads to incorrect binarization and the inability to recognize the serial number.

При бинаризации с применением фиксированного порога L, в получаемом бинаризованном изображении помечают черным все пиксели, яркость которых меньше или равна L. В выбранной таким образом реализации пороговой функции, переходный уровень пиксела равен его яркости. При использовании различных значений порога L получаются бинаризованные изображения, показанные на Фиг. 1В - Фиг. 1Н, в порядке нарастания порога. Значения использованного порога L показаны справа от каждого бинаризованного изображения.In binarization using a fixed threshold L, all pixels whose brightness is less than or equal to L. are marked black in the resulting binarized image. In the threshold function selected in this way, the transition level of the pixel is equal to its brightness. By using different threshold values L, binarized images shown in FIG. 1B - FIG. 1H, in order of increasing threshold. The values of the threshold L used are shown to the right of each binarized image.

Для бинаризованного изображения на Фиг. 1В порог бинаризации L=20 оказывается выше наиболее темных пикселей символа, из-за чего в бинаризованном изображении начинают проявляться разрозненные кластеры черных пикселей, относящиеся к символу. Такой порог соответствует второму этапу, описанному ранее. Изображение на Фиг. 1С (L=27) соответствует моменту, когда разрывы линий исчезают практически полностью, за исключением единичных выпадений черных пикселей, не влияющих на качество распознавания. Это изображение соответствует началу четвертого этапа и минимально допустимому порогу бинаризации. Бинаризованные изображения, получаемые на четвертом этапе, позволяют уверенно проводить распознавание символов. Бинаризованные изображения, получаемые на предшествующих этапах, мало пригодны для распознавания из-за массового нарушения целостности линий символа.For the binarized image in FIG. 1B, the binarization threshold L = 20 is higher than the darkest pixels of the symbol, which is why scattered clusters of black pixels related to the symbol begin to appear in the binarized image. Such a threshold corresponds to the second stage described previously. The image in FIG. 1C (L = 27) corresponds to the moment when line breaks disappear almost completely, with the exception of single drops of black pixels that do not affect the quality of recognition. This image corresponds to the beginning of the fourth stage and the minimum permissible binarization threshold. The binarized images obtained in the fourth stage allow for confident character recognition. Binarized images obtained in the previous steps are not suitable for recognition due to massive violation of the integrity of the lines of the symbol.

Как уже указывалось ранее, в ходе четвертого этапа, дальнейшее увеличение порога ведет к тому, что пиксели в полосе неопределенности постепенно переходят из фона в символ, что сопровождается ростом толщины линий с сохранением структуры символа. Изображения на Фиг. 1D соответствует наилучшему порогу бинаризации L=32, при котором средняя толщина линий символа в бинаризованном изображении равна средней толщине линий исходного символа. При дальнейшем увеличении порога продолжается увеличение толщины линий с сохранением начертания, как показано на Фиг. 1Е. Это изображение соответствует максимально допустимому порогу L=37 и завершению 4 этапа. При максимально допустимом пороге возможно проявление отдельных единичных черных пикселей в месте расположения фона, что не приводит к затруднению распознавания символов. На пятом этапе, как показано на Фиг. 1F (L=45), при увеличении порога сверх максимально допустимого, некоторые пиксели фона в цифровом образе оказываются ниже порога и проявляются в бинаризованном изображении как черные пиксели. За счет этого возникают шумовые кластеры черных пикселей в местах пробелов. На шестом этапе, как показано на Фиг. 1G, при значении порога L=64, которое значительно больше максимально допустимого, шумовые кластеры сливаются с линиями символа. На седьмом этапе, которому соответствует изображение на Фиг. 1H, шумовые кластеры и линии символа полностью сливаются друг с другом, образуя сплошное черное заполнение бинаризованного изображения с белыми включениями. Начиная с пятого этапа, бинаризованное изображение плохо пригодно для распознавания символов из-за массового слияния элементов символа с участками фона. Таким образом, допустимый интервал порога L составляет от 27 до 37, и наилучшее значение порога L=32 лежит приблизительно посередине этого интервала. Чтобы определить наименьшее допустимое, наибольшее допустимое, и наилучшее значения порога, строят гистограмму длины границ на основе полутонового изображения и далее анализируют ее. На Фиг. 2А показана гистограмма 1 длины границ, построенная на основе полутонового изображения, показанного на Фиг. 1А.As mentioned earlier, during the fourth stage, a further increase in the threshold leads to the fact that the pixels in the uncertainty band gradually change from the background to the symbol, which is accompanied by an increase in the thickness of the lines while maintaining the structure of the symbol. The images in FIG. 1D corresponds to the best binarization threshold L = 32, at which the average thickness of the symbol lines in the binarized image is equal to the average thickness of the lines of the original symbol. With a further increase in the threshold, the increase in the thickness of the lines continues while maintaining the outline, as shown in FIG. 1E. This image corresponds to the maximum permissible threshold L = 37 and the completion of stage 4. At the maximum allowable threshold, the manifestation of individual single black pixels at the location of the background is possible, which does not lead to difficulty in character recognition. In a fifth step, as shown in FIG. 1F (L = 45), when the threshold is increased above the maximum allowed, some background pixels in the digital image appear below the threshold and appear in the binarized image as black pixels. Due to this, noise clusters of black pixels appear in the spaces. In a sixth step, as shown in FIG. 1G, with a threshold value of L = 64, which is much larger than the maximum allowable, noise clusters merge with the lines of the symbol. In a seventh step to which the image in FIG. 1H, noise clusters and symbol lines completely merge with each other, forming a solid black filling of the binarized image with white inclusions. Starting from the fifth stage, the binarized image is poorly suited for character recognition due to the mass merging of the elements of the symbol with areas of the background. Thus, the acceptable threshold interval L is from 27 to 37, and the best threshold value L = 32 lies approximately in the middle of this interval. To determine the smallest allowable, largest allowable, and best threshold value, a histogram of the border length is constructed based on the grayscale image and then it is analyzed. In FIG. 2A shows a border length histogram 1 constructed based on the grayscale image shown in FIG. 1A.

Получение гистограммы 1 длины границ основано на наблюдении, которое проиллюстрировано на Фиг. 3. Рассмотрим любую пару пикселей полутонового изображения, имеющих общую границу. Для примера, на Фиг. 3 эти пиксели имеют яркости 10 и 20 и разделены горизонтальным пограничным отрезком между ними. При 0<L<10, в результате бинаризации, оба пикселя в бинаризованном изображении отображаются как белые, граница между черным и белым по границе пикселей в паре не проходит, и вклад этой пары в общую длину границ d=0. При 10≤L<20 пиксель с яркостью 10 отображается как черный, а пиксель с яркостью 20 отображается как белый, так что граница между черным и белым проходит по пограничному отрезку между пикселями, а вклад данной пары пикселей в общую длину границ d=l. При 20≤L≤255 оба пикселя в бинаризованном изображении отображаются как черные, и вклад этой пары в общую длину границ d=0. То есть, при последовательном нарастании L граница между черным и белым в бинаризованном изображении начинает проходить по пограничному отрезку между пикселями в паре при L=10, и перестает проходить по пограничному отрезку между пикселями в паре при L=20. Из этого можно сделать вывод, что для отражения изменения вклада пограничного отрезка между пикселями в гистограмму длины границ, нужно увеличить ячейку этой гистограммы НВ(10) на 1 и уменьшить ячейку НВ(20) на 1.Obtaining a histogram 1 of the boundary length is based on the observation, which is illustrated in FIG. 3. Consider any pair of pixels of a grayscale image having a common border. As an example, in FIG. 3, these pixels have brightnesses of 10 and 20 and are separated by a horizontal boundary line between them. For 0 <L <10, as a result of binarization, both pixels in the binarized image are displayed as white, the border between black and white along the pixel boundary in the pair does not pass, and the contribution of this pair to the total border length d = 0. For 10≤L <20, a pixel with a brightness of 10 is displayed as black, and a pixel with a brightness of 20 is displayed as white, so that the border between black and white passes along the border line between the pixels, and the contribution of this pair of pixels to the total length of the borders is d = l. At 20≤L≤255, both pixels in the binarized image are displayed as black, and the contribution of this pair to the total length of the boundaries is d = 0. That is, with a successive increase in L, the border between black and white in the binarized image begins to pass along the border line between pixels in a pair at L = 10, and ceases to pass along the border line between pixels in a pair at L = 20. From this we can conclude that in order to reflect the change in the contribution of the boundary segment between pixels to the histogram of the length of the boundaries, it is necessary to increase the cell of this histogram HB (10) by 1 and reduce the cell HB (20) by 1.

В более общем виде, пара граничащих пикселей вносит вклад +1 (инкремент) в ячейку гистограммы, соответствующую наименьшему значению яркости пикселя в паре, и вклад -1 (декремент) в ячейку гистограммы, соответствующую наибольшему значению яркости пикселя в паре. Чтобы построить гистограмму длины границ полутонового изображения, нужно рассмотреть все пары граничащих пикселей таким образом, и дополнительно учесть увеличение длины границ на краях изображения. Чтобы учесть вклад всех возможных пар, можно рассматривать границы каждого пикселя не со всеми соседями, а только с соседями справа и снизу, что исключает ошибочное рассмотрение каждой границы дважды. Для большинства пикселей в изображении, за исключением выходящих на правом и нижнем краю изображения, нужно оценить их вклад в две пары с соседними пикселями. Таким образом, количество пар, которые нужно рассмотреть, почти вдвое превышает количество пикселей в полутоновом изображении. Для пикселей на краю изображения, положительный вклад стороны пикселя, проходящей по краю изображения, в общую длину границ, возникает в момент перехода, то есть, когда порог бинаризации становится равным яркости такого пикселя. Соответственно, для каждого пикселя с яркостью I, находящегося на краю изображения, нужно дополнительно увеличить ячейку НВ(I) на количество сторон пикселя, выходящих на край изображения. Для каждой пары граничащих пикселей, используя описанное выше наблюдение, нужно сделать два обращения к гистограмме длины границ. Для почти всех пикселей изображения, таким образом, нужно по 4 обращения к гистограмме длины границ. Имеется возможность, сохранив общий принцип учета вклада каждой пары граничащих пикселей в гистограмму длины границ, с целью повышения быстродействия, уменьшить количество обращений к гистограмме длины границ. Такая возможность использована в примере реализации заявленного способа и будет описана ниже.More generally, a pair of bordering pixels contributes +1 (increment) to the histogram cell corresponding to the lowest pixel brightness in the pair, and -1 (decrement) to the histogram cell corresponding to the highest pixel brightness in the pair. To build a histogram of the length of the borders of a grayscale image, you need to consider all pairs of bordering pixels in this way, and additionally take into account the increase in the length of the borders at the edges of the image. To take into account the contribution of all possible pairs, we can consider the boundaries of each pixel not with all neighbors, but only with the neighbors on the right and bottom, which eliminates the erroneous consideration of each border twice. For most pixels in the image, with the exception of those emerging on the right and bottom edges of the image, you need to evaluate their contribution to two pairs with adjacent pixels. Thus, the number of pairs to be considered is almost double the number of pixels in a grayscale image. For pixels at the edge of the image, the positive contribution of the side of the pixel extending along the edge of the image to the total length of the borders occurs at the moment of transition, that is, when the binarization threshold becomes equal to the brightness of such a pixel. Accordingly, for each pixel with brightness I located on the edge of the image, it is necessary to additionally increase the cell HB (I) by the number of sides of the pixel facing the edge of the image. For each pair of bordering pixels, using the observation described above, you need to make two calls to the histogram of the border length. For almost all pixels of the image, therefore, you need 4 accesses to the histogram of the border length. It is possible, having retained the general principle of taking into account the contribution of each pair of bordering pixels to the histogram of the border length, in order to improve performance, reduce the number of calls to the histogram of the border length. Such an opportunity was used in an example implementation of the claimed method and will be described below.

Для получения гистограммы 1 длины границ используют вычислительный процесс, блок-схема которого приведена на Фиг. 4. В этом процессе по отдельности рассматривают все пиксели полутонового изображения. При обработке изображений общепринятым является расположение строки с меньшим номером сверху от рассматриваемой строки, и пикселя с меньшим номером слева от рассматриваемого пикселя. Такой порядок нумерации используется и в данном описании. Для каждого пикселя, вначале обнуляют накопительную сумму М (шаг 102), а затем анализируют соотношения яркости I рассматриваемого пикселя и четырех граничащих с ним пикселей сверху, слева, снизу и справа (шаги 103 - 106). Накопительную сумму М инкрементируют каждый раз, когда яркость I рассматриваемого пикселя оказывается больше либо равна яркости граничащего пикселя сверху или слева. Аналогично, накопительную сумму М инкрементируют каждый раз, когда яркость I рассматриваемого пикселя оказывается больше яркости граничащего пикселя снизу или справа.To obtain a histogram 1 of the boundary length, a computational process is used, the block diagram of which is shown in FIG. 4. In this process, all pixels of a grayscale image are individually considered. When processing images, it is generally accepted that the row with the lower number is above the row in question and the pixel with the lower number to the left of the pixel in question. This numbering order is used in this description. For each pixel, first, the cumulative sum M is reset to zero (step 102), and then the brightness ratios I of the pixel in question and the four pixels adjacent to it are analyzed from above, left, bottom, and right (steps 103 - 106). The cumulative sum M is incremented each time when the brightness I of the pixel in question is greater than or equal to the brightness of the bordering pixel from above or to the left. Similarly, the cumulative sum M is incremented each time when the brightness I of the pixel in question is greater than the brightness of the bordering pixel from below or to the right.

Исследуем более подробно, что происходит в переходный момент, когда порог бинаризации L изменяется от значения (I-1) к переходному значению I, то есть, когда в бинаризованном изображении рассматриваемый пиксель меняет цвет с белого на черный. Будем обозначать при помощи D увеличение длины границ бинаризованного изображения, проходящих по всем четырем сторонам рассматриваемого пикселя, в момент его перехода из белого состояния в черное. D выражается в единицах, равных длине стороны пикселя. На Фиг. 5, при помощи значений, указанных в соответствующих квадратах пикселей, показаны яркости граничащих пикселей. На Фиг. 4А все 4 пикселя ярче рассматриваемого, то есть, М=0. При переходе все 4 стороны рассматриваемого пикселя увеличивают длину границ на D=4.Let us examine in more detail what happens at the transition moment, when the binarization threshold L changes from the value (I-1) to the transition value I, that is, when the pixel in question changes color from white to black in the binarized image. We will denote by D the increase in the length of the boundaries of the binarized image extending along all four sides of the considered pixel at the moment of its transition from the white state to the black one. D is expressed in units equal to the length of the side of the pixel. In FIG. 5, using the values indicated in the respective squares of the pixels, the brightness of the adjacent pixels is shown. In FIG. 4A, all 4 pixels are brighter than the considered one, that is, M = 0. Upon transition, all 4 sides of the pixel in question increase the length of the borders by D = 4.

В случае на Фиг. 5В, из 4 граничащих пикселей один темнее рассматриваемого и три светлее, то есть, М=1. До перехода, между более темным пикселем и рассматриваемым пикселем проходит граница, показанная пунктирной линией, и она исчезает в момент перехода. В то же время, между тремя более светлыми пикселями и рассматриваемым пикселем, в момент перехода, добавляются три пограничных отрезка, показанные жирной линией. В сумме, это увеличивает длину границ на D=2.In the case of FIG. 5B, out of 4 adjacent pixels, one is darker than the considered one and three are lighter, that is, M = 1. Before the transition, the border shown by the dashed line passes between the darker pixel and the considered pixel, and it disappears at the moment of transition. At the same time, between the three lighter pixels and the pixel in question, at the moment of transition, three boundary segments are shown, shown by the bold line. In total, this increases the length of the boundaries by D = 2.

В случае на Фиг. 5С, из 4 граничащих пикселей два темнее рассматриваемого и два светлее, то есть, М=2. При переходе исчезают два граничных отрезка и два появляются, что дает итоговое значение D=0. И, наконец, на Фиг. 5D и Фиг. 5Е показаны случаи с М=3 и М=4, соответственно. При переходе исчезает больше границ, чем добавляется, что дает D=-2 и D=-4, соответственно.In the case of FIG. 5C, out of 4 adjacent pixels, two are darker than the considered one and two are lighter, that is, M = 2. During the transition, two boundary segments disappear and two appear, which gives the final value D = 0. And finally, in FIG. 5D and FIG. 5E shows cases with M = 3 and M = 4, respectively. Upon transition, more boundaries disappear than are added, which gives D = -2 and D = -4, respectively.

В целом, для всех описанных случаев верной оказывается формула D=4-2M, приведенная на Фиг. 5F. Вычисление по этой формуле выполняют на шаге 107, и добавляют полученное значение D к ячейке НВ(I) гистограммы 1 длины границ, соответствующей значению яркости I рассматриваемого пикселя.In general, for all the cases described, the formula D = 4-2M shown in FIG. 5F. The calculation by this formula is performed at step 107, and the obtained value D is added to the cell HB (I) of the histogram 1 of the border length corresponding to the brightness value I of the pixel in question.

Особого рассмотрения требует соседство рассматриваемого пикселя с пикселем с такой же яркостью I. Ни при каком пороге бинаризации между ними не может образоваться граница, поскольку они совершают переход одновременно. Исходя из наблюдения, показанного на Фиг. 3, эта пара пикселей одновременно дает как инкремент, так и декремент ячейки НВ(I), и потому вообще не вносит вклада в гистограмму длины границ. Чтобы корректно обработать этот случай, на шагах 103 - 106, для граничащего пикселя сверху или слева используется сравнение «больше либо равно», а для граничащего пикселя снизу или справа используется сравнение «больше». Один из пары граничащих пикселей оказывается слева от другого или же снизу от другого. Оба пикселя, при выполнении шага 107, изменяют ячейку НВ(I) гистограммы 1 длины границ. За счет различия в используемом сравнении для расположения пары пикселей сверху-снизу или же слева-справа, вклады этих пикселей в ячейку НВ(I) оказываются противоположными. Один из пикселей дает вклад длины пограничного отрезка между ними, равный 1, а другой пиксель дает вклад, равный -1. В результате суммирования этих вкладов, граница между пикселями равной яркости I вовсе не влияет на ячейку НВ(I) гистограммы 1 длины границ. Также, нужно рассмотреть влияние тех сторон рассматриваемого пикселя, которые выходят на край изображения. В случае выхода стороны рассматриваемого пикселя на край изображения, соответствующий граничащий пиксель отсутствует, и в соответствующем этому шаге 103 - 106 не происходит инкрементирования значения М. Соответственно, в момент перехода рассматриваемого пикселя его сторона, выходящая на край изображения, всегда добавляется к ячейке НВ(I) гистограммы 1 длины границ. Это соответствует формуле D=4-2M, вычисляемой на шаге 107. Описанный эффект эквивалентен тому, как если бы за краем изображения находились пиксели, имеющие яркость больше любой возможной яркости пикселя в самом изображении. Если линия символа находится вплотную к кромке изображения, ее граница, в том числе и участок вдоль края, полностью учитывается в общей длине границ бинаризованного изображения.The neighborhood of the considered pixel with a pixel with the same brightness I requires special consideration. At no threshold of binarization can a boundary be formed between them, since they make a transition at the same time. Based on the observation shown in FIG. 3, this pair of pixels simultaneously gives both the increment and decrement of the HB (I) cell, and therefore does not contribute to the histogram of the border length at all. To correctly handle this case, at steps 103 - 106, the comparison "greater than or equal to" is used for the bordering pixel on the top or left, and the comparison "greater" is used for the bordering pixel on the bottom or right. One of the pair of adjacent pixels appears to the left of the other or to the bottom of the other. Both pixels, in step 107, change the cell HB (I) of the histogram 1 of the border length. Due to the difference in the comparison used to arrange a pair of pixels from top to bottom or from left to right, the contributions of these pixels to the HB (I) cell turn out to be opposite. One of the pixels gives a contribution of the length of the boundary segment between them, equal to 1, and the other pixel gives a contribution of -1. As a result of summing these contributions, the border between pixels of equal brightness I does not at all affect the cell HB (I) of histogram 1 of the border length. Also, you need to consider the influence of those sides of the pixel in question that go to the edge of the image. If the side of the considered pixel goes to the edge of the image, the corresponding bordering pixel is absent, and in the corresponding step 103-106 there is no increment of the value of M. Accordingly, at the moment of the transition of the considered pixel, its side facing the edge of the image is always added to the HB cell ( I) histograms of 1 border length. This corresponds to the formula D = 4-2M, calculated in step 107. The described effect is equivalent to the fact that as if beyond the edge of the image there were pixels having a brightness greater than any possible pixel brightness in the image itself. If the symbol line is close to the edge of the image, its border, including the portion along the edge, is fully taken into account in the total length of the boundaries of the binarized image.

Представленный на Фиг. 4 процесс построения гистограммы длины границ оптимизирован по быстродействию, но выполняет те же действия над гистограммой длины границ, которые изображены на Фиг. 3. Процесс на Фиг. 4 группирует действия, связанные с парами, куда входит каждый пиксель, так чтобы уменьшить общее количество обращений к ячейкам гистограммы длины границ, хранимым в оперативной памяти процессора. При рассмотрении каждого пикселя обращение к ячейке гистограммы происходит лишь однажды, а операции декремента не используются. Операции инкремента выполняются для одной и той же переменной М, которая может храниться в регистре процессора и требовать минимальных затрат времени на инкремент. Кроме того, процесс на Фиг. 4 позволяет вычислить дополнительную составляющую для учета длины тех сторон пикселей, которые находятся на краю изображения, не применяя для этого дополнительные шаги.Presented in FIG. 4, the process of constructing a histogram of the length of the boundaries is optimized for speed, but performs the same actions on the histogram of the length of the borders, which are depicted in FIG. 3. The process of FIG. 4 groups the actions associated with the pairs where each pixel enters, so as to reduce the total number of calls to the histogram cells of the border length stored in the processor RAM. When considering each pixel, the histogram cell is accessed only once, and decrement operations are not used. Increment operations are performed for the same variable M, which can be stored in the processor register and require minimal time increment. In addition, the process of FIG. 4 allows you to calculate an additional component to take into account the length of those sides of the pixels that are on the edge of the image, without applying additional steps.

Рассмотрим полученную гистограмму 1 длины границ. При помощи линии 2 показан график зависимости длины границ B(L). Длина границ B(L) для заданного уровня яркости L представляет собой сумму всех ячеек гистограммы 1 длины границ от нулевого уровня до заданного уровня L.Consider the obtained histogram 1 of the length of the boundaries. Using line 2 shows a graph of the dependence of the length of the boundaries B (L). The length of the boundaries B (L) for a given level of brightness L is the sum of all cells of the histogram 1 of the length of the boundaries from zero to a given level L.

Для удобства рассмотрения, яркостной диапазон возможных значений порога бинаризации L разделен на отдельные интервалы при помощи штриховых линий 6-13. Для значений яркости слева от линии 6, полностью отсутствуют пиксели с такими значениями, что видно по нулевым значениям гистограммы 3 яркости и гистограммы 1 длины границ. Между линиями 6 и 7 расположены значения яркости, соответствующие второму и третьему этапу, где символ проявляется в бинаризованном изображении лишь частично. В частности, здесь находится порог бинаризации для получения изображения на Фиг. 1В.For convenience of consideration, the brightness range of the possible values of the binarization threshold L is divided into individual intervals using dashed lines 6-13. For brightness values to the left of line 6, there are completely no pixels with such values that can be seen from the zero values of the histogram 3 of brightness and histogram 1 of the length of the borders. Between lines 6 and 7 there are brightness values corresponding to the second and third stages, where the symbol appears in the binarized image only partially. In particular, there is a binarization threshold for image acquisition in FIG. 1B.

Минимально допустимый уровень бинаризации L=27 и изображение на Фиг. 1С соответствует линии 7. Максимально допустимый уровень бинаризации L=37 и изображение на Фиг. 1Е соответствует линии 9. Наилучший уровень бинаризации L=32 и изображение на Фиг. 1D соответствует линии 8.The minimum permissible binarization level L = 27 and the image in FIG. 1C corresponds to line 7. The maximum allowable binarization level L = 37 and the image in FIG. 1E corresponds to line 9. The best binarization level is L = 32 and the image in FIG. 1D corresponds to line 8.

Как уже описывалось ранее, на четвертом этапе увеличения порога бинаризации, в интервале между линиями 7 и 9, длина границ бинаризованного изображения B(L) с ростом L прирастает в минимальной степени. Соответственно, ячейки HB(L) гистограммы 1 длины границ на этом участке принимают очень малые значения, близкие к нулю. Поэтому, для нахождения максимально и минимального допустимых уровней достаточно найти интервал, где абсолютное значение ячеек HB(L) гистограммы 1 длины границ будет меньше некоторого эмпирически заданного предела. В нашем примере такой предел HBlim равен 5.As already described earlier, at the fourth stage of increasing the binarization threshold, in the interval between lines 7 and 9, the length of the boundaries of the binarized image B (L) grows to a minimum with increasing L. Accordingly, the cells HB (L) of histogram 1 of the length of the boundaries in this section take very small values close to zero. Therefore, to find the maximum and minimum acceptable levels, it is enough to find the interval where the absolute value of the cells HB (L) of histogram 1 of the boundary length will be less than a certain empirically specified limit. In our example, such a limit of HB lim is 5.

На интервале между линиями 9 и 10, соответствующем пятому этапу, происходит резкий рост значений ячеек гистограммы 1 длины границ, обусловленный появлением шумовых кластеров в области фона изображения. Справа от линии 10 ячейки HB(L) становятся отрицательными, что соответствует снижению длины границ B(L) из-за слияния черных кластеров друг с другом. Колебания значений ячеек между линиями 10 и 11, и 11 и 12 связаны с двухмодовым характером фона изображения. Линия 13 отделяет участок яркостного интервала, правее которого все пиксели в бинаризованном изображении имеют черный цвет, а длина границ B(L) постоянна и равна длине края изображения. Этот интервал соответствует восьмому этапу.In the interval between lines 9 and 10, corresponding to the fifth stage, there is a sharp increase in the values of the histogram cells 1 of the boundary length due to the appearance of noise clusters in the background image area. To the right of line 10, the HB (L) cells become negative, which corresponds to a decrease in the length of the B (L) boundaries due to the fusion of black clusters with each other. Fluctuations in the values of cells between lines 10 and 11, and 11 and 12 are associated with the two-mode nature of the background image. Line 13 separates the portion of the luminance interval to the right of which all the pixels in the binarized image are black and the length of the borders B (L) is constant and equal to the length of the edge of the image. This interval corresponds to the eighth stage.

В простом варианте реализации заявленного изобретения, находят минимальный и максимальный допустимый уровни бинаризации, соответствующие линиям 7 и 9. Для этого не требуется рассматривать поведение гистограммы длины границ на участке между линиями 9 и 13, соответствующему этапам с пятого по восьмой. Следует искать лишь интервал, соответствующий четвертому этапу. Для этого начинают перебирать значения уровней яркости от линии 6 в сторону увеличения. При этом, ищут интервал, на котором абсолютное значение ячеек |HB(L)| гистограммы 1 длины границ оказывается меньше эмпирически заданного предела HBlim. Как только значение |HB(L)| на протяжении нескольких последовательных уровней уйдет выше предела HBlim, нужно закончить поиск. Наилучший уровень бинаризации находят как середину найденного интервала, что соответствует среднему арифметическому минимального и максимального допустимых уровней бинаризации. Найденный наилучший уровень применяют для бинаризации полутонового изображения (см. Фиг. 1А) и получения итогового результата бинаризации (см. Фиг. 1D).In a simple embodiment of the claimed invention, the minimum and maximum acceptable levels of binarization corresponding to lines 7 and 9 are found. For this, it is not necessary to consider the behavior of the histogram of the length of the boundaries in the section between lines 9 and 13 corresponding to steps five through eight. Only the interval corresponding to the fourth stage should be sought. To do this, they begin to sort out the values of brightness levels from line 6 in the direction of increase. At the same time, they are looking for the interval at which the absolute value of the cells | HB (L) | histograms 1 of the length of the boundaries are less than the empirically specified limit HB lim . As soon as the value of | HB (L) | for several consecutive levels will go above the limit of HB lim , you need to finish the search. The best level of binarization is found as the middle of the found interval, which corresponds to the arithmetic average of the minimum and maximum acceptable levels of binarization. The found best level is used to binarize a grayscale image (see Fig. 1A) and obtain the final result of binarization (see Fig. 1D).

Однако, этот вариант не опирается на толщину линий в бинаризованном изображении, и не позволяет реализовать дополнительное преимущество, связанное с тем, что заранее известен шрифт, используемый для печати серийного номера. Более сложный, но и более эффективный вариант реализации изобретения использует понятие параметра толщины линии, введенное ранее. Для расчета параметра толщины P(L) используют длину границ B(L), а также количество черных пикселей S(L). Количество черных пикселей S(L) показано кривой 4 на Фиг. 2В, и для заданного уровня L определяется как сумма всех ячеек гистограммы 3 яркости от нулевого уровня до L. По определению, параметр толщины линии вычисляется как

Figure 00000002
.However, this option does not rely on the thickness of the lines in the binarized image, and does not allow to realize the additional advantage associated with the fact that the font used to print the serial number is known in advance. A more complex, but also more effective embodiment of the invention uses the concept of the line thickness parameter introduced earlier. To calculate the thickness parameter P (L), the length of the boundaries B (L) and the number of black pixels S (L) are used. The number of black pixels S (L) is shown by curve 4 in FIG. 2B, and for a given level, L is defined as the sum of all cells of the histogram 3 of brightness from level zero to L. By definition, the line thickness parameter is calculated as
Figure 00000002
.

График P(L) показан кривой 5 на Фиг. 2А. Он не определен при нулевом значении знаменателя, то есть слева от линии 6. В области между линиями 6 и 7 график спадает от начального значения 4,0. Начальное значение 4,0 определяется отношением длины границ к площади для изолированных черных пикселей, которые первыми проявляются в бинаризованном изображении по мере роста порога. Спад графика соответствует образованию кластеров черных пикселей, граница которых растет медленнее площади. Из этих кластеров, при подходе к минимально допустимому значению порога, постепенно формируются линии символов. Уменьшение числа разрывов линий символа соответствует продолжающемуся спаду графика.Graph P (L) is shown by curve 5 in FIG. 2A. It is not defined at a denominator of zero, that is, to the left of line 6. In the area between lines 6 and 7, the graph falls off from the initial value of 4.0. The initial value of 4.0 is determined by the ratio of the length of the borders to the area for isolated black pixels, which first appear in the binarized image as the threshold grows. The decline of the graph corresponds to the formation of clusters of black pixels, the border of which grows slower than the area. From these clusters, when approaching the minimum acceptable threshold value, symbol lines are gradually formed. The decrease in the number of line breaks of the symbol corresponds to the ongoing decline of the graph.

Между линиями 7 и 8, на участке четвертого этапа, символ бинаризуется без существенных разрывов линий и проявлений пикселей фона. График P(L) снижается, отражая рост толщины линий символа по мере роста L. Локальный максимум графика P(L) между линиями 9 и 10 возникает из-за появления мелких изолированных черных пикселей фона на пятом этапе. Эти пиксели значительно увеличивают длину границы. При дальнейшем росте L график продолжает снижаться и выходит на очень малое постоянное значение после линии 13.Between lines 7 and 8, in the section of the fourth stage, the symbol is binarized without significant line breaks and manifestations of background pixels. The P (L) graph decreases, reflecting the increase in the thickness of the symbol lines as L. grows. The local maximum of the P (L) graph between lines 9 and 10 occurs due to the appearance of small isolated black background pixels in the fifth stage. These pixels significantly increase the length of the border. With further growth of L, the graph continues to decline and reaches a very small constant value after line 13.

Путем многократного проведения бинаризации эталонных изображений различных символов цифр шрифта, использованного для печати символов серийного номера израильских шекелей, было определено оптимальное значение параметра ширины линии, равное Popt=0,72. Оно отмечено на Фиг. 2А штриховой линией 15. При этом значении средняя толщина линии в бинаризованном изображении соответствует средней толщине линии печатного эталона шрифта.By repeatedly binarizing reference images of various characters of the numerals of the font used to print the characters of the serial number of Israeli shekels, the optimal value of the line width parameter was determined to be P opt = 0.72. It is noted in FIG. 2A by dashed line 15. With this value, the average line thickness in the binarized image corresponds to the average line thickness of the print font standard.

Для нахождения наилучшего порога бинаризации, двигаются по шкале уровней от линии 6 в сторону возрастания L, и для каждого уровня вычисляют P(L). Как только P(L) станет меньше либо равным оптимальному значению Popt параметра ширины линии, поиск останавливают и используют последнее значение L в качестве наилучшего порога бинаризации. На Фиг. 3А показана точка 14 остановки поиска. Найденный наилучший уровень применяют для бинаризации полутонового изображения (Фиг. 1А) и получения итогового результата бинаризации (Фиг. 1D).To find the best binarization threshold, move along the level scale from line 6 in the direction of increasing L, and P (L) is calculated for each level. As soon as P (L) becomes less than or equal to the optimal value P opt of the line width parameter, the search is stopped and the last value of L is used as the best binarization threshold. In FIG. 3A shows a search stop point 14. The found best level is used for binarization of the grayscale image (Fig. 1A) and obtaining the final result of binarization (Fig. 1D).

Как простой, так и сложный варианты реализации, в ходе поиска порога бинаризации, не достигают значений порога, при которых в бинаризованном изображении в заметной степени появляются черные пиксели, соответствующие фону. Этим обеспечивается независимость результата бинаризации от особенностей фона. Если фон является контрастным и/или многомодовым, но, как бывает в большинстве случаев, его можно отделить от символа при помощи глобального порога, то оба варианта реализации позволяют найти такой порог.Both simple and complex implementations, during the search for the binarization threshold, do not reach the threshold values at which black pixels corresponding to the background appear to a considerable degree in the binarized image. This ensures that the binarization result is independent of the background features. If the background is contrasting and / or multi-mode, but, as happens in most cases, it can be separated from the symbol using a global threshold, then both implementation options allow you to find such a threshold.

Результаты выполнения простого и сложного варианта различаются по обработке пикселей в зоне неопределенности вокруг символа. Простой вариант определяет порог как среднее арифметическое минимального и максимального допустимых значений. Это приблизительное решение обеспечивает практическое отсутствие в бинаризованном изображении разрывов линий символа и черных шумовых пикселей фона, но, не обязательно обеспечивает соответствие эталону средней толщины линий символа. Сложный вариант, дополнительно к отсутствию разрывов линий символа и черных шумовых пикселей фона, обеспечивает соответствие эталону средней толщины линий символа. За счет сохранения эталонной толщины линии, распознавание символов может проводиться с более высокой достоверностью. Простой и сложный варианты реализации незначительно отличаются по времени исполнения, поскольку основное время затрачивается на построение гистограммы 1 длины границ. Время исполнения любого из этих вариантов составляет долю от времени исполнения способа, описанного в прототипе, так как бинаризация с помощью найденного порога проводится однократно, а не множество раз.The results of simple and complex versions differ in processing pixels in the zone of uncertainty around the symbol. A simple option defines the threshold as the arithmetic mean of the minimum and maximum acceptable values. This approximate solution ensures that in the binarized image there are practically no line breaks of the symbol and black noise pixels of the background, but it does not necessarily correspond to the standard of the average thickness of the symbol lines. A complex option, in addition to the absence of line breaks of the symbol and black noise pixels of the background, ensures compliance with the standard of the average thickness of the symbol lines. By maintaining the reference line thickness, character recognition can be performed with higher confidence. Simple and complex implementation options differ slightly in execution time, since most of the time is spent on building a histogram 1 of the border length. The execution time of any of these options is a fraction of the execution time of the method described in the prototype, since binarization using the found threshold is carried out once, and not many times.

Последовательность обработки банкноты с применением заявленного способа в счетно-сортировальной машине показана на Фиг. 6. Машина обеспечивает транспортировку банкнот из подающего кармана, при этом проводится сканирование и распознавание с определением типа банкноты (шаг 201). Если банкнота не распознана, то принимается решение (шаг 210) направить банкноту в карман отбраковки. Это решение реализуется при помощи электромеханического перенаправляющего узла, размещенного в банкнотопроводном тракте счетно-сортировальной машины. Если же банкнота распознана, то выделяют цифровое изображение серийного номера из сканированного образа банкноты и поворачивают его для компенсации перекоса (шаг 203). При выделении изображения, опираются на известное место расположения серийного номера на конкретном типе банкноты.The banknote processing sequence using the inventive method in a counting and sorting machine is shown in FIG. 6. The machine provides transportation of banknotes from the supply pocket, while scanning and recognition is carried out with the determination of the type of banknote (step 201). If the banknote is not recognized, then a decision is made (step 210) to send the banknote to the reject pocket. This solution is implemented using an electromechanical redirecting unit located in the banknote path of a counting and sorting machine. If the banknote is recognized, then a digital image of the serial number is extracted from the scanned banknote image and rotated to compensate for skew (step 203). When selecting images, they rely on the known location of the serial number on a particular type of banknote.

Затем, строят гистограмму длины границ, используя последовательность шагов 100 - 108 (шаг 204). Далее, находят наилучший порог (шаг 205), используя простой либо сложный вариант, описанные ранее. Если используется сложный вариант, на шаге 205, перед выполнением поиска порога, дополнительно строят гистограмму яркости. Найденный наилучший порог применяют для бинаризации изображения (шаг 206).Then, a histogram of the length of the boundaries is constructed using the sequence of steps 100 to 108 (step 204). Next, find the best threshold (step 205) using the simple or complex option described earlier. If a complex version is used, at step 205, before performing a threshold search, a luminance histogram is additionally constructed. The best threshold found is used to binarize the image (step 206).

Распознают полученное бинаризованное изображение (шаг 207) с получением строки серийного номера. Если серийный номер не распознан (шаг 208), то принимают решение о направлении банкноты в карман отбраковки (шаг 210). Если же символ распознан, то направляют банкноту в приемный карман (шаг 209) и записывают серийный номер из массива-строки в электронный отчет о сортировке (шаг 211). Описанную обработку (шаги 201 - 211) повторяют для всех банкнот, находящихся в подающем кармане счетно-сортировальной машины. После этого, распознанные банкноты с успешно распознанным серийным номером оказываются в приемном кармане машины, а в электронном отчете находится список серийных номеров этих банкнот. Банкноты, которые были не распознаны, либо же в серийном номере которых были распознаны не все символы, оказываются в кармане отбраковки. Электронный отчет, содержащий список серийных номеров, может далее использоваться для отслеживания движения банкнот в обороте.The resulting binarized image is recognized (step 207) to obtain a serial number string. If the serial number is not recognized (step 208), then a decision is made on the direction of the banknote in the reject pocket (step 210). If the symbol is recognized, then send the banknote to the receiving pocket (step 209) and write the serial number from the array-string into the electronic sorting report (step 211). The described processing (steps 201 - 211) is repeated for all banknotes located in the feed pocket of the counting and sorting machine. After that, the recognized banknotes with the successfully recognized serial number are in the receiving pocket of the machine, and the electronic report contains a list of serial numbers of these banknotes. Banknotes that were not recognized, or in the serial number of which not all characters were recognized, are in the pocket of rejection. An electronic report containing a list of serial numbers can then be used to track the movement of banknotes in circulation.

Методы, применяемые для распознавания банкноты на шаге 201, выделения изображения серийного номера и его поворота для компенсации перекоса на шаге 203, и распознавания серийного номера на шаге 207, хорошо известны специалистам в области техники для обработки банкнот и широко описаны в патентной литературе.The methods used to recognize the banknote in step 201, extract the image of the serial number and rotate it to compensate for skew in step 203, and recognize the serial number in step 207 are well known to those skilled in the art for processing banknotes and are widely described in the patent literature.

Раскрытый здесь способ не ограничен применением для бинаризации всего серийного номера банкноты целиком. Он также может применяться в устройствах, где полутоновое изображение серийного номера вначале разделяют на отдельные знакоместа, содержащие по одному символу каждый. В этом случае, описанный способ бинаризации может быть применен к изображению каждого знакоместа в отдельности. А именно, для каждого изображения знакоместа должно проводиться построение гистограммы длины границ, нахождение наилучшего порога, и бинаризация с использованием найденного наилучшего порога. Полученные бинаризованные изображения далее должны использоваться для распознавания отдельных символов. Применение заявленного способа к отдельным знакоместам, во многих случаях, позволяет надежно отделить символы от фона даже в тех случаях, когда качественная бинаризация всего серийного номера с помощью глобального порога невозможна. Подобная проблема характерна для банкнот, где серийный номер напечатан полупрозрачной краской на темном контрастном фоне. Яркость пикселей различных символов, напечатанных полупрозрачной краской, сильно зависит от яркости фона и различается для различных знакомест, что приводит к расширению общего градационного интервала яркости пикселей символа. В результате, часто возникает сильное перекрытие градационных интервалов яркости символов и фона в пределах всего номера. Заявленный способ позволяет успешно бинаризовать символы по отдельности, при условии отсутствия существенного перекрытия градационных интервалов яркости символа и фона в пределах каждого из знакомест.The method disclosed herein is not limited to the use of the entire serial number of a banknote for binarization. It can also be used in devices where the grayscale image of the serial number is first divided into separate characters containing one character each. In this case, the described method of binarization can be applied to the image of each familiarity individually. Namely, for each image of familiarity, a histogram of the length of the boundaries, finding the best threshold, and binarization using the found best threshold should be constructed. The resulting binarized images should then be used to recognize individual characters. Application of the claimed method to individual characters, in many cases, allows you to reliably separate the characters from the background even in cases where high-quality binarization of the entire serial number using the global threshold is impossible. A similar problem is typical for banknotes where the serial number is printed in translucent ink on a dark contrasting background. The brightness of the pixels of various symbols printed with translucent ink strongly depends on the brightness of the background and varies for different familiarities, which leads to an extension of the overall gradation interval of brightness of the pixels of the symbol. As a result, often there is a strong overlap of gradation intervals of brightness of characters and background within the entire number. The claimed method allows to successfully binarize the characters individually, provided that there is no significant overlap of the gradation intervals of the brightness of the symbol and background within each of the familiarities.

Claims (31)

1. Способ бинаризации изображений символов на банкноте, в котором получают полутоновое изображение участка банкноты, содержащего по меньшей мере один символ, подлежащий бинаризации, в котором каждый пиксель характеризуется уровнем яркости, и определяют итоговый порог бинаризации и формируют итоговый результат бинаризации, для чего применяют пороговую процедуру с использованием итогового порога бинаризации,1. A method for binarizing symbol images on a banknote, in which a grayscale image of a section of a banknote containing at least one symbol to be binarized is obtained, in which each pixel is characterized by a brightness level, and a final binarization threshold is determined and a final binarization result is generated, for which a threshold procedure using the final binarization threshold, где пороговая процедура является процессом формирования двухуровневого изображения, в котором каждый пиксель соответствует пикселю полутонового изображения,where the threshold procedure is the process of forming a two-level image in which each pixel corresponds to a grayscale image pixel, и имеет один из двух возможных уровней яркости, назначаемый на основе сравнения яркости соответствующего пикселя полутонового изображения с заданным порогом бинаризации, при этомand has one of two possible brightness levels, assigned based on a comparison of the brightness of the corresponding pixel grayscale image with a given threshold for binarization, while для определения итогового порога бинаризации строят гистограмму длины границ указанного полутонового изображения,to determine the final binarization threshold, a histogram of the length of the boundaries of the specified grayscale image is built, для чего задают упорядоченный набор возрастающих значений яркости, возможных в полутоновом изображении,why set an ordered set of increasing brightness values possible in a grayscale image, и, для всех значений яркости в указанном наборе, начиная со значения, следующего за наименьшим, задают значение соответствующей ячейки гистограммы длины границ, как приращение длины границ двухуровневого изображения, получаемого в результате выполнения пороговой процедуры, соответствующее приращению порога, применяемого в пороговой процедуре, до рассматриваемого значения яркости от предшествующего ему значения яркости в указанном наборе,and, for all brightness values in the specified set, starting from the value following the smallest, set the value of the corresponding cell of the histogram of the border length as an increment of the length of the borders of the two-level image obtained as a result of the threshold procedure, corresponding to the increment of the threshold used in the threshold procedure to the considered brightness value from the previous brightness value in the specified set, причем длина границ двухуровневого изображения подсчитывается как сумма длин отрезков, каждый из которых представляет собой пограничный отрезок двух граничащих пикселей с различными уровнями яркости, плюс дополнительная составляющая для учета длины тех сторон пикселей, которые находятся на краю изображения, и по заданному критерию анализируют указанную гистограмму длины границ для нахождения итогового порога бинаризации, при использовании которого результат бинаризации содержит непрерывные линии, содержащиеся в полутоновом изображении участка банкноты.moreover, the length of the boundaries of a two-level image is calculated as the sum of the lengths of the segments, each of which is a boundary segment of two adjacent pixels with different brightness levels, plus an additional component to take into account the length of those sides of the pixels that are on the edge of the image, and the specified histogram of length is analyzed according to a given criterion boundaries for finding the final binarization threshold, when using which the binarization result contains continuous lines contained in a grayscale image zhenii banknote portion. 2. Способ по п. 1, в котором дополнительная составляющая длины границ двухуровневого изображения представляет собой сумму длин тех сторон пикселей двухуровневого изображения с низшим уровнем яркости, которые находятся на краю изображения.2. The method according to claim 1, in which the additional component of the length of the borders of a two-level image is the sum of the lengths of those sides of the pixels of a two-level image with a lower level of brightness that are on the edge of the image. 3. Способ по п. 2, в котором для подсчета гистограммы длины границ полутонового изображения3. The method according to p. 2, in which to calculate the histogram of the length of the borders of the grayscale image первоначально присваивают всем ячейкам гистограммы длины границ нулевые значения, а затемinitially assign to all cells of the histogram of the length of the boundaries zero values, and then анализируют границы между граничащими пикселями, для чего для каждой пары граничащих пикселей полутонового изображения, разделенных пограничным отрезком,analyze the boundaries between adjacent pixels, for which, for each pair of adjacent pixels of a grayscale image, separated by a boundary segment, проводят сравнение яркости пикселей и определяют менее яркий и более яркий пиксель в паре,they compare the brightness of the pixels and determine a less bright and brighter pixel in a pair, после чего увеличивают значение ячейки, соответствующей переходному уровню менее яркого пикселя в паре, на длину пограничного отрезка,then increase the value of the cell corresponding to the transition level of the less bright pixel in the pair by the length of the boundary segment, и уменьшают значение ячейки, соответствующей переходному уровню более яркого пикселя в паре, на длину пограничного отрезка,and reduce the value of the cell corresponding to the transition level of the brighter pixel in the pair by the length of the boundary segment, при этом переходный уровень пикселя представляет собой такой уровень из упорядоченного набора возрастающих значений яркости, при котором значение соответствующего пикселя в двухуровневом изображении, формируемом пороговой процедурой, изменяется при изменении порога, применяемого в пороговой процедуре, до переходного уровня от предшествующего ему уровня в упомянутом упорядоченном наборе,the transitional level of the pixel is such a level from an ordered set of increasing brightness values at which the value of the corresponding pixel in the two-level image formed by the threshold procedure changes when the threshold used in the threshold procedure changes to a transition level from the previous level in the said ordered set , и, для учета дополнительной составляющей длины границ, для каждого пикселя, находящегося на краю изображения, увеличивают значение ячейки гистограммы длины границ, соответствующей переходному уровню этого пикселя, на длину стороны пикселя, находящейся на краю изображения.and, to account for the additional component of the border length, for each pixel located on the edge of the image, increase the cell value of the histogram of the border length corresponding to the transition level of this pixel by the length of the side of the pixel located on the edge of the image. 4. Способ по п. 3, в котором, для совместного проведения анализа длины границ и учета дополнительной составляющей длины границ, рассматривают все пиксели полутонового изображения, таким образом, что для каждого рассматриваемого пикселя определяют накопительную сумму, соответствующую числу границ с менее яркими пикселями, при этом сначала устанавливают накопительную сумму в нулевое значение, а затем если имеется граничащий пиксель, расположенный в строке с меньшим номером, и яркость рассматриваемого пикселя больше либо равна яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка,4. The method according to p. 3, in which, for joint analysis of the length of the borders and taking into account an additional component of the length of the borders, consider all the pixels of the grayscale image, so that for each considered pixel determine the cumulative sum corresponding to the number of borders with less bright pixels, first set the cumulative amount to zero, and then if there is a bordering pixel located in the line with a lower number, and the brightness of the pixel in question is greater than or equal to the brightness of the gran current pixel, then the cumulative amount is increased by the length of the boundary segment, если имеется граничащий пиксель с меньшим номером, расположенный в той же строке, и яркость рассматриваемого пикселя больше либо равна яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка,if there is a bordering pixel with a lower number located on the same line, and the brightness of the pixel in question is greater than or equal to the brightness of the bordering pixel, then the cumulative amount is increased by the length of the boundary segment, если имеется граничащий пиксель, расположенный в строке с большим номером, и яркость рассматриваемого пикселя больше яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка,if there is a bordering pixel located in the line with a large number, and the brightness of the pixel in question is greater than the brightness of the bordering pixel, then the cumulative amount is increased by the length of the boundary segment, если имеется граничащий пиксель с большим номером, расположенный в той же строке, и яркость рассматриваемого пикселя больше яркости граничащего пикселя, то увеличивают накопительную сумму на длину пограничного отрезка, после чего изменяют ячейку гистограммы приращения границ,if there is a bordering pixel with a large number located on the same line, and the brightness of the considered pixel is greater than the brightness of the bordering pixel, then the cumulative sum is increased by the length of the boundary segment, after which the cell of the histogram of the increment of borders is changed, соответствующую переходному уровню рассматриваемого пикселя, на число 4, из которого предварительно вычитается удвоенная накопительная сумма.corresponding to the transitional level of the considered pixel, by the number 4, from which doubled cumulative amount is previously subtracted. 5. Способ по любому из пп. 1-4, в котором, для нахождения итогового порога бинаризации, при использовании которого бинаризованное изображение содержит непрерывные линии,5. The method according to any one of paragraphs. 1-4, in which, to find the final threshold of binarization, when using which the binarized image contains continuous lines, анализируют гистограмму длины границ на предмет нахождения интервала непосредственно следующих друг за другом значений яркости, таких, что значения ячеек гистограммы, соответствующих значениям яркости на указанном интервале, по модулю не превышают заранее заданного предела,analyze the histogram of the length of the boundaries for the determination of the interval immediately following each other brightness values, such that the values of the histogram cells corresponding to the brightness values on the specified interval, modulo do not exceed a predetermined limit, и определяют итоговый порог бинаризации на основе значений конечных точек указанного интервала в соответствии с заранее заданным правилом. and determine the final binarization threshold based on the values of the endpoints of the specified interval in accordance with a predetermined rule. 6. Способ по любому из пп. 1-4, в котором критерий нахождения итогового порога бинаризации обеспечивает квазиоптимальное приближение усредненной толщины линий в итоговом бинаризованном изображении к заданному целевому значению.6. The method according to any one of paragraphs. 1-4, in which the criterion for finding the final binarization threshold provides a quasi-optimal approximation of the average thickness of the lines in the final binarized image to a given target value. 7. Способ по п. 6, в котором7. The method according to p. 6, in which дополнительно формируют гистограмму яркости полутонового изображения, где ячейки соответствуют значениям яркости из упорядоченного набора возрастающих значений яркости, используемого при построении гистограммы длины границ,additionally form a histogram of the brightness of the grayscale image, where the cells correspond to the brightness values from an ordered set of increasing brightness values used in the construction of a histogram of the length of the borders, и, для каждого значения яркости в упорядоченном наборе, задают значение соответствующей ему ячейки как количество пикселей полутонового изображения, переходный уровень которых равен названному значению яркости, а для оценки усредненной толщины линии при пробном значении порога используют параметр толщины, равный отношению суммы всех ячеек гистограммы длины границ на интервале от минимального уровня яркости в наборе до пробного порога к сумме всех ячеек гистограммы яркости на интервале от минимального уровня яркости в упорядоченном наборе до пробного порога,and, for each brightness value in the ordered set, the value of the corresponding cell is set as the number of pixels of a grayscale image whose transition level is equal to the named brightness value, and to estimate the average line thickness at the trial threshold value, a thickness parameter equal to the ratio of the sum of all cells of the length histogram is used boundaries in the interval from the minimum brightness level in the set to the test threshold to the sum of all cells of the brightness histogram in the interval from the minimum brightness level in the ordered abortion to a trial threshold, и, по заданному правилу, в качестве итогового порога бинаризации выбирают такой пробный порог,and, according to a given rule, such a trial threshold is selected as the final binarization threshold, при котором параметр толщины близок к целевому значению,at which the thickness parameter is close to the target value, причем указанное целевое значение заранее выбирают для уменьшения погрешности воспроизведения символа в итоговом результате бинаризации на основе известных начертаний тех символов, которые могут располагаться в пределах участка банкноты.moreover, the specified target value is pre-selected to reduce the error in the reproduction of the character in the final binarization result based on the known styles of those characters that can be located within the banknote section.
RU2019134234A 2019-10-25 2019-10-25 Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries RU2718571C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2019134234A RU2718571C1 (en) 2019-10-25 2019-10-25 Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2019134234A RU2718571C1 (en) 2019-10-25 2019-10-25 Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries

Publications (1)

Publication Number Publication Date
RU2718571C1 true RU2718571C1 (en) 2020-04-08

Family

ID=70156638

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2019134234A RU2718571C1 (en) 2019-10-25 2019-10-25 Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries

Country Status (1)

Country Link
RU (1) RU2718571C1 (en)

Cited By (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN112364876A (en) * 2020-11-25 2021-02-12 北京紫光青藤微系统有限公司 Efficient bar code binarization method and system
CN112364876B (en) * 2020-11-25 2024-05-14 北京紫光青藤微系统有限公司 Efficient bar code binarization method and system

Citations (4)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
JPH0877300A (en) * 1994-08-31 1996-03-22 Canon Inc Image processor
US9367899B1 (en) * 2015-05-29 2016-06-14 Konica Minolta Laboratory U.S.A., Inc. Document image binarization method
RU2641225C2 (en) * 2014-01-21 2018-01-16 Общество с ограниченной ответственностью "Аби Девелопмент" Method of detecting necessity of standard learning for verification of recognized text
CN109190632A (en) * 2018-08-23 2019-01-11 甘肃政法学院 A kind of binarization method of ancient books file and picture

Patent Citations (4)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
JPH0877300A (en) * 1994-08-31 1996-03-22 Canon Inc Image processor
RU2641225C2 (en) * 2014-01-21 2018-01-16 Общество с ограниченной ответственностью "Аби Девелопмент" Method of detecting necessity of standard learning for verification of recognized text
US9367899B1 (en) * 2015-05-29 2016-06-14 Konica Minolta Laboratory U.S.A., Inc. Document image binarization method
CN109190632A (en) * 2018-08-23 2019-01-11 甘肃政法学院 A kind of binarization method of ancient books file and picture

Cited By (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN112364876A (en) * 2020-11-25 2021-02-12 北京紫光青藤微系统有限公司 Efficient bar code binarization method and system
CN112364876B (en) * 2020-11-25 2024-05-14 北京紫光青藤微系统有限公司 Efficient bar code binarization method and system

Similar Documents

Publication Publication Date Title
Gatos et al. Automatic table detection in document images
Yang et al. An adaptive logical method for binarization of degraded document images
CN102509383B (en) Feature detection and template matching-based mixed number identification method
KR100472887B1 (en) Image processing method and apparatus using self-adaptive binarization
Ye et al. Stroke-model-based character extraction from gray-level document images
US20070253040A1 (en) Color scanning to enhance bitonal image
US20080310721A1 (en) Method And Apparatus For Recognizing Characters In A Document Image
US11836969B2 (en) Preprocessing images for OCR using character pixel height estimation and cycle generative adversarial networks for better character recognition
US20160014300A1 (en) Image Binarization
Boiangiu et al. Voting-based OCR system
US9342892B2 (en) Image binarization
Al Abodi et al. An effective approach to offline Arabic handwriting recognition
Michalak et al. Fast Binarization of Unevenly Illuminated Document Images Based on Background Estimation for Optical Character Recognition Purposes.
US8311331B2 (en) Resolution adjustment of an image that includes text undergoing an OCR process
Boudraa et al. An improved skew angle detection and correction technique for historical scanned documents using morphological skeleton and progressive probabilistic hough transform
Liu et al. An object attribute thresholding algorithm for document image binarization
RU2718571C1 (en) Method for binarisation of images of symbols on a banknote based on histogram of length of boundaries
Ahn et al. Textline detection in degraded historical document images
Polyakova et al. Improvement of the Color Text Image Binarization Methodusing the Minimum-Distance Classifier
Wei et al. Investigation of feature selection for historical document layout analysis
Bloomberg et al. Document image applications
RU2520407C1 (en) Method and system of text improvement at digital copying of printed documents
Sulaiman et al. An Efficient Phase-Based Binarization Method for Degraded Historical Documents
Wachenfeld et al. Segmentation of very low resolution screen-rendered text
Brodić et al. An approach to skew detection of printed documents