RU2626661C1 - Method and subsystem of determining digital images of fragments containing documents - Google Patents

Method and subsystem of determining digital images of fragments containing documents Download PDF

Info

Publication number
RU2626661C1
RU2626661C1 RU2016125288A RU2016125288A RU2626661C1 RU 2626661 C1 RU2626661 C1 RU 2626661C1 RU 2016125288 A RU2016125288 A RU 2016125288A RU 2016125288 A RU2016125288 A RU 2016125288A RU 2626661 C1 RU2626661 C1 RU 2626661C1
Authority
RU
Russia
Prior art keywords
contours
digital image
image
processing subsystem
image processing
Prior art date
Application number
RU2016125288A
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 RU2016125288A priority Critical patent/RU2626661C1/en
Priority to US15/195,759 priority patent/US10503997B2/en
Priority to US15/195,726 priority patent/US10387744B2/en
Application granted granted Critical
Publication of RU2626661C1 publication Critical patent/RU2626661C1/en

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F40/00Handling natural language data
    • G06F40/10Text processing
    • G06F40/166Editing, e.g. inserting or deleting
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06TIMAGE DATA PROCESSING OR GENERATION, IN GENERAL
    • G06T11/002D [Two Dimensional] image generation

Landscapes

  • Image Processing (AREA)
  • Image Analysis (AREA)

Abstract

FIELD: physics.
SUBSTANCE: contours in the digital image are determined, the detected contours are divided into four sets of contours corresponding to four different sides in the original digital image, hypotheses about the edges or boundaries of the fragment of the digital image containing the document are constructed based on these contours and hypotheses are evaluated for choosing hypotheses with the highest estimates for representing the boundaries of the fragment of the digital image containing a document in the original digital image obtained.
EFFECT: enabling the detection of document fragments of a digital image.
22 cl, 48 dwg

Description

ОБЛАСТЬ ТЕХНИКИFIELD OF TECHNOLOGY

В настоящем документе рассматривается обработка изображений и, в частности, способ и система для определения содержащего документ фрагмента цифрового изображения при подготовке к различным типам последующей автоматизированной обработки цифрового изображения, включая оптическое распознавание символов.This document discusses image processing and, in particular, a method and system for determining a document-containing fragment of a digital image in preparation for various types of subsequent automated processing of a digital image, including optical character recognition.

УРОВЕНЬ ТЕХНИКИBACKGROUND

Печатные документы на естественном языке до сих пор являются широко распространенным средством коммуникации между людьми, в организациях и используются для донесения информации до ее потребителей. С появлением повсеместно используемых мощных вычислительных ресурсов, включая персональные вычислительные ресурсы, реализованные в смартфонах, планшетах, ноутбуках и персональных компьютерах, а также с распространением более мощных вычислительных ресурсов облачных вычислительных сервисов, центров обработки данных и корпоративных серверов организаций и предприятий, шифрование и обмен информацией на естественном языке все чаще выполняется в виде электронных документов. Печатные документы по своей сути представляют собой изображения, в то время как электронные документы содержат последовательности цифровых кодов символов и знаков на естественном языке. Поскольку электронные документы имеют перед печатными документами преимущества по стоимости, возможностям передачи и рассылки, простоте редактирования и изменения, а также по надежности хранения, за последние 50 лет развилась целая отрасль, поддерживающая способы и системы преобразования печатных документов в электронные. Компьютерные способы и системы оптического распознавания символов совместно с электронными сканерами обеспечивают надежное и экономичное получение изображений печатных документов и компьютерную обработку получаемых цифровых изображений, содержащих текст, для создания электронных документов, соответствующих печатным.Printed documents in natural language are still a widespread means of communication between people in organizations and are used to convey information to its consumers. With the advent of ubiquitous powerful computing resources, including personal computing resources implemented in smartphones, tablets, laptops and personal computers, as well as with the spread of more powerful computing resources of cloud computing services, data centers and corporate servers of organizations and enterprises, encryption and exchange of information in natural language is increasingly performed in the form of electronic documents. Printed documents are inherently images, while electronic documents contain sequences of digital codes of characters and signs in a natural language. Since electronic documents have advantages over printed documents in terms of cost, transfer and distribution capabilities, ease of editing and modification, as well as storage reliability, an entire industry has developed over the past 50 years that supports methods and systems for converting printed documents into electronic ones. Computer methods and optical character recognition systems in conjunction with electronic scanners provide reliable and economical acquisition of images of printed documents and computer processing of digital images containing text to create electronic documents corresponding to printed ones.

РАСКРЫТИЕ ИЗОБРЕТЕНИЯSUMMARY OF THE INVENTION

В настоящем документе рассматриваются автоматизированные способы и системы, управляемые различными ограничениями и параметрами, с помощью которых определяются содержащие документ фрагменты цифрового изображения. Некоторые из параметров ограничивают определение контура и построение гипотез о содержащем документ фрагменте цифрового изображения. С помощью способов и систем настоящего изобретения определяются контуры на цифровом изображении, выявленные контуры делятся на четыре множества контуров, соответствующих четырем различным сторонам в исходном цифровом изображении, на основе этих контуров строятся гипотезы о краях или границах фрагмента цифрового изображения, содержащего документ, и выполняется оценка гипотез для выбора гипотез с самыми высокими оценками для представления границ фрагмента цифрового изображения, содержащего документ, в исходном цифровом изображении.This document discusses automated methods and systems controlled by various constraints and parameters by which fragments of a digital image containing a document are determined. Some of the parameters limit the definition of the contour and hypothesis about the document fragment of the digital image. Using the methods and systems of the present invention, the contours in a digital image are determined, the identified contours are divided into four sets of contours corresponding to four different sides in the original digital image, based on these contours hypotheses about the edges or boundaries of a fragment of a digital image containing a document are constructed, and an estimate is made hypotheses for selecting hypotheses with the highest ratings for representing the boundaries of a fragment of a digital image containing the document in the original digital image.

КРАТКОЕ ОПИСАНИЕ ЧЕРТЕЖЕЙBRIEF DESCRIPTION OF THE DRAWINGS

На Фиг. 1 представлена структурная схема вычислительной системы высокого уровня, например, вычислительной системы, в которой применяется раскрываемый способ определения содержащего документ фрагмента цифрового изображения.In FIG. 1 is a structural diagram of a high-level computing system, for example, a computing system that employs the disclosed method for determining a document-containing fragment of a digital image.

На Фиг. 2A-D показаны два разных типа портативных устройств получения изображений.In FIG. 2A-D show two different types of portable imaging devices.

На Фиг. 3 показано типовое изображение с цифровым кодированием.In FIG. 3 shows a typical digitally encoded image.

На Фиг. 4 показан один вариант цветовой модели RGB.In FIG. 4 shows one embodiment of the RGB color model.

На Фиг. 5 показана другая цветовая модель «оттенок-насыщенность-светлота» («HSL»).In FIG. Figure 5 shows another hue-saturation-lightness (HSL) color model.

На Фиг. 6 показано формирование серого или бинарного изображения из цветного изображения.In FIG. 6 shows the formation of a gray or binary image from a color image.

На Фиг. 7 показано дискретное вычисление градиента яркости.In FIG. 7 shows a discrete calculation of the brightness gradient.

На Фиг. 8 показан градиент, рассчитанный для точки на непрерывной поверхности.In FIG. Figure 8 shows the gradient calculated for a point on a continuous surface.

На Фиг. 9 показан ряд примеров градиента яркости.In FIG. 9 shows a number of examples of the brightness gradient.

На Фиг. 10 показано применение ядра к изображению.In FIG. 10 shows the application of the kernel to an image.

На Фиг. 11 показана свертка изображения.In FIG. 11 shows a convolution of the image.

На Фиг. 12 показан некоторый пример ядра и методики обработки изображений на основе ядра.In FIG. 12 shows some example of a kernel and kernel-based image processing techniques.

На Фиг. 13 и 14 показан общий подход к определению контура.In FIG. 13 and 14 show a general approach to determining the contour.

На Фиг. 15-26 показан частный вариант реализации способа и подсистемы обнаружения контуров.In FIG. 15-26 shows a particular embodiment of the method and subsystem for detecting loops.

На Фиг. 27A-G с помощью блок-схем показан один из вариантов реализации способа и подсистемы обнаружения контуров.In FIG. 27A-G, using flowcharts, one embodiment of a method and a loop detection subsystem is shown.

На Фиг. 28 показан пример сценария обработки изображения, в котором автоматизированная система обработки изображений пытается определить содержащий документ фрагмент цифрового изображения.In FIG. 28 shows an example of an image processing scenario in which an automated image processing system attempts to determine a document-containing fragment of a digital image.

На Фиг. 29 показан первый этап автоматизированного процесса распознавания документов.In FIG. 29 shows the first step of an automated document recognition process.

На Фиг. 30 представлены два дополнительных этапа в процессе распознавания изображений документов.In FIG. 30 presents two additional steps in the process of image recognition of documents.

На Фиг. 31 показано построение гипотезы на основе четырех множеств контуров, рассматриваемых на Фиг. 30.In FIG. 31 shows the construction of a hypothesis based on the four sets of contours considered in FIG. thirty.

На Фиг. 32 показан ряд соображений и критериев для выбораIn FIG. 32 shows a number of considerations and criteria for choosing

кандидатов.candidates.

На Фиг. 33 и 34 представлен расчет значения показателя веса стороны с целью построения гипотезы.In FIG. 33 and 34 presents the calculation of the value of the side weight indicator in order to build a hypothesis.

На Фиг. 35А-Е приведены блок-схемы, на которых показан вариант реализации способа и системы определения документа, к которой относится настоящий документ.In FIG. 35A-E are flow charts showing an embodiment of a method and system for defining a document to which this document relates.

ОПИСАНИЕ ПРЕДПОЧТИТЕЛЬНЫХ ВАРИАНТОВ РЕАЛИЗАЦИИDESCRIPTION OF PREFERRED EMBODIMENTS

Настоящий документ относится к способам и системам определения контуров, включая криволинейные контуры, на цифровых изображениях для использования в последующих задачах обработки цифровых изображений, включая оптическое распознавание символов. В первом подразделе ниже приводится краткое введение в архитектуру вычислительной системы, цифровые изображения и способы обработки цифровых изображений со ссылками на Фиг. 1-12. Во втором подразделе приводится подробное описание способов и систем обнаружения контуров со ссылками на Фиг. 13-27G. В итоговом подразделе приводится одна из возможных реализаций способов и систем настоящего изобретения, которая иллюстрируется блок-схемами со ссылками на Фиг. 28-35Е.This document relates to methods and systems for determining contours, including curved contours, in digital images for use in subsequent digital image processing tasks, including optical character recognition. The first subsection below provides a brief introduction to the architecture of a computing system, digital images, and digital image processing methods with reference to FIG. 1-12. The second subsection provides a detailed description of the loop detection methods and systems with reference to FIG. 13-27G. The final subsection provides one possible implementation of the methods and systems of the present invention, which is illustrated in block diagrams with reference to FIG. 28-35E.

ОбзорOverview

На Фиг. 1 приведена схема архитектуры вычислительной системы верхнего уровня, подобной той вычислительной системе, на которой реализован раскрываемый в текущем документе способ определения содержащих документ фрагментов цифрового изображения. Мобильные устройства получения изображений, включая смартфоны и цифровые камеры, могут быть изображены на диаграмме аналогичным образом, а также могут содержать процессоры, память и внутренние шины. Знакомым с современной наукой и технологиями будет понятно, что программы или подпрограммы управления, содержащие машинные команды, которые хранятся в физической памяти устройства под управлением процессора, представляют компонент управления устройством и являются настолько же физическими, материальными и важными, как и любой другой компонент электромеханического устройства, включая устройства получения изображений. Компьютерная система содержит один или более центральных процессоров (ЦП) 102-105, один или более электронных модулей памяти 108, взаимосвязанных с ЦП через шину подсистемы ЦП/памяти 110 или несколько шин, первый мост 112, который соединяет шину подсистемы ЦП/памяти 110 с дополнительными шинами 114 и 116, либо другие виды средств высокоскоростного соединения, в том числе множественные высокоскоростные последовательные соединения. Эти шины или последовательные соединения, в свою очередь, соединяют ЦП и память со специализированными процессорами, такими как графический процессор 118, а также с одним или более дополнительными мостами 120, взаимосвязанными с высокоскоростными последовательными соединениями или несколькими контроллерами 122-127, например с контроллером 127, который предоставляет доступ к различным типам запоминающих устройств большой емкости 128, электронным дисплеям, устройствам ввода и другим подобным компонентам, подкомпонентам и вычислительным ресурсам.In FIG. 1 is a diagram of a top-level computing system architecture similar to that of a computing system that implements the method for determining digital document fragments contained in a document disclosed in the current document. Mobile imaging devices, including smartphones and digital cameras, can be graphically displayed in the same way, and can also contain processors, memory, and internal buses. Those familiar with modern science and technology will understand that control programs or routines containing machine instructions stored in the physical memory of the device under the control of the processor represent the device control component and are as physical, material and important as any other component of the electromechanical device including imaging devices. A computer system comprises one or more central processing units (CPUs) 102-105, one or more electronic memory modules 108 interconnected with a CPU via a CPU / memory subsystem bus 110 or several buses, a first bridge 112 that connects a CPU / memory subsystem bus 110 s additional buses 114 and 116, or other types of means of high-speed connections, including multiple high-speed serial connections. These buses or serial connections, in turn, connect the CPU and memory to specialized processors, such as the graphics processor 118, as well as to one or more additional bridges 120, interconnected with high-speed serial connections or several controllers 122-127, for example, with the controller 127 , which provides access to various types of mass storage devices 128, electronic displays, input devices, and other similar components, subcomponents, and computing resources m.

На Фиг. 2A-D показаны два типа портативных устройств получения изображений. На Фиг. 2А-С показана цифровая камера 202. Цифровая камера содержит объектив 204, кнопку спуска затвора 205, нажатие которой пользователем приводит к получению цифрового изображения, которое соответствует отраженному свету, поступающему в объектив 204 цифровой камеры. С задней стороны цифровой камеры, которая видна пользователю, когда он держит камеру при съемке цифровых изображений, находится видоискатель 206 и жидкокристаллический дисплей видоискателя 208. С помощью видоискателя 206 пользователь может напрямую просматривать создаваемое объективом 204 камеры изображение, а с помощью жидкокристаллического дисплея 208 - просматривать электронное отображение создаваемого в настоящей момент объективом изображения. Обычно пользователь камеры настраивает фокус камеры с помощью кольца фокусировки 210, смотря при этом через видоискатель 206 или рассматривая изображение на жидкокристаллическом дисплее 208 для выбора требуемого изображения перед нажатием на кнопку 105 спуска затвора с целью цифрового получения изображения и сохранения изображения в электронной памяти цифровой камеры.In FIG. 2A-D show two types of portable image acquisition devices. In FIG. 2A-C, a digital camera 202 is shown. A digital camera includes a lens 204, a shutter button 205, which is pressed by the user to produce a digital image that corresponds to the reflected light entering the digital camera lens 204. On the back of the digital camera, which is visible to the user when he is holding the camera when shooting digital images, is the viewfinder 206 and the liquid crystal display of the viewfinder 208. Using the viewfinder 206, the user can directly view the image created by the camera lens 204, and use the liquid crystal display 208 to view electronic display of the image currently being created by the lens. Typically, the camera user adjusts the focus of the camera using the focus ring 210, while looking through the viewfinder 206 or viewing the image on the liquid crystal display 208 to select the desired image before pressing the shutter button 105 to digitally acquire the image and store the image in the electronic memory of the digital camera.

На Фиг. 2D показан типовой смартфон с передней стороны 220 и задней стороны 222. На задней стороне 222 имеется объектив 224 цифровой камеры и датчик приближения и(или) цифровой экспонометр 226. На передней стороне смартфона 220 под управлением приложения может отображаться получаемое изображение 226, аналогично работе жидкокристаллического дисплея 208 видоискателя цифровой камеры, а также сенсорная кнопка 228 спуска затвора, при прикосновении к которой происходит получение цифрового изображения и сохранение его в памяти смартфона.In FIG. 2D shows a typical smartphone on the front side 220 and the back side 222. On the back side 222 there is a digital camera lens 224 and a proximity sensor and (or) a digital exposure meter 226. On the front side of the smartphone 220, the resulting image 226 can be displayed under the control of the application, similar to the operation of a liquid crystal the digital camera viewfinder display 208, as well as the touch shutter button 228, when touched, a digital image is received and stored in the smartphone's memory.

На Фиг. 3 показано типовое изображение с цифровым кодированием. Кодированное изображение включает двумерный массив пикселей 302. На Фиг. 3 каждый небольшой квадрат, например, квадрат 304, является пикселем, который обычно определяется как наименьшая часть детализации изображения, для которой предусматривается цифровая кодировка. Каждый пиксель представляет собой место, обычно представленное парой цифровых значений, соответствующих значениям на осях прямоугольной систем координат х и у, 306 и 308 соответственно. Таким образом, например, пиксель 304 имеет координаты х, у (39,0), а пиксель 312 - координаты (0,0). В цифровой кодировке пиксель представлен числовыми значениями, указывающими на то, как область изображения, соответствующая пикселю, представляется при печати, отображается на экране компьютера или ином дисплее. Обычно для черно-белых изображений для представления каждого пикселя используется единичное значение в интервале от 0 до 255 с числовым значением, соответствующем уровню серого, на котором передается пиксель. В общепринятом понимании значение «0» соответствует черному цвету, а значение «255» - белому. Для цветных изображений может применяться множество различных числовых значений, указывающих на цвет. В одной из стандартных цветовых моделей, показанной на Фиг. 3, каждый пиксель связан с тремя значениями или координатами (r, g, b), которые указывают на яркость красного, зеленого и синего компонента цвета, отображаемого в соответствующей пикселю области.In FIG. 3 shows a typical digitally encoded image. The encoded image includes a two-dimensional array of pixels 302. In FIG. 3, each small square, for example, square 304, is a pixel, which is usually defined as the smallest part of the image detail for which digital encoding is provided. Each pixel represents a place, usually represented by a pair of digital values corresponding to the values on the axes of the rectangular coordinate systems x and y, 306 and 308, respectively. Thus, for example, pixel 304 has x, y coordinates (39.0), and pixel 312 has coordinates (0,0). In digital encoding, a pixel is represented by numerical values that indicate how the image area corresponding to the pixel is displayed during printing, displayed on a computer screen or other display. Typically, for black-and-white images, a single value in the range from 0 to 255 is used to represent each pixel with a numerical value corresponding to the gray level at which the pixel is transmitted. In the common sense, the value “0” corresponds to black, and the value “255” corresponds to white. For color images, many different numerical values can be used to indicate color. In one of the standard color models shown in FIG. 3, each pixel is associated with three values or coordinates (r, g, b) that indicate the brightness of the red, green, and blue component of the color displayed in the corresponding pixel region.

На Фиг. 4 показан один из вариантов цветовой модели RGB. Тремя координатами основных цветов (r, g, b) представлен весь спектр цветов, как было показано выше со ссылкой на Фиг. 3. Цветовая модель может считаться соответствующей точкам в пределах единичного куба 402, в котором трехмерное цветовое пространство определяется тремя осями координат: (1) r 404; (2) g 406; и (3) b 408. Таким образом, координаты отдельного цвета находятся в интервале от 0 до 1 по каждой из трех цветовых осей. Например, чистый синий цвет максимально возможной яркости соответствует точке 410 по оси b с координатами (0,0,1). Белый цвет соответствует точке 412 с координатами (1,1,1,), а черный цвет - точке 414, началу системы координат с координатами (0,0,0).In FIG. 4 shows one of the options for the RGB color model. The three coordinates of the primary colors (r, g, b) represent the entire spectrum of colors, as shown above with reference to FIG. 3. The color model can be considered corresponding to the points within the unit cube 402, in which the three-dimensional color space is determined by three coordinate axes: (1) r 404; (2) g 406; and (3) b 408. Thus, the coordinates of a single color are in the range from 0 to 1 along each of the three color axes. For example, the pure blue color of the maximum possible brightness corresponds to point 410 along the b axis with coordinates (0,0,1). White color corresponds to point 412 with coordinates (1,1,1,), and black color corresponds to point 414, the beginning of the coordinate system with coordinates (0,0,0).

