RU2820743C1 - Method of producing rectified images of documents folded in half - Google Patents

Method of producing rectified images of documents folded in half Download PDF

Info

Publication number
RU2820743C1
RU2820743C1 RU2023130764A RU2023130764A RU2820743C1 RU 2820743 C1 RU2820743 C1 RU 2820743C1 RU 2023130764 A RU2023130764 A RU 2023130764A RU 2023130764 A RU2023130764 A RU 2023130764A RU 2820743 C1 RU2820743 C1 RU 2820743C1
Authority
RU
Russia
Prior art keywords
document
image
hexagon
quadrangles
folded
Prior art date
Application number
RU2023130764A
Other languages
Russian (ru)
Inventor
Владимир Викторович Арлазаров
Александр Михайлович Ершов
Дмитрий Петрович Николаев
Даниил Вячеславович Тропин
Original Assignee
Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС"
Filing date
Publication date
Application filed by Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС" filed Critical Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС"
Application granted granted Critical
Publication of RU2820743C1 publication Critical patent/RU2820743C1/en

Links

Abstract

FIELD: physics.
SUBSTANCE: invention relates to processing of digitized documents. Upper half of the image comprises a larger portion of the upper half of the document, and the lower half of the image comprises a larger portion of the lower half of the document, wherein the height is greater than the width, wherein the original image I is divided in half into an upper part It and a lower part Ib, a rough approximation of the halves of the document is constructed by two quadrangles, for this purpose, a quadrangle localization algorithm based on detection of boundaries and lines is applied to both halves, output of which is a set of quadrangles sorted by their contour estimate, thus obtaining a plurality of quadrangles Qt located on It, and a plurality of quadrangles Qb located on Ib, wherein each pair of quadrangles is used to make a hexagon, which would represent the outer boundaries of the folded document on the image, a correction algorithm is applied to each formed and refined hexagon, after which the hexagons are sorted by their contour estimate.
EFFECT: high quality of scanning folded documents with resistance to occlusion of the edge of the document.
1 cl, 27 dwg

Description

Заявленное изобретение относится к средствам для работы с документами. В повседневной жизни часто возникает необходимость оцифровки документов. Ранее эта задача решалась при помощи сканеров и систем распознавания. С распространением мобильных телефонов изображения, полученные с камеры, стали более популярны, чем отсканированные изображения. Системы распознавания, запускаемые на таких изображениях, могут испытывать трудности. Например, образ документ (а значит, и текст на документе) может быть проективно искажен, так что нельзя рассчитывать на высокое качество распознавания систем, рассчитанных на сканеры. Поэтому перед распознаванием необходим дополнительный этап - получение ректифицированного изображения - изображение документа, как если бы он отсканирован на планшетном сканере. При получении ректифицированного изображения необходимо, чтобы содержимое документа не было никаким образом искажено (не было разрывов изображения, была сохранена горизонтальность строк и т.д.). Зачастую бывает так, что деловые документы хранятся в сложенном виде. Поэтому, когда возникает необходимость их оцифровать, нужно решить задачу ректификации документа, сложенного пополам.The claimed invention relates to tools for working with documents. In everyday life, there is often a need to digitize documents. Previously, this problem was solved using scanners and recognition systems. With the rise of mobile phones, camera images have become more popular than scanned images. Recognition systems running on such images may experience difficulties. For example, the image of a document (and therefore the text on the document) can be projectively distorted, so one cannot count on high quality recognition of systems designed for scanners. Therefore, before recognition, an additional step is required - obtaining a rectified image - an image of the document, as if it had been scanned on a flatbed scanner. When receiving a rectified image, it is necessary that the contents of the document are not distorted in any way (there are no image breaks, horizontal lines are preserved, etc.). It often happens that business documents are stored folded. Therefore, when the need arises to digitize them, you need to solve the problem of rectifying a document folded in half.

Из уровня техники известны различные способы для получения ректифицированных изображений физически искаженных документов (см. документы Michael S Brown and W Brent Seales. Image restoration of arbitrarily warped documents. IEEE Transactions on pattern analysis and machine intelligence, 26(10):1295-1306, 2004 (1); Shaodi You, Yasuyuki Matsushita, Sudipta Sinha, Yusuke Bou, and Katsushi Ikeuchi. Multiview rectification of folded documents. IEEE transactions on pattern analysis and machine intelligence, 40(2):505-511, 2017 (2); Hao Feng, Yuechen Wang, Wengang Zhou, Jiajun Deng, and Houqiang Li. Doctr: Document image transformer for geometric unwarping and illumination correction. arXiv preprint arXiv: 2110.12942, 2021 (3); Gaofeng Meng, Chunhong Pan, Shiming Xiang, Jiangyong Duan, and Nanning Zheng. Metric rectification of curved document images. IEEE transactions on pattern analysis and machine intelligence, 34(4):707-722, 2011 (4)), однако они не предназначены для решения задачи развертки сложенных пополам документов по одному изображению, полученному с камеры мобильного телефона: в (1) предлагается использовать внешнее дополнительного оборудование, в работе (2) необходимо наличие нескольких изображений на входе, нейросетевой подход (3) не учитывает проективных искажений, возникающих при съемке камерой, в работе (4) накладывается существенное ограничение на модель документа - он должен быть представлен гладкой цилиндрической поверхностью с направляющими, параллельными текстовым строкам. Из источника информации (5) (см. Sagnik Das, Gaurav Mishra, Akshay Sudharshana, and Roy Shilkrot. The common fold: utilizing the four-fold to dewarp printed documents from a single image. In Proceedings of the 2017 ACM Symposium on Document Engineering, pages 125-128, 2017) известен способ для развертки документов, сложенных в несколько раз - это статья. Однако в (5), во-первых, не учитываются проективные искажения, возникающие при съемке камерой, а во-вторых, при детекции каждой части документа по отдельности и последующей склейке возникает разрыв контента на местах склейки.Various methods are known in the prior art for obtaining rectified images of physically warped documents (see Michael S Brown and W Brent Seales, Image restoration of arbitrarily warped documents. IEEE Transactions on pattern analysis and machine intelligence, 26(10):1295-1306, 2004 (1) Shaodi You, Yasuyuki Matsushita, Sudipta Sinha, Yusuke Bou, and Katsushi Ikeuchi. Multiview rectification of folded documents. Hao Feng, Yuechen Wang, Wengang Zhou, Jiajun Deng, and Houqiang Li. Doctr: Document image transformer for geometric unwarping and illumination correction. arXiv preprint arXiv: 2110.12942, 2021 (3); Gaofeng Meng, Chunhong Pan, Shiming Xiang, Jiangyong Duan , and Nanning Zheng. Metric rectification of curved document images. IEEE transactions on pattern analysis and machine intelligence, 34(4):707-722, 2011 (4)), however, they are not designed to solve the problem of unfolding documents folded in half from one image. , obtained from a mobile phone camera: in (1) it is proposed to use external additional equipment, in work (2) it is necessary to have several images at the input, the neural network approach (3) does not take into account projective distortions that arise when shooting with a camera, in work (4) it is superimposed a significant limitation on the document model - it must be represented by a smooth cylindrical surface with guides parallel to the text lines. From reference (5) (see Sagnik Das, Gaurav Mishra, Akshay Sudharshana, and Roy Shilkrot. The common fold: utilizing the four-fold to dewarp printed documents from a single image. In Proceedings of the 2017 ACM Symposium on Document Engineering , pages 125-128, 2017) there is a known method for unfolding documents folded several times - this is the article. However, in (5), firstly, the projective distortions that arise when shooting with a camera are not taken into account, and secondly, when each part of the document is detected separately and then stitched together, a gap in the content occurs at the splice sites.

Предложенный способ позволяет решать задачу развертки сложенных документов по одному изображению, полученному с камеры мобильного телефона и обладает следующими преимуществами:The proposed method allows you to solve the problem of unfolding folded documents using one image obtained from a mobile phone camera and has the following advantages:

- не требует дополнительного оборудования в отличие от (1).- does not require additional equipment, unlike (1).

- принимает на вход одно изображение в отличие от (2).- takes one image as input, unlike (2).

