[go: up one dir, main page]

RU2768544C1 - Method for recognition of text in images of documents - Google Patents

Method for recognition of text in images of documents Download PDF

Info

Publication number
RU2768544C1
RU2768544C1 RU2021121146A RU2021121146A RU2768544C1 RU 2768544 C1 RU2768544 C1 RU 2768544C1 RU 2021121146 A RU2021121146 A RU 2021121146A RU 2021121146 A RU2021121146 A RU 2021121146A RU 2768544 C1 RU2768544 C1 RU 2768544C1
Authority
RU
Russia
Prior art keywords
document
image
text
fields
area
Prior art date
Application number
RU2021121146A
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 RU2021121146A priority Critical patent/RU2768544C1/en
Application granted granted Critical
Publication of RU2768544C1 publication Critical patent/RU2768544C1/en

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING OR CALCULATING; COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F18/00Pattern recognition
    • G06F18/20Analysing
    • G06F18/22Matching criteria, e.g. proximity measures
    • GPHYSICS
    • G06COMPUTING OR CALCULATING; COUNTING
    • G06NCOMPUTING ARRANGEMENTS BASED ON SPECIFIC COMPUTATIONAL MODELS
    • G06N3/00Computing arrangements based on biological models
    • G06N3/02Neural networks
    • GPHYSICS
    • G06COMPUTING OR CALCULATING; COUNTING
    • G06TIMAGE DATA PROCESSING OR GENERATION, IN GENERAL
    • G06T7/00Image analysis
    • G06T7/10Segmentation; Edge detection

Landscapes

  • Engineering & Computer Science (AREA)
  • Theoretical Computer Science (AREA)
  • Physics & Mathematics (AREA)
  • Data Mining & Analysis (AREA)
  • General Physics & Mathematics (AREA)
  • General Engineering & Computer Science (AREA)
  • Life Sciences & Earth Sciences (AREA)
  • Artificial Intelligence (AREA)
  • Computer Vision & Pattern Recognition (AREA)
  • Evolutionary Computation (AREA)
  • Bioinformatics & Computational Biology (AREA)
  • Evolutionary Biology (AREA)
  • Bioinformatics & Cheminformatics (AREA)
  • Health & Medical Sciences (AREA)
  • Biomedical Technology (AREA)
  • Biophysics (AREA)
  • Computational Linguistics (AREA)
  • General Health & Medical Sciences (AREA)
  • Molecular Biology (AREA)
  • Computing Systems (AREA)
  • Mathematical Physics (AREA)
  • Software Systems (AREA)
  • Character Input (AREA)

Abstract

FIELD: computing technology.
SUBSTANCE: computer-implemented method for automatic recognition of text in an image of a document, the method is executed on a computing apparatus containing a processor and a memory storing instructions executed by the processor and containing stages of: obtaining an image of the document; isolating an area of the document in the image; based on the isolated area of the document in the image, classifying a type of the document using a convolutional neural network; binarising the image of the determined type of document in order to separate the text of the document from the background; segmenting the image of the document, with the determined type of document, in order to determine text fields, by determining the coordinates of the bounding rectangles of fields; determining the type of found text fields using structural document templates; conducting text recognition on the identified text fields; validating the recognised text on the identified text fields based on a set of rules related to the data contained in the fields and the expected presentation formats of said data.
EFFECT: increase in the accuracy of extracting information from images of documents.
16 cl, 2 dwg

Description

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

Настоящее техническое решение относится к вычислительной технике, а в частности к способам распознавания текста на изображениях документов посредством методов машинного обучения.The present technical solution relates to computer technology, and in particular to methods for recognizing text on document images using machine learning methods.

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

Из уровня техники известен источник информации US 8,897,563 В1, опубликованный 25.11.2014 года, раскрывающий способ и систему автоматической обработки документов. В данном решении система анализа документов, принимает и обрабатывает задания от множества пользователей, где каждое задание может содержать несколько электронных документов, для извлечения данных из них, посредством метода автоматической предварительной обработки каждого принятого электронного документа с использованием множества изображений. В решении предусмотрены алгоритмы преобразования для улучшения последующего извлечения данных из указанного документа. Указанный способ включает электронное разбиение каждой полученной страницы электронного документа на части; автоматическую обработку каждого фрагмента страницы принятого электронного документа с использованием каждого из множества алгоритмов предварительной обработки изображения для создания множества вариантов изображения каждого фрагмента, а также анализ результатов последующей обработки и извлечения данных для каждого из вариантов изображения частей, чтобы определить, какой результат лучше всего.Known from the prior art is the source of information US 8,897,563 B1, published on November 25, 2014, which discloses a method and system for automatic document processing. In this solution, the document analysis system receives and processes jobs from multiple users, where each job may contain multiple electronic documents, to extract data from them, through a method of automatically pre-processing each received electronic document using multiple images. The solution provides transformation algorithms to improve the subsequent extraction of data from the specified document. The specified method includes electronic splitting of each received page of the electronic document into parts; automatic processing of each page fragment of the received electronic document using each of the multiple image pre-processing algorithms to create a plurality of image options for each fragment, as well as analyzing the results of post-processing and data extraction for each of the image parts options to determine which result is best.

Из уровня техники также известен источник информации RU 2691214 С1, опубликованный 11.06.2019 года, раскрывающий способ распознавания текста с использованием искусственного интеллекта. Способ включает получение изображения текста, при этом текст на изображении содержит одно или более слов в одном или более предложениях; получение изображения текста в качестве первых исходных данных для набора обученных моделей машинного обучения, хранящего информацию о сочетаемости слов и частотности их совместного употребления в реальных предложениях; получение одного или более конечных выходных данных от набора обученных моделей машинного обучения, а также извлечение из одного или более конечных выходных данных одного или более предполагаемых предложений из текста на изображении. Каждое из одного или более предполагаемых предложений содержит вероятные последовательности слов.The source of information RU 2691214 C1, published on 06/11/2019, is also known from the prior art, revealing a text recognition method using artificial intelligence. The method includes obtaining an image of text, wherein the text in the image contains one or more words in one or more sentences; obtaining a text image as the first input data for a set of trained machine learning models that stores information about word compatibility and the frequency of their joint use in real sentences; obtaining one or more final outputs from a set of trained machine learning models; and extracting from one or more final outputs one or more suggested sentences from the text in the image. Each of the one or more proposed sentences contains probable word sequences.

Предлагаемое решение, отличается от известных из уровня техники решений тем, что после выделения области документа на изображении осуществляют классификацию типа документа с применением алгоритмов машинного обучения, а также осуществляют валидацию распознанного текста по набору правил относительно данных, содержащихся в полях, и ожидаемых форматов представления этих данных.The proposed solution differs from the solutions known from the prior art in that after highlighting the document area in the image, the document type is classified using machine learning algorithms, and the recognized text is validated according to a set of rules regarding the data contained in the fields and the expected presentation formats of these data.

СУЩНОСТЬ ИЗОБРЕТЕНИЯSUMMARY OF THE INVENTION

Технической задачей, на решение которой направлено заявленное решение, является разработка способа извлечения информации из изображений документов посредством методов машинного обучения, охарактеризованного в независимом пункте формулы изобретения. Дополнительные варианты реализации настоящего изобретения представлены в зависимых пунктах формулы изобретения.The technical problem to be solved by the claimed solution is the development of a method for extracting information from images of documents using machine learning methods, described in an independent claim. Additional embodiments of the present invention are presented in dependent claims.