На Фиг. 5 показана другая цветовая модель «Оттенок-насыщенность-светлота» («HSL»). В этой цветовой модели цвета содержатся в трехмерной бипирамидальной призме 500 с шестигранным сечением. Оттенок (h) связан с доминантной длиной волны излучения света, воспринимаемого наблюдателем. Значение оттенка находится в интервале от 0° до 360°, начиная с красного цвета 502 в точке 0°, проходя через зеленый 504 в точке 120°, синий 506 в точке 240°, и заканчивая красным 502 в точке 660°. Насыщенность (s), находящаяся в интервале от 0 до 1, обратно связана с количеством белого и черного цвета, смешанного при определенной длине волны или оттенке. Например, чистый красный цвет 502 является полностью насыщенным при насыщенности s=1,0, в то же время розовый цвет имеет насыщенность менее 1,0, но более 0,0, белый цвет 508 является полностью ненасыщенным с s=0,0, а черный цвет 510 также является полностью ненасыщенным с s=0,0. Полностью насыщенные цвета находятся на периметре среднего шестигранника, содержащего точки 502, 504 и 506. Шкала оттенков серого проходит от черного 510 до белого 508 по центральной вертикальной оси 512, представляющей полностью ненасыщенные цвета без оттенка, но с различными пропорциями черного и белого. Например, черный 510 содержит 100% черного и не содержит белого, белый 508 содержит 100% белого и не содержит черного, а исходная точка 513 содержит 50% черного и 50% белого. Светлота (

Figure 00000001
), представленная центральной вертикальной осью 512, указывает на уровень освещенности в интервале от 0 для черного 510, при
Figure 00000001
=0,0, до 1 для белого 508, при
Figure 00000001
=1,0. Для произвольного цвета, представленного на Фиг. 5 точкой 514, оттенок определяется как угол θ 516, между первым вектором из исходной точки 513 к точке 502 и вторым вектором из исходной точки 513 к точке 520, в которой вертикальная линия 522, проходящая через точку 514, пересекает плоскость 524, включающую исходную точку 513 и точки 502, 504 и 506. Насыщенность представлена отношением расстояния представленной точки 514 от вертикальной оси 512 d' к длине горизонтальной линии, проходящей через точку 520 от исходной точки 513 к поверхности бипирамидальной призмы 500, d. Светлота представлена вертикальным расстоянием от представленной точки 514 до вертикального уровня точки 510, представляющей черный цвет. Координаты конкретного цвета в цветовой модели HSL (h, s,
Figure 00000001
) могут быть получены на основе координат цвета в цветовой модели RGB (r, g, b) следующим образом:In FIG. 5 shows another hue-saturation-lightness (HSL) color model. In this color model, colors are contained in a three-dimensional bipyramidal prism 500 with a hexagonal cross section. Hue (h) is associated with the dominant wavelength of the light emitted by the observer. The hue value is in the range from 0 ° to 360 °, starting from red 502 at 0 °, passing through green 504 at 120 °, blue 506 at 240 °, and ending in red 502 at 660 °. Saturation (s) ranging from 0 to 1 is inversely related to the amount of white and black mixed at a specific wavelength or hue. For example, the pure red color 502 is fully saturated at a saturation of s = 1.0, while the pink color has a saturation of less than 1.0, but more than 0.0, the white color 508 is completely unsaturated with s = 0.0, and black 510 is also completely unsaturated with s = 0,0. Fully saturated colors are located on the perimeter of the middle hexagon containing points 502, 504, and 506. The grayscale scale runs from black 510 to white 508 along the central vertical axis 512, which represents completely unsaturated colors without a hue, but with different proportions of black and white. For example, black 510 contains 100% black and does not contain white, white 508 contains 100% white and does not contain black, and the starting point 513 contains 50% black and 50% white. Lightness (
Figure 00000001
), represented by the central vertical axis 512, indicates the level of illumination in the range from 0 for black 510, at
Figure 00000001
= 0.0, up to 1 for white 508, with
Figure 00000001
= 1.0. For the arbitrary color shown in FIG. 5 by point 514, the hue is defined as the angle θ 516, between the first vector from the starting point 513 to the point 502 and the second vector from the starting point 513 to the point 520, at which the vertical line 522 passing through the point 514 intersects the plane 524 including the starting point 513 and points 502, 504 and 506. Saturation is represented by the ratio of the distance of the represented point 514 from the vertical axis 512 d ′ to the length of the horizontal line passing through point 520 from the starting point 513 to the surface of the bipyramidal prism 500, d. Brightness is represented by the vertical distance from the represented point 514 to the vertical level of the point 510, representing black color. Specific color coordinates in the HSL color model (h, s,
Figure 00000001
) can be obtained based on the color coordinates in the RGB color model (r, g, b) as follows:

Figure 00000002
Figure 00000002

где значения r, g и b соответствуют яркости красного, зеленого и синего первичных цветов, нормализованных на интервале [0, 1]; Cmax представляет нормализованное значение яркости, равное максимальному значению из r, g и b; Cmin представляет собой нормализованное значение яркости, равное минимальному значению из r, g и b; а Δ определяется как Cmax-Cmin.where the values of r, g and b correspond to the brightness of red, green and blue primary colors, normalized to the interval [0, 1]; C max represents the normalized brightness value equal to the maximum value of r, g and b; C min is the normalized brightness value equal to the minimum value of r, g and b; and Δ is defined as C max -C min .

На Фиг. 6 показано формирование полутонового или бинарного изображения из цветного изображения. В цветном изображении каждый пиксель обычно связан с тремя значениями: а, b и с 602. Разные цветовые модели используют для представления конкретного цвета разные значения а, b и с. Полутоновое изображение содержит для каждого пикселя только одно значение яркости 604. Бинарное изображение является частным случаем полутонового изображения, которое имеет только два значения яркости «0» и «1». Обычно серые изображения могут иметь 256 или 65 536 разных значений яркости для каждого пикселя, представленного байтом или 16-битным словом соответственно. Таким образом, чтобы преобразовать цветное изображение в полутоновое, три значения а, b и с цветных пикселей необходимо преобразовать в одно значение яркости для полутонового или бинарного изображения. На первом шаге три значения цвета а, b и с, преобразуются в значение яркости L, обычно в интервале [0,0, 1,0] 606. Для определенных цветовых моделей к каждому из цветовых значений 608 применяется функция, и результаты суммируются 610, давая значение яркости. В других цветовых моделях каждое цветовое значение умножается на коэффициент, и полученные результаты суммируются 612, давая значение яркости. В некоторых цветовых системах одно из трех цветовых значений является, фактически, значением 614 яркости. Наконец, в общем случае к трем цветовым значениям 616 применяется функция, которая дает значение яркости. Затем значение яркости квантуется 618, позволяя получить значение яркости оттенков серого в требуемом интервале, обычно [0, 255] для полутоновых изображений и (0,1) для бинарных изображений.In FIG. 6 shows the formation of a grayscale or binary image from a color image. In a color image, each pixel is usually associated with three values: a, b, and 602. Different color models use different values of a, b, and c to represent a particular color. A grayscale image contains for each pixel only one brightness value 604. A binary image is a special case of a grayscale image that has only two brightness values “0” and “1”. Typically, gray images can have 256 or 65,536 different brightness values for each pixel represented by a byte or 16-bit word, respectively. Thus, in order to convert a color image to a grayscale, the three values a, b and c of color pixels must be converted to a single brightness value for a grayscale or binary image. In the first step, the three color values a, b, and c are converted to the brightness value L, usually in the range [0,0, 1,0] 606. For certain color models, a function is applied to each of the color values 608, and the results are summed 610, giving a brightness value. In other color models, each color value is multiplied by a coefficient, and the results are added up 612, giving the brightness value. In some color systems, one of the three color values is, in fact, a brightness value of 614. Finally, in the general case, a function that gives a brightness value is applied to the three color values 616. Then, the brightness value is quantized 618, allowing you to get the brightness value of the shades of gray in the desired interval, usually [0, 255] for grayscale images and (0,1) for binary images.

На Фиг. 7 показано дискретное вычисление градиента яркости. На Фиг. 7 показан небольшой квадратный участок 702 цифрового изображения. Каждая клетка, например, клетка 704, представляет пиксель, а числовое значение в клетке, например, значение «106» в клетке 704, представляет яркость серого цвета. Допустим, пиксель 706 имеет значение яркости «203». Этот пиксель и четыре смежных с ним пикселя показаны на крестообразной схеме 708 справа от участка 702 цифрового изображения. Рассматривая левый 710 и правый 712 соседние пиксели, изменение значения яркости в направлении х, Δх можно дискретно вычислить как:In FIG. 7 shows a discrete calculation of the brightness gradient. In FIG. 7 shows a small square portion 702 of a digital image. Each cell, for example, cell 704, represents a pixel, and a numerical value in the cell, for example, the value "106" in cell 704, represents a gray brightness. Suppose a pixel 706 has a brightness value of “203”. This pixel and four adjacent pixels are shown in a cruciform pattern 708 to the right of the digital image portion 702. Considering the neighboring pixels to the left 710 and right 712, the change in the brightness value in the x, Δx direction can be discretely calculated as:

Figure 00000003
Figure 00000003

Рассматривая нижний 714 и верхний 716 соседние пиксели, изменение значения яркости в вертикальном направлении Δу можно вычислить как:Considering the lower 714 and upper 716 adjacent pixels, the change in the brightness value in the vertical direction Δy can be calculated as:

Figure 00000004
Figure 00000004

Вычисленное значение Δх является оценкой частного дифференциала непрерывной функции яркости относительно оси х в центральном пикселе 706:The calculated Δx value is an estimate of the partial differential of the continuous brightness function with respect to the x axis in the central pixel 706:

Figure 00000005
Figure 00000005

Частный дифференциал функции F относительно координаты у в центральном пикселе 706 рассчитывается по Δу:The partial differential of the function F relative to the coordinate у in the central pixel 706 is calculated by Δу:

Figure 00000006
Figure 00000006

Градиент яркости в пикселе 706 может быть рассчитан следующим образом:The brightness gradient in the pixel 706 can be calculated as follows:

Figure 00000007
Figure 00000007

где i и j представляют собой единичные векторы в направлениях х и у. Модуль вектора градиента и угол вектора градиента далее рассчитываются следующим образом:where i and j are unit vectors in the x and y directions. The modulus of the gradient vector and the angle of the gradient vector are further calculated as follows:

Figure 00000008
Figure 00000008

Направление вектора 720 градиента яркости и угол θ 722 показаны наложенными на участок 702 цифрового изображения на Фиг. 7. Следует учесть, что точки вектора градиента расположены в направлении резкого увеличения яркости от пикселя 706. Модуль вектора градиента указывает на ожидаемое увеличение яркости на единицу приращения в направлении градиента. Конечно же, поскольку градиент оценивается исключительно с помощью дискретных операций, в вычислении, показанном на Фиг. 7, направление и модуль градиента представлены исключительно оценками.The direction of the brightness gradient vector 720 and the angle θ 722 are shown superimposed on the digital image portion 702 of FIG. 7. It should be noted that the points of the gradient vector are located in the direction of a sharp increase in brightness from the pixel 706. The module of the gradient vector indicates the expected increase in brightness per unit increment in the gradient direction. Of course, since the gradient is estimated solely by discrete operations, in the calculation shown in FIG. 7, the direction and modulus of the gradient are presented solely by estimates.

На Фиг. 8 показан градиент, рассчитанный для точки на непрерывной поверхности. На Фиг. 8 представлена непрерывная поверхность z=F(x,y). Непрерывная поверхность 802 строится относительно трехмерной декартовой системы координат 804 и имеет похожую на шляпу форму. Для отображения непрерывного множества точек с постоянным значением z на поверхности могут быть построены контурные линии, например, контурная линия 806. В конкретной точке 808 на контуре, построенном на поверхности, вектор градиента 810, рассчитанный для точки, расположен перпендикулярно к контурной линии и точкам в направлении максимально резкого наклона вверх на поверхности от точки 808.In FIG. Figure 8 shows the gradient calculated for a point on a continuous surface. In FIG. Figure 8 shows the continuous surface z = F (x, y). The continuous surface 802 is constructed relative to the three-dimensional Cartesian coordinate system 804 and has a hat-like shape. To display a continuous set of points with a constant value of z, contour lines can be constructed on the surface, for example, contour line 806. At a specific point 808 on the contour built on the surface, a gradient vector 810 calculated for the point is perpendicular to the contour line and points at the direction of the sharpest slope upward on the surface from point 808.

Обычно вектор градиента яркости направлен перпендикулярно границе яркости, при этом чем больше модуль градиента, тем острее граница, т.е. тем больше разность в яркости пикселей с двух сторон границы. На Фиг. 9 показан ряд примеров градиента яркости. Каждый пример, например, пример 902, содержит центральный пиксель, для которого рассчитывается градиент, и четыре прилегающих пикселя, которые используются для расчета Δх и Δy. Наиболее резкие границы яркости показаны в первой колонке 904. В этих случаях модуль градиента составляет не менее 127,5, а в третьем случае 906-180,3. Относительно небольшая разность на границе, показанная в примере 908, создает градиент с модулем всего 3,9. Во всех случаях вектор градиента расположен перпендикулярно очевидному направлению границы яркости, проходящего через центральный пиксель.Usually, the luminance gradient vector is directed perpendicular to the luminance boundary, and the larger the gradient modulus, the sharper the boundary, i.e. the greater the difference in brightness of pixels on both sides of the border. In FIG. 9 shows a number of examples of the brightness gradient. Each example, for example, example 902, contains a central pixel for which the gradient is calculated, and four adjacent pixels that are used to calculate Δx and Δy. The sharpest boundaries of brightness are shown in the first column 904. In these cases, the gradient modulus is at least 127.5, and in the third case 906-180.3. The relatively small difference at the boundary shown in Example 908 creates a gradient with a modulus of only 3.9. In all cases, the gradient vector is perpendicular to the obvious direction of the brightness border passing through the central pixel.

Многие методы обработки изображений включают применение ядер к сетке пикселей, составляющей изображение. На Фиг. 10 показано применение ядра к изображению. На Фиг. 10 небольшая часть изображения 1002 представлена в виде прямоугольной сетки пикселей. Небольшое ядро 3×3 k 1004 показано ниже изображения I 1002. Ядро применяется к каждому пикселю изображения. В случае ядра 3×3, такого как ядро k 1004, показанное на Фиг. 10, для пикселей на границе можно использовать модифицированное ядро, также изображение можно раздвинуть, скопировав значения яркости для пикселей границы в описывающий прямоугольник из пикселей, чтобы иметь возможность применять ядро к каждому пикселю исходного изображения. Чтобы применить ядро к пикселю изображения, ядро 1004 численно накладывается на окрестности пикселя, к которому применяется 1006 ядро с такими же размерами в пикселях, как у ядра. Применение ядра на окрестностях пикселя, к которому применяется ядро, позволяет получить новое значение для пикселя в преобразованном изображении, полученном применением ядра к пикселям исходного изображения. Для некоторых типов ядер новое значение пикселя, к которому применено ядро, In, вычисляется как сумма произведений значения ядра и пикселя, соответствующего значению 1008 ядра. В других случаях новое значение пикселя является более сложной функцией окрестности для пикселя и ядра 1010. В некоторых других типах обработки изображений новое значение пикселя генерируется функцией, применяемой к окрестностям пикселя без использования ядра 1012.Many image processing methods include applying cores to the pixel grid that makes up the image. In FIG. 10 shows the application of the kernel to an image. In FIG. 10, a small portion of the image 1002 is represented as a rectangular grid of pixels. A small 3 × 3 k 1004 core is shown below image I 1002. A core is applied to each pixel in the image. In the case of a 3 × 3 core, such as the k 1004 core shown in FIG. 10, for the pixels on the border, you can use a modified core, you can also expand the image by copying the brightness values for the pixels of the border into a description rectangle of pixels in order to be able to apply a core to each pixel of the original image. To apply the core to an image pixel, the core 1004 is numerically superimposed on a neighborhood of the pixel to which the 1006 core is applied with the same pixel dimensions as the core. Applying the kernel in the vicinity of the pixel to which the kernel is applied allows you to obtain a new value for the pixel in the converted image obtained by applying the kernel to the pixels of the original image. For some types of cores, the new pixel value to which the core is applied, I n , is calculated as the sum of the products of the core value and the pixel corresponding to 1008 core values. In other cases, the new pixel value is a more complex neighborhood function for the pixel and core 1010. In some other types of image processing, the new pixel value is generated by a function applied to the pixel neighborhoods without using the core 1012.

На Фиг. 11 показана свертка изображения. Обычно ядро свертки последовательно применяется к каждому пикселю изображения, в некоторых случаях к каждому пикселю изображения, не принадлежащему границе, или, в других случаях, для создания новых значений преобразованного изображения. На Фиг. 11 ядро 3×3, выделенное штриховкой 1102, было последовательно применено к первой строке пикселей, не принадлежащих границе в изображении 1104. Каждое новое значение, созданное в результате применения ядра к пикселю в исходном изображении 1106, было перенесено в преобразованное изображение 1107. Другими словами, ядро было последовательно применено к исходным окрестностям каждого пикселя в исходном изображении для создания преобразованного изображения. Этот процесс называется «сверткой» и слабо связан с математической операцией свертки, которая выполняется путем умножения изображений, к которым применено преобразование Фурье с последующим обратным преобразованием Фурье по произведению.In FIG. 11 shows a convolution of the image. Typically, the convolution kernel is applied sequentially to each pixel of the image, in some cases to each pixel of the image that does not belong to the border, or, in other cases, to create new values for the converted image. In FIG. 11, the 3 × 3 core, highlighted by hatching 1102, was sequentially applied to the first row of pixels that do not belong to the border in image 1104. Each new value created by applying the kernel to a pixel in the original image 1106 was transferred to the converted image 1107. In other words , the core was sequentially applied to the source neighborhoods of each pixel in the source image to create a transformed image. This process is called “convolution” and is loosely related to the mathematical operation of convolution, which is performed by multiplying the images to which the Fourier transform is applied, followed by the inverse Fourier transform of the product.

На Фиг. 12 показан некоторый пример ядра и методики обработки изображений на основе ядра. В процессе, называемом «медианной фильтрацией», значения яркости в окрестности исходного изображения 1202 были отсортированы 1204 по возрастанию модулей, и новым значением 1208 для соответствующей окрестности преобразованного изображения было выбрано среднее значение 1206. Гауссово сглаживание и очистка от шумов включают применение гауссова ядра 1210 ко всем окрестностям 1214 исходного изображения для создания значения для центрального пикселя окрестности 1216 в соответствующей окрестности обработанного изображения. Значения в гауссовом ядре рассчитываются по выражению, например, такому, как выражение 1218, и используются для создания дискретного представления гауссовой поверхности над окрестностью, образованной вращением кривой нормального распределения вокруг вертикальной оси, совпадающей с центральным пикселем. Горизонтальная и вертикальная компоненты градиента изображения для каждого пикселя могут быть получены применением соответствующих ядер градиента Gx 1220 и Gy 1222. Были указаны только три из множества различных типов методик обработки изображения на основе свертки.In FIG. 12 shows some example of a kernel and kernel-based image processing techniques. In a process called “median filtering,” luminance values in the vicinity of the original image 1202 were sorted 1204 in increasing order of magnitude, and the average value 1206 was selected for the corresponding neighborhood of the converted image 1206. Gaussian smoothing and noise removal include applying a 1210 Gaussian kernel all neighborhoods 1214 of the original image to create a value for the central pixel of the neighborhood 1216 in the corresponding neighborhood of the processed image. Values in a Gaussian core are calculated using an expression, such as expression 1218, for example, and are used to create a discrete representation of a Gaussian surface over a neighborhood formed by rotating a normal distribution curve around a vertical axis that coincides with a central pixel. The horizontal and vertical components of the image gradient for each pixel can be obtained using the corresponding cores of the gradient G x 1220 and G y 1222. Only three of the many different types of convolution-based image processing techniques were indicated.

Способы и система определения контуров в цифровых изображенияхMethods and system for determining the contours in digital images