- учитывает проективные искажения в отличие от (3), (5).- takes into account projective distortions in contrast to (3), (5).

- гарантирует отсутствие разрыва на сгибе в отличие от (5).- guarantees that there is no tear on the bend, unlike (5).

Помимо этого, важными деталями является то, что предложенный способ подходит для запуска на мобильном телефоне, а также устойчив к частичной окклюзии края документа - например, если его часть скрыта рукой.In addition, important details are that the proposed method is suitable for running on a mobile phone, and is also resistant to partial occlusion of the edge of the document - for example, if part of it is hidden by the hand.

Задачей заявленного изобретения является устранение недостатков известного уровня техники. Технический результат заключается в обеспечении способа получения ректифицированных изображений документов, сложенных пополам, который позволяет обеспечить повышение качества развертки сложенных документов по одному изображению, полученному с камеры мобильного телефона и при этом представленный способ не требует дополнительного оборудования, принимает на вход одно изображение, учитывает проективные искажения, обеспечивает отсутствие разрыва на сгибе, подходит для запуска на мобильном телефоне, а также устойчив к частичной окклюзии края документа - например, если его часть скрыта рукой.The objective of the claimed invention is to eliminate the disadvantages of the prior art. The technical result consists in providing a method for obtaining rectified images of documents folded in half, which makes it possible to improve the quality of scanning folded documents using one image obtained from a mobile phone camera, and the presented method does not require additional equipment, takes one image as input, and takes into account projective distortions , ensures no tearing on the fold, is suitable for running on a mobile phone, and is also resistant to partial occlusion of the edge of the document - for example, if part of it is hidden by the hand.

Поставленная задача решается, а заявленный технический результат достигается посредством заявленного способа получения ректифицированных изображений документов, сложенных пополам.The stated problem is solved, and the stated technical result is achieved through the claimed method of obtaining rectified images of documents folded in half.

Заявленный способ получения ректифицированных изображений документов, сложенных пополам заключается в поступлении на вход модели предъявления документа, причем верхняя половина изображения содержит большую часть верхней половины документа, а нижняя половина изображения содержит большую часть нижней половины документа, при этом высота больше ширины, при этом исходное изображение I делится пополам на верхнюю часть It и нижнюю часть Ib, строится грубое приближение половин документа двумя четырехугольниками, для этого к обеим половинам применяется алгоритм локализации четырехугольников, основанный на детекции границ и прямых, выходом которого является набор четырехугольников, отсортированных по их контурной оценке, таким образом получается множество четырехугольников Qt, расположенных на It и множество четырехугольников Qb, расположенных на Ib, при этом каждая пара четырехугольников используется для того, чтобы составить шестиугольник, который бы представлял внешние границы сложенного документа на изображении, к каждому сформированному и уточненному шестиугольнику применяется алгоритм коррекции, после этого шестиугольники сортируются по их контурной оценке и тот, у которого самая высокая контурная оценка является выходом из этапа локализации, последним этапом является отображение входного изображения, определяемого двумя проективными преобразованиями.The claimed method for obtaining rectified images of documents folded in half is to input a document presentation model, with the upper half of the image containing most of the upper half of the document, and the lower half of the image containing most of the lower half of the document, with the height being greater than the width, and the original image I is divided in half into the upper part I t and the lower part I b , a rough approximation of the halves of the document by two quadrangles is constructed, for this purpose a quadrilateral localization algorithm based on detection of boundaries and lines is applied to both halves, the output of which is a set of quadrangles sorted by their contour score , thus obtaining a set of quadrilaterals Q t located on I t and a set of quadrilaterals Q b located on I b , with each pair of quadrilaterals being used to construct a hexagon that would represent the outer boundaries of the folded document in the image, to each formed and a correction algorithm is applied to the refined hexagon, after that the hexagons are sorted by their contour score and the one with the highest contour score is the output from the localization stage, the last stage is to display the input image determined by two projective transformations.

На фигурах представлены:The figures show:

Фиг. 1: Блок-схема алгоритма, использованного в предлагаемом методеFig. 1: Flowchart of the algorithm used in the proposed method.

Фиг. 2: Блок-схема алгоритма детекции набора четырехугольниковFig. 2: Block diagram of the quadrilateral set detection algorithm

Фиг. 3: (а) Горизонтальные (зеленые) и вертикальные (красные) границы на “общей” карте границ, (б) детектированные прямые (красные и зеленые) и синяя линия, разделяющая изображение пополам, (в) пара четырехугольников (верхний изображен голубым, нижний изображен желтым), истинная линия сгиба (зеленая) и линия сгиба, получена пересечением вертикальных отрезков (красная), (г) ломаная ABCD, аппроксимирующая излом границы на треке, выделенном штрихованным прямоугольником на (а), (д) локализованный шестиугольник, (е) границы, лежащие вдоль детектированного шестиугольника, (ж) ректифицированное изображениеFig. 3: (a) Horizontal (green) and vertical (red) boundaries on the “general” boundary map, (b) detected straight lines (red and green) and a blue line dividing the image in half, (c) a pair of quadrangles (the top one is shown in blue, the bottom one is shown in yellow), the true fold line (green) and the fold line obtained by intersecting vertical segments (red), (d) broken ABCD approximating the boundary break on the track, highlighted by the hatched rectangle in (a), (e) localized hexagon, ( f) boundaries lying along the detected hexagon, (g) rectified image

Фиг. 4: Блок-схема алгоритма формирования шестиугольниковFig. 4: Flowchart of hexagon formation algorithm

Фиг. 5: Примеры непрерывного (Н1, Н2) и разрывного (Н3, Н2) преобразованияFig. 5: Examples of continuous (H1, H2) and discontinuous (H3, H2) transformations

Фиг. 6: Примеры неудовлетворительной и удовлетворительной ректификации: (а) входное изображение с детектированным шестиугольником (синий) и его корректировкой (красная), которая признана невалидной, (б) ректификация по красному шестиугольнику, (в) входное изображение с детектированным шестиугольником (синий) и его корректировкой (зеленая), которая признана валидной, (г) ректификация по зеленому шестиугольникуFig. 6: Examples of unsatisfactory and satisfactory rectification: (a) input image with a detected hexagon (blue) and its correction (red), which is considered invalid, (b) rectification using a red hexagon, (c) input image with a detected hexagon (blue) and its correction (green), which is recognized as valid, (d) rectification using the green hexagon

Фиг. 7: Пример работы алгоритма: (а) Исходное изображение, (б) детектированные границы, (в) детектированные прямые, (г) найденные четырехугольники, (д) построенный и скорректированный шестиугольник, (е) ректифицированное изображениеFig. 7: Example of the algorithm: (a) Original image, (b) detected boundaries, (c) detected straight lines, (d) found quadrilaterals, (e) constructed and corrected hexagon, (f) rectified image

Фиг. 8: Пример работы алгоритма: (а) Исходное изображение, (б) детектированные границы, (в) детектированные прямые, (г) найденные четырехугольники, (д) построенный и скорректированный шестиугольник, (е) ректифицированное изображениеFig. 8: Example of the algorithm: (a) Original image, (b) detected boundaries, (c) detected straight lines, (d) found quadrilaterals, (e) constructed and corrected hexagon, (f) rectified image

Для использования предложенного метода необходимо:To use the proposed method you must:

- камера для получения входного изображения, например, камера смартфона;- a camera for receiving the input image, for example, a smartphone camera;

- вычислительное устройство с любым современным процессором архитектуры ARM или x86, например, настольный компьютер или смартфон.- a computing device with any modern ARM or x86 processor, such as a desktop computer or smartphone.

Пусть дано изображение, на котором находится документ формата А4, которое было получено при съемке камерой. Этот лист сложен пополам таким образом, что линия сгиба параллельна короткой стороне этого документа (далее - сложенный документ). Необходимо восстановить изображение этого документа, как если бы он был отсканирован на планшетном сканере. Далее это изображение будем называть ректифицированным, а саму задачу называть задачей ректификации.Let there be an image containing an A4 document, which was captured by a camera. This sheet is folded in half so that the fold line is parallel to the short side of this document (hereinafter referred to as the folded document). You need to restore the image of this document as if it had been scanned on a flatbed scanner. Below we will call this image rectified, and the task itself will be called the rectification task.