Технический результат заключается в повышении точности извлечения информации из изображений документов. Дополнительным техническим результатом является повышение скорости распознавания текста на изображениях документов. Дополнительным техническим результатом является увеличение производительности вычислительной системы при решении поставленной задачи (т.е. позволяет производить обработку с получением результата (продукта) за меньшее количество времени), тем самым снижается нагрузка на центральный процессор вычислительного устройства, за счет уменьшения количества обрабатываемых запросов.The technical result consists in increasing the accuracy of extracting information from document images. An additional technical result is to increase the speed of text recognition on document images. An additional technical result is an increase in the performance of the computing system when solving the task (i.e., it allows processing to obtain a result (product) in less time), thereby reducing the load on the central processor of the computing device, by reducing the number of processed requests.

Заявленный технический результат достигается за счет работы компьютерно-реализуемого способа автоматического распознавания текста на изображении документа, способ выполняется на вычислительном устройстве, который содержит процессор и память, хранящую инструкции, исполняемые процессором и содержащие этапы, на которых:The claimed technical result is achieved through the operation of a computer-implemented method for automatic text recognition on a document image, the method is performed on a computing device that contains a processor and a memory that stores instructions executable by the processor and contains the steps in which:

на вычислительное устройство получают изображение документа;an image of the document is received on the computing device;

посредством модуля локализации документа, осуществляют выделение области документа на изображении;by means of the document localization module, the selection of the document area on the image is carried out;

посредством модуля классификации типа документа, на основе выделенной области документа на изображении, осуществляют классификацию типа документа с применением сверточной нейронной сети;by means of a document type classification module, based on the selected area of the document in the image, the document type is classified using a convolutional neural network;

посредством модуля бинаризации, осуществляют бинаризацию изображения определенного типа документа для отделения текста документа от фона;by means of the binarization module, perform binarization of the image of a certain type of document to separate the text of the document from the background;

посредством модуля сегментации, осуществляют сегментацию изображения документа, с определенным типом документа на этапе классификации, для определения текстовых полей, путем определения координат ограничивающих прямоугольников полей;through the segmentation module, segmenting the image of the document, with a certain type of document at the stage of classification, to determine the text fields, by determining the coordinates of the bounding boxes of the fields;

посредством модуля сопоставления, определяют тип найденных, на предыдущем этапе, текстовых полей с помощью структурных шаблонов документов;by means of the mapping module, determine the type of text fields found, at the previous stage, using structural document templates;

посредством модуля распознавания текста, осуществляют распознавание текста на выявленных текстовых полях;by means of a text recognition module, perform text recognition on the identified text fields;

посредством модуля валидации, осуществляют валидацию распознанного текста на выявленных текстовых полях по набору правил относительно данных, содержащихся в полях, и ожидаемых форматов представления этих данных.by means of the validation module, the recognized text is validated on the identified text fields according to a set of rules regarding the data contained in the fields and the expected formats for presenting this data.

В частном варианте реализации предлагаемого способа, изображение получено посредством сканирования.In a private embodiment of the proposed method, the image is obtained by scanning.

В другом частном варианте реализации предлагаемого способа, изображение получено посредством фотографирования.In another particular embodiment of the proposed method, the image is obtained by photographing.

В другом частном варианте реализации предлагаемого способа, выделение области документа на по меньшей мере одном изображении осуществляют с применением алгоритма поиска контура наибольшей площади или осуществляют выделение области посредством сегментации с помощью сверточной нейронной сети.In another particular embodiment of the proposed method, the selection of the document area on at least one image is carried out using the algorithm for finding the contour of the largest area or the selection of the area is carried out by segmentation using a convolutional neural network.

В другом частном варианте реализации предлагаемого способа, выделение области документа на изображении с применением алгоритма поиска контура наибольшей площади включает следующие этапы: сжатие размера полученного изображения документа до целевой высоты, зависящей от типа документа, преобразование многоканального изображения в одноканальное изображение, применение к преобразованному одноканальному изображению фильтра медианного размытия, выделение краев изображения, поиск контуров на изображении, выбор контура с наибольшей площадью, выделение ограничивающего прямоугольника для выбранного контура с наибольшей площадью и выравнивание области документа с помощью перспективной проекции с матрицей.In another particular embodiment of the proposed method, the selection of a document area in an image using the largest area contour search algorithm includes the following steps: compressing the size of the resulting document image to a target height depending on the type of document, converting a multi-channel image into a single-channel image, applying to the converted single-channel image median blur filter, select image edges, search for contours in the image, select the contour with the largest area, select the bounding box for the selected contour with the largest area, and flatten the document area using perspective projection with matrix.

В другом частном варианте реализации предлагаемого способа, выделение области документа на изображении с применением сегментации с помощью сверточной нейронной сети включает следующие этапы: на вход обученной сверточной нейронной сети подают многоканальное изображение документа, на выходе получают бинарную маску размера входного изображения, где 1 - это область документа, 0 - это фон.In another particular embodiment of the proposed method, the selection of a document area in an image using segmentation using a convolutional neural network includes the following steps: a multi-channel document image is fed to the input of the trained convolutional neural network, and a binary mask of the input image size is obtained at the output, where 1 is the area document, 0 is the background.

В другом частном варианте реализации предлагаемого способа, сверточная нейронная сеть обучается с помощью алгоритма стохастического градиентного спуска с минимизацией функции потерь.In another particular implementation of the proposed method, the convolutional neural network is trained using the stochastic gradient descent algorithm with minimization of the loss function.

В другом частном варианте реализации предлагаемого способа, под типом документа понимается документ, содержащий персональные данные.In another particular embodiment of the proposed method, the document type is understood as a document containing personal data.

В другом частном варианте реализации предлагаемого способа, документ, содержащий персональные данные, представляет собой: паспорт, СНИЛС, ИНН, страховой полис, водительское удостоверение, свидетельство о рождении, свидетельство о смерти, свидетельство о заключении брака, свидетельство о расторжении брака, документ об образовании, военный билет, трудовая книжка.In another private embodiment of the proposed method, a document containing personal data is: passport, SNILS, TIN, insurance policy, driver's license, birth certificate, death certificate, marriage certificate, divorce certificate, education document , military ID, work book.

В другом частном варианте реализации предлагаемого способа, бинаризация выполняется путем анализа геометрических характеристик связанных компонент.In another particular embodiment of the proposed method, binarization is performed by analyzing the geometric characteristics of the associated components.

В другом частном варианте реализации предлагаемого способа, бинаризация выполняется на основе информации о цвете с применением цветовой модели HSV.In another particular embodiment of the proposed method, binarization is performed based on color information using the HSV color model.

В другом частном варианте реализации предлагаемого способа, дополнительно, после этапа бинаризации, посредством модуля выравнивания, осуществляют выравнивание по меньшей мере одного изображения документа посредством распознавания линий текстовых строк.In another particular embodiment of the proposed method, additionally, after the binarization step, by means of the alignment module, at least one document image is aligned by recognizing lines of text strings.

В другом частном варианте реализации предлагаемого способа, распознавание линий, для осуществления выравнивания, осуществляют с применением алгоритма вероятностного преобразования Хафа.In another particular embodiment of the proposed method, line recognition for alignment is carried out using the probabilistic Hough transform algorithm.

В другом частном варианте реализации предлагаемого способа, для определения текстовых полей, путем определения координат ограничивающих прямоугольников полей, используют анализ гистограмм проекции профилей.In another particular embodiment of the proposed method, to determine the text fields, by determining the coordinates of the bounding rectangles of the fields, the analysis of profile projection histograms is used.

В другом частном варианте реализации предлагаемого способа, тип текстовых полей определяют на основе группировки по строкам, максимальной и минимальной ширины и высоты текстовых полей в шаблоне.In another particular implementation of the proposed method, the type of text fields is determined based on the grouping by lines, the maximum and minimum width and height of the text fields in the template.

В другом частном варианте реализации предлагаемого способа, распознавание текста на выявленных текстовых полях осуществляется с помощью системы TesseractOCR.In another particular embodiment of the proposed method, text recognition on the identified text fields is carried out using the TesseractOCR system.

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