На Фиг. 13 и 14 показан общий подход к определению контура. На Фиг. 13 представлен пример определения контуров, выполненный на примере цифрового изображения. Цифровое изображение 1302 представляет собой фотографию стола 1304, расположенного рядом со стеной с обоями 1306, на которой имеется окно 1308, из которого виден внешний пейзаж. В этом примере цифровое изображение проходит автоматическую обработку для определения интересующих физических объектов. В первой серии шагов обработки цифрового изображения с помощью способов определения контуров, описываемых в настоящем изобретении, определяются контуры, которые, скорее всего, будут соответствовать краям и границам интересующих физических объектов. По результатам определения контуров создается карта контуров 1310, в которой содержатся контуры, соответствующие границам стола 1304, контуры, соответствующие границам документа, лежащего на столе 1312, и контуры, соответствующие части оконной рамы 1314. После этого могут быть выполнены дополнительные шаги по обработке цифрового изображения для использования этих контуров вместе с дополнительной информацией в исходном изображении 1302 для опознания и классификации физических объектов в изображении, включая стол, документ и оконную раму. Описываемый в настоящем документе способ определения контуров подразумевает различные ограничения и параметры для управления определением контуров с целью установления контуров для конкретных целей. В частности, в показанном на Фиг. 13 примере существует множество границ яркости на исходном изображении 1302, соответствующих текстуре пунктирных линий на обоях на стене 1306 за столом. Может быть задан параметр, регулирующий минимальную длину для определяемых контуров, который может иметь значение, исключающее текстуру обоев.In FIG. 13 and 14 show a general approach to determining the contour. In FIG. 13 illustrates an example of edge detection performed with an example of a digital image. The digital image 1302 is a photograph of a table 1304 located next to a wall with wallpaper 1306, on which there is a window 1308, from which an external landscape is visible. In this example, the digital image is automatically processed to determine the physical objects of interest. In the first series of steps for processing a digital image using the contour determination methods described in the present invention, contours are determined that are likely to correspond to the edges and boundaries of physical objects of interest. Based on the results of determining the contours, a contour map 1310 is created, which contains the contours corresponding to the borders of the table 1304, the contours corresponding to the borders of the document lying on the table 1312, and the contours corresponding to the parts of the window frame 1314. After that, additional steps for processing the digital image can be performed to use these paths together with additional information in the original image 1302 to identify and classify physical objects in the image, including a table, a document and a window frame. The contour determination method described herein involves various limitations and parameters for controlling the definition of contours to establish contours for specific purposes. In particular, as shown in FIG. 13 example, there are many brightness borders on the original image 1302, corresponding to the texture of dashed lines on the wallpaper on the wall 1306 at the table. A parameter can be set that regulates the minimum length for the defined contours, which may have a value that excludes the texture of the wallpaper.

На Фиг. 14 показан общий подход к определению контуров с использованием описываемого в настоящем документе метода. На первом этапе 1402 исходное изображение 1302 обрабатывается с целью определения кандидатов начальных (затравочных) точек, из которых могут быть построены и продлены контуры. Результатом первого этапа может являться карта затравочных точек 1404. На втором этапе 1406 начальные границы продлеваются в двух направлениях из каждой затравочной точки для создания начальных контуров 1408. На окончательном этапе 1410 начальные границы продлеваются и объединяются для создания контуров, которые затем могут быть отфильтрованы для создания множества определенных контуров 1412, которое может использоваться для последующих задач обработки изображения. Как описано подробно ниже, каждый из этапов 1402, 1406 и 1410, показанных на Фиг. 14, включает многочисленные процессы. Эти процессы основаны на формировании и сохранении различных многочисленных типов промежуточных результатов и данных. В различных вариантах реализации способов и систем настоящего изобретения могут использоваться различные типы представления данных и промежуточных результатов. Например, в одном варианте реализации промежуточный результат может быть представлен двумерной картой с элементами, соответствующими пикселям на цифровом изображении, но в другом варианте реализации он может быть представлен сохраненными данными со ссылками на исходное изображение.In FIG. Figure 14 shows a general approach to edge detection using the method described herein. In a first step 1402, the original image 1302 is processed to determine candidates for the initial (seed) points from which the contours can be built and extended. The result of the first step can be a map of seed points 1404. In the second step 1406, the initial borders are extended in two directions from each seed point to create the initial contours 1408. At the final step 1410, the initial borders are extended and combined to create contours, which can then be filtered to create a plurality of defined loops 1412, which may be used for subsequent image processing tasks. As described in detail below, each of steps 1402, 1406, and 1410 shown in FIG. 14 includes numerous processes. These processes are based on the formation and storage of various numerous types of intermediate results and data. In various embodiments of the methods and systems of the present invention, various types of data presentation and intermediate results may be used. For example, in one embodiment, an intermediate result may be represented by a two-dimensional map with elements corresponding to pixels in a digital image, but in another embodiment, it may be represented by stored data with reference to the original image.

На Фиг. 15-26 показан частный вариант реализации способа и подсистемы обнаружения контуров. На Фиг. 15-26 приведены подробные пошаговые иллюстрации, способствующие пониманию блок-схем, а также приводится описание блок-схем с учетом того, какой вариант реализации описан в последующем подразделе.In FIG. 15-26 shows a particular embodiment of the method and subsystem for detecting loops. In FIG. Figures 15-26 provide detailed step-by-step illustrations that help to understand the flowcharts, and also describe the flowcharts taking into account which implementation option is described in the next subsection.

На Фиг. 15 показан первый этап сжатия. На Фиг. 15 исходное полученное цифровое изображение 1502 имеет высоту 1536 пикселей и ширину 2048 пикселей. Разность между высотой и шириной составляет 512 пикселей 1504. Исходное изображение 1502 сжимается для создания сжатых изображений 1506 и 1507, каждое из которых имеет различный коэффициент сжатия. Первое сжатое изображение 1506 сжимается с коэффициентом сжатия

Figure 00000009
и, в результате, имеет высоту 768 пикселей и ширину 1024 пикселей. Разность между шириной и высотой сжатого изображения составляет 256 пикселей 1508. Второе сжатое изображение сжимается с коэффициентом сжатия
Figure 00000010
, при этом разность между шириной и высотой второго сжатого изображения составляет 128 пикселей 1510. В описываемом варианте реализации изобретения исходное изображение сжимается с одним или более коэффициентами сжатия для создания одного или более соответствующих сжатых изображений, на которых разность между шириной и высотой изображения ниже порогового числа пикселей, например, ниже 300 пикселей. Для сжатия цифрового изображения могут использоваться различные способы. В одном простом способе для создания сжатых изображений из исходного изображения удаляются равноудаленные строки и столбцы пикселей. При более сложных способах могут выполняться различные операции сглаживания, сдвига и интерполяции для предотвращения непреднамеренного удаления необходимых деталей или их искажения при сжатии.In FIG. 15 shows a first compression step. In FIG. 15, the original obtained digital image 1502 has a height of 1536 pixels and a width of 2048 pixels. The difference between the height and width is 512 pixels 1504. The original image 1502 is compressed to create compressed images 1506 and 1507, each of which has a different compression ratio. The first compressed image 1506 is compressed with a compression ratio
Figure 00000009
and, as a result, has a height of 768 pixels and a width of 1024 pixels. The difference between the width and height of the compressed image is 256 pixels 1508. The second compressed image is compressed with a compression ratio
Figure 00000010
wherein the difference between the width and height of the second compressed image is 128 pixels 1510. In the described embodiment, the original image is compressed with one or more compression factors to create one or more corresponding compressed images in which the difference between the width and height of the image is below the threshold number pixels, for example, below 300 pixels. Various methods can be used to compress a digital image. In one simple method for creating compressed images, equidistant rows and columns of pixels are removed from the original image. With more complex methods, various smoothing, shifting, and interpolation operations can be performed to prevent inadvertent removal of necessary parts or their distortion during compression.

На Фиг. 16 показан следующий этап обработки при реализации процесса определения контуров. Исходное изображение или сжатая версия исходного изображения 1602 сглаживается 1604 с помощью медианного фильтра или свертки с применением гауссова ядра с целью создания сглаженного изображения 1606. Затем к каждому цветовому каналу сглаженного изображения применяются ядра градиента Gx и Gy для создания трех пар карт горизонтальной компоненты градиента и вертикальной компоненты градиента 1608-1613. Например, ядро горизонтальной компоненты градиента, прошедшее свертку с красным каналом сглаженного изображения 1614, создает карту горизонтальной компоненты градиента для красного канала 1608. Понятие «Gi(X)» используется как для указания на свертку ядра компоненты градиента в направлении i с цветовым каналом X изображения, так и для указания на карту компоненты градиента, создаваемую при свертке. При формировании и сохранении в долговременной памяти шести карт компонент градиента 1608-1613 или, как вариант, при их формировании в оперативной памяти, модули компонент градиента затем используются для создания «карты градиента» 1616. Каждый элемент карты градиента, например, элемент i 1618, содержит модуль градиента 1620 и угол направления градиента 1622. Небольшая блок-схема на Фиг. 16 показывает процесс формирования карты градиента. Сначала на этапе 1624 для каждого цветового канала вычисляется сумма абсолютных значений компонент градиента и сохраняется в переменных Ri, Gi и Bi. Если Ri превышает Gi, в соответствии с определением на этапе 1626, и если Ri превышает Bi, в соответствии с определением на этапе 1628, на этапе 1630 рассчитывается градиент для клетки или пикселя i с использованием компонент градиента для красного канала. Если Ri не превышает ни Gi, ни Bi, то на этапе 1632 определяется, является ли Bi, больше Gi. Если Bi превышает Gi, то на этапе 1634 на основе компонент градиента синего канала рассчитывается модуль и направление градиента для клетки или пикселя i. В ином случае модуль и угол направления градиента рассчитываются по компонентам градиента зеленого канала на этапе 1636. Этот процесс, показанный на блок-схемах 1624, 1626, 1628, 1630, 1632, 1634 и 1636, повторяется для каждого пикселя или клетки i в сглаженном изображении 1606. Следует отметить, что в определенных вариантах реализации свертка выполняется только для пикселей изображения, на которые возможно наложение ядра, при этом в создаваемой с помощью свертки карте имеется меньшее количество столбцов и строк, чем в исходной карте. В других вариантах реализации все исходные изображения расширяются путем копирования, с тем, чтобы ядра могли быть применены ко всем пикселям или клеткам в изображении, или для граничных пикселей и клеток используются модифицированные ядра. В связи с этим карта градиента 1616 представляет собой карту модулей и направлений градиента для каждого пикселя или клетки сглаженного изображения, при этом градиент для каждого пикселя основан на цветовом канале сглаженного изображения, для которого сумма компонент градиента является максимальной.In FIG. 16 shows the next processing step in the implementation of the contour determination process. The original image or compressed version of the original image 1602 is smoothed 1604 using a median filter or convolution using a Gaussian kernel to create a smoothed image 1606. Then, G x and G y gradient cores are applied to each color channel of the smoothed image to create three pairs of cards of the horizontal gradient component and the vertical gradient component 1608-1613. For example, the core of the horizontal gradient component that has convolved with the red channel of the smoothed image 1614 creates a map of the horizontal gradient component for the red channel 1608. The term “G i (X)” is used to indicate the convolution of the core of the gradient component in the i direction with the color channel X image, and to indicate the map components of the gradient created by the convolution. When forming and storing six cards of gradient components 1608-1613 in long-term memory, or, alternatively, when forming them in RAM, the gradient component modules are then used to create a “gradient map” 1616. Each element of the gradient map, for example, element i 1618, contains a gradient modulus 1620 and an angle of direction of the gradient 1622. The small block diagram of FIG. 16 shows a gradient map generation process. First, at step 1624, for each color channel, the sum of the absolute values of the gradient components is calculated and stored in the variables R i , G i and B i . If R i exceeds G i , as determined in step 1626, and if R i exceeds B i , as determined in step 1628, the gradient for the cell or pixel i is calculated in step 1630 using the gradient components for the red channel. If R i does not exceed neither G i nor B i , then at step 1632 it is determined whether B i is greater than G i . If B i exceeds G i , then at step 1634, the modulus and gradient direction for the cell or pixel i are calculated based on the blue channel gradient components. Otherwise, the modulus and gradient angle are calculated from the green channel gradient components in step 1636. This process, shown in flowcharts 1624, 1626, 1628, 1630, 1632, 1634, and 1636, is repeated for each pixel or cell i in the smoothed image 1606. It should be noted that in certain implementations, convolution is performed only for image pixels onto which the kernel can be superimposed, while in the map created by convolution there are fewer columns and rows than in the original map. In other embodiments, all source images are expanded by copying so that the kernels can be applied to all pixels or cells in the image, or modified kernels are used for the border pixels and cells. In this regard, gradient map 1616 is a map of gradient modules and directions for each pixel or cell of the smoothed image, and the gradient for each pixel is based on the color channel of the smoothed image for which the sum of the gradient components is maximum.

На Фиг. 17 показано ядро подавления немаксимумов («ядро NMS»). Ядро NMS 1702 содержит три области: (1) центральный пиксель 1704; (2) непосредственная окрестность 1706; и (3) расширенная окрестность 1708. Применение ядра NMS для пикселей подразумевает, как обычно, наложение ядра NMS, чтобы область центрального пикселя 1704 ядра NMS накладывалась на пиксель, к которому применяется ядро. При применении ядра решается, передается ли яркость пикселя, к которому применяется ядро, или наоборот, передается ли на карту или изображение значение яркости 0. Если яркость расположенного ниже центрального пикселя выше яркости расположенного ниже пикселя в непосредственной окрестности и если яркость пикселя под областью центрального пикселя выше или равна яркости любого пикселя, лежащего ниже расширенной окрестности, то на образующееся изображение или карту передается значение яркости центрального пикселя. В ином случае на образующееся изображение или карту передается значение 0. Процесс принятия решений формально выражен 1710 на Фиг. 17. При свертке ядра NMS с изображением или картой выбираются пиксели или клетки изображения, или карты с локальной максимальной яркостью для передачи на образующуюся карту или изображение.In FIG. 17 shows a non-maximum suppression core (“NMS core”). The NMS core 1702 contains three areas: (1) the center pixel 1704; (2) the immediate vicinity of 1706; and (3) an extended neighborhood of 1708. Using the NMS core for pixels implies, as usual, superimposing the NMS core so that the area of the central pixel 1704 of the NMS core overlaps with the pixel to which the core is applied. When applying the kernel, it is decided whether the brightness of the pixel to which the kernel is applied is transferred, or vice versa, whether the brightness value of 0 is transmitted to the card or image. If the brightness of the lower central pixel is higher than the brightness of the lower pixel in the immediate vicinity and if the brightness of the pixel is below the central pixel If it is higher than or equal to the brightness of any pixel lying below the extended neighborhood, the brightness value of the central pixel is transmitted to the resulting image or map. Otherwise, the value 0 is transmitted to the resulting image or map. The decision-making process is formally expressed 1710 in FIG. 17. When convolving the NMS core with an image or map, the pixels or cells of the image, or maps with local maximum brightness, are selected for transmission to the resulting map or image.

На Фиг. 18 показаны дополнительные шаги процесса обнаружения контура, приводящие к созданию карты точек, которая содержит указания на исходные пиксели, из которых начинаются контуры, что было описано выше со ссылкой на карту точек 1404 на Фиг. 14. Карта градиента 1802, сформированная в ходе описанного выше процесса на Фиг. 16, свертывается с ядром NMS для создания промежуточной карты точек 1804. Ядро NMS рассматривает компоненту модуля градиента для каждой клетки карты градиента, передающую значение локальных максимальных градиентов с карты градиента на промежуточную карту точек 1804. Далее к промежуточной карте точек применяется пороговая фильтрация 1806 для создания окончательной карты точек 1808, содержащей самые большие значения модулей градиента, при этом все другие клетки содержат значение 0 в результате свертки ядра NMS или установления порога. В определенных вариантах реализации создается индекс 1810, содержащий ссылки на затравочные пиксели на карте точек для создания отсортированной карты точек 1812. Индекс сортируется по убыванию модулей градиента, поэтому большая часть перспективных затравочных пикселей обрабатываются с более высоким приоритетом, чем менее перспективные затравочные пиксели. Следует отметить, что в альтернативных вариантах реализации может использоваться сортированный массив структур данных, каждая из которых содержит координаты и модуль градиента для затравочного пикселя, а не сохраняет разреженную карту точек.In FIG. 18 shows additional steps of the path detection process leading to the creation of a point map that contains indications of the source pixels from which the paths begin, as described above with reference to the point map 1404 in FIG. 14. A gradient map 1802 generated during the process described above in FIG. 16 is collapsed with the NMS core to create an intermediate point map of 1804. The NMS core considers the gradient module component for each cell of the gradient map, transmitting the value of local maximum gradients from the gradient map to the intermediate point map of 1804. Next, threshold filtering 1806 is applied to the intermediate point map the final map of points 1808 containing the largest values of the moduli of the gradient, while all other cells contain a value of 0 as a result of convolution of the NMS core or setting a threshold. In certain implementations, an index 1810 is created that contains references to the seed pixels on the point map to create a sorted map of points 1812. The index is sorted in descending order of the gradient modules, so most promising seed pixels are processed with higher priority than less promising seed pixels. It should be noted that in alternative implementations, a sorted array of data structures can be used, each of which contains the coordinates and the gradient modulus for the seed pixel, and does not save a sparse map of points.

При наличии карты точек, отсортированной карты точек или иной структуры данных, содержащей затравочные точки, процесс обнаружения контуров продолжается, как описано выше со ссылкой на карту или изображение 1408 на Фиг. 14, для начала построения контура от затравочных пикселей или точек. На Фиг. 19 показан общий процесс построения контура. Из заданного затравочного пикселя или точки на карте точек 1902 начальный контур может иметь одно из возможных направлений, показанных стрелками, например, стрелкой 1904. На этапе 1906 выбора исходного направления границы выбирается конкретное направление для начального контура и создается вектор 1908 длины L, конец которого соответствует затравочному пикселю 1902, а направление - выбранному направлению. При этом начальный контур представляет собой отрезок с двумя конечными точками, соответствующими концу и началу построенного вектора. В приведенном ниже описании векторы также могут называться «отрезками», поскольку, как описано ниже, контур представлен последовательностью векторов. Эти элементы представления контура также могут быть представлены как векторы с начальной точкой, модулем или углом направления, или в виде отрезков с координатами для начальной и конечной точки отрезка.With a point map, a sorted point map, or other data structure containing seed points, the loop detection process continues as described above with reference to the map or image 1408 in FIG. 14 to begin building a path from the seed pixels or dots. In FIG. 19 shows the general process of constructing a contour. From a given seed pixel or point on a point map 1902, the initial contour can have one of the possible directions shown by arrows, for example, arrow 1904. At step 1906, the initial direction of the boundary is selected for a specific direction for the initial contour and a vector 1908 of length L is created, the end of which corresponds to the seed pixel 1902, and the direction to the selected direction. In this case, the initial contour is a segment with two end points corresponding to the end and beginning of the constructed vector. In the description below, vectors can also be called “segments” because, as described below, a path is represented by a sequence of vectors. These contour representation elements can also be represented as vectors with a starting point, a module, or an angle of direction, or in the form of segments with coordinates for the starting and ending points of the segment.

На Фиг. 20 представлен расчет модуля проекции градиента пикселя р по вектору начального контура r, исходящего из затравочного пикселя или затравочной точки i. Как показано на Фиг. 20, предполагаемый исходный вектор r 2002 для контура, совпадающего с затравочным пикселем i 2004, рассматривается в процессе выбора направления начального контура. Пиксель р 2006 расположен вдоль вектора r 2002. Имеется вектор градиента 2008, связанный с пикселем р на карте градиента. Этот вектор градиента имеет угол направления θр 2010, который также присутствует на карте градиента. Угол 2012, θr, является углом направления для вектора r. Угол Ψ является углом между вектором градиента для пикселя р и вектором r 2002. Вектор pr 2016 является проекцией вектора градиента 2008 на вектор r 2002. В показанном построении угол Ψ легко рассчитывается на основе углов направлений θр и θr 2018. Отношение модулей векторов pr и вектора градиента для пикселя р равно косинусу угла Ψ 2220. Таким образом, модуль вектора проекции pr вычисляется как произведение косинуса Ψ и модуля вектора градиента, исходящего из пикселя р 2222. Как вариант, для расчета модуля вектора проекции pr 2224 может использоваться скалярное произведение вектора градиента 2008 и вектора r. Замена результата 2222 на выражение скалярного произведения дает выражение для определения модуля вектора проекции pr 2226.In FIG. 20 shows a calculation of the modulus of the projection of the gradient of the pixel p from the vector of the initial contour r, coming from the seed pixel or seed point i. As shown in FIG. 20, the estimated initial vector r 2002 for the contour matching the seed pixel i 2004 is considered in the process of selecting the direction of the initial contour. The pixel p 2006 is located along the vector r 2002. There is a gradient vector 2008 associated with the pixel p on the gradient map. This gradient vector has a direction angle θ p 2010, which is also present on the gradient map. The angle 2012, θ r , is the direction angle for the vector r. The angle Ψ is the angle between the gradient vector for the pixel p and the vector r 2002. The vector pr 2016 is the projection of the gradient vector 2008 onto the vector r 2002. In the shown construction, the angle Ψ is easily calculated based on the direction angles θ p and θ r 2018. The ratio of the moduli of the vectors pr and the gradient vector for the pixel p is equal to the cosine of the angle Ψ 2220. Thus, the projection vector module pr is calculated as the product of the cosine Ψ and the gradient vector module coming from the pixel p 2222. Alternatively, a scalar can be used to calculate the projection vector module pr 2224 product of 2008 gradient vector and r vector. Replacing result 2222 with an expression of the scalar product gives an expression for determining the modulus of the projection vector pr 2226.