В качестве метода решения задачи ректификации сложенного документа предлагается детектировать шестиугольник его внешней границы и проективно преобразовать каждую его половину по отдельности. Для реализации этого способа предлагается использовать следующий алгоритм.As a method for solving the problem of rectification of a folded document, it is proposed to detect the hexagon of its outer boundary and projectively transform each of its halves separately. To implement this method, it is proposed to use the following algorithm.

Рассмотрим схему на фиг. 1. Предполагается, что модель предъявления документа такова, что верхняя половина изображения содержит большую часть верхней половины документа, а нижняя половина изображения содержит большую часть нижней половины документа, при этом высота больше ширины. Поэтому сначала исходное изображение I делится пополам на верхнюю часть It и нижнюю часть Ib, и строится грубое приближение половин документа двумя четырехугольниками. Для этого к обеим половинам применяется алгоритм локализации четырехугольников (раздел 1), основанный на детекции границ и прямых, выходом которого является набор четырехугольников, отсортированных по их контурной оценке. Таким образом получается множество четырехугольников Qt расположенных на It и множество четырехугольников Qb, расположенных на Ib.Consider the circuit in Fig. 1. It is assumed that the document presentation model is such that the top half of the image contains most of the top half of the document, and the bottom half of the image contains most of the bottom half of the document, with the height being greater than the width. Therefore, first the original image I is divided in half into the upper part I t and the lower part I b , and a rough approximation of the document halves is constructed using two quadrangles. To do this, a quadrilateral localization algorithm (Section 1), based on edge and line detection, is applied to both halves, the output of which is a set of quadrilaterals sorted by their contour score. Thus, we obtain a set of quadrangles Q t located on I t and a set of quadrangles Q b located on I b .

Каждая пара четырехугольников используется для того, чтобы составить шестиугольник, который бы представлял внешние границы сложенного документа на изображении. Для того, чтобы составить такой шестиугольник, используются специальные уточняющие техники (раздел 2). К каждому сформированному и уточненному шестиугольнику применяется алгоритм коррекции (раздел 3) для того, чтобы он соответствовал критерию неразрывности. После этого шестиугольники сортируются по их контурной оценке и тот, у которого самая высокая контурная оценка является выходом из этапа локализации (раздел 4).Each pair of quads is used to construct a hexagon that represents the outer boundaries of the folded document in the image. In order to create such a hexagon, special clarifying techniques are used (section 2). A correction algorithm (Section 3) is applied to each generated and refined hexagon to ensure that it meets the continuity criterion. After this, the hexagons are sorted by their contour score and the one with the highest contour score is the output from the localization stage (Section 4).

Последним этапом алгоритма является отображение входного изображения, определяемое двумя проективными преобразованиями. Полученное таким образом изображение является выходом предложенного алгоритма. Рассмотрим детально все блоки схемы на фиг. 1, выделенные пунктиром.The last step of the algorithm is to display the input image, defined by two projective transformations. The image thus obtained is the output of the proposed algorithm. Let us consider in detail all the blocks of the circuit in Fig. 1, highlighted with a dotted line.

1. Поиск четырехугольников1. Finding quadrilaterals

На Фиг. 2 представлена блок-схема алгоритма детекции набора четырехугольников.In FIG. Figure 2 shows a block diagram of the quadrilateral set detection algorithm.

Рассмотрим ее этапы.Let's consider its stages.

1.1. Выделение границ1.1. Border selection

Здесь и далее будем говорить, что вектор и имеет горизонтальное направление, если угол между ним и направляющим вектором горизонтального направления на изображении лежит во множестве, иначе - что он имеет преимущественно вертикальное направление. Поиск границ на изображении начинается с выполнения морфологических операций. Изображение увеличивается на δm (=5) в каждую сторону повторением граничных пикселей (Здесь и далее все параметры предложенного алгоритма, настраиваемые вручную, обозначаются греческими буквами, их значения представлены в скобках. Единицы измерения метрического расстояния совпадают с расстоянием, порождаемым сеткой размером 1 пиксель.). Затем проводится операция морфологического замыкания с размером окна ω (=3) пикселей. После этого производится размытие фильтром Гаусса с вертикальной дисперсией σe (=0.83) и нулевой горизонтальной дисперсией. На размытом изображении считается производная вдоль вертикального направления вычислением модулей разности соседних пикселей. Вышеописанная операция выполняется поканально, после чего результаты работы усредняются и получается серое изображение границ. На нем выполняется подавление немаксимумов - те пиксели, рядом с которыми есть более яркие или значение которых меньше θ (=2), зануляются, а остальные заполняются фиксированным значением. После этого ненулевые пиксели объединяются в компоненты 8-связности, содержащие не более одного пикселя в каждом столбце изображения. Такие компоненты связности далее будут называться треками. Треки фильтруются по количеству пикселей: если его длина меньше, чем ρe (=10%) от длины самого длинного трека, то все пиксели в нем также зануляются. Полученную карту горизонтальных границ обозначим Eh. Аналогично происходит детекция вертикальных границ и вводится соответствующая карта границ Ev. Карты границ Ev и Eh наложены на входное изображение на фиг. 3. а.Here and further we will say that the vector has a horizontal direction if the angle between it and the direction vector of the horizontal direction in the image lies in the set , otherwise - that it has a predominantly vertical direction. Finding boundaries in an image begins with performing morphological operations. The image is enlarged by δ m (=5) in each direction by repeating the boundary pixels (Here and below, all parameters of the proposed algorithm, which are manually adjusted, are denoted by Greek letters, their values are presented in parentheses. The units of measurement of the metric distance coincide with the distance generated by a grid of 1 pixel size .). Then the morphological closure operation is carried out with a window size of ω (=3) pixels. After this, blur is performed using a Gaussian filter with vertical dispersion σ e (=0.83) and zero horizontal dispersion. In a blurred image, the derivative along the vertical direction is calculated by calculating the absolute values of the difference between neighboring pixels. The above operation is performed channel by channel, after which the results of the work are averaged and a gray image of the boundaries is obtained. It performs suppression of non-maxima - those pixels next to which there are brighter ones or whose value is less than θ (=2) are zeroed, and the rest are filled with a fixed value. Non-zero pixels are then combined into 8-connected components containing at most one pixel in each image column. Such connected components will be called tracks below. Tracks are filtered by the number of pixels: if its length is less than ρ e (=10%) of the length of the longest track, then all pixels in it are also zeroed. Let us denote the resulting map of horizontal boundaries as E h . Vertical boundaries are detected similarly and the corresponding boundary map E v is introduced. The boundary maps E v and E h are superimposed on the input image in FIG. 3. a.

1.2. Детекция прямых1.2. Detection of straight lines

После вычисления карт границ Eh и Ev происходит поиск прямых горизонтального и вертикального направления соответственно. Для вертикального направления карта границ разделяется на две (горизонтально пополам): . Изображения размываются при помощи фильтра Гаусса с дисперсией σh (=1) и получаются размытые карты границ . К изображениям применяется быстрое преобразование Хафа (6). Для вертикальных границ находится глобальный максимум М на хаф-образе по обоим изображениям, после чего на каждом из них находится по νmax (=15) локальных максимумов, значения в которых составляют не менее ρ1 (=20%) от М, и в круге радиуса δ1 (=10) от которого нету более ярких локальных максимумов. Для горизонтальных границ аналогично находятся νmax локальных максимумов на изображении . Найденные локальные максимумы переводятся в прямые покоординатно с помощью обратного БПХ. Три множества прямых - два набора вертикальных и один наборгоризонтальных прямых Lh - являются результатом работы данного этапа. На фиг. 3.б представлен результат работы данного этапа.After calculating the boundary maps E h and E v , the search for straight lines in the horizontal and vertical directions, respectively, occurs. For the vertical direction, the boundary map is divided into two (horizontally in half): . Images blurred using a Gaussian filter with dispersion σ h (=1) and blurred boundary maps are obtained . To images the fast Hough transform (6) is applied. For vertical boundaries, the global maximum M is found on the half-image for both images, after which on each of them there are ν max (=15) local maxima, the values of which are at least ρ 1 (=20%) of M, and in circle of radius δ 1 (=10) from which there are no brighter local maxima. For horizontal boundaries, ν max local maxima in the image are similarly found . The found local maxima are converted into straight lines coordinate-wise using inverse FPC. Three sets of straight lines - two sets of vertical ones and one set of horizontal straight lines L h - are the result of the work of this stage. In fig. 3.b shows the result of this stage.