Реализация изобретения будет описана в дальнейшем в соответствии с прилагаемыми чертежами, которые представлены для пояснения сути изобретения и никоим образом не ограничивают область изобретения. К заявке прилагаются следующие чертежи:The implementation of the invention will be described hereinafter in accordance with the accompanying drawings, which are presented to explain the essence of the invention and in no way limit the scope of the invention. The following drawings are attached to the application:

Фиг.1, иллюстрирует блок-схему работы предлагаемого компьютерно-реализуемого способа автоматического распознавания текста на по меньшей мере одном изображении документа.1 illustrates a block diagram of the operation of the proposed computer-implemented automatic text recognition method on at least one document image.

Фиг. 2, иллюстрирует пример схемы работы вычислительного устройства.Fig. 2 illustrates an example of a computing device operation scheme.

ДЕТАЛЬНОЕ ОПИСАНИЕ ИЗОБРЕТЕНИЯDETAILED DESCRIPTION OF THE INVENTION

В приведенном ниже подробном описании реализации изобретения приведены многочисленные детали реализации, призванные обеспечить отчетливое понимание настоящего изобретения. Однако, квалифицированному в предметной области специалисту, будет очевидно каким образом можно использовать настоящее изобретение, как с данными деталями реализации, так и без них. В других случаях хорошо известные методы, процедуры и компоненты не были описаны подробно, чтобы не затруднять излишне понимание особенностей настоящего изобретения.In the following detailed description of the implementation of the invention, numerous implementation details are provided to provide a clear understanding of the present invention. However, one skilled in the art will appreciate how the present invention can be used, both with and without these implementation details. In other instances, well-known methods, procedures, and components have not been described in detail so as not to unnecessarily obscure the features of the present invention.

Кроме того, из приведенного изложения будет ясно, что изобретение не ограничивается приведенной реализацией. Многочисленные возможные модификации, изменения, вариации и замены, сохраняющие суть и форму настоящего изобретения, будут очевидными для квалифицированных в предметной области специалистов.Furthermore, it will be clear from the foregoing that the invention is not limited to the present implementation. Numerous possible modifications, changes, variations and substitutions that retain the spirit and form of the present invention will be apparent to those skilled in the subject area.

Нижеуказанные термины и определения применяются в данной заявке, если иное явно не указано. Ссылки на методики, используемые при описании данного изобретения, относятся к хорошо известным методам, включая изменения этих методов и замену их эквивалентными методами, известными специалистам в данной области техники.The following terms and definitions apply in this application, unless otherwise expressly stated. References to techniques used in the description of this invention refer to well-known methods, including modifications of these methods and replacing them with equivalent methods known to those skilled in the art.