На Фиг. 21 показано создание промежуточных вычисленных значений, которые используются в процессе выбора направления границы. На Фиг. 21 показан затравочный пиксель с координатами (х,у) 2102 вместе с кандидатом вектора начального контура 2104. Для кандидата вектора границы создаются промежуточные результаты,

Figure 00000011
2108 и Н(х,у,r) 2110, где r является вектором 2104 и также называется направлением начальной границы, при этом фактически имеется в виду угол направления вектора r. Имеется 10 пикселей, включая затравочный пиксель 2102, которые лежат под вектором 2104, представляющим кандидата начального контура. Значение
Figure 00000012
вычисляется как сумма модулей проекций векторов, связанных с пикселями i1-i10, разделенная на количество элементов множества пикселей под начальным контуром. H(х,у,r) представляет собой гистограмму 2112, на которой направление градиента пикселей под вектором начального контура представлено в виде бинов гистограммы. Как показано в выражении 2114, количество пикселей, зарегистрированных в каждом бине Hi, гистограммы, соответствует количеству пикселей направлений градиента в интервале направлений, представленных бином. Бин 2116 с максимальным значением соответствует общему направлению градиента пикселей под начальным контуром. При правильном направлении начального контура направление вектора 2104 должно быть в целом перпендикулярно направлениям градиента пикселей под вектором 2104.In FIG. Figure 21 shows the creation of intermediate calculated values that are used in the process of selecting the direction of the boundary. In FIG. 21 shows a seed pixel with coordinates (x, y) 2102 together with the candidate vector of the initial contour 2104. Intermediate results are created for the candidate boundary vector,
Figure 00000011
2108 and H (x, y, r) 2110, where r is the vector 2104 and is also called the direction of the initial boundary, while in fact the angle of the direction of the vector r is meant. There are 10 pixels, including a seed pixel 2102, which lie beneath a vector 2104 representing a candidate for the initial contour. Value
Figure 00000012
it is calculated as the sum of the modules of the projections of the vectors associated with the pixels i 1 -i 10 divided by the number of elements of the set of pixels under the initial contour. H (x, y, r) is a histogram 2112, in which the direction of the gradient of pixels under the vector of the initial contour is presented in the form of histogram bins. As shown in expression 2114, the number of pixels recorded in each bin H i of the histogram corresponds to the number of pixels of the gradient directions in the range of directions represented by the bin. Bean 2116 with the maximum value corresponds to the general direction of the gradient of pixels under the initial path. With the right direction of the initial contour, the direction of the vector 2104 should be generally perpendicular to the directions of the pixel gradient below the vector 2104.

На Фиг. 22 представлена блок-схема процесса выбора направления границ, в котором выбирается направление начального контура для затравочного пикселя. На этапе 2202 процесс получает координаты затравочного пикселя. На этапе 2204 происходит инициализация (установка нулевых значений) множества кандидатов. Множество кандидатов является множеством структур данных кандидатов, каждое из которых включает направление r и значение

Figure 00000013
. В цикле for шагов 2206-2213 рассматривается каждое направление r от 0° до 360°. Следует, опять же, отметить, что r в настоящем описании считается как вектором, так и направлением, где направление представляет собой направление ориентации вектора r. На этапе 2207 для рассматриваемого направления вычисляется гистограмма H(х,у,r). На этапе 2208 для бина с максимальным значением в Н(х,у,r) устанавливается индекс j. На этапе 2209 определяется, является ли направление r перпендикулярным углу в диапазоне углов, соответствующих бину с максимальным значением и его ближайшим соседям. Если направление r является перпендикулярным углу в этом диапазоне, то на этапе 2210 определяется, превышает ли значение или число пикселей, назначенное бину с максимальным значением, пороговое значение В. Если да, то на этапе 2211 рассчитывается значение
Figure 00000014
для рассматриваемого направления, и на этапе 2212 в множество кандидатов добавляется запись для рассматриваемого направления. В ином случае направление r удаляется из множества направлений кандидатов. После завершения цикла for 2206-2213, если количество кандидатов во множестве составляет меньше 0, как определено на этапе 2214, то на этапе 2215 возвращается вектор со значением 0 для указания на то, что предпочтительное направление контура для затравочного пикселя не может быть установлено. В ином случае на этапе 2216 выбирается один кандидат из множества с максимальным значением
Figure 00000014
Если значение
Figure 00000013
для выбранного кандидата превышает пороговое значение
Figure 00000015
, как определено на этапе 2218, то на этапе 2220 возвращается направление r, содержащееся у выбранного кандидата. В ином случае на этапе 2215 возвращается нулевой вектор, указывающий на невозможность определения направления для затравочного пикселя. Таким образом, выбор исходного направления контура для затравочного пикселя включает выбор направления, согласованного с направлениями векторов градиента для пикселей в окрестности начального контура, когда имеется консенсус в окрестности с учетом направления градиента.In FIG. 22 is a flowchart of a boundary direction selection process in which an initial outline direction for a seed pixel is selected. At step 2202, the process obtains the coordinates of the seed pixel. At step 2204, initialization (zeroing) of a plurality of candidates occurs. A plurality of candidates is a plurality of candidate data structures, each of which includes a direction r and a value
Figure 00000013
. In the for loop of steps 2206-2213, each direction r from 0 ° to 360 ° is considered. It should again be noted that r in the present description is considered both a vector and a direction, where the direction is the direction of orientation of the vector r. At step 2207, a histogram H (x, y, r) is computed for the direction in question. At step 2208, an index j is set for a bin with a maximum value of H (x, y, r) . At step 2209, it is determined whether the direction r is perpendicular to the angle in the range of angles corresponding to the bin with the maximum value and its nearest neighbors. If the direction r is perpendicular to the angle in this range, then at step 2210 it is determined whether the value or number of pixels assigned to the bin with the maximum value exceeds threshold value B. If yes, then at step 2211 the value is calculated
Figure 00000014
for the direction in question, and at step 2212, an entry for the direction in question is added to the plurality of candidates. Otherwise, the direction r is removed from the multiple directions of the candidates. After completion of the for 2206-2213 cycle, if the number of candidates in the set is less than 0, as determined at step 2214, then at step 2215 a vector is returned with a value of 0 to indicate that the preferred outline direction for the seed pixel cannot be set. Otherwise, at step 2216, one candidate is selected from the set with the maximum value
Figure 00000014
If the value
Figure 00000013
for selected candidate exceeds threshold
Figure 00000015
as determined at step 2218, then at step 2220, the direction r contained in the selected candidate is returned. Otherwise, at step 2215, a zero vector is returned indicating that it is not possible to determine the direction for the seed pixel. Thus, the selection of the initial direction of the contour for the seed pixel includes the selection of the direction consistent with the directions of the gradient vectors for the pixels in the vicinity of the initial contour, when there is consensus in the neighborhood, taking into account the direction of the gradient.

На Фиг. 23 и 24 представлен выбор направления для продления контура. Процесс выбора направления продления контура в целом аналогичен процессу выбора исходных направлений контура для затравочных пикселей, описанному выше со ссылкой на Фиг. 20-22. При этом в процессе продления контура следующий вектор длины L продлевается из конечного пикселя строящегося контура, а не из затравочной точки в двух противоположных направлениях. На Фиг. 23 показан следующий кандидат вектора 2302, продленного из конечного пикселя 2304 формируемого контура. В этом случае в качестве направлений кандидатов рассматриваются только направления с углом 2α 2306. Иными словами, следующий отрезок контура 2302 может быть наклонен относительно направления предыдущего уже существующего отрезка контура 2308 на угол до α. В ином случае процесс выбора направления аналогичен процессу выбора направления для начальных векторов, соответствующих начальному контуру для затравочного пикселя.In FIG. 23 and 24 show the choice of direction for extending the contour. The process of selecting the direction of extending the contour is generally similar to the process of selecting the initial directions of the contour for the seed pixels described above with reference to FIG. 20-22. Moreover, in the process of extending the contour, the next vector of length L is extended from the final pixel of the contour under construction, and not from the seed point in two opposite directions. In FIG. 23 shows the next candidate vector 2302, extended from the final pixel 2304 of the generated contour. In this case, only directions with an angle of 2306 are considered as candidate directions. In other words, the next segment of contour 2302 can be tilted relative to the direction of the previous existing segment of contour 2308 by an angle of up to α. Otherwise, the direction selection process is similar to the direction selection process for initial vectors corresponding to the initial contour for the seed pixel.

На Фиг. 25 показан процесс построения контура. Этот процесс начинается в затравочном пикселе 2502. Исходный вектор 2504 строится для образования начального контура с направлением, выбранным согласно приведенному выше описанию со ссылкой на Фиг. 20-22. Затем начальный вектор продлевается в каждом направлении за счет последовательного добавления продлевающих векторов, например, векторов 2506-2508, для каждого конца контура. Если направление следующего продления из конкретной конечной точки контура определить невозможно, то продленный в этом направлении контур оканчивается в этой конечной точке.In FIG. 25 shows the process of constructing a contour. This process begins at the seed pixel 2502. An initial vector 2504 is constructed to form an initial contour with a direction selected according to the above description with reference to FIG. 20-22. Then, the initial vector is extended in each direction by sequentially adding extension vectors, for example, vectors 2506-2508, for each end of the contour. If the direction of the next extension from a particular endpoint of the contour cannot be determined, then the extended contour in this direction ends at that endpoint.

На Фиг. 26 представлено соединение двух контуров для образования единого результирующего контура. На Фиг. 26 первый многосегментный контур 2602 заканчивается в конечной точке 2604, а второй многосегментный контур 2606 заканчивается в конечной точке 2608. Первый и второй контуры 2602 и 2606 могут представлять две дискретные и различные границы яркости в пределах изображения или могут представлять две части одной границы яркости с разрывом, разделяющим эти две части. В последнем случае обе части соединяются для формирования единого непрерывного контура. В процессе объединения оба контура продлеваются из соответствующих конечных точек, на что указывают прерывистые векторы 2610 и 2612, продлеваемые из последних отрезков 2614 и 2616 первого 2602 и второго 2606 контуров. Продление может выполняться за счет использования направления последнего отрезка каждого контура, предшествующего конечной точке, или может выполняться за счет использования метода аппроксимации на основе направлений последних n отрезков в каждом контуре. Может использоваться множество различных методов аппроксимации, в том числе методы линейной регрессии, при которых окончательная часть контуров представляется линейной, квадратичной или кубической аппроксимацией, если конечные части контуров представляются искривленными. Продленные контуры пересекаются в точке 2620. Угол пересечения β 2622 и перпендикулярные расстояния d1 2624 и d2 2626 вычисляются для определения, необходимо ли объединять эти два контура. Если угол β не превышает пороговое значение, и если минимальное из двух расстояний d1 и d2 не превышает минимальное расстояние, то строится связующий отрезок 2630 для объединения двух контуров с целью создания единого результирующего контура.In FIG. 26 shows the connection of two loops to form a single resulting loop. In FIG. 26, the first multi-segment loop 2602 ends at the end point 2604, and the second multi-segment loop 2606 ends at the end point 2608. The first and second circuits 2602 and 2606 can represent two discrete and different brightness boundaries within the image or can represent two parts of the same brightness border with a gap separating these two parts. In the latter case, both parts are connected to form a single continuous circuit. In the process of combining, both contours are extended from the corresponding end points, as indicated by discontinuous vectors 2610 and 2612, extended from the last segments 2614 and 2616 of the first 2602 and second 2606 circuits. Extension can be performed by using the direction of the last segment of each path preceding the end point, or can be performed by using the approximation method based on the directions of the last n segments in each path. Many different approximation methods can be used, including linear regression methods, in which the final part of the contours is represented by a linear, quadratic, or cubic approximation if the final parts of the contours appear to be curved. Extended contours intersect at point 2620. The intersection angle β 2622 and the perpendicular distances d 1 2624 and d 2 2626 are calculated to determine whether the two contours need to be combined. If the angle β does not exceed the threshold value, and if the minimum of two distances d 1 and d 2 does not exceed the minimum distance, then a connecting segment 2630 is constructed to combine the two contours in order to create a single resulting contour.

На Фиг. 27A-G с помощью блок-схем и представлений структур данных показан один из вариантов реализации способа и подсистемы обнаружения контуров. На Фиг. 27А приведена блок-схема подпрограммы «найти контуры». На этапе 2702 происходит получение цифрового изображения, а также размещение и инициализация массива контуров структуры данных контуров. На этапе 2703 определяется минимальный коэффициент сжатия Cmin, необходимый для сжатия полученного изображения, чтобы при этом разность между высотой и шириной сжатого изображения была ниже порогового числа пикселей. На этапе 2704 определяется максимальный полезный коэффициент сжатия Cmax. В цикле for этапов 2705-2707 вызывается подпрограмма «определить контуры» для сжатия исходного изображения с коэффициентом сжатия в интервале [Cmin, Cmax] и определения контуров в сжатом изображении. Количество полученных сжатых изображений может зависеть от параметризованной итерации интервала сжатия, от размеров полученного цифрового изображения и от других факторов. В определенных случаях формируется только одно сжатое изображение. В других случаях контуры исходного изображения определяются без сжатия, если диспропорция и размеры исходного изображения меньше порогового значения пикселей. На этапе 2708 вызывается подпрограмма «объединить определенные контуры» для совмещения контуров, выявленных в цикле for 2705-2707. На этапе 2709 вызывается подпрограмма «выбрать итоговые контуры» для выбора итогового множества контуров в качестве выявленных контуров для использования в последующих процессах обработки цифрового изображения.In FIG. 27A-G, using flowcharts and representations of data structures, one embodiment of a method and a loop detection subsystem is shown. In FIG. 27A is a flowchart of the find contours subroutine. At step 2702, a digital image is acquired, as well as the placement and initialization of the contour array of the contour data structure. At step 2703, the minimum compression ratio C min required to compress the resulting image is determined so that the difference between the height and width of the compressed image is below the threshold number of pixels. At step 2704, the maximum effective compression ratio C max is determined. In the for loop of steps 2705-2707, the "determine contours" subroutine is called to compress the original image with a compression coefficient in the interval [C min , C max ] and determine the contours in the compressed image. The number of received compressed images may depend on the parameterized iteration of the compression interval, on the size of the resulting digital image, and on other factors. In certain cases, only one compressed image is generated. In other cases, the contours of the original image are determined without compression if the imbalance and size of the original image is less than the threshold pixel value. At step 2708, the “merge defined paths” routine is called to align the paths identified in the for loop 2705-2707. At step 2709, the “select final contours” subroutine is called to select the final set of contours as the identified contours for use in subsequent digital image processing processes.

На Фиг. 27В представлена структура данных, использующаяся в описанном варианте реализации. Структура данных контуров 2712 представляет собой массив данных контуров, каждый из которых включает массив cs 2713, в котором хранится начальная точка и конечная точка 2714 для каждых контуров, выявленных в конкретном сжатом изображении или, в определенных случаях, исходном изображении. Помимо этого, структура данных контуров содержит указание на количество определенных контуров 2716 и ссылку 2717 на сжатое изображение или, в определенных случаях, на исходное изображение 2718, в котором определены контуры. Это, конечно же, только одна из возможных структур данных, используемых в одном из возможных способов для представления контуров, определенных в одном или более цифровых изображениях.In FIG. 27B shows a data structure used in the described embodiment. The contour data structure 2712 is an array of contour data, each of which includes an cs 2713 array that stores the start point and end point 2714 for each contours identified in a particular compressed image or, in certain cases, the original image. In addition, the contour data structure contains an indication of the number of defined contours 2716 and a link 2717 to a compressed image or, in certain cases, to the original image 2718 in which the contours are defined. This, of course, is only one of the possible data structures used in one of the possible methods for representing the contours defined in one or more digital images.

На Фиг. 27С показана блок-схема подпрограммы «определить контуры», вызываемой на этапе 2706 на Фиг. 27А. На этапе 2720 принимается изображение (обычно сжатое изображение С) и поступает ссылка на структуру данных контуры. На этапе 2721 устанавливаются значения для ряда параметров, управляющих определением контуров. К ним относятся: (1) L, длина отрезков, используемых для построения контуров; (2) α, максимальный угол изгиба следующего отрезка по отношению к текущему, окончательному отрезку контура; (3) h, количество бинов в гистограмме H(х,у,r), (4) В, минимальное значение для бина гистограммы с максимальным значением; (5)

Figure 00000016
минимальное
Figure 00000013
значение для начального отрезка; и (6) Re, радиус окрестности контура. Эти значения могут быть жестко заданы, поступать из файла конфигурации или быть указаны через интерфейс пользователя.In FIG. 27C shows a block diagram of a “determine contours” routine called in step 2706 of FIG. 27A. At step 2720, an image (typically a compressed image C) is received and a link is made to the contour data structure. At step 2721, values are set for a series of parameters that control the definition of loops. These include: (1) L, the length of the segments used to construct the contours; (2) α, the maximum bending angle of the next segment with respect to the current, final segment of the contour; (3) h, the number of bins in the histogram H (x, y, r) , (4) B, the minimum value for the histogram bin with the maximum value; (5)
Figure 00000016
the minimum
Figure 00000013
value for the initial segment; and (6) R e , the radius of the neighborhood of the contour. These values can be hard-coded, come from a configuration file, or be specified through the user interface.

На этапе 2722, полученное изображение С сглаживается, как описано выше со ссылкой на этап 1604 на Фиг. 16. В цикле for этапов 2723-2725 создаются карты компонент градиента для каждого из трех цветовых каналов в сжатом изображении С, как описано выше со ссылкой на Фиг. 16. На этапе 2726 создаются карта градиента и карта точек с индексом (1802 и 1812 на Фиг. 18). В цикле for этапов 2727-2730, в карту градиента для каждого пикселя i на изображении С вносится запись, как описано выше со ссылкой на Фиг. 16. На этапе 2731 ядро NMS применяется к карте градиента для формирования промежуточной карты точек (1804 на Фиг. 18). На этапе 2732 промежуточная карта точек фильтруется до 0 записей j, при этом модули градиента будут меньше порогового значения (1806 на Фиг. 18). На этапе 2733 на карте точек (1810 на Фиг. 18) создается отсортированный индекс. Наконец, на этапе 2734 вызывается подпрограмма «построить контуры» для построения контуров, совпадающих с определенными затравочными пикселями, на которые указывает карта точек, созданная на этапах 2731-2733.At step 2722, the obtained image C is smoothed as described above with reference to step 1604 in FIG. 16. In the for loop of steps 2723-2725, gradient component maps are created for each of the three color channels in the compressed image C, as described above with reference to FIG. 16. At step 2726, a gradient map and a map of points with an index are created (1802 and 1812 in FIG. 18). In the for loop of steps 2727-2730, a record is entered into the gradient map for each pixel i in image C, as described above with reference to FIG. 16. At step 2731, the NMS core is applied to the gradient map to form an intermediate point map (1804 in FIG. 18). At step 2732, an intermediate point map is filtered to 0 entries j, while the gradient moduli will be less than the threshold value (1806 in FIG. 18). At step 2733, a sorted index is created on the point map (1810 in FIG. 18). Finally, at step 2734, the "build contours" routine is called to construct the paths matching the specific seed pixels that are indicated by the point map created in steps 2731-2733.