1.3. Сбор и фильтрация четырехугольников1.3. Collection and filtering of quadrilaterals

Обозначим линию, разделяющую изображение I пополам Is. В каждой половине формируется множество четырехугольников . Каждый четырехугольник qt формируется пересечением четырех прямых: одной горизонтальной прямой Ih ∈ Lh, прямой Is и двух вертикальных прямых . Для формирования множества Qt формируются все такие возможные четырехугольники, полностью лежащие в It. Каждому четырехугольнику ставится в соответствие его контурная оценка s(qt), предложенная в (7) (ее аналог будет рассмотрен в разделе 4), после чего все четырехугольники сортируются в порядке убывания этой оценки.Let us denote the line dividing the image I in half by I s . Many quadrangles are formed in each half . Each quadrilateral q t is formed by the intersection of four lines: one horizontal line I h ∈ L h , a line I s and two vertical lines . To form the set Q t , all such possible quadrilaterals that lie entirely in I t are formed. Each quadrilateral is assigned its contour estimate s(q t ), proposed in (7) (its analogue will be considered in Section 4), after which all quadrangles are sorted in descending order of this estimate.

Аналогично формируется множество Qb четырехугольников, полностью лежащих в Ib.The set Q b of quadrangles completely lying in I b is formed in a similar way.

2. Построение шестиугольников2. Construction of hexagons

На Фиг. 4 представлена блок-схема алгоритма формирования шестиугольников по двум четырехугольников. Рассмотрим ее этапы.In FIG. Figure 4 shows a block diagram of the algorithm for forming hexagons from two quadrangles. Let's consider its stages.

Здесь и далее под точками сгиба мы понимаем точки, в которых линия сгиба пересекает внешнюю границу документа (точка F на Фиг. 3. а)Here and below, by fold points we mean the points at which the fold line intersects the outer border of the document (point F in Fig. 3.a)

Рассмотрим пару четырехугольников qt Qt, qb ∈ Qb. Чтобы сформировать шестиугольник, используются все отрезки этих четырехугольников, кроме тех, которые лежат на прямой Is. Можно было бы подумать, что для получения шестиугольника достаточно пересечь соответствующие вертикальные сегменты qt и qb. Однако поскольку в общем случае половины документа не плоские и их контуры не являются прямыми линиями, эти пересечения могут не соответствовать точкам сгиба (Фиг. 3. в). В связи с этим мы анализируем контуры, а не прямые. Рассмотрим карту границ Ev. Каждому вертикальному отрезку четырехугольников qt, qb ставится в соответствие трек с карты границ и рассматривается далее.Consider a pair of quadrilaterals qt Qt, qb∈Qb. To form a hexagon, all segments of these quadrilaterals are used, except those that lie on line Is. One might think that to obtain a hexagon it is sufficient to intersect the corresponding vertical segments qt and qb. However, since in general the document halves are not flat and their outlines are not straight lines, these intersections may not correspond to fold points (Fig. 3c). Because of this, we analyze contours rather than straight lines. Consider the boundary map Ev. Each vertical segment of quadrilaterals qt, qb the track from the border map is matched and considered further.

А именно, для каждого трека ev вычисляется число его пикселей на удалении не более, чем (=3) от данного отрезка s. После этого выбирается трек с наибольшим таким числом и считается соответствующим отрезку s:Namely, for each track e v the number of its pixels at a distance of no more than (=3) from a given segment s. After this, the track with the largest such number is selected and is considered to correspond to the segment s:

Если это число для больше, чем ρmin (=50%) длины s, то такой трек считается валидным.If this number is for is greater than ρ min (=50%) of length s, then such a track is considered valid.

После того, как вертикальным отрезкам сопоставлены валидные треки (если были найдены), проверяется, есть ли пара вертикальных отрезков st ∈ qt, sb ∈ qb, таких что . Будем обозначать такой и будем говорить, что он соответствует двум вертикальным отрезкам. Если такая пара отрезков есть и с левой, и с правой стороны изображения, создается до четырех шестиугольников - вариантов положения документа - по рассматриваемой паре четырехугольников (qt, qb). Для их формирования мы используем два примитива: угол, аппроксимирующий излом границы, вызванный складыванием бумаги (раздел 2.1) и линию сгиба (раздел 2.2). Варианты определяются этими примитивами следующим образом: h1 определяется двумя углами, h2 - левым углом и линией сгиба, h3 - правым углом и линией сгиба, h4 - одной линией сгиба.After valid tracks are associated with vertical segments (if found), it is checked whether there is a pair of vertical segments s t ∈ q t , s b ∈ q b such that . We will denote this and we will say that it corresponds to two vertical segments. If such a pair of segments exists on both the left and right sides of the image, up to four hexagons are created - variants of the position of the document - based on the pair of quadrangles in question (q t , q b ). To form them, we use two primitives: an angle that approximates the edge break caused by folding the paper (Section 2.1) and a fold line (Section 2.2). Options are defined by these primitives as follows: h 1 is defined by two corners, h 2 - by a left corner and a fold line, h 3 - by a right corner and a fold line, h 4 - by one fold line.

2.1. Поиск точек сгиба2.1. Finding bend points

Рассмотрим общий для двух вертикальных отрезков st, sb (например, красный трек внутри области, отмеченной пунктиром на Фиг. 3. а). Нашей целью является поиск точки сгиба (F на том же фиг.) как точки с наибольшим изломом границы.Let's consider common for two vertical segments s t , s b (for example, the red track inside the area marked with a dotted line in Fig. 3.a). Our goal is to find the bend point (F in the same figure) as the point with the greatest break in the boundary.

Чтобы найти точку сгиба, построим трехзвенную ломаную ABCD с центральным отрезком ВС и внешними отрезками АВ и CD на треке. Занумеруем точки от 0 до N сверху вниз и обозначим индекс произвольной точки p трека как i(p). Начиная с произвольной точки , построим оптимальную ломаную следующим образом. Рассмотрим произвольную точку как точку В для ломаной ABCD. Сначала считая, что , построим кратчайший отрезок , такой, что линейная регрессия, построенная по точкам между ними, будет иметь квадратичную ошибку, превышающую εc(=0.2) и после этого возьмем точку C*, как точку, предшествующую To find the bend point, we construct a three-link polyline ABCD with a central segment BC and external segments AB and CD on the track. Let's number the points from 0 to N from top to bottom and denote the index of an arbitrary point p of the track as i(p). Starting from an arbitrary point , let's construct an optimal broken line as follows. Consider an arbitrary point as point B for the broken line ABCD. First considering that , let's construct the shortest segment , such that a linear regression built on the points between them will have a square error exceeding ε c (=0.2) and after that we take point C * as the point preceding

Здесь distA обозначает алгербаическое рассстояние между точкой и прямой.Here dist A denotes the algerbaic distance between a point and a line.

После этого, считая, что i(В) > i(А), формируется отрезок А*В максимальной длины таким образом, что аналогичная регрессия будет иметь квадратичную ошибку не более εo(=1). Аналогично, считая, что i(С*) < i(D), строится отрезок С*D* (Фиг. 3. г). Угол, соответствующий данной ломаной, строится по отрезкам А*В и С*D*, как наибольший угол между прямыми, содержащими эти отрезки. Вершиной угла является точка пересечения отрезков А*В и С*D*. Если эти прямые не пересекаются, вершиной угла считается середина отрезка ВС*.After this, assuming that i(B) > i(A), a segment A * B of maximum length is formed in such a way that a similar regression will have a squared error of no more than ε o (=1). Similarly, assuming that i(C * ) < i(D), the segment C * D * is constructed (Fig. 3.d). The angle corresponding to this broken line is constructed along the segments A * B and C * D * , as the largest angle between the lines containing these segments. The vertex of the angle is the intersection point of the segments A * B and C * D * . If these lines do not intersect, the vertex of the angle is considered to be the middle of the segment BC * .