Под термином «тип документа» понимается вид документа, содержащий персональные данные. Тип документа может быть, но не ограничиваясь: паспорт (паспорт гражданина или заграничный паспорт), СНИЛС, ИНН, страховой полис, водительское удостоверение, свидетельство о рождении, свидетельство о смерти, свидетельство о заключении брака, свидетельство о расторжении брака, документ об образовании, военный билет, трудовая книжка.The term "document type" means the type of document containing personal data. The type of document can be, but not limited to: passport (citizen's passport or foreign passport), SNILS, TIN, insurance policy, driver's license, birth certificate, death certificate, marriage certificate, divorce certificate, education document, military ID, work book.

На Фиг. 1 проиллюстрирована схема работы компьютерно-реализуемого способа автоматического распознавания текста на изображении документа.On FIG. 1 illustrates the scheme of operation of a computer-implemented method for automatic text recognition on a document image.

На вычислительное устройство, посредством средств сетевого взаимодействия, получают изображение документа. Изображение документа может быть получено любым известным способом, например, посредством сканирования, фотографирования, а также может использоваться изображение созданного электронного документа.On the computing device, by means of network interaction, receive an image of the document. The image of the document can be obtained by any known method, for example, by scanning, photographing, and the image of the created electronic document can also be used.

На шаге 102, посредством модуля локализации документа, осуществляют выделение области документа на изображении с применением алгоритма поиска контура наибольшей площади или осуществляют выделение области посредством сегментации с помощью сверточной нейронной сети.At step 102, by means of the document localization module, the selection of the document area in the image is performed using the largest area contour search algorithm or the area selection is performed by segmentation using a convolutional neural network.

Выделение области документа на изображении с применением алгоритма поиска контура наибольшей площади включает следующие этапы.The selection of the document area on the image using the algorithm for finding the contour of the largest area includes the following steps.

1. Осуществляют масштабирование изображения, т.е. выполняют сжатие размера изображения до определенной целевой высоты, которая зависит от типа документа. Операция позволяет ускорить последующую обработку и исключить детали изображения, которые не требуются для локализации документа (например, фон).1. Carry out the scaling of the image, i.e. compressing the image size to a certain target height, which depends on the document type. The operation allows you to speed up subsequent processing and exclude image details that are not required for document localization (for example, the background).

2. Преобразовывают цветное RGB изображения документа в одноканальное изображение оттенков серого цвета.2. Convert the RGB color image of the document into a single-channel grayscale image.

3. Применяют фильтр медианного размытия для сглаживания деталей изображения документа таких как текст. Каждый пиксель изображения заменяется на медианное значение интенсивностей пикселей из окружающей области квадратной формы с размером равным характерной высоте текста документа на изображении.3. Apply a median blur filter to smooth out document image details such as text. Each pixel of the image is replaced by the median value of the pixel intensities from the surrounding area of a square shape with a size equal to the characteristic height of the document text in the image.

4. Выделяют края с помощью алгоритма Кэнни, описанного в статье J. F. Canny, A computational approach to edge detection, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 8, no. 6, pp.679-698, November 1986.4. Edge detection using the Canny algorithm described in J. F. Canny, A computational approach to edge detection, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 8, no. 6, pp. 679-698, November 1986.

5. Осуществляют поиск контуров посредством способа, описанного в статье Satoshi Suzuki and others. Topological structural analysis of digitized binary images by border following. Computer Vision, Graphics, and Image Processing, 30(1):32-46, 1985.5. Search for contours using the method described in the article by Satoshi Suzuki and others. Topological structural analysis of digitized binary images by border following. Computer Vision, Graphics, and Image Processing, 30(1):32-46, 1985.

6. Выбирают контур наибольшей площади, который принимается за границы документа на изображении.6. Select the contour of the largest area, which is taken beyond the boundaries of the document in the image.

7. Выделяют ограничивающий прямоугольник для выбранного контура максимальной площади.7. Select the bounding box for the selected maximum area contour.

8. Выравнивают область документа на изображении с помощью перспективной проекции с матрицей, которая определяется с применением алгоритма RANSAC к четырем точкам - углам выбранного прямоугольника.8. Align the document area on the image using a perspective projection with a matrix, which is determined using the RANSAC algorithm to four points - the corners of the selected rectangle.

В другом варианте реализации для выделения области документа на изображении применяется сегментация изображения с помощью сверточной нейронной сети U-Net, описанной в статье Ronneberger, Olaf; Fischer, Philipp; Brox, Thomas. U-Net: Convolutional Networks for Biomedical Image Segmentation. 2015.In another implementation, image segmentation using a U-Net convolutional neural network, described in Ronneberger, Olaf, is used to highlight a document area in an image; Fischer, Philipp; Brox, Thomas. U-Net: Convolutional Networks for Biomedical Image Segmentation. 2015.

На вход сверточной нейронной сети подают цветное сканированное или сфотографированное изображение, или изображение созданного электронного документа, на выходе получают бинарную маску размера входного изображения с элементами 1 для области документа и 0 для окружающего фона. Нейронная сеть обучается с помощью алгоритма стохастического градиентного спуска с минимизацией функции потерь на наборе размеченных примеров, которые представляют собой пары: вход - исходное изображение, выход - бинарная маска области документа.The input of the convolutional neural network is a color scanned or photographed image, or an image of a created electronic document, the output is a binary mask of the size of the input image with elements 1 for the document area and 0 for the surrounding background. The neural network is trained using the stochastic gradient descent algorithm with minimization of the loss function on a set of labeled examples, which are pairs: input - original image, output - binary mask of the document area.

На шаге 104, посредством модуля классификации типа документа, на основе выделенной области документа, на изображении документа осуществляют классификацию типа документа с применением сверточной нейронной сети ResNet описанной в статье Не et al. Deep Residual Learning for Image Recognition. IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016.At step 104, by means of the document type classification module, based on the selected area of the document, a document type classification is performed on the document image using the ResNet convolutional neural network described in the article by He et al. Deep Residual Learning for Image Recognition. IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2016.

На вход сверточной нейронной сети подают цветное или черно-белое изображение документа, на выходе получают вектор распределения вероятностей по возможным типам документов.A color or black-and-white image of a document is fed to the input of a convolutional neural network, and a probability distribution vector for possible types of documents is obtained at the output.

1. Полученное изображение преобразуют к размеру 224×224 пикселей.1. The resulting image is converted to a size of 224×224 pixels.

2. Осуществляют нормализацию преобразованного изображения.2. Normalize the converted image.

3. К нормализованному изображению применяется последовательность операций сверточной нейронной сети ResNet, а именно операции свертки, пулинг, softmax.3. The sequence of operations of the ResNet convolutional neural network is applied to the normalized image, namely the operations of convolution, pooling, softmax.

4. На выходе нейронной сети получают вектор распределения вероятностей по типам документов, например, [0.8, 0.1, 0.1].4. At the output of the neural network, a vector of probability distribution by types of documents is obtained, for example, [0.8, 0.1, 0.1].

5. В качестве результата принимается тип документа с наибольшей вероятностью. Наиболее вероятный тип документа определяется по индексу наибольшего элемента полученного ранее вектора, выраженного величиной сигнала на выходе нейронной сети. Модель нейронной сети содержит выходы для каждого типа документа, выбирается выход с наибольшим по значению сигналом. Сигналы вычисляются нейронной сетью на основе входного изображения посредством последовательности операций матричного умножения с параметрами, подобранными при обучении модели на наборе примеров, а также операций нелинейного преобразования (обнуление отрицательных значений) и пулинга (выбор максимального элемента из области). Для наглядности, выходные сигналы преобразуются в распределение вероятности (вектор положительных элементов такого же размера в сумме дающих значение 1) с помощью операции softmax.5. The document type with the highest probability is taken as the result. The most probable document type is determined by the index of the largest element of the previously obtained vector, expressed by the value of the signal at the output of the neural network. The neural network model contains outputs for each type of document, the output with the largest signal value is selected. The signals are calculated by the neural network based on the input image through a sequence of matrix multiplication operations with parameters selected when training the model on a set of examples, as well as non-linear transformation operations (zeroing negative values) and pooling (selecting the maximum element from the region). For clarity, the output signals are converted to a probability distribution (a vector of positive elements of the same size that sum to a value of 1) using the softmax operation.

Например, вектор распределения вероятностей представлен как [0.8, 0.1, 0.1]. Необходимо определить к какому типу документа относится данный вектор из трех возможных типов: паспорт, СНИЛС, ИНН, причем вектор относится к типу документа «паспорт», если первый элемент вектора имеет наибольшее значение [0.8, 0.1, 0.1], вектор относится к типу документа «СНИЛС», если второй элемент вектора имеет наибольшее значение [0.1, 0.8, 0.1], вектор относится к типу документа «ИНН», если третий элемент вектора имеет наибольшее значение [0.1, 0.1, 0.8]. Таким образом, нейронная сеть отнесет ранее полученный вектор распределения вероятностей [0.8, 0.1, 0.1] к типу документа «паспорт».For example, the probability distribution vector is represented as [0.8, 0.1, 0.1]. It is necessary to determine which type of document this vector belongs to from three possible types: passport, SNILS, TIN, and the vector refers to the document type "passport", if the first element of the vector has the largest value [0.8, 0.1, 0.1], the vector refers to the document type "SNILS" if the second element of the vector has the largest value [0.1, 0.8, 0.1], the vector belongs to the document type "TIN" if the third element of the vector has the largest value [0.1, 0.1, 0.8]. Thus, the neural network will attribute the previously obtained probability distribution vector [0.8, 0.1, 0.1] to the “passport” document type.

Параметры модели нейронной сети подбираются в процессе обучения по алгоритму стохастического градиентного спуска на наборе размеченных примеров. Примеры для обучения представляют собой пары: вход - изображение документа, выход - тип документа.The parameters of the neural network model are selected during the learning process using the stochastic gradient descent algorithm on a set of labeled examples. Examples for training are pairs: input - document image, output - document type.

На этапе 106 посредством модуля бинаризации, осуществляют бинаризацию изображения определенного типа документа для отделения текста документа от фона. Значение каждого пикселя исходного изображения заменяется на 1, если пиксель относится к тексту поля документа, или 0 в противном случае.At step 106, by means of the binarization module, the image of a certain type of document is binarized to separate the text of the document from the background. The value of each pixel in the original image is replaced by 1 if the pixel belongs to the text field of the document, or 0 otherwise.

В одном варианте реализации бинаризация выполняется на основе информации о цвете, что применимо для типов документов, в которых текст отличается от фона по цветовому признаку. Например, текст имеет черный цвет, а фон белый. В таком случае бинаризация может быть выполнена с использованием цветовой модели HSV, когда принимается что пиксели текста имеют значения в определенных, экспериментально подобранных путем анализа набора примеров, диапазонах каналов Hue и Value.In one implementation, binarization is performed based on color information, which is applicable for types of documents in which text differs from background in color. For example, the text is black and the background is white. In this case, binarization can be performed using the HSV color model, when it is assumed that the text pixels have values in certain, experimentally selected by analyzing a set of examples, ranges of the Hue and Value channels.

В другом варианте реализации бинаризация области изображения документа или отдельных подобластей изображения документа выполняется путем анализа геометрических характеристик связанных компонент по алгоритму:In another embodiment, the binarization of the document image area or individual subareas of the document image is performed by analyzing the geometric characteristics of the associated components according to the algorithm:

1. Цветное изображение документа преобразуют в оттенки серого по формуле:1. The color image of the document is converted to shades of gray according to the formula:

у=0.299⋅R+0.587⋅G+0.114⋅Вy=0.299⋅R+0.587⋅G+0.114⋅B

где R, G, В - интенсивности красного, зеленого и синего каналов соответственно,where R, G, B are the intensities of the red, green and blue channels, respectively,

у - получаемое в результате значение интенсивности пикселя в оттенках серого.y is the resulting grayscale value of the pixel intensity.

2. Выполняют бинаризацию изображения в оттенках серого с выбором порога по алгоритму Отцу, описанному в статье Nobuyuki Otsu. A threshold selection method from gray-level histograms. IEEE Trans. Sys. Man. Cyber. 9 (1): 62-66. doi:10.1109/TSMC. 1979.4310076, 1979. Для пикселей, интенсивность которых выше подобранного порогового значения, задается значение 1, для остальных - 0. В полученной бинарной маске выделены текстовые поля и отдельные, относительно яркие, элементы фона.2. The image is binarized in shades of gray with the choice of a threshold according to the Father algorithm described in the article by Nobuyuki Otsu. A threshold selection method from gray-level histograms. IEEE Trans. Sys. man. Cyber. 9(1): 62-66. doi:10.1109/TSMC. 1979.4310076, 1979. For pixels whose intensity is higher than the selected threshold value, the value is set to 1, for the rest - 0. In the resulting binary mask, text fields and separate, relatively bright, background elements are highlighted.

3. Выполняют склеивание отдельных символов текста с помощью морфологической операции замыкания, представляющей собой результат последовательного применения операций дилатации и эрозии с прямоугольным ядром размера W×1, где W - параметр наибольшего расстояния между символами в поле, который подбирается экспериментально на наборе примеров. В операции дилатации каждый пиксель заменяется на максимальное значение из окружающей области ядра, в операции эрозии - на минимальное значение.3. Gluing individual text characters is performed using a morphological closing operation, which is the result of sequential application of dilation and erosion operations with a rectangular kernel of size W × 1, where W is the parameter of the largest distance between characters in the field, which is selected experimentally on a set of examples. In the dilation operation, each pixel is replaced by the maximum value from the surrounding area of the nucleus, in the erosion operation - by the minimum value.

4. Выделяют связанные компоненты - группы пикселей со значением 1, которые имеют среди окружающих 8-ми пикселей хотя бы один пиксель со значением 1. Для выделения связанных компонент применяется алгоритм, описанный в статье Kesheng Wu, Ekow Otoo, and Kenji Suzuki. Optimizing two-pass connected-component labeling algorithms. Pattern Analysis and Applications, 12(2): 117-135, Jun 2009. В результате получается маска изображения, где каждый пиксель имеет значение равное индексу компоненты, к которой он принадлежит.4. Related components are selected - groups of pixels with a value of 1, which have at least one pixel with a value of 1 among the surrounding 8 pixels. The algorithm described in the article by Kesheng Wu, Ekow Otoo, and Kenji Suzuki is used to select related components. Optimizing two-pass connected-component labeling algorithms. Pattern Analysis and Applications, 12(2): 117-135, Jun 2009. The result is an image mask where each pixel has a value equal to the index of the component it belongs to.

5. Выбирают связанные компоненты с признаками, характерными для текстовых полей определенного типа документа. Например, в качестве критерия используется характерная высота текстового поля в документе. Например, при распознавании паспорта в качестве критерия отбора компонент, соответствующих распознаваемым текстовым полям, используется высота, поскольку текст полей имеет больший размер по сравнению с прочим текстом документа в рассматриваемых визуальных зонах. Пиксели компонент с высотой менее порогового значения относятся к фону (задается значение 0). Тем самым производится отделение текстовых полей от фона документа. Также могут быть использованы следующие геометрические характеристики: ширина, площадь, координаты центра, моменты инерции.5. Select related components with features specific to text fields of a certain type of document. For example, the characteristic height of a text field in a document is used as a criterion. For example, when recognizing a passport, height is used as a selection criterion for components corresponding to recognizable text fields, since the text of the fields is larger than the rest of the document text in the considered visual zones. Pixels of components with a height less than the threshold value belong to the background (set to 0). This separates the text fields from the background of the document. The following geometric characteristics can also be used: width, area, center coordinates, moments of inertia.

Дополнительно, на шаге 108, посредством модуля выравнивания, могут осуществлять выравнивание изображения документа посредством распознавания линий текстовых строк, если данное выравнивание не было осуществлено на этапе 102, по способу перспективной проекции.Additionally, at step 108, by means of the alignment module, the alignment of the document image can be performed by recognizing the lines of text lines, if this alignment was not performed at step 102, according to the perspective projection method.

В одном варианте реализации выравнивание производится по способу распознавания линий текстовых строк с применением алгоритма вероятностного преобразования Хафа, описанного в статье Jiri Matas, Charles Galambos, and Josef Kittler. Robust detection of lines using the progressive probabilistic hough transform. Computer Vision and Image Understanding, 78(1):119-137, 2000. Алгоритм выравнивания включает следующие шаги:In one implementation, the alignment is performed according to the method of recognizing the lines of text strings using the probabilistic Hough transform algorithm described in the article by Jiri Matas, Charles Galambos, and Josef Kittler. Robust detection of lines using the progressive probabilistic hough transform. Computer Vision and Image Understanding, 78(1):119-137, 2000. The alignment algorithm includes the following steps:

1. Цветное изображение преобразуют в оттенки серого.1. A color image is converted to grayscale.

2. Выполняют бинаризацию с выбором порога по алгоритму Отцу.2. Binarization is performed with the choice of the threshold according to the Father's algorithm.

3. Применяют морфологическую операцию замыкания для склеивания символов текстовых полей.3. Apply the morphological closure operation to glue the characters of the text fields.

4. Выделяют края с помощью алгоритма Кэнни.4. Select the edges using the Canny algorithm.

5. Выполняют распознавание линий с помощью вероятностного преобразования Хафа.5. Perform line recognition using a probabilistic Hough transform.

6. Осуществляют кластеризацию линий по углу наклона к горизонтальной оси.6. The lines are clustered according to the angle of inclination to the horizontal axis.

7. Угол с наибольшим числом представляющих его линий считается углом поворота документа.7. The corner with the most lines representing it is considered the document's rotation angle.

8. Выравнивание документа осуществляется путем поворота на найденный угол.8. Alignment of the document is carried out by turning to the found angle.

На шаге 110 посредством модуля сегментации, осуществляют сегментацию изображения документа, с определенным типом документа на этапе классификации, для определения текстовых полей, путем определения координат ограничивающих прямоугольников полей. Сегментацию осуществляют с применением способа анализа гистограмм проекции профилей, который включает следующие шаги.In step 110, the segmentation module performs the segmentation of the document image, with a certain type of document in the classification step, to determine the text fields, by determining the coordinates of the bounding boxes of the fields. The segmentation is carried out using a profile projection histogram analysis method, which includes the following steps.

1. К бинарной маске текста полей применяют морфологическую операцию замыкания.1. A morphological closure operation is applied to the binary mask of the field text.

2. Строят гистограммы вертикальной проекции профилей: для каждой отметки по вертикальной оси подсчитывается количество пикселей со значением 1.2. Build histograms of the vertical projection of the profiles: for each mark on the vertical axis, the number of pixels with a value of 1 is counted.

3. Посредством анализа выбросов на гистограмме вертикальной проекции профилей определяют вертикальные координаты границ строк текста на изображении документа. Значения на гистограмме сравниваются с экспериментально подобранным на наборе примеров порогом. Интервалы на гистограмме со значениями, превышающими порог считаются соответствующими строкам текста.3. By analyzing the outliers on the histogram of the vertical projection of the profiles, the vertical coordinates of the boundaries of the lines of text on the image of the document are determined. The values on the histogram are compared with the threshold experimentally selected on a set of examples. Intervals on the histogram with values exceeding the threshold are considered to correspond to lines of text.

4. Для каждой выделенной на шаге 3 строки производят определение горизонтальных координат границ отдельных полей с помощью гистограммы горизонтальной проекции профилей (для каждой отметки по горизонтальной оси посчитывается количество пикселей со значением 1). Значения на гистограмме сравниваются с экспериментально подобранным порогом, значения, превышающие порог, считаются относящимися к полям документа.4. For each line selected at step 3, the horizontal coordinates of the boundaries of individual fields are determined using the histogram of the horizontal projection of the profiles (for each mark along the horizontal axis, the number of pixels with a value of 1 is calculated). Values on the histogram are compared with an experimentally selected threshold, values exceeding the threshold are considered to be related to the fields of the document.

5. Выполняют расширение найденных ограничивающих прямоугольников полей с некоторым экспериментально подобранным на наборе примеров масштабным коэффициентом.5. Expansion of the found bounding rectangles of the fields is performed with some scale factor experimentally selected on a set of examples.

На шаге 112 посредством модуля сопоставления, определяют тип найденных, на предыдущем этапе, текстовых полей с помощью структурных шаблонов документов.At step 112, by means of the mapping module, the type of text fields found in the previous step is determined using structural document templates.

Структурный шаблон документа представляет собой упорядоченный, по вертикальным координатам, список строк, где каждая строка состоит из упорядоченных, по горизонтальной координате, полей.The structural template of the document is a list of lines ordered by vertical coordinates, where each line consists of fields ordered by horizontal coordinates.

Например, паспорт, согласно структурному шаблону документа, содержит поля фамилии, имени, отчества в разных строках, пола и даты рождения в одной строке, 1-3 строки места рождения. Для полученной, посредством анализа гистограмм проекции профилей, структуры полей в виде разделения по строкам можно подобрать соответствие с типами полей в шаблоне.For example, a passport, according to the structural template of the document, contains the fields of the last name, first name, patronymic in different lines, gender and date of birth in one line, 1-3 lines of the place of birth. For the field structure obtained by analyzing the profile projection histograms in the form of division by rows, you can match the field types in the template.

Каждое поле в шаблоне характеризуется типом, максимальной и минимальной шириной и высотой. По способу автоматического перебора назначаются типы полей наилучшим образом соответствующие шаблону документа. Например, при распознавании зоны основной информации паспорта в результате сегментации получили 6 строк. В соответствии с шаблоном, строка 1 содержит тип поля «Фамилия», строка 2 - «Имя», строка 3 - «Отчество», строка 4 - поля «Пол» и «Дата рождения», строки 5, 6 - «Место рождения». Проверяется количество полей, сегментированных в строках, а также размеры полей на удовлетворение ограничений, заданных в шаблоне. В случае обнаружения несоответствий правилам шаблона, конкретная строка и относящиеся к ней поля считаются не распознанными. В описанном случае выполняется простой перебор строк шаблона.Each field in the template is characterized by a type, maximum and minimum width and height. According to the method of automatic enumeration, field types are assigned in the best way corresponding to the document template. For example, when recognizing the basic information zone of a passport, 6 lines were obtained as a result of segmentation. In accordance with the template, line 1 contains the field type "Last name", line 2 - "First name", line 3 - "Patronymic", line 4 - the fields "Gender" and "Date of birth", lines 5, 6 - "Place of birth" . The number of fields segmented in rows is checked, as well as the size of the fields to satisfy the constraints specified in the template. If any inconsistencies with the template rules are found, the particular string and related fields are considered not recognized. In the described case, a simple enumeration of the template strings is performed.

На шаге 114 посредством модуля распознавания текста, осуществляют распознавание текста на выявленных текстовых полях с применением системы TesseractOCR, описанной в статье R. Smith An Overview of the Tesseract OCR Engine. Ninth International Conference on Document Analysis and Recognition (ICDAR 2007). 2007.In step 114, the text recognition module performs text recognition on the identified text fields using the TesseractOCR system described in R. Smith An Overview of the Tesseract OCR Engine. Ninth International Conference on Document Analysis and Recognition (ICDAR 2007). 2007.

На шаге 116 посредством модуля валидации, осуществляют валидацию распознанного текста на выявленных текстовых полях по набору правил относительно данных, содержащихся в полях, и ожидаемых форматов представления этих данных.At step 116, the recognized text in the identified text fields is validated by the validator module against a set of rules regarding the data contained in the fields and the expected formats for presenting this data.

Например, для поля «номер документа» проверяется, что все распознанные символы являются цифрами и количество символов равно количеству позиций номера в документе.For example, for the "document number" field, it is checked that all recognized characters are digits and the number of characters is equal to the number of positions of the number in the document.

На Фиг. 2 далее будет представлена общая схема вычислительного устройства (200), обеспечивающего обработку данных, необходимую для реализации заявленного решения.On FIG. 2, the general scheme of the computing device (200) will be presented below, providing the data processing necessary for the implementation of the claimed solution.

В общем случае устройство (200) содержит такие компоненты, как: один или более процессоров (201), по меньшей мере одну память (202), средство хранения данных (203), интерфейсы ввода/вывода (204), средство В/В (205), средства сетевого взаимодействия (206).In general, the device (200) contains such components as: one or more processors (201), at least one memory (202), a data storage medium (203), input/output interfaces (204), an I/O means ( 205), networking tools (206).

Процессор (201) устройства выполняет основные вычислительные операции, необходимые для функционирования устройства (200) или функциональности одного или более его компонентов. Процессор (201) исполняет необходимые машиночитаемые команды, содержащиеся в оперативной памяти (202).The processor (201) of the device performs the basic computing operations necessary for the operation of the device (200) or the functionality of one or more of its components. The processor (201) executes the necessary machine-readable instructions contained in the main memory (202).

Память (202), как правило, выполнена в виде ОЗУ и содержит необходимую программную логику, обеспечивающую требуемый функционал.The memory (202) is typically in the form of RAM and contains the necessary software logic to provide the desired functionality.

Средство хранения данных (203) может выполняться в виде HDD, SSD дисков, рейд массива, сетевого хранилища, флэш-памяти, оптических накопителей информации (CD, DVD, MD, Blue-Ray дисков) и т.п. Средство (203) позволяет выполнять долгосрочное хранение различного вида информации, например, вышеупомянутых файлов с наборами данных пользователей, базы данных, содержащих записи измеренных для каждого пользователя временных интервалов, идентификаторов пользователей и т.п.The data storage means (203) can be in the form of HDD, SSD disks, raid array, network storage, flash memory, optical information storage devices (CD, DVD, MD, Blue-Ray disks), etc. The means (203) allows long-term storage of various types of information, for example, the above-mentioned files with user data sets, a database containing records of time intervals measured for each user, user identifiers, etc.

Интерфейсы (204) представляют собой стандартные средства для подключения и работы с серверной частью, например, USB, RS232, RJ45, LPT, COM, HDMI, PS/2, Lightning, FireWire и т.п.Interfaces (204) are standard means for connecting and working with the server part, for example, USB, RS232, RJ45, LPT, COM, HDMI, PS/2, Lightning, FireWire, etc.

Выбор интерфейсов (204) зависит от конкретного исполнения устройства (200), которое может представлять собой персональный компьютер, мейнфрейм, серверный кластер, тонкий клиент, смартфон, ноутбук и т.п.The choice of interfaces (204) depends on the specific implementation of the device (200), which can be a personal computer, mainframe, server cluster, thin client, smartphone, laptop, and the like.

В качестве средств В/В данных (205) в любом воплощении системы, реализующей описываемый способ, может использоваться клавиатура. Аппаратное исполнение клавиатуры может быть любым известным: это может быть, как встроенная клавиатура, используемая на ноутбуке или нетбуке, так и обособленное устройство, подключенное к настольному компьютеру, серверу или иному компьютерному устройству. Подключение при этом может быть, как проводным, при котором соединительный кабель клавиатуры подключен к порту PS/2 или USB, расположенному на системном блоке настольного компьютера, так и беспроводным, при котором клавиатура осуществляет обмен данными по каналу беспроводной связи, например, радиоканалу, с базовой станцией, которая, в свою очередь, непосредственно подключена к системному блоку, например, к одному из USB-портов. Помимо клавиатуры, в составе средств В/В данных также может использоваться: джойстик, дисплей (сенсорный дисплей), проектор, тачпад, манипулятор мышь, трекбол, световое перо, динамики, микрофон и т.п.As means of I/O data (205) in any embodiment of the system that implements the described method, a keyboard can be used. The keyboard hardware can be any known: it can be either a built-in keyboard used on a laptop or netbook, or a separate device connected to a desktop computer, server, or other computer device. In this case, the connection can be either wired, in which the keyboard connection cable is connected to the PS / 2 or USB port located on the system unit of the desktop computer, or wireless, in which the keyboard exchanges data via a wireless communication channel, for example, a radio channel, with base station, which, in turn, is directly connected to the system unit, for example, to one of the USB ports. In addition to the keyboard, the following I/O devices can also be used: joystick, display (touchscreen), projector, touchpad, mouse, trackball, light pen, speakers, microphone, etc.

Средства сетевого взаимодействия (206) выбираются из устройства, обеспечивающий сетевой прием и передачу данных, например, Ethernet карту, WLAN/Wi-Fi модуль, Bluetooth модуль, BLE модуль, NFC модуль, IrDa, RFID модуль, GSM модем и т.п. С помощью средств (205) обеспечивается организация обмена данными по проводному или беспроводному каналу передачи данных, например, WAN, PAN, ЛВС (LAN), Интранет, Интернет, WLAN, WMAN или GSM.Means of network interaction (206) are selected from a device that provides network data reception and transmission, for example, an Ethernet card, WLAN/Wi-Fi module, Bluetooth module, BLE module, NFC module, IrDa, RFID module, GSM modem, etc. With the help of means (205) the organization of data exchange over a wired or wireless data transmission channel, for example, WAN, PAN, LAN (LAN), Intranet, Internet, WLAN, WMAN or GSM, is provided.

Компоненты устройства (200) сопряжены посредством общей шины передачи данных (210).The components of the device (200) are connected via a common data bus (210).

В настоящих материалах заявки было представлено предпочтительное раскрытие осуществление заявленного технического решения, которое не должно использоваться как ограничивающее иные, частные воплощения его реализации, которые не выходят за рамки испрашиваемого объема правовой охраны и являются очевидными для специалистов в соответствующей области техники.In these application materials, a preferred disclosure of the implementation of the claimed technical solution was presented, which should not be used as limiting other, private embodiments of its implementation, which do not go beyond the scope of the requested legal protection and are obvious to specialists in the relevant field of technology.

Claims (24)

1. Компьютерно-реализуемый способ автоматического распознавания текста на изображении документа, способ выполняется на вычислительном устройстве, содержащем процессор и память, хранящую инструкции, исполняемые процессором и содержащие этапы, на которых:1. A computer-implemented method for automatic text recognition on a document image, the method is performed on a computing device containing a processor and a memory that stores instructions executed by the processor and contains the steps of: на вычислительное устройство получают изображение документа;an image of the document is received on the computing device; посредством модуля локализации документа, осуществляют выделение области документа на изображении;by means of the document localization module, the selection of the document area on the image is carried out; посредством модуля классификации типа документа, на основе выделенной области документа на изображении осуществляют классификацию типа документа с применением сверточной нейронной сети;by means of a document type classification module, based on the selected area of the document in the image, the document type is classified using a convolutional neural network; посредством модуля бинаризации, осуществляют бинаризацию изображения определенного типа документа для отделения текста документа от фона;by means of the binarization module, perform binarization of the image of a certain type of document to separate the text of the document from the background; посредством модуля сегментации, осуществляют сегментацию изображения документа, с определенным типом документа на этапе классификации, для определения текстовых полей, путем определения координат ограничивающих прямоугольников полей;through the segmentation module, segmenting the image of the document, with a certain type of document at the stage of classification, to determine the text fields, by determining the coordinates of the bounding boxes of the fields; посредством модуля сопоставления, определяют тип найденных, на предыдущем этапе, текстовых полей с помощью структурных шаблонов документов;by means of the mapping module, determine the type of text fields found, at the previous stage, using structural document templates; посредством модуля распознавания текста, осуществляют распознавание текста на выявленных текстовых полях;by means of a text recognition module, perform text recognition on the identified text fields; посредством модуля валидации, осуществляют валидацию распознанного текста на выявленных текстовых полях по набору правил относительно данных, содержащихся в полях, и ожидаемых форматов представления этих данных.by means of the validation module, the recognized text is validated on the identified text fields according to a set of rules regarding the data contained in the fields and the expected formats for presenting this data. 2. Способ по п. 1, отличающийся тем, что изображение получено посредством сканирования.2. The method according to p. 1, characterized in that the image is obtained by scanning. 3. Способ по п. 1, отличающийся тем, что изображение получено посредством фотографирования.3. The method according to p. 1, characterized in that the image is obtained by photographing. 4. Способ по п. 1, отличающийся тем, что выделение области документа на изображении осуществляют с применением алгоритма поиска контура наибольшей площади или осуществляют выделение области посредством сегментации с помощью сверточной нейронной сети.4. The method according to claim 1, characterized in that the selection of the document area in the image is carried out using the algorithm for finding the contour of the largest area or the area is selected by segmentation using a convolutional neural network. 5. Способ по п. 4, отличающийся тем, что выделение области документа на изображении с применением алгоритма поиска контура наибольшей площади включает следующие этапы: сжатие размера полученного изображения документа до целевой высоты, зависящей от типа документа, преобразование многоканального изображения в одноканальное изображение, применение к преобразованному одноканальному изображению фильтра медианного размытия, выделение краев изображения, поиск контуров на изображении, выбор контура с наибольшей площадью, выделение ограничивающего прямоугольника для выбранного контура с наибольшей площадью и выравнивание области документа с помощью перспективной проекции с матрицей.5. The method according to claim 4, characterized in that the selection of a document area in the image using the largest area contour search algorithm includes the following steps: compressing the size of the resulting document image to a target height depending on the type of document, converting a multi-channel image into a single-channel image, applying to the transformed single-channel image of the median blur filter, select the edges of the image, search for contours in the image, select the contour with the largest area, select the bounding box for the selected contour with the largest area, and flatten the document area using perspective projection with matrix. 6. Способ по п. 4, отличающийся тем, что выделение области документа на изображении с применением сегментации с помощью сверточной нейронной сети включает следующие этапы: на вход обученной сверточной нейронной сети подают многоканальное изображение документа, на выходе получают бинарную маску размера входного изображения, где 1 - это область документа, 0 - это фон.6. The method according to claim 4, characterized in that the selection of the document area in the image using segmentation using a convolutional neural network includes the following steps: a multi-channel image of the document is fed to the input of the trained convolutional neural network, the output is a binary mask of the size of the input image, where 1 is the document area, 0 is the background. 7. Способ по п. 6, отличающийся тем, что сверточная нейронная сеть обучается с помощью алгоритма стохастического градиентного спуска с минимизацией функции потерь.7. The method according to claim 6, characterized in that the convolutional neural network is trained using the stochastic gradient descent algorithm with minimization of the loss function. 8. Способ по п. 1, отличающийся тем, что под типом документа понимается документ, содержащий персональные данные.8. The method according to p. 1, characterized in that the document type is understood as a document containing personal data. 9. Способ по п. 8, отличающийся тем, что документ, содержащий персональные данные, представляет собой: паспорт, СНИЛС, ИНН, страховой полис, водительское удостоверение, свидетельство о рождении, свидетельство о смерти, свидетельство о заключении брака, свидетельство о расторжении брака, документ об образовании, военный билет, трудовая книжка.9. The method according to claim 8, characterized in that the document containing personal data is: passport, SNILS, TIN, insurance policy, driver's license, birth certificate, death certificate, marriage certificate, divorce certificate , document on education, military ID, work book. 10. Способ по п. 1, отличающийся тем, что бинаризация выполняется путем анализа геометрических характеристик связанных компонент.10. The method according to p. 1, characterized in that the binarization is performed by analyzing the geometric characteristics of the associated components. 11. Способ по п. 1, отличающийся тем, что бинаризация выполняется на основе информации о цвете с применением цветовой модели HSV.11. The method of claim. 1, characterized in that the binarization is performed based on color information using the HSV color model. 12. Способ по п. 1, отличающийся тем, что дополнительно, после этапа бинаризации, посредством модуля выравнивания, осуществляют выравнивание изображения документа посредством распознавания линий текстовых строк.12. The method according to claim 1, characterized in that additionally, after the binarization step, by means of the alignment module, the document image is aligned by recognizing lines of text strings. 13. Способ по п. 12, отличающийся тем, что распознавание линий, для осуществления выравнивания, осуществляют с применением алгоритма вероятностного преобразования Хафа.13. The method according to claim 12, characterized in that the line recognition for alignment is carried out using a probabilistic Hough transform algorithm. 14. Способ по п. 1, отличающийся тем, что для определения текстовых полей, путем определения координат ограничивающих прямоугольников полей, используют анализ гистограмм проекции профилей.14. The method according to claim 1, characterized in that to determine the text fields, by determining the coordinates of the bounding rectangles of the fields, the analysis of histograms of the profile projection is used. 15. Способ по п. 1, отличающийся тем, что тип текстовых полей определяют на основе группировки по строкам, максимальной и минимальной ширины и высоты текстовых полей в шаблоне.15. The method according to claim 1, characterized in that the type of text fields is determined based on the grouping by lines, the maximum and minimum width and height of the text fields in the template. 16. Способ по п. 1, отличающийся тем, что распознавание текста на выявленных текстовых полях осуществляется с помощью системы TesseractOCR.16. The method according to claim 1, characterized in that text recognition on the identified text fields is carried out using the TesseractOCR system.
RU2021121146A 2021-07-16 2021-07-16 Method for recognition of text in images of documents RU2768544C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2021121146A RU2768544C1 (en) 2021-07-16 2021-07-16 Method for recognition of text in images of documents

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2021121146A RU2768544C1 (en) 2021-07-16 2021-07-16 Method for recognition of text in images of documents

Publications (1)

Publication Number Publication Date
RU2768544C1 true RU2768544C1 (en) 2022-03-24

Family

ID=80819458

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2021121146A RU2768544C1 (en) 2021-07-16 2021-07-16 Method for recognition of text in images of documents

Country Status (1)

Country Link
RU (1) RU2768544C1 (en)

Cited By (4)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN114743030A (en) * 2022-04-20 2022-07-12 杭州网易智企科技有限公司 Image recognition method, image recognition device, storage medium and computer equipment
CN116416621A (en) * 2023-03-15 2023-07-11 上海合合信息科技股份有限公司 A method and device for extracting text from a reflective image
CN117542067A (en) * 2023-12-18 2024-02-09 北京长河数智科技有限责任公司 Region labeling form recognition method based on visual recognition
RU2828182C1 (en) * 2024-02-16 2024-10-07 Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС" Device for recognizing conditionally rigid business documents with automatic binding of their fields

Citations (9)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU51245U1 (en) * 2005-08-22 2006-01-27 Федеральное государственное унитарное предприятие "Научно-исследовательский институт "Восход" TERRITORIAL INFORMATION SYSTEM
US20140201180A1 (en) * 2012-09-14 2014-07-17 Broadbandtv, Corp. Intelligent Supplemental Search Engine Optimization
US20140268247A1 (en) * 2012-08-15 2014-09-18 Fuji Xerox Co., Ltd. Systems and Methods for Efficiently Capturing High-Quality Scans of Multi-Page Documents with Hand-Held Devices
RU2691214C1 (en) * 2017-12-13 2019-06-11 Общество с ограниченной ответственностью "Аби Продакшн" Text recognition using artificial intelligence
US20190205690A1 (en) * 2018-01-04 2019-07-04 Wipro Limited System and method for performing optical character recognition
US10387531B1 (en) * 2015-08-18 2019-08-20 Google Llc Processing structured documents using convolutional neural networks
RU2698997C1 (en) * 2016-09-06 2019-09-02 Электа, Инк. Neural network for generating synthetic medical images
RU2701088C1 (en) * 2018-10-03 2019-09-24 Публичное Акционерное Общество "Сбербанк России" (Пао Сбербанк) Method and system for trusted paperless presentation of documents
RU2744769C1 (en) * 2020-07-04 2021-03-15 Общество с ограниченной ответственностью "СЭНДБОКС" Method for image processing using adaptive technologies based on neural networks and computer vision

Patent Citations (9)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU51245U1 (en) * 2005-08-22 2006-01-27 Федеральное государственное унитарное предприятие "Научно-исследовательский институт "Восход" TERRITORIAL INFORMATION SYSTEM
US20140268247A1 (en) * 2012-08-15 2014-09-18 Fuji Xerox Co., Ltd. Systems and Methods for Efficiently Capturing High-Quality Scans of Multi-Page Documents with Hand-Held Devices
US20140201180A1 (en) * 2012-09-14 2014-07-17 Broadbandtv, Corp. Intelligent Supplemental Search Engine Optimization
US10387531B1 (en) * 2015-08-18 2019-08-20 Google Llc Processing structured documents using convolutional neural networks
RU2698997C1 (en) * 2016-09-06 2019-09-02 Электа, Инк. Neural network for generating synthetic medical images
RU2691214C1 (en) * 2017-12-13 2019-06-11 Общество с ограниченной ответственностью "Аби Продакшн" Text recognition using artificial intelligence
US20190205690A1 (en) * 2018-01-04 2019-07-04 Wipro Limited System and method for performing optical character recognition
RU2701088C1 (en) * 2018-10-03 2019-09-24 Публичное Акционерное Общество "Сбербанк России" (Пао Сбербанк) Method and system for trusted paperless presentation of documents
RU2744769C1 (en) * 2020-07-04 2021-03-15 Общество с ограниченной ответственностью "СЭНДБОКС" Method for image processing using adaptive technologies based on neural networks and computer vision

Cited By (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
CN114743030A (en) * 2022-04-20 2022-07-12 杭州网易智企科技有限公司 Image recognition method, image recognition device, storage medium and computer equipment
CN116416621A (en) * 2023-03-15 2023-07-11 上海合合信息科技股份有限公司 A method and device for extracting text from a reflective image
CN117542067A (en) * 2023-12-18 2024-02-09 北京长河数智科技有限责任公司 Region labeling form recognition method based on visual recognition
RU2828182C1 (en) * 2024-02-16 2024-10-07 Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС" Device for recognizing conditionally rigid business documents with automatic binding of their fields
RU2837835C1 (en) * 2024-06-27 2025-04-07 Общество с ограниченной ответственностью "СМАРТ ЭНДЖИНС СЕРВИС" Method of identifying and detecting identity documents

Similar Documents

Publication Publication Date Title
AU2017302248B2 (en) Label and field identification without optical character recognition (OCR)
CN104463195B (en) Printing digit recognizing method based on template matches
Poco et al. Extracting and retargeting color mappings from bitmap images of visualizations
AU2014321165B2 (en) Image searching method and apparatus
RU2768544C1 (en) Method for recognition of text in images of documents
CN104408449B (en) Intelligent mobile terminal scene literal processing method
EP2579211A2 (en) Graph-based segmentation integrating visible and NIR information
Fabrizio et al. Text detection in street level images
US9224207B2 (en) Segmentation co-clustering
Mehri et al. Texture feature evaluation for segmentation of historical document images
CN109376717A (en) Personal identification method, device, electronic equipment and the storage medium of face comparison
Yindumathi et al. Analysis of image classification for text extraction from bills and invoices
CN108280469A (en) A kind of supermarket's commodity image recognition methods based on rarefaction representation
CN108830275A (en) Dot character, the recognition methods of dot matrix digit and device
US20240331346A1 (en) Division of images into separate color layers
Goyal et al. On solving leaf classification using linear regression
CN118761591A (en) Project matching method and system based on automatic data recognition
US12211083B2 (en) System and method for validating product photography
Böschen et al. Survey and empirical comparison of different approaches for text extraction from scholarly figures
CN109460768B (en) Text detection and removal method for histopathology microscopic image
Ghandour et al. Building shadow detection based on multi-thresholding segmentation
Di Ruberto et al. On different colour spaces for medical colour image classification
Akoushideh et al. Text localization in digital images using a hybrid method
Jha et al. Character Segmentation on Indian Vehicle License Plate using K-means, OTSU and Niblack algorithm
CN119672744B (en) A document classification method and system based on template matching