На Фиг. 27D показана блок-схема подпрограммы «построить контуры», вызываемой на этапе 2734 на Фиг. 27С. На этапе 2736 подпрограмма получает сжатое изображение С, карту точек с индексом и ссылку на структуру данных контуры. В цикле for этапов 2737-2751 каждая затравочная точка на карте точек рассматривается в порядке убывания модуля градиента, при этом используется индекс, связанный с картой точек. На этапе 2738 вызывается подпрограмма «выбрать направление границы для затравочной точки» с целью определения направления начального контура, включая совмещение построенного вектора с затравочной точкой. Следует отметить, что подпрограмма «выбрать направление» границы для затравочной точки» описана выше со ссылкой на Фиг. 22. Если направление не возвращается, текущая итерация цикла for этапов 2737-2751 заканчивается, и рассматривается следующая затравочная точка. В ином случае на этапе 2740 из затравочной точки создается исходный вектор в соответствии с заданным направлением, как описано выше со ссылкой на Фиг. 19. Во внутреннем цикле for этапов 2741-2749 начальный контур продлевается в обоих направлениях через вызванную на этапе 2745 подпрограмму «выбрать направление границы для продления». Эта подпрограмма описана выше со ссылкой на Фиг. 24, а процесс построения контуров в целом описан выше со ссылкой на Фиг. 25. После завершения контура все затравочные точки в окрестности контура, определенные радиусом Re, удаляются с карты точек и из индекса для предотвращения инициации новых контуров в чрезмерной близости к установленному текущему контуру. Наконец, после завершения внешнего цикла for этапов 2737-2751, на этапе 2752 заполняется структура данных контура в массиве контуров.In FIG. 27D shows a block diagram of the construct contours subroutine called in step 2734 of FIG. 27C. At step 2736, the routine receives a compressed image C, a map of points with an index, and a link to the contour data structure. In the for loop of steps 2737-2751, each seed point on the point map is considered in decreasing order of the gradient modulus, using the index associated with the point map. At step 2738, the subroutine “select the direction of the boundary for the seed point” is called to determine the direction of the initial contour, including combining the constructed vector with the seed point. It should be noted that the “select direction” boundary routine for the seed point ”is described above with reference to FIG. 22. If the direction does not return, the current iteration of the for loop of steps 2737-2751 ends and the next seed point is considered. Otherwise, at step 2740, an initial vector is created from the seed point in accordance with the specified direction, as described above with reference to FIG. 19. In the internal for loop of steps 2741-2749, the initial contour is extended in both directions through the subroutine “select the direction of the boundary for extension” called in step 2745. This routine is described above with reference to FIG. 24, and the contouring process as a whole has been described above with reference to FIG. 25. After completing the contour, all the seed points in the vicinity of the contour defined by the radius R e are removed from the point map and from the index to prevent the initiation of new contours in excessive proximity to the established current contour. Finally, after completing the external for loop of steps 2737-2751, at step 2752, the outline data structure in the outline array is populated.

На Фиг. 27Е показана блок-схема подпрограммы «объединить определенные контуры», вызываемой на этапе 2708 на Фиг. 27А. На этапе 2754 размещается структура данных результатов, и поступает ссылка на структуру данных контуров. В цикле for этапов 2756-2759 рассматриваются структура данных каждого контура в структуре данных контуров. Структура данных каждого контура в структуре данных контуров соответствует конкретному сжатому изображению или, в определенных случаях, исходному изображению. На этапе 2757 вызывается подпрограмма «соединить контуры» для объединения любых частей более длинных контуров, разделенных разрывом, как описано выше со ссылкой на Фиг. 26, и контуров, выявленных для рассматриваемого сжатого изображения. На этапе 2758 вызывается подпрограмма «изменить масштаб контуров» для изменения масштаба определенных в сжатом изображении контуров до масштаба исходного изображения. На этапе 2760 вызывается подпрограмма «выполнить слияние контуров» для слияния всех контуров, найденных во всех сжатых изображениях, и передача контуров, объединенных подпрограммой «объединение контуров» после слияния в структуру данных результатов на этапе 2761. Следует отметить, что подпрограмма «соединить контуры» принимается полиморфной и принимает ссылку на структуру данных контуров и на индекс сжатого изображения, как описано на этапе 2757, или принимает один аргумент, ссылающийся на структуру данных результатов.In FIG. 27E shows a block diagram of a “merge defined circuits” routine called up at step 2708 in FIG. 27A. At step 2754, the result data structure is placed, and a link is received to the contour data structure. The for loop of steps 2756-2759 examines the data structure of each contour in the contour data structure. The data structure of each path in the path data structure corresponds to a particular compressed image or, in certain cases, the original image. At step 2757, the “connect contours” routine is called to merge any parts of longer contours separated by a gap, as described above with reference to FIG. 26, and the contours detected for the compressed image in question. At step 2758, the “resize contours” routine is called to resize the contours defined in the compressed image to the scale of the original image. At step 2760, the “perform contour merging” subroutine is called to merge all the contours found in all compressed images and transfer the contours combined by the “contour merge” subroutine into the result data structure at step 2761. It should be noted that the “connect contours” subroutine is accepted as polymorphic and accepts a reference to the contour data structure and to the index of the compressed image, as described in step 2757, or takes one argument referring to the result data structure.

На Фиг. 27F показана блок-схема подпрограммы «соединить контуры», вызываемой на этапе 2757 на Фиг. 27. На этапе 2764 подпрограмма получает сжатое изображение С, использующееся в качестве индекса для структуры данных контуров, на которую также поступает ссылка. В цикле do-while этапов 2765-2773 объединяются пары контуров, выявленные в сжатом изображении С. На этапе 2766 локальной переменной прогресс присваивается значение false(ложь). На этапе 2767 для пары контуров с конечными точками на расстоянии D одна от другой выполняется поиск выявленных контуров. Следует отметить, что для D в определенных вариантах реализации могут быть заданы параметры. При обнаружении следующей пары в соответствии с определением на этапе 2768, на этапах 2769-2771 рассматривается с учетом конечных точек и продления двух контуров, что было описано выше со ссылкой на Фиг. 26, следует ли объединять два контура. Если установлено, что два контура должны быть объединены, то на этапе 2772 для локальной переменной прогресс задается значение true(истина), два контура объединяются, как описано выше со ссылкой на Фиг. 26, и один из исходных контуров в паре удаляется, а второй модифицируется для представления двух объединенных контуров. Цикл do-while этапов 2766-2773 продолжает итерации до тех пор, пока локальная переменная прогресс сохраняет значение true(истина), как определено на этапе 2773.In FIG. 27F shows a block diagram of a connect loop routine called in step 2757 of FIG. 27. At step 2764, the subroutine obtains a compressed image C, which is used as an index for the contour data structure, which is also referred to. The do-while loop of steps 2765-2773 combines the pairs of paths identified in the compressed image C. At step 2766, the progress variable is set to false (false). At step 2767, for a pair of loops with endpoints at a distance D from one another, a search for the detected loops is performed. It should be noted that for D in certain embodiments, parameters can be set. When the next pair is detected in accordance with the determination at step 2768, at steps 2769-2771, it is considered taking into account the end points and the extension of the two loops, as described above with reference to FIG. 26, whether two circuits should be combined. If it is determined that the two circuits should be combined, then at step 2772 the progress is set to true (true) for the local variable, the two circuits are combined as described above with reference to FIG. 26, and one of the original loops in the pair is deleted, and the second is modified to represent two merged loops. The do-while loop of steps 2766-2773 continues to iterate until the local progress variable holds true (true), as determined in step 2773.

На Фиг. 27G показана блок-схема подпрограммы «выполнить слияние контуров», вызываемой на этапе 2760 на Фиг. 27Е. На этапе 2776 подпрограмма получает ссылку на структуру данных результатов и на структуру данных контуров. Затем в цикле do-while этапов 2777-2785 определенные на сжатом изображении контуры объединяются со структурой данных результатов. На этапе 2778 локальной переменной прогресс присваивается значение false(ложъ). На этапе 2779 в выявленных контурах на сжатом изображении выполняется поиск следующего контура, несовпадающего с любым контуром, уже имеющимся в структуре данных результатов. Если, в соответствии с определением на этапе 2780, такой контур обнаружен, то на этапе 2781 определяются все контуры, совпадающие с найденным контуром, среди контуров, определенных в сжатом изображении. На этапе 2782 выбирается лучший из этих контуров и добавляется к структуре данных результатов. Затем, на этапе 2783 из структуры данных контуров удаляются изначально найденный и совпадающий контуры. На этапе 2784 локальной переменной ход выполнения присваивается значение истина. Цикл do-while повторяется до тех пор, пока на этапе 2785 локальной переменной прогресс не будет присвоено значение false(ложъ).In FIG. 27G shows a block diagram of the “perform contour merge” routine called in step 2760 of FIG. 27E. At step 2776, the routine obtains a link to the result data structure and to the contour data structure. Then, in the do-while loop of steps 2777-2785, the contours defined on the compressed image are combined with the result data structure. At step 2778, the local variable is set to false. At step 2779, in the identified contours in the compressed image, a search is made for the next contour that does not coincide with any contour already existing in the result data structure. If, in accordance with the determination in step 2780, such a contour is detected, then in step 2781 all contours matching the found contour are determined among the contours defined in the compressed image. At step 2782, the best of these loops is selected and added to the result data structure. Then, at step 2783, the initially found and matching contours are deleted from the loop data structure. At step 2784, the local variable is set to true. The do-while loop repeats until, at step 2785, the local variable progress is set to false.

Способы и системы, к которым относится настоящий документMethods and systems to which this document relates

На Фиг. 28 показан пример сценария обработки изображения, в котором автоматизированная система обработки изображений пытается определить содержащий документ фрагмент цифрового изображения. На Фиг. 28 на цифровом изображении 2802 содержится документ 2804, лежащий поверх стопки других листов бумаги 2806-2809. Автоматизированная система обработки цифровых изображений может быть, например, подкомпонентом автоматизированной системы распознавания текста, которая направлена на определение содержащих текст документов на цифровых изображениях и на формирование электронных документов, соответствующих содержащим текст документам. Следует сразу же отметить, что способы и системы настоящего изобретения могут определять содержащие документ фрагменты цифрового изображения с нелинейными границами, в том числе документы, искаженные при обработке изображения, в связи с искажением перспективы и иными оптическими эффектами, физическим искажением документов из-за смятия или сгиба, и документы с искривленными границами в их нормальной физической форме. В текущем примере как содержащий текст документ 2804, так и лежащие ниже листы бумаги 2806-2809, для простоты иллюстрации и ясности описания имеют линейные границы, но изображения документов с нелинейными границами уверенно распознаются в ходе описанных ниже процессов распознания документов.In FIG. 28 shows an example of an image processing scenario in which an automated image processing system attempts to determine a document-containing fragment of a digital image. In FIG. 28, digital image 2802 contains a document 2804 lying on top of a stack of other sheets of paper 2806-2809. An automated digital image processing system may, for example, be a subcomponent of an automated text recognition system that aims to identify documents containing text in digital images and to generate electronic documents corresponding to documents containing text. It should be immediately noted that the methods and systems of the present invention can determine fragments of a digital image containing a document with non-linear boundaries, including documents distorted during image processing due to perspective distortion and other optical effects, physical distortion of documents due to crushing or fold, and documents with curved borders in their normal physical form. In the current example, both the text-containing document 2804 and the sheets of paper 2806-2809 below have linear borders for simplicity of illustration and description, but images of documents with non-linear borders are confidently recognized during the document recognition processes described below.

На Фиг. 29 показан первый этап автоматизированного процесса распознавания документов. Способы и системы обнаружения контуров, описанные в предшествующем пункте, применяются к полученному цифровому изображению 2802 для создания карты или структуры данных 2902, которая содержит контуры, соответствующие границам яркости в исходном изображении 2802. Значения входных параметров для способов и систем обнаружения контура регулируются с целью определения контуров, которые наиболее вероятно соответствуют границам документов полностью или частично. В этом случае, например, сильно криволинейные контуры, например, контуры, связанные с искривленными буквами текста, например, буква «s», не определяются в результате применения значений параметров.In FIG. 29 shows the first step of an automated document recognition process. The path detection methods and systems described in the preceding paragraph are applied to the obtained digital image 2802 to create a map or data structure 2902 that contains contours corresponding to the brightness boundaries in the original image 2802. The input parameter values for the path detection methods and systems are adjusted to determine contours that most likely match the borders of documents in whole or in part. In this case, for example, strongly curved contours, for example, contours associated with curved letters of the text, for example, the letter “s”, are not determined as a result of applying the parameter values.

На Фиг. 30 представлены два дополнительных этапа в процессе распознавания изображений документов. Контуры, полученные за счет применения процесса обнаружения контуров 2902, разделяются на первое множество контуров 2904, которые имеют преимущественно вертикальное направление, и второе множество контуров 2906, которые имеют преимущественно горизонтальное направление. В качестве примера, эти контуры, имеющие направление ориентации между 45° и 135°, считаются вертикально ориентированными в одном из вариантов реализации, а контуры с направлениями ориентации от 0° до 45° и от 135° до 180° считаются ориентированными горизонтально. Направление ориентации кривых линий можно определить за счет использования многочисленных возможных способов для подбора линии к кривой линии, включая обычно используемые методы линейной регрессии или более простые геометрические способы, например, аппроксимацию кривой с помощью линии, совпадающей с конечными точками кривой или совпадающей с точками рядом с конечными точками кривой линии. После этого направление ориентации для кривой проходит аппроксимацию как направление ориентации для прямой линии, применяемой для кривой.In FIG. 30 presents two additional steps in the process of image recognition of documents. The contours obtained by applying the loop detection process 2902 are divided into a first plurality of loops 2904, which have a predominantly vertical direction, and a second set of loops 2906, which have a predominantly horizontal direction. As an example, these contours having an orientation direction between 45 ° and 135 ° are considered to be vertically oriented in one embodiment, and contours with orientation directions from 0 ° to 45 ° and from 135 ° to 180 ° are considered horizontal oriented. The direction of the orientation of the curved lines can be determined by using numerous possible methods for fitting the line to the curved line, including commonly used linear regression methods or simpler geometric methods, for example, approximating a curve using a line that matches the end points of the curve or matches the points next to end points of a curve line. After that, the orientation direction for the curve is approximated as the orientation direction for the straight line used for the curve.

Далее, как также показано на Фиг. 30, контуры, направленные преимущественно вертикально 2904, разделяются на левые контуры 2908 и правые контуры 2910. Аналогичным образом по большей части горизонтально направленные контуры 2906 разделяются на верхние контуры 2912 и нижние контуры 2914. В одном варианте реализации эти операции не дают строгое разделение, поскольку некоторые контуры могут заканчиваться в обоих разделах. В одном варианте реализации горизонтальная граница карты направленных преимущественно вертикально контуров 2904 разделяется на три вертикальных участка 2916-2918, определенных следующим образом: (1) левый участок 2916 от х=0,0 до 0,4, где х - координата на горизонтальной оси Декартовой системы координат цифрового изображения; (2) центральная область 2917 от х=0,4 до 0.6; и (3) правый участок 2918 от x=0,6 до 1,0. Следует отметить, что координаты x являются относительным координатами относительно ширины цифрового изображения 1.0. Левые контуры 2908 являются преимущественно вертикально направленными в карте контуров 2904, содержащимися в левой и центральной вертикальной области 2916 и 2917. Правые контуры 2910 преимущественно направлены вертикально и появляются в центральной 2917 и правой 2918 области карты 2904 преимущественно вертикально направленных контуров. Например, в результате нестрогого разделения небольшое множество контуров 2920 появляется в карте правых контуров 2908 и в карте левых контуров 2910. Аналогичное разделение вертикальной оси карты преимущественно горизонтально направленных контуров 2906 используется для создания верхней 2912 и нижней 2914 карт контуров из множества преимущественно горизонтально направленных контуров 2906.Further, as also shown in FIG. 30, outlines directed primarily vertically 2904 are divided into left outlines 2908 and right outlines 2910. Similarly, for the most part, horizontally directed outlines 2906 are divided into upper outlines 2912 and lower outlines 2914. In one embodiment, these operations do not give strict separation, since some contours may end in both sections. In one embodiment, the horizontal boundary of the map of vertically directed paths 2904 is divided into three vertical sections 2916-2918, defined as follows: (1) the left section 2916 from x = 0.0 to 0.4, where x is the coordinate on the horizontal axis of Cartesian digital image coordinate systems; (2) the central region 2917 from x = 0.4 to 0.6; and (3) the right portion 2918 from x = 0.6 to 1.0. It should be noted that the x coordinates are relative coordinates relative to the width of the digital image 1.0. The left contours 2908 are predominantly vertically directed in the contour map 2904 contained in the left and central vertical regions 2916 and 2917. The right contours 2910 are predominantly directed vertically and appear in the central 2917 and right 2918 regions of the card 2904 of predominantly vertically directed contours. For example, as a result of non-strict separation, a small number of contours 2920 appear in the map of the right contours 2908 and in the map of the left contours 2910. A similar division of the vertical axis of the map of predominantly horizontally directed contours 2906 is used to create upper 2912 and lower 2914 contour maps from the set of mainly horizontally directed contours 2906 .

Следует отметить, что для простоты иллюстрации и наглядности множества контуров 2904 и 2906, создаваемые при первом разделении контуров, и четыре множества контуров 2908, 2910, 2912 и 2914, создаваемые при втором нестрогом разделении, показаны в виде изображений или карт. При этом они могут быть представлены в электронном виде как структуры данных, включающие координаты конечных точек каждого контура и также могут быть представлены множеством других способов. В последующем описании четыре нестрогих разделения 2908, 2910, 2912 и 2914 называются «множествами контуров» и, в частности, «множеством левых контуров» 2908, «множеством правых контуров» 2910, «множеством верхних контуров» 2912 и «множеством нижних контуров» 2914.It should be noted that for simplicity of illustration and clarity, the set of loops 2904 and 2906 created during the first separation of loops, and the four sets of loops 2908, 2910, 2912 and 2914 created during the second loose separation, are shown in the form of images or maps. Moreover, they can be represented in electronic form as data structures, including the coordinates of the end points of each circuit and can also be represented in many other ways. In the following description, the four non-strict partitions 2908, 2910, 2912 and 2914 are called “sets of contours” and, in particular, “many left contours” 2908, “many right contours” 2910, “many upper contours” 2912 and “many lower contours” 2914 .

На следующем этапе четыре множества контуров проходят фильтрацию и сортировку по длине контуров или, как вариант, по количеству пикселей, содержащихся в контурах. Верхние n контуров каждого множества контуров сохраняются для последующей обработки, где n является параметром. В одном из вариантов реализации n равно 10. Выбор n верхних контуров-кандидатов может быть основан на длине, количестве пикселей в пределах контура и иных подобных критериях. В определенных вариантах реализации эти критерии объединяются с дополнительными критериями, включая среднюю величину модуля градиента для пикселей в пределах контура, меру равномерности направления градиента в пределах контура и иные подобные критерии. При альтернативном варианте фильтрации также может использоваться информация о цветах исходного цифрового изображения.In the next step, four sets of contours are filtered and sorted by the length of the contours or, alternatively, by the number of pixels contained in the contours. The upper n contours of each set of contours are stored for further processing, where n is a parameter. In one embodiment, n is 10. The selection of n upper candidate contours may be based on the length, number of pixels within the contour, and other similar criteria. In certain implementations, these criteria are combined with additional criteria, including the average value of the gradient modulus for pixels within the contour, a measure of the uniformity of the gradient direction within the contour, and other similar criteria. With an alternative filtering option, the color information of the original digital image may also be used.