После того, как для каждой точки построена такая ломаная, на треке находитсяAfter for each point such a broken line was built, on the track there is

точка с наименьшим углом, построенным для нее. Если этот угол превосходит (=170 градусов), то считается, что искомый излом на треке не был найден. В противном случае вершина угла является выходом алгоритма поиска точек сгиба на треке.the point with the smallest angle constructed for it. If this angle exceeds (=170 degrees), then it is considered that the desired break on the track was not found. Otherwise, the corner vertex is the output of the algorithm for finding bend points on the track.

2.2. Детекция прямой сгиба2.2. Straight bend detection

Альтернатива h2 использует левую точку сгиба и линию сгиба, альтернатива h3 использует правую точку сгиба и линию сгиба, альтернатива h4 использует только линию сгиба. Сначала для каждого варианта опишем алгоритм определения линии сгиба, а затем - алгоритм определения координат недостающих вершин.Alternative h 2 uses the left fold point and fold line, alternative h 3 uses the right fold point and fold line, alternative h 4 uses only the fold line. First, for each option, we will describe the algorithm for determining the fold line, and then the algorithm for determining the coordinates of the missing vertices.

Линия сгиба для h2 и h3 выбирается из множества Lh, в котором содержатся все горизонтальные прямые. Искомая линия сгиба выбирается как ярчайшая (в терминах БПХ-образа) прямая среди тех прямых, которые находятся на расстоянии не более (=15) от точки сгиба. Если прямых в окрестности рассматриваемой точки нет, то варианты h2, h3 далее не рассматриваются.The fold line for h 2 and h 3 is selected from the set L h , which contains all horizontal lines. The desired fold line is selected as the brightest (in terms of the BPH image) straight line among those straight lines that are located at a distance of no more than (=15) from the bend point. If there are no straight lines in the vicinity of the point under consideration, then the options h 2 , h 3 are not considered further.

Для h4 прямая сгиба находится следующим образом. Сначала вычисляются точки пересечения прямых, содержащих горизонтальные отрезки qt и qb, с левой и правой границей изображения. Затем для каждой прямой из набора горизонтальных прямых находятся пересечения с теми же границами изображения. После чего выбираются те прямые, для которых пересечение с левой границей лежит между на удалении хотя бы (=10) от каждого, а с правой - между с аналогичными минимальными расстояниями от них.For h 4 the fold line is found as follows. First, the intersection points are calculated straight lines containing horizontal segments q t and q b , with the left and right borders of the image. Then, for each line from the set of horizontal lines, intersections with the same image boundaries are found. After that, those lines are selected for which the intersection with the left boundary lies between at least at a distance (=10) from each, and on the right - between with similar minimum distances from them.

Из выбранных прямых выбирается та, которой соответствует самое большое значение на БПХ-образе, она и будет являться искомой линией сгиба. После этого мы рассматриваем треки (их может быть больше одного), соответствующие линии сгиба, у которых длина составляет хотя бы (=40%) ширины изображения. Установление того, какой трек соответствует линии сгиба, производится тем же способом, что и в разделе 2. После этого для каждого такого трека проводится проверка на то, что не менее (=90%) его длины лежит внутри . Если для какого-то из найденных треков это не так, то он больше не участвует в рассмотрении.From the selected straight lines, the one that corresponds to the largest value on the BPC image is selected, and it will be the desired fold line. After this, we consider tracks (there may be more than one) corresponding to fold lines whose length is at least (=40%) image width. Determining which track corresponds to the fold line is carried out in the same way as in section 2. After this, for each such track a check is made to ensure that at least (=90%) of its length lies inside . If this is not the case for any of the found tracks, then it is no longer included in the consideration.

После этого мы увеличиваем оставшиеся треки, добавляя β(=3) пикселя слева в той же строке изображения, что и его самая левая точка и β пикселей справа в той же строке изображения, что и его самая правая точка. После этого они пересекаются с Если трек, общий для пары вертикальных отрезков есть и слева, и справа, то ищется пересечение с левым треком. Точка пересечения (если она нашлась) теперь рассматривается как вершина шестиугольника.We then augment the remaining tracks by adding β(=3) pixels to the left in the same image row as its leftmost point and β pixels to the right in the same image row as its rightmost point. After this they intersect with If a track common to a pair of vertical segments is on both the left and the right, then an intersection with the left track is sought. The intersection point (if found) is now treated as the vertex of a hexagon.

Для вариантов h2, h3, h4 известны пять вершин (все, кроме одной вершины на линии сгиба) и линия сгиба. Без ограничения общности предположим, что известна левая вершина. Чтобы достроить правую вершину линия сгиба пересекается с правыми вертикальными отрезками qt and qb. После этого берется середина отрезка между этими пересечениями, и она считается правой внутренней вершиной.For options h 2 , h 3 , h 4 five vertices are known (all but one vertex on the fold line) and the fold line. Without loss of generality, assume that the left vertex is known. To complete the right vertex, the fold line intersects with the right vertical segments q t and q b . After this, the middle of the segment between these intersections is taken, and it is considered the right internal vertex.

3. Коррекция шестиугольника для соответствия критерию неразрывности3. Correction of the hexagon to meet the continuity criterion

Когда используется отображение, определяемое двумя проективными преобразованиями для того, чтобы ректифицировать шестиугольник, отвечающий внешнему контуру документа - верхняя половина проективно преобразовывается на верхнюю половину ректифицированного изображения, нижняя половина проективно преобразовывается на нижнюю половину ректифицированного изображения -существует возможность того, что текст будет разрезан в месте соединения половин (красная часть Фиг. 5).When a mapping defined by two projective transformations is used to rectify a hexagon corresponding to the outer contour of a document - the top half is projectively mapped to the top half of the rectified image, the bottom half is projectively mapped to the bottom half of the rectified image - there is a possibility that the text will be cut in place connecting the halves (red part of Fig. 5).

Оказывается, для отсутствия разрыва имеет место следующий критерий. Пусть на плоскости даны два четырехугольника: A1B1CD и A2B2CD, смежные по стороне CD и лежащие в разных полуплоскостях относительно нее, и прямоугольники А11'С'D' и А2'B2'С'D' со смежной стороной С'D' в разных полуплоскостях относительно нее. Пусть Н1 - проективное преобразование из A1B1CD в А11'С'D', а Н2 - проективное преобразование из A2B2CD в А22'С'D'. Пусть Н - преобразование, равное H1 на полуплоскости, в которой лежит A1B1CD и равное Н2 на полуплоскости, в которой лежит A2B2CD. Тогда H корректно определено тогда и только тогда, когда прямые А1В1, А2В2 и CD пересекаются в одной точке (синяя часть Фиг. 3).It turns out that the following criterion holds for the absence of a discontinuity. Let two quadrilaterals be given on the plane: A 1 B 1 CD and A 2 B 2 CD, adjacent on the side CD and lying in different half-planes relative to it, and rectangles A 1 'B 1 'C'D' and A 2 'B 2 'C'D' with adjacent side C'D' in different half-planes relative to it. Let H 1 be a projective transformation from A 1 B 1 CD to A 1 'B 1 'C'D', and H 2 be a projective transformation from A 2 B 2 CD to A 2 'B 2 'C'D'. Let H be a transformation equal to H 1 on the half-plane in which A 1 B 1 CD lies and equal to H 2 on the half-plane in which A 2 B 2 CD lies. Then H is correctly defined if and only if the lines A 1 B 1 , A 2 B 2 and CD intersect at one point (blue part of Fig. 3).