На Фиг. 31 показано построение гипотезы на основе четырех множеств контуров, рассматриваемых на Фиг. 30. На Фиг. 31 четыре множества контуров представлены четырьмя картами контуров 3102-3105. Опять же, множества контуров могут быть представлены структурами данных, картами или любыми другими представлениями множества контуров. Также следует подчеркнуть, что контуры могут быть представлены кривыми линиями или прямыми линиями. Гипотеза создается путем выбора одного контура из каждого множества контуров с последующим построением многоугольника из выбранных контуров. На Фиг. 31 кривые стрелки, например, кривая стрелка 3106, указывают на выбор контура из каждого множества контуров для создания расположения контуров 3108-3111, показанной в левой нижней части на Фиг. 31. Затем контуры, по необходимости, продлеваются для образования многоугольника 3112 с четырьмя вершинами 3114-3117. Прерывистые линии, например, прерывистые линии 3117-3121, представляют собой продление контуров для образования многоугольника. Эти продленные контуры могут быть получены различными методиками продления контуров, включая определение наиболее подходящей линии для кривого контура с использованием способов линейной регрессии, геометрического продления, при этом кривой сегмент продлевается по линии, соединяющей две точки в пределах кривого сегмента или иными способами применения линий к кривым. Линейные сегменты продлеваются по прямой в том же направлении, что линейный сегмент с любого одного конца или с обоих концов. Следует отметить, что, несмотря на то, что построенный многоугольник на Фиг. 31 лежит полностью в границах исходного изображения, продление контуров может привести к тому, что полигон будет лежать частично за пределами исходного изображения. Например, продление контуров двух приблизительно перпендикулярных контуров может привести к построению вершины за пределами границы исходного изображения. Многоугольник, в котором часть границ и вершин лежит за пределами границ исходного изображения, является допустимым с учетом описанных ниже ограничений. В целом, способы и системы настоящего изобретения составляют все возможные гипотезы или, иными словами, все возможные сочетания четырех контуров, каждый из которых выбирается из другого множества контуров, и выполняется оценка гипотезы для выбора лучшего контура кандидата для документа.In FIG. 31 shows the construction of a hypothesis based on the four sets of contours considered in FIG. 30. In FIG. 31, four sets of loops are represented by four loop cards 3102-3105. Again, multiple outlines can be represented by data structures, maps, or any other representations of multiple outlines. It should also be emphasized that the contours can be represented by curved lines or straight lines. A hypothesis is created by selecting one contour from each set of contours with the subsequent construction of a polygon from the selected contours. In FIG. 31, curved arrows, for example, curved arrow 3106, indicate the selection of a contour from each set of contours to create the location of the contours 3108-3111 shown in the lower left of FIG. 31. Then, the contours, as necessary, are extended to form a polygon 3112 with four vertices 3114-3117. Dashed lines, for example, dashed lines 3117-3121, are contours extended to form a polygon. These extended contours can be obtained by various contour extension methods, including determining the most suitable line for the curved contour using linear regression, geometric extension methods, while the curve segment is extended along the line connecting two points within the curve segment or by other ways of applying lines to the curves . Line segments extend in a straight line in the same direction as a line segment from either one end or both ends. It should be noted that, despite the fact that the constructed polygon in FIG. 31 lies completely within the boundaries of the original image, the extension of the contours can lead to the fact that the polygon will lie partially outside the original image. For example, extending the outlines of two approximately perpendicular outlines can lead to the construction of a vertex outside the boundary of the original image. A polygon in which part of the boundaries and vertices lies outside the boundaries of the original image is valid, taking into account the restrictions described below. In general, the methods and systems of the present invention constitute all possible hypotheses or, in other words, all possible combinations of four contours, each of which is selected from a different set of contours, and the hypothesis is evaluated to select the best candidate contour for the document.

На Фиг. 32 показан ряд соображений и критериев для выбора кандидатов. Гипотеза-кандидат 3202 представляет собой четырехсторонний многоугольник или четырехугольник со сторонами длиной а 3203, b 3204, с 3205 и d 3206. Многоугольник 3202 имеет две диагонали 3208 и 3209 длиной р и q. Многоугольник имеет четыре угла е 3212, ƒ 3213, g 3214 и h 3215. Гипотеза, или многоугольник 3202, также может быть распрямлен до прямоугольника, имеющего стороны длиной с' 3218 и b' 3220, показанные прерывистыми линиями на Фиг. 32. Прямоугольник из прерывистых линий со сторонами 3222-3225 представляет исходную границу цифрового изображения. Эта исходная граница продлевается в геометрическом представлении, показанном на Фиг. 32, до прямоугольника, показанного прерывистыми линиями 3226-3229 с высотой Не 3230 и шириной We 3232. Для этого продления могут применяться параметры TH 3234 и TW 3236, как показано на Фиг. 32.In FIG. 32 shows a number of considerations and criteria for selecting candidates. Candidate hypothesis 3202 is a four-sided polygon or quadrangle with sides of length a 3203, b 3204, c 3205 and d 3206. Polygon 3202 has two diagonals 3208 and 3209 of length p and q. The polygon has four angles e 3212, ƒ 3213, g 3214 and h 3215. Hypothesis, or polygon 3202, can also be rectified to a rectangle having sides with lengths of '3218 and b' 3220, shown by broken lines in FIG. 32. A rectangle of dashed lines with sides 3222-3225 represents the original border of the digital image. This initial boundary is extended in the geometric representation shown in FIG. 32, to the rectangle shown by broken lines 3226-3229 with a height of H e 3230 and a width of W e 3232. For this extension, the parameters T H 3234 and T W 3236 can be applied, as shown in FIG. 32.

С правой стороны на Фиг. 32 перечислены шесть различных критериев для оценки гипотезы. Первый критерий 3240 заключается в том, что углы многоугольника расположены в пределах большого прямоугольника высотой Не и шириной We, со сторонами 3226-3229. Второй критерий 3242 заключается в том, что многоугольник должен быть выпуклым. В выпуклом многоугольнике все внутренние углы имеют значение менее 180°, при этом отрезок линии, соединяющий любые две произвольно расположенные точки на границах многоугольника, не содержит какие-либо точки за пределами многоугольника. Для каждой стороны многоугольника x рассчитывается показатель качества стороны qx 3244. Этот показатель принимает одно из трех значений: 1, 20

Figure 00000017
- 2 и 0, в зависимости от отношения
Figure 00000018
как показано в выражении 3246 на Фиг. 32. Показатель качества по площади 3248 рассчитывается аналогичным образом, как показано в выражении 3250, из площади многоугольника 3252. Показатель качества по площади qA имеет одно из трех значений 1,
Figure 00000019
- 0,75, и 0, в зависимости от значения коэффициента
Figure 00000020
Показатель качества по углам qy 3254 рассчитывается для каждого угла у многоугольника в соответствии с выражением 3256. Показатель качества по углам qy может принимать четыре значения, находящиеся в интервале от 1 до 0, при этом для углов ближе к 90° присваиваются более высокие значения. Показатель качества по соотношению сторон qS 3258 рассчитывается в соответствии с псевдокодом 3260, если известно отношение ширины документа к высоте документа
Figure 00000021
. По сути, показатель качества по соотношению сторон qS имеет значение 1, когда отношение ширины к высоте распрямленного многоугольника или прямоугольника приближается к известному отношению ширины документа к его высоте, в ином случае отношение равно 0.On the right side in FIG. 32 lists six different criteria for evaluating a hypothesis. 3240 The first criterion is that the corners of the polygon are within a large rectangle of height H f and the width W e, with sides 3226-3229. The second criterion 3242 is that the polygon must be convex. In a convex polygon, all internal angles have a value less than 180 °, while the line segment connecting any two arbitrarily located points at the boundaries of the polygon does not contain any points outside the polygon. For each side of the polygon x, the quality index of the side q x 3244 is calculated. This indicator takes one of three values: 1, 20
Figure 00000017
- 2 and 0, depending on the ratio
Figure 00000018
as shown in expression 3246 in FIG. 32. The quality indicator for the area 3248 is calculated in the same way, as shown in expression 3250, from the area of the polygon 3252. The quality indicator for the area qA has one of three values 1,
Figure 00000019
- 0.75, and 0, depending on the value of the coefficient
Figure 00000020
The quality index for angles q y 3254 is calculated for each angle near the polygon in accordance with the expression 3256. The quality index for angles q y can take four values ranging from 1 to 0, with higher values being assigned for angles closer to 90 ° . The aspect ratio qS 3258 is calculated in accordance with pseudo-code 3260, if the ratio of the width of the document to the height of the document is known
Figure 00000021
. In fact, the quality index in terms of the aspect ratio qS has a value of 1 when the ratio of the width to the height of the straightened polygon or rectangle approaches the known ratio of the width of the document to its height, otherwise the ratio is 0.

На Фиг. 33 и 34 представлен расчет значения показателя веса стороны с целью построения гипотезы. На Фиг. 33 показан расчет веса для пикселя, лежащего в пределах или вдоль одной из сторон гипотезы. Двунаправленная стрелка 3302 представляет направление стороны гипотезы, а прерывистая двунаправленная стрелка 3304 представляет направление р, перпендикулярное стороне 3302. Пиксель i 3306 лежит на стороне 3302 гипотезы. Пиксель связан с вектором градиента gradienti 3308, что было описано в предыдущем разделе. Длина проекции градиента 3308 на вектор р, имеющая направление, равное направлению р, может быть рассчитана как скалярное произведение градиента и р, как показано в выражении 3312 на Фиг. 33. Угол α 3314 между связанным с пикселем градиентом и направлением р рассчитывается по выражению 3314 и служит как числовое указание на то, насколько близко направление градиента пикселя соответствует направлению р, имеющему значение 0, когда градиент и направление р являются взаимно перпендикулярными, и значение 1, когда градиент и направление р параллельны. Затем значение угла α может быть использовано в выражении 3316 для расчета весового значения weighti для заданного пикселя i. Чем ближе связанный с пикселем градиент соответствует направлению, перпендикулярному стороне многоугольника, тем больше вес пикселя.In FIG. 33 and 34 presents the calculation of the value of the side weight indicator in order to build a hypothesis. In FIG. 33 shows a weight calculation for a pixel lying within or along one side of a hypothesis. The bidirectional arrow 3302 represents the direction of the side of the hypothesis, and the discontinuous bidirectional arrow 3304 represents the direction p, perpendicular to the side 3302. Pixel i 3306 lies on the side 3302 of the hypothesis. The pixel is associated with the gradient i 3308 gradient vector, which was described in the previous section. The projection length of the gradient 3308 onto the vector p, having a direction equal to the direction p, can be calculated as the scalar product of the gradient and p, as shown in expression 3312 in FIG. 33. The angle α 3314 between the gradient associated with the pixel and the direction p is calculated using the expression 3314 and serves as a numerical indication of how close the direction of the gradient of the pixel corresponds to the direction p having a value of 0, when the gradient and direction p are mutually perpendicular, and the value 1 when the gradient and direction p are parallel. Then, the angle α can be used in expression 3316 to calculate the weight value weight i for a given pixel i. The closer the gradient associated with the pixel corresponds to the direction perpendicular to the side of the polygon, the greater the weight of the pixel.

На Фиг. 34 представлен расчет совокупного весового значения weighthy для гипотезы. На Фиг. 34 сторона гипотезы представлена сплошной двунаправленной стрелкой 3402 и прерывистой двунаправленной стрелкой 3404. Стрелка 3402 представляет контур, а прерывистая стрелка 3404 представляет продление контура для создания гипотезы. Стрелка накладывается на ряд пикселей, показанных прерывистыми линиями, например, пиксель 3406 исходного изображения. Количество пикселей, охватываемых контурной частью стороны, 3402, равно SF 3408 и имеет числовое значение 19 в представленном на Фиг. 34 примере. Количество пикселей, охватываемых продленной частью стороны, FE 3410 имеет значение 11 в представленном на Фиг. 34 примере. Отношение q 3412 является отношением SF к SF+FE. Вес стороны, weightside 3414 рассчитывается по выражению 3416. Показатель weightside р имеет значение, основанное на весовых значениях пикселей контура Wi и весовых значениях пикселей, связанных с продлением части стороны W0. Показатель веса стороны weighthyp для гипотезы представляет собой сумму весов, рассчитанных для сторон 3418. В качестве варианта для получения значений Wi и W0 может использоваться средний вес пикселя.In FIG. 34 presents the calculation of the total weight value of weight hy for the hypothesis. In FIG. 34, the hypothesis side is represented by a solid bidirectional arrow 3402 and an intermittent bidirectional arrow 3404. Arrow 3402 represents an outline, and intermittent arrow 3404 represents an extension of an outline to create a hypothesis. The arrow is superimposed on a series of pixels shown by dashed lines, for example, pixel 3406 of the original image. The number of pixels covered by the contour portion of the side, 3402, is equal to SF 3408 and has a numerical value of 19 in FIG. 34 example. The number of pixels covered by the extended portion of the side, FE 3410, has a value of 11 in FIG. 34 example. The ratio q 3412 is the ratio of SF to SF + FE. The weight of the side, weight side 3414 is calculated by the expression 3416. The weight side p has a value based on the weight values of the pixels of the contour W i and the weight values of the pixels associated with the extension of part of the side W 0 . The side weight index weight hyp for the hypothesis is the sum of the weights calculated for the parties 3418. Alternatively, the average pixel weight can be used to obtain the values of W i and W 0 .

На Фиг. 35А-Е приведены блок-схемы, на которых показан один вариант реализации способа определения документа и системы, к которым относится настоящий документ. На этапе 3502 принимается цифровое изображение, являющееся изображением документа или содержащее фрагмент документа. На этапе 3503 устанавливаются значения параметров для выявления контуров в пределах полученного изображения в соответствии со способом обнаружения контуров и системы, описанной в предыдущем подразделе настоящего документа. Затем на этапе 3504 вызывается описанная выше подпрограмма «найти контуры» для обнаружения контуров в цифровом изображении. На этапе 3505 выявленные контуры разделяются на множества вертикальных и горизонтальных контуров (2904 и 2906 на Фиг. 30 соответственно). На этапе 3506 множество вертикальных контуров проходит нестрогое разделение на множество левых и правых контуров (2908 и 2910 на Фиг. 30). На этапе 3507 множество горизонтальных контуров проходит нестрогое разделение на множества верхних и нижних контуров (2912 и 2914 на Фиг. 30). На этапе 3508 множества контуров фильтруются и сортируются по длине, по количеству пикселей, совпадающих с каждым контуром, или по другим дополнительным критериям. Если полученное изображение связано с информацией, указывающей на размер, положение и направление границы документа, как определено на этапе 3509, множество контуров, соответствующее этой границе, на этапе 3510 заменяется известной стороной. В качестве одного примера полученное изображение может быть представлено автоматической фотографией паспорта, в которой паспорт имеет заданное положение в пределах цифрового изображения, при этом верхняя граница паспорта имеет горизонтальную ориентацию в положении с известным относительным расстоянием от верхней границы цифрового изображения. На этапе 3511 вызывается подпрограмма «выбрать документ» для определения изображения или фрагмента изображения, содержащего документ, в пределах полученного цифрового изображения. Если документ выбирается вызовом подпрограммы «выбрать документ», как определено на этапе 3512, то на этапе 3513 возвращается указатель на описание границ документа. В ином случае на этапе 3514 возвращается нулевой указатель.In FIG. 35A-E are flowcharts showing one embodiment of a method for determining a document and the system to which this document relates. At step 3502, a digital image is received, which is an image of a document or containing a fragment of a document. At step 3503, parameter values are set to detect the contours within the acquired image in accordance with the method for detecting contours and the system described in the previous subsection of this document. Then, at 3504, the “find outlines” subroutine described above is called to detect outlines in the digital image. At 3505, the detected loops are divided into multiple vertical and horizontal loops (2904 and 2906 in FIG. 30, respectively). At step 3506, the plurality of vertical contours are loosely divided into a plurality of left and right contours (2908 and 2910 in FIG. 30). At step 3507, the plurality of horizontal loops are loosely divided into multiple upper and lower loops (2912 and 2914 in FIG. 30). At 3508, multiple contours are filtered and sorted by length, by the number of pixels matching each contour, or by other additional criteria. If the obtained image is associated with information indicating the size, position and direction of the document border, as determined at step 3509, the set of contours corresponding to this border at step 3510 is replaced by a known party. As one example, the resulting image can be represented by an automatic photograph of a passport in which the passport has a predetermined position within the digital image, while the upper border of the passport has a horizontal orientation in a position with a known relative distance from the upper border of the digital image. At 3511, a “select document” subroutine is called to determine the image or image fragment containing the document within the resulting digital image. If the document is selected by calling the "select document" subroutine, as determined at step 3512, then at step 3513, a pointer to a description of the boundaries of the document is returned. Otherwise, at step 3514, a null pointer is returned.

На Фиг. 35В показана блок-схема подпрограммы «выбрать документ», вызываемой на этапе 3511 на Фиг. 35А. На этапе 3516 подпрограмма «выбрать документ» получает четыре множества контуров, подготовленных на этапах 3504-3510 на Фиг. 35А, и исходное полученное изображение. На этапе 3517 массив из четырех элементов cur_hyp инициализируется нулями, указатель h устанавливается на ноль, а локальная переменная val принимает значение -1. Затем в цикле do-while этапов 3518-3523 подпрограмма «выбрать документ» на этапе 3519 итеративно вызывает подпрограмму «следующая гипотеза» для создания следующей гипотезы. При создании гипотезы в соответствии с определением на этапе 3520 подпрограмма «выбрать документ» выполняет оценку гипотезы через вызов подпрограммы «оценка гипотезы» на этапе 3521 с сохранением на этапе 3523 оценки и указателя для созданной гипотезы, когда оценка, возвращаемая подпрограммой «оценка гипотезы» превышает значение, сохраненное в локальной переменной val, в соответствии с определением на этапе 3522. Если дальнейшие гипотезы не создаются, как определено на этапе 3520, и если текущее сохраненное в локальной переменной val значение превышает пороговое значение, как определено на этапе 3524, на этапе 3525 возвращается указатель на лучшую сформированную гипотезу. В ином случае на этапе 3526 возвращается нулевой указатель. В описываемом варианте реализации лучшая гипотеза имеет оценку с максимальным значением модуля.In FIG. 35B is a flowchart of a “select document” routine invoked in step 3511 of FIG. 35A. At step 3516, the “select document” routine receives four sets of contours prepared at steps 3504-3510 of FIG. 35A, and the original image obtained. At step 3517, an array of four cur_hyp elements is initialized to zeros, the pointer h is set to zero, and the local variable val takes the value -1. Then, in the do-while loop of steps 3518-3523, the “select document” routine at step 3519 iteratively calls the “next hypothesis” routine to create the next hypothesis. When creating a hypothesis in accordance with the definition at step 3520, the “select document” subroutine evaluates the hypothesis through a call to the hypothesis evaluation subroutine at step 3521, saving the estimate and index for the created hypothesis at step 3523 when the estimate returned by the hypothesis evaluation subroutine exceeds the value stored in the local variable val, as defined in step 3522. If no further hypotheses are created, as determined in step 3520, and if the current value stored in the local variable val is exceeded AET threshold, as determined in step 3524, in step 3525 returns a pointer to the generated best hypothesis. Otherwise, at step 3526, a null pointer is returned. In the described embodiment, the best hypothesis has an estimate with a maximum modulus value.

На Фиг. 35С показана блок-схема подпрограммы «следующая гипотеза», вызываемая на этапе 3519 на Фиг. 35В. На этапе 3530 подпрограмма «следующая гипотеза» получает четыре множества контуров, исходное изображение и переменную массива cur_ryp. Если в переменной cur_hyp содержатся только нули, в соответствии с определением на этапе 3531, подпрограмма «следующая гипотеза» на этапе 3532 создает гипотезу по умолчанию, состоящую из четырех сторон исходного изображения. Затем переменной массива cur_hyp на этапе 3533 присваивается значение {0,1,1,1}, а на этапе 3534 возвращается указатель на гипотезу по умолчанию. Гипотеза по умолчанию предполагает, что изображение документа составляет все полученное цифровое изображение. Если переменная массива cur_hyp содержит не только нули, как определено на этапе 3531, то, если переменная массива cur_hyp содержит значения {0,1,1,1}, как определено на этапе 3535, и если все множества контуров имеют, по меньшей мере, один член или контур в соответствии с определением на этапе 3536, то для переменной массива cur_hyp на этапе 3537 задаются значения {1,1,1,1} для инициации создания всех возможных гипотез из членов четырех множеств гипотез. В ином случае на этапе 3538 возвращается нулевой указатель. Если в результате получается комбинаторная гипотеза, при которой сохраненные в переменной cur_hyp значения равны {1,1,1,1}, то на этапе 3539 вызывается подпрограмма «создать гипотезу» для создания гипотезы на основе текущих значений переменной массива cur_hyp. Эти четыре значения указывают на определение контура для выбора из каждого множества четырех контуров с целью формирования следующей гипотезы. Поскольку множества контуров проходят сортировку, изначально сформированные гипотезы могут быть наиболее вероятными для представления границ документа, при этом при формировании гипотез в определенных вариантах реализации может происходить «короткое замыкание», если создаются исходные гипотезы достаточного качества. Если подпрограммой «создание гипотезы» на основе значений в массиве cur_typ успешно создается гипотеза, как описано на этапе 3540, то на этапе 3541 возвращается указатель на гипотезу. В ином случае выполняется переход к этапу 3542, первому этапу из серии обусловленных этапов, использующихся для установления значений, хранящихся в массиве cur_hyp для обозначения контуров для следующей гипотезы. Если в четвертом множестве контуров имеется член контура после члена, назначенного текущим значением четвертого элемента в массиве cur_hyp, в соответствии с определением на этапе 3542, то четвертый элемент в массиве cur_hyp на этапе 3543 увеличивается, и на этапе 3539 вызывается подпрограмма «создание гипотезы». В ином случае, если в третьем множестве контуров имеется член, следующий за членом, назначенным по третьему значению в массиве cur_hyp, в соответствии с определением на этапе 3544, то значение, хранящееся в третьем элементе массива cur_hyp, увеличивается, а для четвертого значения в массиве cur_hyp на этапе 3545 задается значение 1, после чего на этапе 3539 вызывается подпрограмма «создание гипотезы». В ином случае, если сохраненное во втором множестве контуров значение содержит член, следующий за членом, определенный по текущему значению второго элемента в массиве cur_hyp, в соответствии с определением на этапе 3546, то второй элемент массива cur_hyp увеличивается, а третьему и четвертому элементам в массиве cur_hyp на этапе 3547 задается значение 1, после чего на этапе 3539 выполняется вызов к подпрограмме «создание гипотезы». В ином случае, если первое множество контуров содержит член, следующий за членом, определенный по текущему значению первого элемента в массиве cur_hyp, в соответствии с определением на этапе 3548, то на этапе 3549 первое значение, сохраненное в массиве cur_hyp, увеличивается, а для оставшихся значений задается значение 1, после чего на этапе 3539 выполняется вызов к подпрограмме «создать гипотезу». В ином случае, дальнейшие гипотезы-кандидаты отсутствуют, и на этапе 3550 возвращается нулевой указатель.In FIG. 35C shows a block diagram of the “next hypothesis” routine that is called up at block 3519 in FIG. 35B. At block 3530, the “next hypothesis” routine obtains four sets of contours, the original image, and the cur_ryp array variable. If the cur_hyp variable contains only zeros, as defined in step 3531, the “next hypothesis” routine in step 3532 creates a default hypothesis consisting of four sides of the original image. Then, the variable cur_hyp is assigned the value {0,1,1,1} at step 3533, and a pointer to the hypothesis is returned by default at step 3534. The hypothesis by default assumes that the image of the document constitutes the entire digital image obtained. If the cur_hyp array variable contains not only zeros, as determined in step 3531, then if the cur_hyp array variable contains the values {0,1,1,1}, as determined in step 3535, and if all sets of contours have at least one term or contour as defined in step 3536, then for the array variable cur_hyp in step 3537 the values {1,1,1,1} are set to initiate the creation of all possible hypotheses from the members of four sets of hypotheses. Otherwise, at step 3538, a null pointer is returned. If the result is a combinatorial hypothesis in which the values stored in the cur_hyp variable are {1,1,1,1}, then at step 3539 the “create hypothesis” subroutine is called to create a hypothesis based on the current values of the cur_hyp array variable. These four values indicate a contour definition for selecting from each set of four contours in order to formulate the following hypothesis. Since the sets of contours are sorted, initially formed hypotheses may be most likely to represent the boundaries of the document, while during the formation of hypotheses in certain implementations, a “short circuit” may occur if initial hypotheses of sufficient quality are created. If the hypothesis creation routine based on the values in the cur_typ array successfully creates a hypothesis, as described in step 3540, then in step 3541 a pointer to the hypothesis is returned. Otherwise, it proceeds to step 3542, the first step from a series of conditional steps used to establish the values stored in the cur_hyp array to indicate the contours for the next hypothesis. If in the fourth set of contours there is a contour member after the member assigned by the current value of the fourth element in the cur_hyp array, as defined in step 3542, then the fourth element in the cur_hyp array in step 3543 is incremented, and the “hypothesis creation” routine is called in step 3539. Otherwise, if the third set of loops contains a member following the member assigned by the third value in the cur_hyp array, as defined in step 3544, then the value stored in the third element of the cur_hyp array increases, and for the fourth value in the array cur_hyp is set to 1 at 3545, after which the hypothesis creation routine is called at 3539. Otherwise, if the value stored in the second set of contours contains the term following the term determined by the current value of the second element in the cur_hyp array, as defined in step 3546, then the second element of the cur_hyp array is incremented, and the third and fourth elements in the array at 3547, cur_hyp is set to 1, after which at 3539 a call is made to the hypothesis creation routine. Otherwise, if the first set of loops contains a member following the member determined by the current value of the first element in the cur_hyp array, as defined in step 3548, then in step 3549 the first value stored in the cur_hyp array is incremented, and for the remaining values is set to 1, after which, at step 3539, a call is made to the “create hypothesis” routine. Otherwise, there are no further candidate hypotheses, and at step 3550 a null pointer is returned.

На Фиг. 35D показана блок-схема подпрограммы «создать гипотезу», вызываемой на этапе 3539 на Фиг. 35С. На этапе 3554 подпрограмма «создать гипотезу» получает переменную массива cur_hyp, четыре множества контуров и исходное цифровое изображение. На этапе 3555 значения элементов в массиве cur_hyp используются для выбора соответствующих контуров из четырех множеств контуров, как описано выше со ссылкой на Фиг. 31. Затем на этапе 3556 стороны по необходимости продлеваются для создания четырехстороннего многоугольника, что также описано выше со ссылкой на Фиг. 31. Продление сторон может выполняться путем определения наиболее подходящего отрезка линии, соответствующего кривому контуру и продлевающему этот отрезок или путем продления одного или обоих концов линейного контура. Если на этапах 3555 и 3556 был успешно создан четырехсторонний многоугольник в соответствии с определением на этапе 3557, то на этапе 3558 подпрограмма определяет, продлевается ли четырехсторонний многоугольник далее за пороговое расстояние за пределы границ исходного изображения в соответствии с приведенным выше описанием со ссылкой на Фиг. 32. Если четырехсторонний многоугольник не продлевается более чем на пороговое расстояние за пределы границ исходного изображения, и если четырехсторонний многоугольник является выпуклым, в соответствии с определением на этапе 3559, то на этапе 3560 строится структура данных гипотезы, содержащая координаты вершин многоугольника, а на этапе 3561 возвращается указатель на гипотезу. Конечно же, во многих вариантах реализации, в подпрограмму «создать гипотезу» может поступать пустая структура данных гипотезы для сохранения координат новых вершин, соответствующих создаваемой гипотезе с возвратом булевых значений, указывающих на то, была построена гипотеза или нет. Если четырехсторонний многоугольник не может быть создан, то при превышении многоугольником пороговых расстояний, соответствующих границам цифрового изображения или при невыпуклом создаваемом многоугольнике, на этапе 3562 возвращается нулевой указатель.In FIG. 35D is a flowchart of the Create Hypothesis subroutine invoked in step 3539 of FIG. 35C. At step 3554, the hypothesis subroutine receives the cur_hyp array variable, four sets of paths, and the original digital image. At 3555, the values of the elements in the cur_hyp array are used to select the corresponding outlines from the four sets of outlines, as described above with reference to FIG. 31. Then, at step 3556, the sides are extended as necessary to create a four-sided polygon, which is also described above with reference to FIG. 31. The extension of the sides can be carried out by determining the most suitable segment of the line corresponding to the curved contour and extending this segment or by extending one or both ends of the linear contour. If the quadrilateral polygon was successfully created in steps 3555 and 3556 as defined in step 3557, then in step 3558 the subroutine determines whether the quadrilateral polygon is extended beyond the threshold distance beyond the boundaries of the original image in accordance with the above description with reference to FIG. 32. If the four-sided polygon does not extend more than a threshold distance beyond the boundaries of the original image, and if the four-sided polygon is convex, as defined in step 3559, then in step 3560 a hypothesis data structure containing the coordinates of the vertices of the polygon is constructed, and in step 3561 returns a hypothesis pointer. Of course, in many implementations, the “create hypothesis” subroutine may receive an empty hypothesis data structure to preserve the coordinates of new vertices corresponding to the created hypothesis with the return of Boolean values indicating whether the hypothesis was built or not. If the four-sided polygon cannot be created, then when the polygon exceeds the threshold distances corresponding to the boundaries of the digital image or if the polygon is not convex, the null pointer is returned at 3562.

На Фиг. 35Е показана блок-схема подпрограммы «оценка гипотезы», вызываемой на этапе 3521 на Фиг. 35В. На этапе 3566 подпрограмма «оценка гипотезы» получает четыре множества контуров, исходное цифровое изображение, массив cur_hyp и ссылку на структуру данных гипотезы. На этапе 3567 подпрограмма «оценка гипотезы» задает четырем локальным переменным q1, q2, q3, и q4 значение 0, вместе с локальной переменной wS. В цикле for на этапах 3568-3571 подпрограмма «оценка гипотезы» рассматривает каждую сторону гипотетического многоугольника, рассчитывая для каждой стороны значение показателя качества стороны qx, что было описано выше со ссылкой на Фиг. 32, и вес для стороны weightside, описанный выше со ссылкой на Фиг. 33-34. На этапе 3570 рассчитанный показатель качества стороны добавляется к локальной переменной q1, а рассчитанный вес для стороны weightside добавляется к локальной переменной wS. В цикле for на этапах 3572-3574 для каждого угла многоугольника рассчитывается показатель качества по углам и добавляется к локальной переменной q3. Показатель качества по углам описан выше со ссылкой на Фиг. 32. На этапе 3575 рассчитываются показатели качества по площади и качества по соотношению сторон qA и qS и добавляются к локальным переменным q2 и qA, соответственно. Показатели качества по площади и качества по соотношению сторон описаны выше со ссылкой на Фиг. 32. На этапе 3576 для назначенной суммы значений четырех локальных переменных q1, q2, q3 и q4 задается значение G. Затем на этапе 3577 рассчитывается гипотетическая оценка в виде взвешенных сумм локальных переменных wS и G, значение сохраняется в локальных переменных G и wS с возможным возведением в интегральную или дробную степень е1 и е2. Если рассчитанная оценка близка к нулю или находится в пределах нулевого порогового расстояния, в соответствии с определением на этапе 3578, то на этапе 3579 возвращается нулевое значение. В противном случае на этапе 3580 возвращается вычисленная оценка.In FIG. 35E shows a block diagram of a hypothesis evaluation subroutine called in step 3521 of FIG. 35B. At step 3566, the hypothesis evaluation routine receives four sets of contours, the original digital image, the cur_hyp array, and a link to the hypothesis data structure. At step 3567, the hypothesis evaluation routine sets the four local variables q1, q2, q3, and q4 to 0, along with the local variable wS. In the for loop at steps 3568-3571, the hypothesis evaluation subroutine considers each side of the hypothetical polygon, calculating for each side the value of the side quality index q x , which was described above with reference to FIG. 32, and the weight for the weight side described above with reference to FIG. 33-34. At 3570, the calculated side quality score is added to the local variable q1, and the calculated weight for the weight side is added to the local variable wS. In the for loop at steps 3572-3574, for each corner of the polygon, a quality indicator for the angles is calculated and added to the local variable q3. The corner quality score is described above with reference to FIG. 32. At step 3575, the quality indicators by area and quality are calculated by the aspect ratio qA and qS and added to the local variables q2 and qA, respectively. Quality indicators by area and quality by aspect ratio are described above with reference to FIG. 32. At step 3576, the value G is set for the assigned sum of the values of the four local variables q1, q2, q3, and q4. Then, at step 3577, a hypothetical estimate is calculated in the form of weighted sums of the local variables wS and G, the value is stored in local variables G and wS with possible raising to an integral or fractional power of e 1 and e 2 . If the calculated estimate is close to zero or within the zero threshold distance, as determined at step 3578, then at step 3579, a zero value is returned. Otherwise, at block 3580, the calculated estimate is returned.

Хотя настоящее изобретение описывается на примере конкретных вариантов реализации, предполагается, что оно не ограничено только этими вариантами реализации. Специалистам в данной области техники будут очевидны возможные модификации в пределах сущности настоящего изобретения. Например, любые из множества различных параметров реализации и проектирования, в том числе модульная организация, язык программирования, аппаратная платформа, структуры управления, структуры данных и прочие параметры реализации и проектирования могут варьироваться для получения альтернативных вариантов реализации способов и систем настоящего изобретения.Although the present invention is described by the example of specific embodiments, it is believed that it is not limited to only these embodiments. Possible modifications within the spirit of the present invention will be apparent to those skilled in the art. For example, any of a variety of different implementation and design parameters, including modular organization, programming language, hardware platform, control structures, data structures, and other implementation and design parameters may vary to provide alternative implementations of the methods and systems of the present invention.

Следует понимать, что представленное выше описание раскрываемых вариантов реализации приведено для того, чтобы оно могло дать возможность любому специалисту в данной области техники воспроизвести или применить настоящее изобретение. Специалистам в данной области техники будут очевидны возможные модификации представленных вариантов реализации, при этом общие принципы, представленные здесь, без отступления от сущности и объема настоящего изобретения могут быть применены в рамках других вариантов реализации. Таким образом, подразумевается, что настоящее изобретение не ограничено представленными здесь вариантами реализации. Напротив, в его объем входят все возможные варианты реализации, согласующиеся с раскрываемыми в настоящем документе принципами и новыми отличительными признаками.It should be understood that the above description of the disclosed embodiments is provided in order to enable any person skilled in the art to reproduce or apply the present invention. Possible modifications to the presented embodiments will be apparent to those skilled in the art, while the general principles presented here, without departing from the essence and scope of the present invention, can be applied within other embodiments. Thus, it is understood that the present invention is not limited to the embodiments presented here. On the contrary, it includes all possible implementation options that are consistent with the principles and new distinguishing features disclosed in this document.

Claims (99)