Преобразуем в соответствии с критерием каждый из вариантов расположения документа. Для трех горизонтальных отрезков шестиугольника применяется алгоритм (8), вычисляющий три прямые, проходящие через одну точку и приближающие эти отрезки. После того, как были получены эти прямые, вершины шестиугольника пересчитываются: результирующие верхние и нижние прямые пересекаются с соответствующими вертикальными прямыми. Результирующая линия сгиба пересекается с верхними вертикальными отрезками. Обозначим оператор преобразования шестиугольника к модели единой горизонтальной точки схода V. Таким образом из шестиугольника h получается новый, h'=V(h).We transform each of the document layout options in accordance with the criterion. For three horizontal segments of a hexagon, algorithm (8) is used, which calculates three straight lines passing through one point and approximating these segments. Once these lines have been obtained, the vertices of the hexagon are recalculated: the resulting top and bottom lines intersect with the corresponding vertical lines. The resulting fold line intersects with the top vertical segments. Let us denote the operator of transforming a hexagon to a model of a single horizontal vanishing point V. Thus, from a hexagon h a new one is obtained, h'=V(h).

4. Фильтрация и ранжирование шестиугольников4. Filtering and ranking hexagons

Для каждого шестиугольника из множества {h} вычисляется его контурная оценка, являющаяся количественной мерой яркости шестиугольника. Для этого карты границ размываются фильтром Гаусса с дисперсией σ(=1.83). При вычислении контурной оценки рассматриваются семь отрезков: стороны шестиугольников и отрезок на линии сгиба. Для каждого из них вычисляются следующие значения: сумма пикселей pm вдоль отрезка и количество нулевых пикселей rm вдоль отрезка. Количество нулевых пикселей вдоль каждого отрезка суммируется и делится на длину всех отрезков l, в результате чего получается отношение Также мы вычисляем значение штрафа q, предложенном в (7). Рассмотрим вершину шестиугольника vn, расположенную не на сгибе. К q добавляется сумма βp(=10) ближайших к vn пикселей, лежащих вне h вдоль сторон, пересекающихся в vn. В случае вершины, лежащей на линии сгиба vc вычисялется сумма βp(=10) ближайших к vc пикселей, лежащих вне h вдоль линии сгиба (Фиг. 3. е). Тогда контурной оценкой шестиугольника называется числоFor each hexagon from the set {h}, its contour score is calculated, which is a quantitative measure of the brightness of the hexagon. For this, boundary maps blurred by a Gaussian filter with dispersion σ(=1.83). When calculating the contour estimate, seven segments are considered: the sides of the hexagons and the segment on the fold line. For each of them, the following values are calculated: the sum of pixels p m along the segment and the number of zero pixels r m along the segment. The number of zero pixels along each segment is summed and divided by the length of all segments l, resulting in the ratio We also calculate the value of the penalty q proposed in (7). Consider the vertex of the hexagon vn , which is not located on the fold. To q is added the sum β p (=10) of the pixels closest to v n lying outside h along the sides intersecting at v n . In the case of a vertex lying on the fold line v c , the sum β p (=10) of the pixels closest to v c lying outside h along the fold line is calculated (Fig. 3. f). Then the contour estimate of the hexagon is the number