1. Подсистема обработки изображений, входящая в состав устройства, прибора или системы, которая получает цифровое изображение и вводит его в подсистему обработки изображений с целью определения содержащего документ фрагмента цифрового изображения, при этом подсистема обработки изображений включает:1. The image processing subsystem, which is part of a device, device or system that receives a digital image and enters it into the image processing subsystem in order to determine the fragment of the digital image containing the document, the image processing subsystem includes: выделенный слой аппаратного обеспечения или слой аппаратного обеспечения, используемый совместно с устройством, прибором или системой, включающий один или более процессоров, один или более модулей памяти;a dedicated hardware layer or a hardware layer used in conjunction with a device, device or system, including one or more processors, one or more memory modules; команды в машинном коде, хранящиеся в одном или более физических устройств хранения данных, которые при выполнении одним или более из одного или более процессоров управляют подсистемой обработки изображений со следующими целями:instructions in machine code stored in one or more physical data storage devices that, when executed by one or more of one or more processors, control the image processing subsystem for the following purposes: получение цифрового изображения,digital image acquisition, определение контуров, соответствующих границам яркости в цифровом изображении;definition of contours corresponding to the brightness limits in a digital image; создание четырех множеств контуров, каждое из которых включает контуры, выбранные из выявленных контуров;creation of four sets of contours, each of which includes circuits selected from the identified contours; создание гипотез, каждая из которых содержит данные, которые описывают четырехсторонний многоугольник, расположение и направление которого относительно полученного цифрового изображения определяется путем объединения контуров, выбранных из каждого из четырех множеств контуров;creating hypotheses, each of which contains data that describes a four-sided polygon, the location and direction of which relative to the received digital image is determined by combining the paths selected from each of the four sets of paths; оценка созданных гипотез;assessment of the created hypotheses; выбор гипотезы из числа созданных гипотез на основе сформированных оценок;selection of a hypothesis from among the created hypotheses based on the generated estimates; сохранение выбранной гипотезы в памяти для указания на границы содержащего документ фрагмента изображения.storing the selected hypothesis in memory to indicate the boundaries of the image containing the document. 2. Подсистема обработки изображений по п. 1, отличающаяся тем, что подсистема обработки изображений определяет контуры, соответствующие границам яркости в цифровом изображении за счет следующего:2. The image processing subsystem according to claim 1, characterized in that the image processing subsystem determines the contours corresponding to the brightness boundaries in the digital image due to the following: применения многочисленных значений параметров, регулирующих определение контуров; иthe use of numerous parameter values governing the definition of circuits; and определения контуров за счет:definition of contours due to: определения затравочных пикселей в пределах цифрового изображения, совпадающих с границами яркости,determining the seed pixels within the digital image matching the brightness boundaries, для каждого из множества затравочных пикселейfor each of the plurality of seed pixels построения начального контура, который включает затравочный пиксель, иconstructing an initial contour that includes a seed pixel, and итеративного продления обоих концов начального контура вдоль границы яркости для создания выявленного контура.iteratively extending both ends of the initial contour along the brightness boundary to create an identified contour. 3. Подсистема обработки изображений по п. 2, отличающаяся тем, что значения параметров включают:3. The image processing subsystem according to claim 2, characterized in that the parameter values include: длину отрезка L;segment length L; максимальный угол изгиба отрезка а;the maximum bending angle of the segment a; количество бинов в гистограмме h;the number of bins in the histogram h; минимальное значение бина гистограммы В;minimum value of histogram B bin; значение минимальной суммы модулей проекции S0;the value of the minimum sum of projection modules S 0 ; радиус контура Re.contour radius R e . 4. Подсистема обработки изображений по п. 1, отличающаяся тем, что подсистема обработки изображений создает четыре множества контуров, каждый из которых включает контуры, выбранные из выявленных контуров за счет следующего:4. The image processing subsystem according to claim 1, characterized in that the image processing subsystem creates four sets of contours, each of which includes circuits selected from the identified contours due to the following: разделения выявленных контуров на первое множество преимущественно вертикально направленных контуров и второе множество преимущественно горизонтально направленных контуров;dividing the identified contours into a first set of predominantly vertically directed contours and a second set of predominantly horizontally directed contours; выбора контуров из первого множества преимущественно вертикально направленных контуров для добавления к правому и левому множеству контуров;selecting contours from the first set of predominantly vertically directed contours to add to the right and left set of contours; выбора контуров из второго множества преимущественно горизонтально направленных контуров для добавления к верхнему и нижнему множеству контуров.selecting contours from the second set of predominantly horizontally directed contours to add to the upper and lower set of contours. 5. Подсистема обработки изображений по п. 4,5. The image processing subsystem according to claim 4, отличающаяся тем, что выбор контуров из первого множества преимущественно вертикально направленных контуров, добавляемых к правому множеству контуров, включает выбор контуров, лежащих в правосторонней области полученного цифрового изображения, у которой ширина больше половины ширины полученного цифрового изображения, при этом правая граница правосторонней области совпадает с правой границей полученного цифрового изображения; иcharacterized in that the selection of the contours from the first set of predominantly vertically directed contours added to the right set of contours includes the selection of contours lying in the right-side region of the obtained digital image, whose width is more than half the width of the obtained digital image, while the right border of the right-side region the right border of the received digital image; and отличающаяся тем, что выбор контуров из первого множества преимущественно вертикально направленных контуров, добавляемых к левому множеству контуров, включает выбор контуров, лежащих в левосторонней области полученного цифрового изображения, у которой ширина больше половины ширины полученного цифрового изображения, при этом левая граница левосторонней области совпадает с левой границей полученного цифрового изображения.characterized in that the selection of contours from the first set of predominantly vertically directed contours added to the left set of contours includes the selection of contours lying in the left-side region of the obtained digital image, whose width is more than half the width of the obtained digital image, while the left border of the left-side region coincides with left border of the resulting digital image. 6. Подсистема обработки изображений по п. 4,6. The image processing subsystem according to claim 4, отличающаяся тем, что выбор контуров из второго множества преимущественно горизонтально направленных контуров, добавляемых к верхнему множеству контуров, включает выбор контуров, лежащих в верхней области полученного цифрового изображения, у которой высота больше половины высоты цифрового изображения, при этом верхняя граница верхней области совпадает с верхней границей полученного цифрового изображения;characterized in that the selection of the contours from the second set of predominantly horizontally directed contours added to the upper set of contours includes the selection of the contours lying in the upper region of the obtained digital image, whose height is more than half the height of the digital image, while the upper boundary of the upper region coincides with the upper the border of the received digital image; отличающаяся тем, что выбор контуров из второго множества преимущественно горизонтально направленных контуров, добавляемых к нижнему множеству контуров, включает выбор контуров, лежащих в нижней области полученного цифрового изображения, у которой высота больше половины высоты цифрового изображения, при этом нижняя граница нижней области совпадает с нижней границей полученного цифрового изображения.characterized in that the selection of the contours from the second set of predominantly horizontally directed contours added to the lower set of contours includes the selection of the contours lying in the lower region of the resulting digital image, whose height is more than half the height of the digital image, while the lower boundary of the lower region coincides with the lower the border of the resulting digital image. 7. Подсистема обработки изображений по п. 4, отличающаяся тем, что после создания четырех множеств контуров, каждый из которых включает контуры, выбранные из выявленных контуров, при этом подсистема обработки изображений:7. The image processing subsystem according to claim 4, characterized in that after creating four sets of contours, each of which includes circuits selected from the identified contours, while the image processing subsystem: фильтрует каждый из четырех множеств контуров с использованием критериев фильтрации для удаления контуров, чтобы множество контуров содержало не более порогового числа контуров.filters each of the four sets of paths using filtering criteria to remove the paths so that the set of paths contains no more than the threshold number of paths. 8. Подсистема обработки изображений по п. 7, отличающаяся тем, что критерии фильтрации включают один или более следующих критериев:8. The image processing subsystem according to claim 7, characterized in that the filtering criteria include one or more of the following criteria: длина контура;contour length; величина кривизны контура;contour curvature value; количество пикселей, перекрываемых контуром в полученном цифровом изображении.the number of pixels overlapped by the contour in the resulting digital image. 9. Подсистема обработки изображений по п. 7, отличающаяся тем, что после фильтрации каждое множество контуров сортируется по длине или по количеству пикселей, перекрываемых контуром в полученном цифровом изображении.9. The image processing subsystem according to claim 7, characterized in that after filtering each set of contours is sorted by length or by the number of pixels overlapped by the contour in the resulting digital image. 10. Подсистема обработки изображений по п. 1, отличающаяся тем, что подсистема обработки изображений создает гипотезы за счет следующего:10. The image processing subsystem according to claim 1, characterized in that the image processing subsystem creates hypotheses due to the following: итеративного создания следующей комбинации из четырех контуров, выбранных из четырех множеств контуров;iteratively creating the next combination of four loops selected from four sets of loops; попытки использования четырех контуров из созданной комбинации для создания четырехстороннего многоугольника;attempts to use four contours from the created combination to create a four-sided polygon; при успешном создании четырехстороннего многоугольника, когда четырехсторонний многоугольник является выпуклым и когда ни одна из вершин четырехстороннего многоугольника не лежит за пределами прямоугольника, представляющего границу полученного цифрового изображения, выполнения кодировки четырехстороннего многоугольника в структуре данных гипотезы для выполнения оценки до тех пор, пока не исчезнет возможность создания дополнительных комбинаций четырех контуров, выбранных из четырех множеств контуров.upon successful creation of a four-sided polygon, when the four-sided polygon is convex, and when none of the vertices of the four-sided polygon lies outside the rectangle that represents the boundary of the resulting digital image, encoding the four-sided polygon in the hypothesis data structure to perform the assessment until the opportunity disappears creating additional combinations of four contours selected from four sets of contours. 11. Подсистема обработки изображений по п. 10, отличающаяся тем, что подсистема обработки изображений предпринимает попытку использования четырех контуров из созданной комбинации для создания четырехстороннего многоугольника за счет продления одного или более отрезков линий, подстроенных к одному или более контуров.11. The image processing subsystem according to claim 10, characterized in that the image processing subsystem attempts to use four contours from the created combination to create a four-sided polygon by extending one or more line segments adjusted to one or more contours. 12. Подсистема обработки изображений по п. 1, отличающаяся тем, что подсистема обработки изображений использует кодировку четырехстороннего многоугольника, соответствующего созданной гипотезе, для выполнения оценки созданной гипотезы за счет следующего:12. The image processing subsystem according to claim 1, characterized in that the image processing subsystem uses the encoding of a four-sided polygon corresponding to the created hypothesis to evaluate the created hypothesis due to the following: для каждой стороны четырехстороннего многоугольника - вычисление показателя качества стороны и веса стороны;for each side of a four-sided polygon - calculation of a side quality indicator and side weight; для каждого угла четырехстороннего многоугольника - вычисление показателя качества по углам;for each corner of a four-sided polygon - calculation of a quality indicator by corners; вычисление показателя качества по площади четырехстороннего многоугольника;calculation of a quality indicator by the area of a quadrilateral polygon; если известно отношение ширины к высоте документа, соответствующего содержащему документ фрагменту изображения, - вычисление показателя качества по соотношению сторон;if the ratio of the width to the height of the document corresponding to the image fragment containing the document is known, the calculation of the quality indicator by the aspect ratio; объединение показателей качества стороны, веса стороны, показателя качества по углам, показателя качества по площади и показателя качества по соотношению сторон для создания численной оценки созданной гипотезы.the combination of indicators of the quality of the side, the weight of the side, a quality indicator in the corners, a quality indicator for the area and a quality indicator for the aspect ratio to create a numerical estimate of the created hypothesis. 13. Подсистема обработки изображений по п. 12,13. The image processing subsystem according to p. 12, отличающаяся тем, что назначенное показателю качества стороны значение увеличивается с увеличением отношения длины стороны к длине соответствующей границы полученного цифрового изображения;characterized in that the value assigned to the quality index of the side increases with increasing ratio of the length of the side to the length of the corresponding boundary of the obtained digital image; отличающаяся тем, что назначенное показателю качества по углам значение увеличивается по мере приближения угла к значению 90°;characterized in that the value assigned to the quality indicator in the corners increases as the angle approaches 90 °; отличающаяся тем, что назначенное показателю качества по площади значение увеличивается по мере увеличения отношения площади четырехстороннего многоугольника к площади полученного цифрового изображения;characterized in that the value assigned to the quality indicator by area increases as the ratio of the area of the four-sided polygon to the area of the resulting digital image increases; отличающаяся тем, что значение показателя качества по соотношению сторон увеличивается по мере достижения отношением ширины к высоте прямоугольника, соответствующего четырехстороннему многоугольнику, известного отношения ширины к высоте документа, соответствующего содержащему документ фрагменту изображения.characterized in that the value of the quality index in terms of aspect ratio increases as the ratio of width to height of the rectangle corresponding to the four-sided polygon reaches a known ratio of width to height of the document corresponding to the image fragment containing the document. 14. Подсистема обработки изображений по п. 12, отличающаяся тем, что вес, рассчитанный для стороны, связан с:14. The image processing subsystem according to claim 12, characterized in that the weight calculated for the side is associated with: разностью между суммой весов пикселей контура, соответствующих стороне, и суммой весов пикселей, которые связаны с этой стороной, но не связаны с контуром;the difference between the sum of the weights of the pixels of the contour corresponding to the side, and the sum of the weights of the pixels that are associated with this side, but are not associated with the contour; отношением числа пикселей в контуре, соответствующих стороне, к числу пикселей, связанных со стороной.the ratio of the number of pixels in the path corresponding to the side to the number of pixels associated with the side. 15. Подсистема обработки изображений по п. 14, отличающаяся тем, что вес пикселя рассчитывается по проекции градиента яркости, связанного с пикселем, и вектора, перпендикулярного стороне.15. The image processing subsystem according to claim 14, characterized in that the weight of the pixel is calculated by the projection of the brightness gradient associated with the pixel and the vector perpendicular to the side. 16. Способ определения содержащего документ фрагмента цифрового изображения, реализуемый подсистемой обработки изображений, входящей в состав устройства, прибора или системы, которая получает цифровое изображение и вводит полученное цифровое изображение в подсистему обработки изображений, включающей следующее:16. A method for determining a document-containing fragment of a digital image implemented by an image processing subsystem that is part of a device, device or system that receives a digital image and enters the resulting digital image into an image processing subsystem, including the following: получение цифрового изображения;digital image acquisition; определение контуров, соответствующих границам яркости в цифровом изображении;definition of contours corresponding to the brightness limits in a digital image; создание четырех множеств контуров, каждое из которых включает контуры, выбранные из выявленных контуров;creation of four sets of contours, each of which includes circuits selected from the identified contours; создание гипотез, каждая из которых содержит данные, которые описывают четырехсторонний многоугольник, расположение и направление которого относительно полученного цифрового изображения определяется путем объединения контуров, выбранных из каждого из четырех множеств контуров;creating hypotheses, each of which contains data that describes a four-sided polygon, the location and direction of which relative to the received digital image is determined by combining the paths selected from each of the four sets of paths; оценка созданных гипотез;assessment of the created hypotheses; выбор гипотезы из числа созданных гипотез на основе сформированных оценок;selection of a hypothesis from among the created hypotheses based on the generated estimates; сохранение выбранной гипотезы в памяти для указания на границы содержащего документ фрагмента изображения.storing the selected hypothesis in memory to indicate the boundaries of the image containing the document. 17. Способ по п. 16, отличающийся тем, что определение контуров, соответствующих границам яркости в цифровом изображении, дополнительно включает:17. The method according to p. 16, characterized in that the determination of the contours corresponding to the brightness limits in the digital image, further includes: применение многочисленных значений параметров, регулирующих определение контуров; иthe use of numerous parameter values governing the definition of circuits; and определение контуров за счет следующегоdefinition of contours due to the following определение затравочных пикселей в пределах цифрового изображения, совпадающих с границами яркости,the determination of the seed pixels within the digital image that coincide with the boundaries of brightness, для каждого из множества затравочных пикселейfor each of the plurality of seed pixels построение начального контура, который включает затравочный пиксель, иplotting an initial path that includes a seed pixel, and итеративное продление обоих концов начального контура вдоль границы яркости для создания выявленного контура.iteratively extending both ends of the initial contour along the brightness boundary to create an identified contour. 18. Способ по п. 16, отличающийся тем, что создание четырех множеств контуров, каждое из которых включает контуры, выбранные из выявленных контуров, дополнительно включает следующее:18. The method according to p. 16, characterized in that the creation of four sets of circuits, each of which includes circuits selected from the identified circuits, further includes the following: разделение выявленных контуров на первое множество преимущественно вертикально направленных контуров и второе множество преимущественно горизонтально направленных контуров;dividing the identified contours into a first set of predominantly vertically directed contours and a second set of predominantly horizontally directed contours; выбор контуров из первого множества преимущественно вертикально направленных контуров для добавления к правому и левому множеству контуров;selecting contours from the first set of predominantly vertically directed contours to add to the right and left set of contours; выбор контуров из второго множества преимущественно горизонтально направленных контуров для добавления к верхнему и нижнему множеству контуров.selecting contours from the second set of predominantly horizontally directed contours to add to the upper and lower set of contours. 19. Способ по п. 16, отличающийся тем, что создание гипотезы дополнительно включает:19. The method according to p. 16, characterized in that the creation of a hypothesis further includes: итеративное создание следующей комбинации из четырех контуров, выбранных из четырех множеств контуров;iterative creation of the following combination of four loops selected from four sets of loops; попытка использования четырех контуров из созданной комбинации для создания четырехстороннего многоугольника;an attempt to use four contours from the created combination to create a four-sided polygon; при успешном создании четырехстороннего многоугольника, когда четырехсторонний многоугольник является выпуклым и когда ни одна из вершин четырехстороннего многоугольника не лежит за пределами прямоугольника, представляющего границу полученного цифрового изображения, выполнение кодировки четырехстороннего многоугольника в структуре данных гипотезы для выполнения оценки до тех пор, пока не исчезнет возможность создания дополнительных комбинаций четырех контуров, выбранных из четырех множеств контуров.upon successful creation of a four-sided polygon, when the four-sided polygon is convex and when none of the vertices of the four-sided polygon lies outside the rectangle representing the boundary of the resulting digital image, encoding the four-sided polygon in the hypothesis data structure to perform an assessment until the opportunity disappears creating additional combinations of four contours selected from four sets of contours. 20. Способ по п. 19, отличающийся тем, что попытка использования четырех контуров из созданной комбинации для создания четырехстороннего многоугольника дополнительно включает продление одного или более отрезков линий, подстроенных к одному или более контуров.20. The method according to p. 19, characterized in that the attempt to use four contours from the created combination to create a four-sided polygon further includes the extension of one or more line segments that are tuned to one or more contours. 21. Способ по п. 16, дополнительно включающий кодировку четырехстороннего многоугольника, соответствующего созданной гипотезе, для выполнения оценки созданной гипотезы за счет следующего:21. The method according to p. 16, further comprising encoding a four-sided polygon corresponding to the created hypothesis, to evaluate the created hypothesis due to the following: для каждой стороны четырехстороннего многоугольника - вычисление показателя качества стороны и веса стороны;for each side of a four-sided polygon - calculation of a side quality indicator and side weight; для каждого угла четырехстороннего многоугольника - вычисление показателя качества по углам;for each corner of a four-sided polygon - calculation of a quality indicator by corners; вычисление показателя качества по площади четырехстороннего многоугольника;calculation of a quality indicator by the area of a quadrilateral polygon; если известно отношение ширины к высоте документа, - вычисление показателя качества по соотношению сторон;if the ratio of the width to the height of the document is known, - the calculation of the quality indicator by the aspect ratio; объединение показателей качества стороны, веса стороны, показателя качества по углам, показателя качества по площади и показателя качества по соотношению сторон для создания численной оценки созданной гипотезы.the combination of indicators of the quality of the side, the weight of the side, a quality indicator in the corners, a quality indicator for the area and a quality indicator for the aspect ratio to create a numerical estimate of the created hypothesis. 22. Физическое устройство хранения данных, в котором хранятся команды в машинном коде, которые при выполнении одним или более процессорами, относящимися к слою аппаратного обеспечения подсистемы обработки изображений, которая содержит один или более процессоров и одно или более запоминающих устройств и которая включена в устройство, прибор или систему, получающие цифровое изображение и вводящие полученное цифровое изображение в подсистему обработки изображений, выполняют управление подсистемой обработки изображений с целью определения содержащего документ фрагмента цифрового изображения за счет выполнения следующих этапов:22. A physical data storage device that stores instructions in machine code that, when executed by one or more processors related to the hardware layer of the image processing subsystem, which contains one or more processors and one or more storage devices and which is included in the device, a device or system that receives a digital image and enters the resulting digital image into the image processing subsystem controls the image processing subsystem to determine ia containing a document fragment of a digital image by performing the following steps: получение цифрового изображения;digital image acquisition; определение контуров, соответствующих границам яркости в цифровом изображении;definition of contours corresponding to the brightness limits in a digital image; создание четырех множеств контуров, каждое из которых включает контуры, выбранные из выявленных контуров;creation of four sets of contours, each of which includes circuits selected from the identified contours; создание гипотез, каждая из которых содержит данные, которые описывают четырехсторонний многоугольник, расположение и направление которого относительно полученного цифрового изображения определяются путем объединения контуров, выбранных из каждого из четырех множеств контуров;creating hypotheses, each of which contains data that describes a four-sided polygon, the location and direction of which relative to the received digital image are determined by combining the paths selected from each of the four sets of paths; оценка созданных гипотез;assessment of the created hypotheses; выбор гипотезы из числа созданных гипотез на основе сформированных оценок;selection of a hypothesis from among the created hypotheses based on the generated estimates; сохранение выбранной гипотезы в памяти для указания на границы содержащего документ фрагмента цифрового изображения.storing the selected hypothesis in memory to indicate the boundaries of the fragment of the digital image containing the document.
RU2016125288A 2016-06-22 2016-06-24 Method and subsystem of determining digital images of fragments containing documents RU2626661C1 (en)

Priority Applications (3)

Application Number Priority Date Filing Date Title
RU2016125288A RU2626661C1 (en) 2016-06-24 2016-06-24 Method and subsystem of determining digital images of fragments containing documents
US15/195,759 US10503997B2 (en) 2016-06-22 2016-06-28 Method and subsystem for identifying document subimages within digital images
US15/195,726 US10387744B2 (en) 2016-06-22 2016-06-28 Method and system for identifying extended contours within digital images

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2016125288A RU2626661C1 (en) 2016-06-24 2016-06-24 Method and subsystem of determining digital images of fragments containing documents

Publications (1)

Publication Number Publication Date
RU2626661C1 true RU2626661C1 (en) 2017-07-31

Family

ID=59632239

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2016125288A RU2626661C1 (en) 2016-06-22 2016-06-24 Method and subsystem of determining digital images of fragments containing documents

Country Status (1)

Country Link
RU (1) RU2626661C1 (en)

Cited By (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2715515C2 (en) * 2018-03-30 2020-02-28 Акционерное общество "Лаборатория Касперского" System and method of detecting image containing identification document

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US5694228A (en) * 1994-08-09 1997-12-02 Ricoh Company,Ltd. Document image processor with defect detection
US6804414B1 (en) * 1998-05-01 2004-10-12 Fujitsu Limited Image status detecting apparatus and document image correcting apparatus
RU2511616C2 (en) * 2008-06-02 2014-04-10 Эдванст Трэк Энд Трэйс Method of identification of printed form of document and device for this purpose
US20140368891A1 (en) * 2013-06-12 2014-12-18 Kodak Alaris Inc. Method for detecting a document boundary
US20160092417A1 (en) * 2014-09-30 2016-03-31 Konica Minolta Laboratory U.S.A., Inc. Horizontal and vertical line detection and removal for document images

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US5694228A (en) * 1994-08-09 1997-12-02 Ricoh Company,Ltd. Document image processor with defect detection
US6804414B1 (en) * 1998-05-01 2004-10-12 Fujitsu Limited Image status detecting apparatus and document image correcting apparatus
RU2511616C2 (en) * 2008-06-02 2014-04-10 Эдванст Трэк Энд Трэйс Method of identification of printed form of document and device for this purpose
US20140368891A1 (en) * 2013-06-12 2014-12-18 Kodak Alaris Inc. Method for detecting a document boundary
US20160092417A1 (en) * 2014-09-30 2016-03-31 Konica Minolta Laboratory U.S.A., Inc. Horizontal and vertical line detection and removal for document images

Cited By (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2715515C2 (en) * 2018-03-30 2020-02-28 Акционерное общество "Лаборатория Касперского" System and method of detecting image containing identification document
US10867170B2 (en) 2018-03-30 2020-12-15 AO Kaspersky Lab System and method of identifying an image containing an identification document

Similar Documents

Publication Publication Date Title
RU2628266C1 (en) Method and system of preparing text-containing images to optical recognition of symbols
RU2680765C1 (en) Automated determination and cutting of non-singular contour of a picture on an image
US10366469B2 (en) Method and system that efficiently prepares text images for optical-character recognition
US8134578B2 (en) Hybrid importance maps for content aware digital image resizing
US10503997B2 (en) Method and subsystem for identifying document subimages within digital images
US8374428B2 (en) Color balancing for partially overlapping images
JP2007504719A (en) System and method for detecting and correcting red eyes in an image suitable for embedded applications
CN109636890B (en) Texture fusion method and device, electronic equipment, storage medium and product
CN116580028B (en) Object surface defect detection method, device, equipment and storage medium
CN107622504A (en) Method and apparatus for handling picture
CN111583381A (en) Rendering method and device of game resource map and electronic equipment
US11704807B2 (en) Image processing apparatus and non-transitory computer readable medium storing program
RU2608239C1 (en) Method and system for determining suitability of document image for optical character recognition and other image processing operations
RU2626661C1 (en) Method and subsystem of determining digital images of fragments containing documents
US20230394871A1 (en) Method for verifying the identity of a user by identifying an object within an image that has a biometric characteristic of the user and separating a portion of the image comprising the biometric characteristic from other portions of the image
US20210342972A1 (en) Automatic Content-Aware Collage
CN116798041A (en) Image recognition method and device and electronic equipment
US11200708B1 (en) Real-time color vector preview generation
CN113343987B (en) Text detection processing method and device, electronic equipment and storage medium
RU2628172C1 (en) Method and system for determining expanded contours on digital images
CN114549825A (en) Target detection method and device, electronic equipment and storage medium
RU2636097C1 (en) Method and system of preparing text-containing images to optical recognition of symbols
US11043015B2 (en) Generating reflections within images
CN117078910A (en) Image processing method, device, equipment and storage medium
Wei et al. Objective image quality assessment based on saliency map

Legal Events

Date Code Title Description
QZ41 Official registration of changes to a registered agreement (patent)

Free format text: LICENCE FORMERLY AGREED ON 20151118

Effective date: 20171031

QC41 Official registration of the termination of the licence agreement or other agreements on the disposal of an exclusive right

Free format text: LICENCE FORMERLY AGREED ON 20151118

Effective date: 20180710

PC43 Official registration of the transfer of the exclusive right without contract for inventions

Effective date: 20181121

QB4A Licence on use of patent

Free format text: LICENCE FORMERLY AGREED ON 20201211

Effective date: 20201211

QC41 Official registration of the termination of the licence agreement or other agreements on the disposal of an exclusive right

Free format text: LICENCE FORMERLY AGREED ON 20201211

Effective date: 20220311