Из множества шестиугольников {h'} выбирается такой h'*, чтоFrom the set of hexagons {h'}, select h'* such that

где (h') - шестиугольник h, из которого h' был получен под действием оператора V, Rt(h') и Rb(h') _ соотношения сторон (9) верхней и нижней половины шестиугольника h*, вычисленные в модели камеры-обскуры с фокусным расстоянием λ(=0.705) и принципиальной точкой в центре исходного изображения, R0 - истинное соотношение сторон, равное для бумаги формата А4.Where (h') - hexagon h, from which h' was obtained under the action of the operator V, R t (h') and R b (h') _ aspect ratios (9) of the upper and lower half of the hexagon h * , calculated in the camera model -pinholes with focal length λ(=0.705) and the principal point in the center of the original image, R 0 - true aspect ratio equal to for A4 paper.

После этого вычисляются расстояния между соответствующими вершинами h'* и h* = (h'*), а также углы между старыми и новыми отрезками. Если какой-то из этих углов превосходит (=2.56 градусов), или какое-то из этих расстояний больше, чем (=1%) высоты изображения, то в таком случае мы считаем, что коррекция шестиугольника при приведении его к модели единой точки схода может повредить горизонтальность текста, такой шестиугольник считается невалидным и вывод алгоритма локализации пустой.After this, the distances between the corresponding vertices h' * and h * = (h' * ), as well as the angles between the old and new segments. If any of these angles exceeds (=2.56 degrees), or whichever of these distances is greater than (=1%) of the image height, then in this case we believe that correcting the hexagon when bringing it to the model of a single vanishing point can damage the horizontality of the text, such a hexagon is considered invalid and the output of the localization algorithm is empty.

Необходимость такой проверки продиктована следующим. Рассмотрим Фиг. 6. На ней изображены результаты работы алгоритма на двух различных изображениях. В обоих случаях найденные шестиугольники (изображены синим на Фиг. 6. а, в) отвечают истинным расположениям документа. Однако, документа на первом изображении не соответствует модели двух плоскостей, так что шестиугольник h* сильно изменяется под действием оператора V и ректификация по скорректированному шестиугольнику h'* (изображен красным на Фиг. 6. а) неудовлетворительная (Фиг. 6. б). Документ на втором изображении соответствует модели двух плоскостей, так что шестиугольник h* (изображен зеленым на Фиг. 6. в) считается валидным и ректификация удовлетворительная (Фиг. 6. г).The need for such verification is dictated by the following. Consider Fig. 6. It shows the results of the algorithm on two different images. In both cases, the found hexagons (shown in blue in Fig. 6. a, c) correspond to the true locations of the document. However, the document in the first image does not correspond to the two-plane model, so that the hexagon h * changes greatly under the action of the operator V and the rectification using the adjusted hexagon h' * (shown in red in Fig. 6. a) is unsatisfactory (Fig. 6. b). The document in the second image corresponds to the two-plane model, so the hexagon h * (shown in green in Fig. 6. c) is considered valid and the rectification is satisfactory (Fig. 6. d).

5. Проективное преобразование5. Projective transformation

Если выбранный шестиугольник h'* признан невалидным, то возвращается исходное изображение. В противном случае каждая половина шестиугольника проективно преобразуется (с использованием билинейной интерполяции (10)) на соответствующую половину ректифицированного изображения (2100 × 2970). Это изображение является выходом алгоритма.If the selected hexagon h' * is invalid, the original image is returned. Otherwise, each half of the hexagon is projectively transformed (using bilinear interpolation (10)) to the corresponding half of the rectified image (2100 × 2970). This image is the output of the algorithm.

Примеры реализации способа представлены на фиг. 7 и 8.Examples of implementation of the method are presented in Fig. 7 and 8.

Описанный алгоритм может быть расширен и адаптирован для локализации и проективной нормализации сложенных один раз документов с прямой сгиба, непараллельной коротким сторонам документа, пересекающей обе длинные стороны документа.The described algorithm can be extended and adapted for localization and projective normalization of once-folded documents with a straight fold, non-parallel to the short sides of the document, intersecting both long sides of the document.

В таком случае документ на изображении может быть представлен шестиугольником и для его детекции предлагается использовать алгоритм из этапов 1 и 2.In this case, the document in the image can be represented by a hexagon, and to detect it, it is proposed to use the algorithm from stages 1 and 2.

Пусть детектирован шестиугольник h. Для того, чтобы проективно нормализовать его верхний и нижний четырехугольники, необходимо определить, в каких отношениях линия сгиба делит боковые стороны листа бумаги на ректифицированном изображении. Эти отношения могут быть вычислены при помощи алгоритма (11) восстановления образа прямоугольника на изображении, применяя его к одной из частей детектированного шестиугольника как образу прямоугольника с соотношением сторон R0(см. п. 4).Let a hexagon h be detected. In order to projectively normalize its upper and lower quadrangles, it is necessary to determine in what respects the fold line divides the sides of the sheet of paper in the rectified image. These ratios can be calculated using algorithm (11) for restoring the image of a rectangle in the image, applying it to one of the parts of the detected hexagon as an image of a rectangle with aspect ratio R 0 (see section 4).

Критерий отсутствия разрыва при конкатенации образов верхнего и нижнего четырехугольников может быть переформулирован следующим образом.The criterion for the absence of a discontinuity when concatenating the images of the upper and lower quadrilaterals can be reformulated as follows.

Пусть на плоскости даны два четырехугольника: A1B1CD и A2B2CD, смежные по стороне CD и лежащие в разных полуплоскостях относительно нее, точка V11В1 CD, точка V22В2 CD и прямоугольник А1122', разделенный прямой С'D' таким образом, что точка С' лежит на стороне А12' и делит ее в отношении x1, а точка D' лежит на стороне В12 и делит ее в отношении xr. Пусть Н1 - проективное преобразование из A1B1CD в А11'С'D', а Н2 - проективное преобразование из A2B2CD в А22'С'D'. Пусть Н - преобразование, равное Н1 на полуплоскости, в которой лежит A1B1CD и равное Н2 на полуплоскости, в которой лежит A2B2CD. Тогда Н корректно определено тогда и только тогда, когда выполняется соотношениеLet there be two quadrilaterals on the plane: A 1 B 1 CD and A 2 B 2 CD, adjacent on the side CD and lying in different half-planes relative to it, point V 1 = A 1 B 1 CD, point V 2 = A 2 B 2 CD and rectangle A 1 'B 1 'B 2 'A 2 ', divided by line C'D' in such a way that point C' lies on side A 1 'A 2 ' and divides it in the ratio x 1 , and point D' lies on side B 1 'B 2 and divides it in the ratio x r . Let H 1 be a projective transformation from A 1 B 1 CD to A 1 'B 1 'C'D', and H 2 be a projective transformation from A 2 B 2 CD to A 2 'B 2 'C'D'. Let H be a transformation equal to H 1 on the half-plane in which A 1 B 1 CD lies and equal to H 2 on the half-plane in which A 2 B 2 CD lies. Then H is correctly defined if and only if the relation

Данное соотношение, подобно условию существования единой точки схода в п. 3, накладывает ограничение на взаимное расположение отрезков и . Зафиксировав положение отрезка CD, можно найти такие и , суммарное квадратное отклонение которых от соответствующих отрезков минимально и при этом соблюдается ограничение L (существование обеспечивается тем фактом, что семейство искомых параметров двухпараметрическое, а количество накладываемых условий равно трем).This relationship, similar to the condition for the existence of a single vanishing point in paragraph 3, imposes a restriction on the relative position of the segments And . Having fixed the position of the segment CD, we can find the following And , the total square deviation of which from the corresponding segments is minimal and at the same time the constraint L is observed (existence is ensured by the fact that the family of required parameters is two-parameter, and the number of imposed conditions is equal to three).

После приведения отрезков А1В1, А2В2 к соответствию критерию отсутствия разрыва при конкатенации проективно нормализованных четырехугольников предлагается применить этап 4 без учета проверки соотношения сторон в выборе лучшего шестиугольника, после чего проективно исправить лучший шестиугольник, отобразив его четырехугольники на соответствующие четырехугольники ректифицированного изображения.After bringing the segments A 1 B 1 , A 2 B 2 to correspond to the criterion of the absence of a gap in the concatenation of projectively normalized quadrilaterals, it is proposed to apply stage 4 without taking into account the check of the aspect ratio in choosing the best hexagon, and then projectively correct the best hexagon by mapping its quadrilaterals to the corresponding quadrilaterals of the rectified Images.

Таким образом, заявленный способ позволяет достичь следующих технических результатов:Thus, the claimed method allows to achieve the following technical results:

- получение изображения документов, как если бы они были отсканированы на планшетном сканере, без применения последних, с использованием лишь камеры и вычислительного устройства;- obtaining images of documents as if they were scanned on a flatbed scanner, without using the latter, using only a camera and a computing device;

- обеспечение возможности запуска на ректифицированных изображениях сложенных пополам документов систем распознавания, предназначенных для изображений, полученных с планшетного сканера. Такие системы являются менее ресурсоемкими и легковесными, чем системы распознавания, предназначенные для фотографий;- providing the ability to run recognition systems designed for images obtained from a flatbed scanner on rectified images of documents folded in half. Such systems are less resource-intensive and lightweight than recognition systems designed for photographs;

- обеспечение возможности получения ректифицированных изображений на одном устройстве, оснащенном камерой, например, на смартфоне, что позволяет не терять время на передачу данных между устройствами. При этом не требует мощного вычислителя (видеокарты) для быстрой работы на конечных пользовательских устройствах;- providing the ability to obtain rectified images on one device equipped with a camera, for example, a smartphone, which allows you to avoid wasting time transferring data between devices. At the same time, it does not require a powerful computer (video card) for fast operation on end user devices;

- обеспечение возможности хранить и использовать физические документы, предназначенные для оцифровки системами распознавания, в сложенном пополам виде;- providing the ability to store and use physical documents intended for digitization by recognition systems, folded in half;

- обеспечение возможности отсекать случаи, когда документ на изображении не удовлетворяет модели предъявления (две плоские половины страницы формата А4);- providing the ability to cut off cases when the document in the image does not satisfy the presentation model (two flat halves of an A4 page);

- обеспечение возможности находить и ректифицировать документы, частично скрытые рукой. Возможность держать документ в руках при съемке значительно повышает пользовательский опыт;- providing the ability to find and rectify documents partially hidden by hand. The ability to hold a document in your hands while shooting significantly improves the user experience;

- алгоритм не требует информации о заполнении документа для его геометрической нормализации.- the algorithm does not require information about the filling of the document for its geometric normalization.

Список литературыBibliography

(1) Michael S Brown and Brent Seales. Image restoration of arbitrarily warped documents. IEEE Transactions on pattern analysis and machine intelligence, 26(10):1295-1306, 2004.(1) Michael S Brown and Brent Seales. Image restoration of arbitrarily warped documents. IEEE Transactions on pattern analysis and machine intelligence, 26(10):1295–1306, 2004.

(2) Shaodi You, Yasuyuki Matsushita, Sudipta Sinha, Yusuke Bou, and Katsushi Ikeuchi. Multiview rectification of folded documents. IEEE transactions on pattern analysis and machine intelligence, 40(2):505-511, 2017.(2) Shaodi You, Yasuyuki Matsushita, Sudipta Sinha, Yusuke Bou, and Katsushi Ikeuchi. Multiview rectification of folded documents. IEEE transactions on pattern analysis and machine intelligence, 40(2):505–511, 2017.

(3) Hao Feng, Yuechen Wang, Wengang Zhou, Jiajun Deng, and Houqiang Li. Doctr: Document image transformer for geometric unwarping and illumination correction. arXiv preprint arXiv:2110.12942, 2021.(3) Hao Feng, Yuechen Wang, Wengang Zhou, Jiajun Deng, and Houqiang Li. Doctr: Document image transformer for geometric unwarping and illumination correction. arXiv preprint arXiv:2110.12942, 2021.

(4) Gaofeng Meng, Chunhong Pan, Shiming Xiang, Jiangyong Duan, and Nanning Zheng. Metric rectification of curved document images. IEEE transactions on pattern analysis and machine intelligence, 34(4):707-722, 2011.(4) Gaofeng Meng, Chunhong Pan, Shiming Xiang, Jiangyong Duan, and Nanning Zheng. Metric rectification of curved document images. IEEE transactions on pattern analysis and machine intelligence, 34(4):707–722, 2011.

(5) Sagnik Das, Gaurav Mishra, Akshay Sudharshana, and Roy Shilkrot. The common fold: utilizing the four-fold to dewarp printed documents from a single image. In Proceedings of the 2017 ACM Symposium on Document Engineering, pages 125-128, 2017(5) Sagnik Das, Gaurav Mishra, Akshay Sudharshana, and Roy Shilkrot. The common fold: utilizing the four-fold to dewarp printed documents from a single image. In Proceedings of the 2017 ACM Symposium on Document Engineering, pages 125-128, 2017

(6) Martin L Brady. A fast discrete approximation algorithm for the radon transform. SIAM Journal on Computing, 27(1):107-119, 1998.(6) Martin L Brady. A fast discrete approximation algorithm for the radon transform. SIAM Journal on Computing, 27(1):107-119, 1998.

(7) Natalya Skoryukina, Dmitry P Nikolaev, Alexander Sheshkus, and Dmitry Polevoy. Real time rectangular document detection on mobile devices. In Seventh International Conference on Machine Vision (ICMV 2014), volume 9445, pages 458-463. SPIE, 2015.(7) Natalya Skoryukina, Dmitry P Nikolaev, Alexander Sheshkus, and Dmitry Polevoy. Real time rectangular document detection on mobile devices. In Seventh International Conference on Machine Vision (ICMV 2014), volume 9445, pages 458-463. SPIE, 2015.

(8) Julia Shemiakina, Ivan Konovalenko, Daniil Tropin, and Igor Faradjev. Fast projective image rectification for planar objects with manhattan structure. In Twelfth International Conference on Machine Vision (ICMV 2019), volume 11433, pages 450-458. SPIE, 2020.(8) Julia Shemiakina, Ivan Konovalenko, Daniil Tropin, and Igor Faradjev. Fast projective image rectification for planar objects with manhattan structure. In Twelfth International Conference on Machine Vision (ICMV 2019), volume 11433, pages 450-458. SPIE, 2020.

(9) Zhengyou Zhang and Li-Wei He. Whiteboard scanning and image enhancement. Digital signal processing, 17(2):414-132, 2007.(9) Zhengyou Zhang and Li-Wei He. Whiteboard scanning and image enhancement. Digital signal processing, 17(2):414-132, 2007.

(10) Anton Trusov and Elena Limonova. The analysis of projective transformation algorithms for image recognition on mobile devices. In Twelfth International Conference on Machine Vision (ICMV 2019), volume 11433, pages 250-257. SPIE, 2020.(10) Anton Trusov and Elena Limonova. The analysis of projective transformation algorithms for image recognition on mobile devices. In Twelfth International Conference on Machine Vision (ICMV 2019), volume 11433, pages 250-257. SPIE, 2020.

(11) Daniil V. Tropin, Ivan A. Konovalenko, Natalya S. Skoryukina, Dmitry P. Nikolaev and Vladimir V. Arlazarov. Improved algorithm of ID card detection by a priori knowledge of the document aspect ratio. In Thirteenth International Conference on Machine Vision (ICMV 2020), volume 11605, pages 407-415. SPIE, 2021.(11) Daniil V. Tropin, Ivan A. Konovalenko, Natalya S. Skoryukina, Dmitry P. Nikolaev and Vladimir V. Arlazarov. Improved algorithm of ID card detection by a priori knowledge of the document aspect ratio. In Thirteenth International Conference on Machine Vision (ICMV 2020), volume 11605, pages 407-415. SPIE, 2021.

Claims (1)

Способ получения ректифицированных изображений документов, сложенных пополам, заключающийся в поступлении на вход модели предъявления документа, причем верхняя половина изображения содержит большую часть верхней половины документа, а нижняя половина изображения содержит большую часть нижней половины документа, при этом высота больше ширины, отличающийся тем, что исходное изображение I делится пополам на верхнюю часть It и нижнюю часть Ib, строится грубое приближение половин документа двумя четырехугольниками, для этого к обеим половинам применяется алгоритм локализации четырехугольников, основанный на детекции границ и прямых, выходом которого является набор четырехугольников, отсортированных по их контурной оценке, таким образом получается множество четырехугольников Qt, расположенных на It, и множество четырехугольников Qb, расположенных на Ib, при этом каждая пара четырехугольников используется для того, чтобы составить шестиугольник, который бы представлял внешние границы сложенного документа на изображении, к каждому сформированному и уточненному шестиугольнику применяется алгоритм коррекции, после этого шестиугольники сортируются по их контурной оценке и тот, у которого самая высокая контурная оценка, является выходом из этапа локализации, последним этапом является отображение входного изображения, определяемого двумя проективными преобразованиями.A method for obtaining rectified images of documents folded in half, which consists of inputting a document presentation model, wherein the upper half of the image contains most of the upper half of the document, and the lower half of the image contains most of the lower half of the document, the height being greater than the width, characterized in that the original image I is divided in half into the upper part I t and the lower part I b , a rough approximation of the halves of the document by two quadrangles is constructed, for this, a quadrilateral localization algorithm based on detection of boundaries and lines is applied to both halves, the output of which is a set of quadrangles sorted by their contour estimation, thus obtaining a set of quadrilaterals Q t located on I t and a set of quadrilaterals Q b located on I b , with each pair of quadrilaterals being used to construct a hexagon that would represent the outer boundaries of the folded document in the image, a correction algorithm is applied to each generated and refined hexagon, after which the hexagons are sorted by their contour score and the one with the highest contour score is the output of the localization stage, the last stage being the display of the input image defined by two projective transformations.
RU2023130764A 2023-11-24 Method of producing rectified images of documents folded in half RU2820743C1 (en)

Publications (1)

Publication Number Publication Date
RU2820743C1 true RU2820743C1 (en) 2024-06-07

Family

ID=

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US7463772B1 (en) * 2004-09-13 2008-12-09 Google Inc. De-warping of scanned images
US20170076169A1 (en) * 2011-10-17 2017-03-16 Sharp Laboratories of America (SLA), Inc. System and Method for Scanned Document Correction
RU2631765C1 (en) * 2016-04-26 2017-09-26 Общество с ограниченной ответственностью "Аби Девелопмент" Method and system of correcting perspective distortions in images occupying double-page spread
CN111353961A (en) * 2020-03-12 2020-06-30 上海合合信息科技发展有限公司 Document curved surface correction method and device
US10991081B1 (en) * 2020-12-31 2021-04-27 VoyagerX, Inc. Book scanning using machine-trained model

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US7463772B1 (en) * 2004-09-13 2008-12-09 Google Inc. De-warping of scanned images
US20170076169A1 (en) * 2011-10-17 2017-03-16 Sharp Laboratories of America (SLA), Inc. System and Method for Scanned Document Correction
RU2631765C1 (en) * 2016-04-26 2017-09-26 Общество с ограниченной ответственностью "Аби Девелопмент" Method and system of correcting perspective distortions in images occupying double-page spread
CN111353961A (en) * 2020-03-12 2020-06-30 上海合合信息科技发展有限公司 Document curved surface correction method and device
US10991081B1 (en) * 2020-12-31 2021-04-27 VoyagerX, Inc. Book scanning using machine-trained model

Similar Documents

Publication Publication Date Title
JP4847592B2 (en) Method and system for correcting distorted document images
US10289924B2 (en) System and method for scanned document correction
JP4047352B2 (en) Image distortion correction program, image distortion correction apparatus, and image distortion correction method
US7301564B2 (en) Systems and methods for processing a digital captured image
RU2631765C1 (en) Method and system of correcting perspective distortions in images occupying double-page spread
US8717632B2 (en) Image processing method, image processing device and scanner
US8634659B2 (en) Image processing apparatus, computer readable medium storing program, and image processing method
JP4551018B2 (en) Image combiner
US10430948B2 (en) Method and system for preparing text images for optical-character recognition
US8811751B1 (en) Method and system for correcting projective distortions with elimination steps on multiple levels
US8897600B1 (en) Method and system for determining vanishing point candidates for projective correction
CN110427946B (en) Document image binarization method and device and computing equipment
US10504215B2 (en) Method of correcting a captured image, method of selecting a drawing sketched on a page or on two adjacent pages of a notebook, a relative app for smartphone, a hardback notebook and a hardback agenda
US8913836B1 (en) Method and system for correcting projective distortions using eigenpoints
JP6045625B2 (en) Image processing apparatus, region detection method, and computer program
WO2014047856A1 (en) Method and device for determining video foreground main image area
JP4993615B2 (en) Image recognition method and apparatus
RU2469400C1 (en) Method to convert bitmapped image into metafile
CN108460738A (en) Medical image sloped correcting method based on B-spline
JP6542230B2 (en) Method and system for correcting projected distortion
CN115619656A (en) Digital file deviation rectifying method and system
JP6797046B2 (en) Image processing equipment and image processing program
US9077926B2 (en) Image processing method and image processing apparatus
Poleg et al. Alignment and mosaicing of non-overlapping images
RU2820743C1 (en) Method of producing rectified images of documents folded in half