[go: up one dir, main page]

RU2363047C1 - Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images - Google Patents

Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images Download PDF

Info

Publication number
RU2363047C1
RU2363047C1 RU2007140039/09A RU2007140039A RU2363047C1 RU 2363047 C1 RU2363047 C1 RU 2363047C1 RU 2007140039/09 A RU2007140039/09 A RU 2007140039/09A RU 2007140039 A RU2007140039 A RU 2007140039A RU 2363047 C1 RU2363047 C1 RU 2363047C1
Authority
RU
Russia
Prior art keywords
color
text
image
words
lines
Prior art date
Application number
RU2007140039/09A
Other languages
Russian (ru)
Other versions
RU2007140039A (en
Inventor
Евгений Петрович Смирнов (RU)
Евгений Петрович Смирнов
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 RU2007140039/09A priority Critical patent/RU2363047C1/en
Publication of RU2007140039A publication Critical patent/RU2007140039A/en
Application granted granted Critical
Publication of RU2363047C1 publication Critical patent/RU2363047C1/en

Links

Images

Landscapes

  • Image Analysis (AREA)

Abstract

FIELD: information technology.
SUBSTANCE: invention relates to detection of text in a bitmap image and a method of detecting spam, containing a bitmap image. The method of detecting text involves (a) identification of background colour in a two-colour bitmap image; (b) finding closed contours around each separate image of combined colour pixels, distinct from the said background colour; (c) exception from examination of contours which are too small or too big; (d) finding the presumed alpha characters on all closed contours, interpreted as contours of alpha characters; (e) division of lines of alpha characters found into sets, interpreted as probable words; (f) exception from examination of words in the lines which are too small or too big; (g) counting the number of pixels of non-background colour inside contours remaining after filtration; (h) determining on content of text in the image based on the ratio of the number of pixels of non-background colour inside contours remaining after filtration to the total number of pixels of non-background colour and under the condition that, at least one line remains.
EFFECT: simple and reliable method of detecting text and spam in bitmap images.
17 cl, 57 dwg

Description

Область изобретенияField of Invention

Настоящее изобретение относится к способам обнаружения текста в растровом изображении и к связанным с ними способам выявления спама, содержащего растровое изображение.The present invention relates to methods for detecting text in a bitmap image and to related methods for detecting spam containing a bitmap image.

Уровень техникиState of the art

В настоящее время весьма остро стоят вопросы выявления спама в принимаемых по сети связи электронных сообщениях. Причем если для распознавания спама в виде обычных текстовых сообщений имеется много различных технических решений, то в случае текстового спама, внедренного в изображение, задача сильно усложняется, поскольку сначала надо обнаружить наличие текста в изображении, а потом уже определить, относится ли этот текст к спаму.Currently, there are very acute issues of detecting spam in electronic communications received over the communication network. Moreover, if there are many different technical solutions for recognizing spam in the form of ordinary text messages, then in the case of text spam embedded in the image, the task is much more complicated, since you first need to detect the presence of text in the image, and then determine whether this text refers to spam .

Известен способ многоэтапного анализа информации растрового изображения (патент РФ №2234734, опубл. 20.08.2004), в котором анализ осуществляют в два этапа: сначала - этап предварительного распознавания с применением менее точных методов распознавания, а затем - этап точного распознавания тех объектов, которые остались нераспознанными после первого этапа. На первом этапе сегментируют изображение на области, таблицы, фрагменты текста, строки, слова, символы, а на втором этапе уточняют эту сегментацию с учетом дополнительной информации, полученной на первом этапе.A known method of multi-stage analysis of information of a raster image (RF patent No. 2234734, publ. 08.20.2004), in which the analysis is carried out in two stages: first, the preliminary recognition stage using less accurate recognition methods, and then the stage of accurate recognition of those objects remained unrecognized after the first stage. At the first stage, the image is segmented into areas, tables, text fragments, lines, words, symbols, and at the second stage, this segmentation is specified taking into account additional information obtained at the first stage.

Сходный принцип реализован и в способе анализа растрового изображения (патент РФ №2251151, опубл. 27.04.2005), когда все возможные в изображении объекты разделяют на уровни, отличающиеся степенью сложности (символ, слово, строка, абзац, таблица, область). Затем устанавливают принадлежность каждого объекта тому или иному уровню и устанавливают связи между объектами разных уровней и одного уровня сложности. Дальше выдвигают гипотезу о наличии свойств того или иного объекта и проверяют эту гипотезу, корректируя свойства объектов, связанных с анализируемым.A similar principle is implemented in the method of analyzing a raster image (RF patent No. 2251151, publ. 04/27/2005), when all possible objects in the image are divided into levels that differ in degree of difficulty (character, word, line, paragraph, table, region). Then establish the belonging of each object to a particular level and establish connections between objects of different levels and one level of complexity. Then they put forward a hypothesis about the presence of the properties of an object and test this hypothesis by adjusting the properties of objects associated with the analyzed one.

В обоих этих способах фактически осуществляют распознавание элементов текста, имеющегося в изображении, что усложняет и удлиняет обработку поступающих по сети связи изображений.In both of these methods, the recognition of elements of the text contained in the image is actually carried out, which complicates and lengthens the processing of images received through the communication network.

В заявке США №2004/0221062 (опубл. 04.11.2004) описан способ, в котором для идентификации контентных признаков осуществляется предварительная визуализация принятого сообщения в первом формате, после чего это сообщение преобразуется в чисто символьное сообщение во втором формате, чтобы до фильтрации текста исключить, скажем, декоративные компоненты. Здесь также осуществляется распознавание текста.In the application US No. 2004/0221062 (published 04.11.2004) a method is described in which, for identification of content attributes, the received message is preliminarily visualized in the first format, after which this message is converted into a purely character message in the second format, to exclude before filtering the text , say, decorative components. It also provides text recognition.

Распознавание текста осуществляется и в патенте США №7171046 (опубл. 30.01.2007).Recognition of the text is carried out in US patent No. 7171046 (publ. 30.01.2007).

В заявке США №2005/0281455 (опубл. 22.12.2005) раскрыт способ различения текста и картинки в изображении с помощью нейронной сети. В этом способе изображение разделяется на данные изображения в уровнях серого для блоков изображения. Обученная нейронная сеть обрабатывает непрерывные пикселы, генерируя доверенное значение текста для каждого из пикселов и получая наибольшее доверенное значение текста, которое сравнивается с порогом для определения статуса блока изображения. К недостаткам можно отнести проблемы переобучения нейронных сетей или необходимость тратить время на обучение такой сети.In the application US No. 2005/0281455 (publ. 22.12.2005) disclosed a method of distinguishing between text and pictures in the image using a neural network. In this method, the image is divided into image data in gray levels for image blocks. A trained neural network processes continuous pixels, generating a trusted text value for each of the pixels and obtaining the largest trusted text value, which is compared with a threshold to determine the status of an image block. The disadvantages include the problems of retraining neural networks or the need to spend time training such a network.

В патенте США №6470094 (опубл. 22.10.2002) раскрыта обобщенная локализация текстов в изображениях, когда в изображении в качестве символа выделяются совокупности смежных пикселов, которые, в свою очередь, объединяются в слова.In US patent No. 6470094 (publ. 10/22/2002) disclosed a generalized localization of texts in images, when in the image as a symbol are selected sets of adjacent pixels, which, in turn, are combined into words.

Наиболее близким к заявленному изобретению можно считать способ обнаружения текста в видеоизображениях (патент США №6608930, опубл. 19.08.2003). В этом способе в видеоизображениях сначала выделяют один цвет, что дает контрастное изображение, которое еще усиливают с помощью маски 3×3. Кроме того, медианной фильтрацией удаляют случайный шум из изображения («соль и перец»). Обнаруживают край изображения, причем используют адаптивный порог (если у пиксела все соседи краевые, порог для текущего пиксела понижается). Затем осуществляют (в кадре или подкадрах) краевую фильтрацию, в которой удаляют из анализа те области, где текста нет или где он не может быть надежно обнаружен. Далее объединяют в единый символ краевые пикселы, находящие друг от друга на расстоянии меньше заданного. При этом определяются границы символа по осям координат и количество пикселов, и все это сравнивается с заранее заданными порогами. Потом процессор определяет, лежат ли соседние символы в одной строке. Определяется среднее значение серого для выделенного текста и сравнивается с уровнями белого и черного, чтобы назначить фон белым, а текст черным.Closest to the claimed invention can be considered a method for detecting text in video images (US patent No. 6608930, publ. 08/19/2003). In this method, one color is first isolated in the video images, which gives a contrast image, which is still enhanced with a 3 × 3 mask. In addition, random noise from the image (“salt and pepper”) is removed by median filtering. The edge of the image is detected, and an adaptive threshold is used (if the pixel has all neighbors edge, the threshold for the current pixel decreases). Then, edge filtering (in a frame or subframes) is carried out, in which those areas where there is no text or where it cannot be reliably detected are removed from the analysis. Next, edge pixels are combined into a single symbol, located at a distance less than a given from each other. In this case, the boundaries of the symbol along the coordinate axes and the number of pixels are determined, and all this is compared with predetermined thresholds. Then the processor determines whether adjacent characters are on the same line. The average gray value for the selected text is determined and compared with white and black levels to make the background white and the text black.

Этот способ, однако, имеет ограниченные возможности вследствие того, что требует достаточно много вычислений.This method, however, has limited capabilities due to the fact that it requires a lot of calculations.

Раскрытие изобретенияDisclosure of invention

Таким образом, цель заявленного изобретения состоит в обеспечении более простого и надежного способа обнаружения текста в растровом изображении.Thus, the purpose of the claimed invention is to provide a simpler and more reliable way to detect text in a bitmap image.

Указанный технический результат достигается в первом объекте настоящего изобретения за счет обеспечения способа обнаружения текста в растровом двухцветном изображении, заключающегося в том, что: распознают фоновый цвет в растровом двухцветном изображении; находят границы замкнутого контура, описанного вокруг каждого из отдельных рисунков слитных пикселов цвета, отличного от фонового цвета, и запоминают его координаты; сравнивают размеры каждого из замкнутых контуров с первыми заранее заданными пределами; исключают из дальнейшего рассмотрения те замкнутые контуры, размеры которых не попадают в первые заранее заданные пределы; интерпретируют каждый из оставшихся замкнутых контуров как контур текстового символа; находят предполагаемые строки текстовых символов по всем замкнутым контурам, интерпретированным как контуры текстовых символов; разбивают найденные предполагаемые строки текстовых символов на наборы, интерпретируемые как вероятные слова; сравнивают количества контуров, интерпретированных как контуры текстовых символов, в каждом из вероятных слов со вторыми заранее заданными пределами; исключают из дальнейшего рассмотрения те вероятные слова, в которых количество контуров, интерпретированных как контуры текстовых символов, не попадает во вторые заранее заданные пределы; сравнивают оставшиеся количества вероятных слов в каждой предполагаемой строке с третьими заранее заданными пределами; исключают из дальнейшего рассмотрения те из предполагаемых строк, в которых количество вероятных слов не попадает в третьи заранее заданные пределы; подсчитывают в оставшемся изображении количество пикселов упомянутого цвета, отличного от фонового цвета; вычисляют отношение подсчитанного количества пикселов упомянутого цвета, отличного от фонового цвета, к ранее подсчитанному количеству пикселов того же цвета в исходном двухцветном изображении; если вычисленное в предыдущей операции отношение больше четвертого заранее заданного предела, то считают факт наличия оставшихся предполагаемых строк с вероятными словами обнаружением текста в растровом изображении.The specified technical result is achieved in the first object of the present invention by providing a method for detecting text in a two-color raster image, which consists in the following: the background color is recognized in the two-color raster image; find the boundaries of the closed loop described around each of the individual patterns of fused pixels of a color different from the background color, and remember its coordinates; comparing the sizes of each of the closed loops with the first predetermined limits; exclude from further consideration those closed loops whose sizes do not fall within the first predetermined limits; interpret each of the remaining closed loops as the outline of a text symbol; find the estimated lines of text characters along all closed circuits, interpreted as the contours of text characters; break the found prospective strings of text characters into sets interpreted as likely words; comparing the number of outlines interpreted as outlines of text characters in each of the likely words with the second predetermined limits; exclude from further consideration those probable words in which the number of outlines interpreted as outlines of text characters does not fall into the second predetermined limits; comparing the remaining number of likely words in each expected line with the third predetermined limits; exclude from further consideration those of the proposed lines in which the number of likely words does not fall into the third predetermined limits; counting in the remaining image the number of pixels of said color other than the background color; calculating the ratio of the counted number of pixels of said color other than the background color to the previously counted number of pixels of the same color in the original two-color image; if the ratio calculated in the previous operation is greater than the fourth predetermined limit, then consider the fact of the presence of the remaining expected lines with likely words by detecting the text in the bitmap image.

Указанный технический результат достигается во втором объекте настоящего изобретения за счет обеспечения способа обнаружения текста в растровом многоцветном изображении, заключающегося в том, что: приводят растровое многоцветное изображение к растровому двухцветному изображению; распознают фоновый цвет в растровом двухцветном изображении; находят границы замкнутого контура, описанного вокруг каждого из отдельных рисунков слитных пикселов цвета, отличного от фонового цвета, и запоминают его координаты; сравнивают размеры каждого из замкнутых контуров с первыми заранее заданными пределами; исключают из дальнейшего рассмотрения те замкнутые контуры, размеры которых не попадают в первые заранее заданные пределы; интерпретируют каждый из оставшихся замкнутых контуров как контур текстового символа; находят предполагаемые строки текстовых символов по всем замкнутым контурам, интерпретированным как контуры текстовых символов; разбивают найденные предполагаемые строки текстовых символов на наборы, интерпретируемые как вероятные слова; сравнивают количества контуров, интерпретированных как контуры текстовых символов, в каждом из вероятных слов со вторыми заранее заданными пределами; исключают из дальнейшего рассмотрения те вероятные слова, в которых количество контуров, интерпретированных как контуры текстовых символов, не попадает во вторые заранее заданные пределы; сравнивают оставшиеся количества вероятных слов в каждой предполагаемой строке с третьими заранее заданными пределами; исключают из дальнейшего рассмотрения те из предполагаемых строк, в которых количество вероятных слов не попадает в третьи заранее заданные пределы; подсчитывают в оставшемся изображении количество пикселов упомянутого цвета, отличного от фонового цвета; вычисляют отношение подсчитанного количества пикселов упомянутого цвета, отличного от фонового цвета, к ранее подсчитанному количеству пикселов того же цвета в исходном двухцветном изображении; если вычисленное в предыдущей операции отношение больше четвертого заранее заданного предела, то считают факт наличия оставшихся предполагаемых строк с вероятными словами обнаружением текста в растровом изображении.The specified technical result is achieved in the second object of the present invention by providing a method for detecting text in a raster multicolor image, which consists in the following: result in a raster multicolor image in a raster two-color image; recognize the background color in a two-color raster image; find the boundaries of the closed loop described around each of the individual patterns of fused pixels of a color different from the background color, and remember its coordinates; comparing the sizes of each of the closed loops with the first predetermined limits; exclude from further consideration those closed loops whose sizes do not fall within the first predetermined limits; interpret each of the remaining closed loops as the outline of a text symbol; find the estimated lines of text characters along all closed circuits, interpreted as the contours of text characters; break the found prospective strings of text characters into sets interpreted as likely words; comparing the number of outlines interpreted as outlines of text characters in each of the likely words with the second predetermined limits; exclude from further consideration those probable words in which the number of outlines interpreted as outlines of text characters does not fall into the second predetermined limits; comparing the remaining number of likely words in each expected line with the third predetermined limits; exclude from further consideration those of the proposed lines in which the number of likely words does not fall into the third predetermined limits; counting in the remaining image the number of pixels of said color other than the background color; calculating the ratio of the counted number of pixels of said color other than the background color to the previously counted number of pixels of the same color in the original two-color image; if the ratio calculated in the previous operation is greater than the fourth predetermined limit, then consider the fact of the presence of the remaining expected lines with likely words by detecting the text in the bitmap image.

В данном способе приведение к растровому двухцветному изображению осуществляют с помощью следующих операций: преобразуют цвета растрового многоцветного изображения в оттенки серого; строят для преобразованного изображения гистограмму частот оттенков серого; находят центр тяжести построенной гистограммы; задают порог черно-белого на уровне 3/4 от первого использованного цвета до найденного центра тяжести.In this method, casting to a two-color raster image is carried out using the following operations: convert the colors of the multi-color raster image to shades of gray; building a histogram of frequencies of shades of gray for the converted image; find the center of gravity of the plotted histogram; set the threshold for black and white at 3/4 from the first color used to the found center of gravity.

Особенностью обоих данных способов является то, что при распознавании фонового цвета подсчитывают количество пикселов каждого из двух цветов растрового изображения и выбирают в качестве фонового цвета тот цвет из двух цветов, который имеет большее количество подсчитанных пикселов.A feature of both of these methods is that when recognizing the background color, the number of pixels of each of the two colors of the bitmap image is counted and the color of the two colors that has the largest number of counted pixels is selected as the background color.

Другая особенность обоих данных способов состоит в том, что в процессе или после нахождения границ каждого из замкнутых контуров заменяют цвет в рисунке слитных пикселов, лежащем в данном замкнутом контуре, на цвет фона.Another feature of both of these methods is that during or after finding the boundaries of each of the closed loops, the color in the fused pixel pattern lying in this closed loop is replaced with the background color.

Еще одна особенность обоих данных способов состоит в том, что замкнутые контуры представляются описывающими их прямоугольниками.Another feature of both of these methods is that closed loops are represented by rectangles describing them.

Еще одна особенность обоих данных способов состоит в том, что нахождение предполагаемых строк текстовых символов осуществляют с помощью следующих операций: выбирают очередной контур текстового символа, не участвующий в какой-либо из предполагаемых строк; осуществляют нанизывание строки слева и справа от выбранного контура текстового символа; производят объединение левой и правой подстрок для формирования новой строки. Нужно добавить, что продолжение нанизывания строки продолжается именно с того символа, который был сейчас выбран следующим.Another feature of both of these methods is that the proposed lines of text characters are found using the following operations: choose the next contour of the text character that is not involved in any of the proposed lines; stringing the line to the left and right of the selected outline of the text symbol; combine the left and right substrings to form a new line. It must be added that the continuation of stringing the line continues with the character that was now chosen next.

Еще одна особенность обоих данных способов состоит в том, что разбиение предполагаемых строк текстовых символов на вероятные слова осуществляют с помощью следующих операций: находят в каждой из предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов; строят гистограмму частот найденных расстояний; выбирают в качестве самого частого расстояния абсциссу первого максимума построенной гистограммы; сравнивают в каждой из предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов с выбранным самым частым расстоянием; интерпретируют расстояние между контурами текстовых символов как разрыв между вероятными словами, если оно превышает удвоенное самое частое расстояние.Another feature of both of these methods is that the division of the alleged lines of text characters into probable words is carried out using the following operations: find in each of the proposed lines the distances between all adjacent pairs of contours of text characters; build a histogram of the frequencies of the distances found; the abscissa of the first maximum of the constructed histogram is selected as the most frequent distance; in each of the proposed lines, the distances between all adjacent pairs of contours of text characters with the selected most frequent distance are compared; interpret the distance between the contours of text characters as a gap between likely words if it exceeds twice the most frequent distance.

Наконец, еще одна особенность обоих данных способов состоит в том, что при распознавании фонового цвета подсчитывают в исходном изображении количество пикселов цвета, отличного от фонового, а после исключения вероятных слов, в которых количество контуров текстовых символов не попадает во вторые заранее заданные пределы, и предполагаемых строк, в которых количество вероятных слов не попадает в третьи заранее заданные пределы, выполняют следующие операции: подсчитывают в оставшемся изображении количество пикселов цвета, отличного от фонового цвета; вычисляют отношение подсчитанного количества пикселов цвета, отличного от фонового цвета, к ранее подсчитанному количеству пикселов того же цвета в исходном двухцветном изображении; исключают из дальнейшего рассмотрения изображение, если для него вычисленное в предыдущей операции отношение меньше четвертого заранее заданного предела.Finally, another feature of both of these methods is that when recognizing the background color, the number of color pixels in the source image is different from the background, and after excluding likely words in which the number of contours of text characters does not fall into the second predefined limits, and the expected lines in which the number of likely words does not fall into the third predetermined limits, perform the following operations: count in the remaining image the number of pixels of a color other than the background shaded color; calculating the ratio of the counted number of pixels of a color other than the background color to the previously counted number of pixels of the same color in the original two-color image; exclude from further consideration the image if for him the ratio calculated in the previous operation is less than the fourth predetermined limit.

Указанный технический результат достигается в третьем объекте настоящего изобретения за счет обеспечения способа выявления спама, содержащего растровое изображение, заключающийся в том, что: осуществляют обнаружение текста в растровом изображении по одному из вышеприведенных способов; формируют сигнатуру обнаруженного текста; сравнивают сформированную сигнатуру с эталонными шаблонами спама, хранящимися в базе данных; считают принятое электронное сообщение спамом при совпадении с заранее заданной точностью сформированной сигнатуры с, по меньшей мере, одним эталонным шаблоном спама.The specified technical result is achieved in the third object of the present invention by providing a method for detecting spam containing a bitmap, which consists in the following: detect text in a bitmap according to one of the above methods; form the signature of the detected text; comparing the generated signature with the reference spam patterns stored in the database; consider the received electronic message to be spam when they coincide with a predetermined accuracy of the generated signature with at least one reference spam template.

При этом сигнатуру формируют на основе длин слов, оставшихся после сравнения с вторыми заранее заданными пределами, и количества предполагаемых строк, оставшихся после сравнения с третьими заранее заданными пределами.In this case, the signature is formed on the basis of the word lengths remaining after comparison with the second predetermined limits and the number of expected lines remaining after comparison with the third predetermined limits.

Краткое описание чертежейBrief Description of the Drawings

Заявленное изобретение поясняется далее со ссылками на прилагаемые чертежи, предназначенные только для иллюстрации заявленного изобретения.The claimed invention is explained below with reference to the accompanying drawings, intended only to illustrate the claimed invention.

Фиг.1 является блок-схемой алгоритма, иллюстрирующего реализацию способа обнаружения текста в растровом многоцветном изображении по настоящему изобретению.1 is a flowchart illustrating an implementation of a method for detecting text in a bitmap multicolor image of the present invention.

Фиг.2 является примером спама в виде изображения, которое обычно находится внутри спам-писем.Figure 2 is an example of spam in the form of an image, which is usually located inside spam emails.

Фиг.3 иллюстрирует шаг приведения многоцветного изображения на фиг.2 к двухцветному.Figure 3 illustrates the step of bringing the multi-color image in figure 2 to two-color.

Фиг.4 иллюстрирует вырисовывание контуров вокруг вероятных символов с фиг.3.Figure 4 illustrates the outlines around the probable symbols of figure 3.

Фиг.5 иллюстрирует процесс создания контура вокруг вероятного символа.5 illustrates the process of creating a path around a probable symbol.

Фиг.6 иллюстрирует оставшиеся контуры на фиг.4 после удаления слишком маленьких и слишком больших контуров (а также удаления прочего шума).6 illustrates the remaining contours in figure 4 after removing too small and too large contours (as well as removing other noise).

Фиг.7 иллюстрирует компьютерную систему, на которой может быть реализовано настоящее изобретение.7 illustrates a computer system on which the present invention may be implemented.

Фиг.8 иллюстрирует процесс разделения оставшихся контуров на слова.Fig. 8 illustrates the process of dividing the remaining contours into words.

Фиг.9 иллюстрирует процесс разделения текстовых строк на слова.Fig.9 illustrates the process of dividing text strings into words.

Фиг.10 является блок-схемой алгоритма, показывающего подробности получения решения о наличии спама по алгоритму на фиг.1.Figure 10 is a block diagram of an algorithm showing the details of obtaining a decision on the presence of spam according to the algorithm in figure 1.

Фиг.11 является блок-схемой алгоритма по преобразованию цветного изображения к двухцветному.11 is a flowchart for converting a color image to a two-color one.

Фиг.12 иллюстрирует гистограмму частот оттенков серого при выполнении алгоритма по преобразованию цветного изображения к двухцветному.12 illustrates a histogram of gray-scale frequencies when performing an algorithm for converting a color image to a two-color one.

Фиг.13 является блок-схемой алгоритма по выбору одного из двух цветов как фонового.13 is a flowchart for selecting one of two colors as a background.

Фиг.14 является блок-схемой алгоритма, показывающего подробности выполнения шага нахождения предполагаемых строк.Fig is a block diagram of an algorithm showing the details of the step of finding the expected lines.

Фиг.15-17 иллюстрируют процесс выполнения шага нахождения предполагаемых строк.Figures 15-17 illustrate the process of performing the step of finding prospective rows.

Фиг.18 является блок-схемой алгоритма разбиения предполагаемых строк на вероятные слова.Fig is a block diagram of an algorithm for breaking the proposed lines into probable words.

Фиг.19-20 являются блок-схемами алгоритмов по нанизыванию символов в строку как с левой стороны, так и с правой.Figs. 19-20 are block diagrams of algorithms for stringing characters into a string both on the left side and on the right.

Фиг.21-56 иллюстрируют вышеописанный процесс в деталях и с дополнительными комментариями.21-56 illustrate the above process in detail and with additional comments.

Фиг.57 является дополнительной иллюстрацией алгоритма по нанизыванию символов в строку как с левой стороны, так и с правой.Fig. 57 is a further illustration of an algorithm for stringing characters into a string both on the left side and on the right.

Описание предпочтительных вариантов осуществленияDescription of Preferred Embodiments

Ниже будет описан, как более общий, второй из вышеприведенных способов, т.е. способ обнаружения текста в растровом многоцветном изображении. Способ обнаружения текста в растровом двухцветном изображении отличается лишь тем, что не требует шага приведения растрового многоцветного изображения к двухцветному.Below will be described, as a more general, the second of the above methods, i.e. A method for detecting text in a bitmap multicolor image. The method for detecting text in a two-color raster image differs only in that it does not require a step of converting a raster multi-color image to a two-color one.

Настоящее изобретение предназначено для использования в любом вычислительном средстве, способном воспринимать и обрабатывать как текстовые данные, так и данные изображений. Это могут быть серверы, персональные компьютеры (ПК), персональные цифровые ассистенты (PDA), переносные компьютеры (ноутбуки), компактные компьютеры (лаптопы) и любые иные существующие или разрабатываемые, а также будущие вычислительные устройства, подключаемые к компьютерной сети. Настоящее изобретение наиболее просто реализуется посредством соответствующего программного обеспечения (software), однако его можно также при желании воплотить и в аппаратном (hardware) или программно-аппаратном (firmware) виде. В случае программной реализации настоящего изобретения в память вычислительного средства (пусть это будет для наглядности компьютер) заносятся соответствующие программные коды, под управлением которых в ходе их считывания процессор компьютера осуществляет действия того или иного способа по настоящему изобретению. На фиг.7 изображена примерная схема компьютерной системы, на которой может быть реализовано настоящее изобретение.The present invention is intended for use in any computing device capable of perceiving and processing both text data and image data. These can be servers, personal computers (PCs), personal digital assistants (PDAs), laptops (laptops), compact computers (laptops) and any other existing or developed computers, as well as future computing devices connected to a computer network. The present invention is most easily implemented through the appropriate software (software), however, it can also, if desired, be embodied in hardware (hardware) or software-hardware (firmware) form. In the case of a software implementation of the present invention, the corresponding program codes are entered into the memory of the computing means (let it be for illustrative purposes), under the control of which the computer processor performs the actions of one or another method of the present invention during their reading. 7 shows an exemplary diagram of a computer system on which the present invention can be implemented.

На фиг.1 показана блок-схема алгоритма для осуществления способа обнаружения текста в растровом многоцветном изображении по настоящему изобретению. На вход компьютера поступает растровое изображение. В случае векторного изображения его необходимо предварительно преобразовать в растровое, что условно показано пунктирным блоком 101. Это можно сделать с помощью соответствующей библиотеки. На растре рисуется рисунок с заданными размерами и масштабом, после чего растр готов для использования.Figure 1 shows a flowchart of an algorithm for implementing a method for detecting text in a raster multicolor image of the present invention. A bitmap image is input to the computer. In the case of a vector image, it must first be converted to a raster one, which is conventionally shown by the dashed block 101. This can be done using the appropriate library. A drawing is drawn on the raster with the specified size and scale, after which the raster is ready for use.

Поступающее на вход компьютера изображение в общем случае является многоцветным. Для удобства дальнейшей работы его необходимо перевести в двухцветное (к примеру, черно-белое) изображение. Эта операция осуществляется на шаге 102 и подробно описывается на фиг.11.The image arriving at the computer input is generally multicolor. For the convenience of further work, it must be converted into a two-color (for example, black and white) image. This operation is carried out in step 102 and is described in detail in FIG. 11.

Для приведения многоцветного растрового изображения к двухцветному растровому изображению (фиг.11) сначала на шаге 1101 преобразуют цвета растрового многоцветного изображения в оттенки серого. На фиг.2 приведен пример многоцветного изображения, а на фиг.3 это же изображение показано в оттенках серого.To convert a multicolor raster image to a two-color raster image (Fig. 11), first, in step 1101, the colors of the raster multicolor image are converted to shades of gray. Figure 2 shows an example of a multi-color image, and figure 3 shows the same image in shades of gray.

Далее на шаге 1102 строят для преобразованного изображения гистограмму частот оттенков серого. Пример такой гистограммы приведен на фиг.12. Затем находят центр тяжести построенной гистограммы и определяют его абсциссу Хцт на шаге 1103 (см. фиг.11). После этого на шаге 1104 находят абсциссу X1 первого уровня серого этой гистограммы.Next, in step 1102, a histogram of the frequencies of shades of gray is constructed for the converted image. An example of such a histogram is shown in Fig. 12. Then, the center of gravity of the constructed histogram is found and its abscissa X ct is determined at step 1103 (see Fig. 11). After that, at step 1104, the abscissa X 1 of the first gray level of this histogram is found.

Наконец, на шаге 1105 задают порог черно-белого на уровне расстояния X1+3/4цт-X1) от первого уровня серого до найденного центра тяжести.Finally, in step 1105 the threshold is set to black and white level, the distance X 1 + 3/4 (X 1 -X ct) from the first gray level found before the center of gravity.

Операция шага 102 (на фиг.1) может осуществляться и иными средствами, например, цвета темнее RGB (127, 127, 127) становятся черными, светлее - белыми.The operation of step 102 (in FIG. 1) can be carried out by other means, for example, colors darker than RGB (127, 127, 127) become black, lighter - white.

После приведения на шаге 102 многоцветного растрового изображения к двухцветному растровому изображению на шаге 103А распознают фоновый цвет в этом растровом двухцветном изображении. Эта процедура иллюстрируется блок-схемой на фиг.13.After the multicolor raster image is converted to a two-color raster image in step 102, the background color in this two-color raster image is recognized in step 103A. This procedure is illustrated in the flowchart of FIG. 13.

Для распознавания фонового цвета сначала на шагах 1301 и 1302 подсчитывают количество пикселов каждого из двух цветов растрового двухцветного изображения. Подсчитанные количества пикселов обоих цветов сравнивают друг с другом на шаге 1303 и на шаге 1304 выбирают в качестве фонового цвета тот из этих двух цветов, который имеет большее количество подсчитанных пикселов.To recognize the background color, first, in steps 1301 and 1302, the number of pixels of each of the two colors of the two-color raster image is counted. The counted pixel numbers of both colors are compared with each other in step 1303, and in step 1304, one of these two colors that has a larger number of counted pixels is selected as the background color.

Операцию 103А (на фиг.1) распознавания фона можно осуществлять и иными средствами, например, взяв цветом фона цвет, преобладающий на крае рисунка.The operation 103A (in FIG. 1) of background recognition can be carried out by other means, for example, by taking the background color as the color prevailing at the edge of the picture.

После определения фонового цвета на шаге 104А находят границы замкнутого контура, описанного вокруг каждого из отдельных рисунков слитных пикселов цвета, отличного от фонового цвета, и запоминают его координаты. Этот шаг иллюстрируется на фиг.4 и 5.After determining the background color in step 104A, the boundaries of the closed loop described around each of the individual patterns of fused pixels of a color other than the background color are found and its coordinates are stored. This step is illustrated in FIGS. 4 and 5.

Когда на шаге 104А определены границы (и координаты) всех замкнутых контуров вокруг каждого отдельного рисунка слитных пикселов «нефонового» цвета, на шаге 105 сравнивают размеры каждого из этих замкнутых контуров с первыми заранее заданными пределами. Эти пределы устанавливают эмпирически в процессе анализа имеющихся образцов изображений с текстом. В том случае, когда размеры какого-либо замкнутого контура не попадают в эти первые заранее заданные пределы, данный замкнутый контур исключают из дальнейшего рассмотрения (шаг 106). На шаге 105А проверяют наличие еще нерассмотренных контуров. Если остался хотя бы один, то алгоритм возвращается к шагу 105. Каждый из оставшихся замкнутых контуров интерпретируют как контур текстового символа и продолжают процесс обработки.When the boundaries (and coordinates) of all closed loops around each individual pattern of fused “non-phonon” color pixels are determined in step 104A, the sizes of each of these closed loops with the first predetermined limits are compared in step 105. These limits are established empirically in the process of analyzing available samples of images with text. In the case when the dimensions of any closed loop do not fall into these first predetermined limits, this closed loop is excluded from further consideration (step 106). At step 105A, the presence of pending loops is checked. If at least one is left, the algorithm returns to step 105. Each of the remaining closed loops is interpreted as the outline of a text symbol and the processing continues.

На шаге 107 находят предполагаемые строки текстовых символов по всем замкнутым контурам, интерпретированным как контуры текстовых символов. Эта процедура иллюстрируется на фиг.6. Более подробно шаг 107 проиллюстрирован на блок-схеме на фиг.14.At step 107, the expected strings of text characters are found over all closed loops, interpreted as loops of text characters. This procedure is illustrated in Fig.6. In more detail, step 107 is illustrated in the block diagram of FIG.

В процессе нахождения предполагаемых строк сначала на шаге 1401 выбирают следующий свободный контур текстового символа, не участвующий в какой-либо из предполагаемых строк. На шаге 1402 происходит нанизывание левой подстроки, после чего происходит нанизывание правой подстроки на шаге 1403. После получения левой и правой подстрок происходит их объединение на шаге 1404. Получив новую строку, алгоритм проверяет, есть ли оставшиеся свободные контуры для построения новых строк. Если таковые есть, то алгоритм снова переходит к шагу 1401. В противном случае алгоритм заканчивает свою работу. На фиг.15-17 иллюстрируется результат нанизывания строки слева и справа.In the process of finding the expected lines, first, at step 1401, the next free contour of the text character is selected that is not involved in any of the estimated lines. In step 1402, the left substring is strung, after which the right substring is strung in step 1403. After receiving the left and right substrings, they are merged in step 1404. After receiving a new string, the algorithm checks to see if there are any remaining free contours for constructing new strings. If there are any, then the algorithm proceeds to step 1401. Otherwise, the algorithm ends its work. On Fig-17 illustrates the result of stringing the string left and right.

Более подробно шаги 1402 и 1403 рассмотрены на фиг.19 и 20. Переход в левую текстовую подстроку подробно представлен на фиг.19. Вначале вычисляют верхнюю и нижнюю границу контура на этапе 1901. Для этого увеличивают высоту контура текущего символа на 1/3 вверх и на 1/3 вниз. На шаге 1902 находят контур с координатой y центра внутри заданных границ и ближайшей координатой х от левой стороны текущего контура. При этом этот контур не должен являться частью какой-либо текстовой строки. Если на этапе 1903 контур найден, то далее на этапе 1904 он добавляется к началу подстроки и устанавливается как текущий на этапе 1905. Фиг.20 иллюстрирует тот же самый алгоритм, но для правой стороны.Steps 1402 and 1403 are described in more detail in FIGS. 19 and 20. The transition to the left text substring is presented in detail in FIG. 19. First, calculate the upper and lower boundary of the contour in step 1901. To do this, increase the height of the contour of the current symbol by 1/3 up and 1/3 down. At step 1902, a contour is found with the y coordinate of the center inside the given boundaries and the nearest x coordinate from the left side of the current contour. However, this contour should not be part of any text string. If the loop is found in step 1903, then in step 1904 it is added to the beginning of the substring and is set to the current one in step 1905. FIG. 20 illustrates the same algorithm, but for the right side.

На шаге 108 после нахождения предполагаемых строк текстовых символов их разбивают на наборы, интерпретируемые как вероятные слова. Эта процедура более подробно показана на фиг.8.At step 108, after finding the expected strings of text characters, they are divided into sets that are interpreted as likely words. This procedure is shown in more detail in FIG.

Для того чтобы разбить предполагаемые строки на вероятные слова, сначала на шаге 1801 находят в каждой из предполагаемых строк расстояния между всеми парами соседних контуров текстовых символов. После этого на шаге 1802 строят гистограмму частот найденных расстояний. На шаге 1803 находят абсциссу Х первого максимума построенной гистограммы и выбирают Х в качестве самого частого расстояния. Затем на шаге 1804 сравнивают в каждой из предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов с двойным выбранным самым частым расстоянием Х. Если сравниваемое расстояние превышает удвоенное самое частое расстояние Х, то на шаге 1805 интерпретируют это расстояние как разрыв между вероятными словами. На шаге 1806 проверяют наличие оставшихся пар соседних контуров, и если еще остались непроверенные пары контуров, то алгоритм возвращается к шагу 1804. Результат выполнения этой процедуры проиллюстрирован на фиг.9.In order to break the proposed lines into probable words, first at step 1801, the distances between all pairs of adjacent contours of text characters are found in each of the proposed lines. After that, at step 1802, a histogram of the frequencies of the distances found is built. At step 1803, the abscissa X 1m of the first maximum of the plotted histogram is found and X 1m is selected as the most frequent distance. Then, at step 1804, in each of the proposed lines, the distances between all adjacent pairs of contours of text characters with the double selected most frequent distance X 1 m are compared . If the distance to be compared exceeds twice the most frequent distance X 1 m , then at step 1805 this distance is interpreted as the gap between the likely words. At step 1806, the presence of the remaining pairs of adjacent loops is checked, and if there are still unverified pairs of loops, the algorithm returns to step 1804. The result of this procedure is illustrated in Fig. 9.

После того, как на шаге 108 (на фиг.1) предполагаемые строки разбиты (разделены) на вероятные слова, на шаге 109 сравнивают количества упомянутых контуров, интерпретированных как контуры текстовых символов, в каждом из вероятных слов со вторыми заранее заданными пределами. Эти вторые заранее заданные пределы определяются, как и первые заранее заданные пределы, эмпирически и могут составлять, например, минимум 2, максимум 16. Если количество замкнутых контуров, интерпретированных как контуры текстовых символов, какого-либо вероятного слова не попадает во вторые заранее заданные пределы, то на шаге 110 это вероятное слово исключают из дальнейшего рассмотрения. На шаге 109А проверяют наличие еще нерассмотренных слов. Если осталось хотя бы одно слово, то алгоритм возвращается к шагу 109. Затем на шаге 111 сравнивают количества оставшихся вероятных слов в каждой предполагаемой строке с третьими заранее заданными пределами, которые задаются эмпирически, как и уже упоминавшиеся первые и вторые заранее заданные пределы. Если количество вероятных слов в какой-либо предполагаемой строке не попадает в третьи заранее заданные пределы, эту предполагаемую строку на шаге 112 исключают из дальнейшего рассмотрения. На шаге 111 A проверяют наличие еще нерассмотренных строк. Если осталась хотя бы одна строка, то алгоритм возвращается к шагу 111. Далее на этапе 113 считают количество черных пикселов (N2) внутри оставшихся контуров, которые представляют символы или буквы. Далее вычисляется отношение количества черных пикселов (N2) внутри оставшихся контуров к количеству пикселов (N1), отличных от цвета фона. При условии, что это отношение попадает в четвертый заданный предел, то принимают решение о том, что анализируемое растровое изображение содержит текст.After the alleged lines are broken (divided) into probable words in step 108 (in FIG. 1), in step 109 the number of the mentioned outlines, interpreted as outlines of text characters, in each of the possible words with the second predetermined limits is compared. These second predefined limits are defined, like the first predefined limits, empirically and can be, for example, minimum 2, maximum 16. If the number of closed loops, interpreted as the contours of text characters, any probable word does not fall into the second predefined limits , then at step 110 this probable word is excluded from further consideration. At step 109A, the presence of pending words is checked. If at least one word is left, the algorithm returns to step 109. Then, at step 111, the number of remaining probable words in each expected line is compared with the third predetermined limits, which are set empirically, as well as the first and second predetermined limits already mentioned. If the number of likely words in any proposed line does not fall into the third predetermined limits, this expected line in step 112 is excluded from further consideration. At step 111 A, check for pending rows. If at least one line remains, then the algorithm returns to step 111. Next, at step 113, the number of black pixels (N 2 ) inside the remaining outlines that represent characters or letters is counted. Next, the ratio of the number of black pixels (N 2 ) inside the remaining outlines to the number of pixels (N 1 ) other than the background color is calculated. Provided that this ratio falls within the fourth predetermined limit, a decision is made that the analyzed raster image contains text.

На фиг.1 показаны еще несколько операций, которые стоит рассмотреть более подробно.Figure 1 shows several more operations that are worth considering in more detail.

В частности, после того, как на шаге 104А найдены границы и координаты замкнутых контуров, или в процессе этого нахождения, на шаге 104В заменяют цвет в рисунке слитных пикселов, лежащем в данном замкнутом контуре, на цвет фона. Это делается для того, чтобы исключить возможность ложного (повторного) рассмотрения уже найденного замкнутого контура.In particular, after the boundaries and coordinates of the closed loops are found in step 104A, or during this finding, in step 104B, the color in the fused pixel pattern lying in the closed loop is replaced with the background color. This is done in order to exclude the possibility of a false (re) examination of an already found closed loop.

Кроме того, после распознавания на шаге 103В фонового цвета подсчитывают в исходном изображении количество N1 пикселов цвета, отличного от фонового. После же выполнения шагов 110 и 112 по исключению вероятных слов, в которых количество контуров текстовых символов не попадает во вторые заранее заданные пределы, и предполагаемых строк, в которых количество вероятных слов не попадает в третьи заранее заданные пределы, на шаге 113 подсчитывают в оставшемся изображении количество N2 пикселов цвета, отличного от фонового цвета. Затем вычисляют отношение подсчитанного на шаге 114 количества N2 пикселов «нефонового» цвета к подсчитанному на шаге 103В количеству N1 пикселов того же цвета в исходном двухцветном изображении и сравнивают (шаг 114) это отношение N2/N1 с четвертым заранее заданным (эмпирически, как и предыдущие) пределом. Если это отношение оказывается меньше четвертого заранее заданного предела, анализируемое изображение исключают из дальнейшего рассмотрения (шаг 115). В противном случае делается вывод о наличии текста в этом изображении (шаг 116).In addition, after recognizing the background color in step 103B, the number N 1 pixels of a color other than the background are counted in the original image. After performing steps 110 and 112 to eliminate probable words in which the number of contours of text characters does not fall into the second predetermined limits, and expected lines in which the number of probable words does not fall into the third predefined limits, at step 113, the remaining image is counted the number N 2 pixels of a color other than the background color. Then, the ratio of the number of N 2 pixels of the “non-phonon” color calculated in step 114 to the number of N 1 pixels of the same color calculated in step 103B in the original two-color image is calculated, and this ratio N 2 / N 1 is compared with the fourth predetermined (empirically , as previous) limit. If this ratio is less than the fourth predetermined limit, the analyzed image is excluded from further consideration (step 115). Otherwise, it is concluded that there is text in this image (step 116).

Случай анализа двухцветного растрового изображения отличается от рассмотренного случая анализа многоцветного растрового изображения только лишь отсутствием шага 102, на котором многоцветное изображение приводят к двухцветному (а значит, и всей последовательности шагов 1101-1105 на фиг.11).The case of analysis of a two-color raster image differs from the considered case of analysis of a multi-color raster image only in the absence of step 102, in which the multi-color image leads to two-color (and, therefore, the entire sequence of steps 1101-1105 in FIG. 11).

В качестве дополнительной иллюстрации работы алгоритма на фиг.1 приведены фиг.21-57, на которых изображено поэтапное выполнение всех шагов алгоритма с приведенными комментариями.As an additional illustration of the operation of the algorithm in Fig. 1, Figs. 21-57 are shown, which depict the phased execution of all steps of the algorithm with the comments given.

Рассмотренные способы обнаружения текста в растровом изображении могут использоваться как самостоятельно, так и для определения того, является ли данное изображение спамом. В этом случае, как показано на фиг.10, сначала выполняется один из способов, проиллюстрированных на фиг.1, а затем выход этого способа (из блока 116) попадает в блок 1001 на фиг.10, где формируют сигнатуру обнаруженного текста. Это формирование сигнатуры можно выполнять так же, как это делается, к примеру, в патенте США №7158961 (опубл. 02.01.2007), где раскрыты способ и устройство для оценки сходства, сравнивающие эскизы объектов, генерируемые как векторы, соответствующие объектам, где каждая координата вектора связана с соответствующим весом. Эти веса перемножаются с заранее заданным вектором хеширования, и произведения суммируются. Получается компактное представление объекта. В данном случае сигнатуру формируют на основе длин вероятных слов, оставшихся после сравнения со вторыми заранее заданными пределами.The above methods for detecting text in a raster image can be used both independently and to determine whether a given image is spam. In this case, as shown in FIG. 10, one of the methods illustrated in FIG. 1 is first performed, and then the output of this method (from block 116) falls into block 1001 of FIG. 10, where the signature of the detected text is generated. This signature formation can be performed in the same way as is done, for example, in US Pat. No. 7158961 (publ. 02.01.2007), where a method and apparatus for evaluating similarity are disclosed, comparing object sketches generated as vectors corresponding to objects where each the vector coordinate is related to the corresponding weight. These weights are multiplied with a predefined hash vector, and the products are summed. It turns out a compact representation of the object. In this case, the signature is formed on the basis of the lengths of the likely words remaining after comparison with the second predetermined limits.

Далее на шаге 1002 сравнивают сформированную сигнатуру с эталонными шаблонами спама, хранящимися в базе данных. Эти эталонные шаблоны находят в процессе анализа изображений с текстами, которые однозначно отнесены к спамовым. При совпадении с заранее заданной точностью сформированной сигнатуры с, по меньшей мере, одним эталонным шаблоном спама анализируемое растровое изображение считают спамом.Next, at step 1002, the generated signature is compared with the spam reference patterns stored in the database. These reference patterns are found in the process of analyzing images with texts that are unambiguously classified as spam. When coinciding with a predetermined accuracy of the generated signature with at least one reference spam template, the analyzed bitmap image is considered spam.

Настоящее изобретение описано выше со ссылками на сопровождающие чертежи на примере вариантов его осуществления. Специалистам очевидно, что в этих вариантах могут быть сделаны различные модификации, дополнения и даже замены без отхода от сущности настоящего изобретения, объем притязаний по которому определяется прилагаемой формулой изобретения с учетом эквивалентов.The present invention is described above with reference to the accompanying drawings on the example of options for its implementation. It will be apparent to those skilled in the art that various modifications, additions, and even replacements can be made in these embodiments without departing from the spirit of the present invention, the scope of which is determined by the appended claims taking into account equivalents.

Claims (17)

1. Способ обнаружения текста в растровом двухцветном изображении, заключающийся в том, что:
распознают фоновый цвет в упомянутом растровом двухцветном изображении;
находят границы замкнутого контура, описанного вокруг каждого из отдельных рисунков слитных пикселов цвета, отличного от упомянутого фонового цвета, и запоминают его координаты;
сравнивают размеры каждого из упомянутых замкнутых контуров с первыми заранее заданными пределами;
исключают из дальнейшего рассмотрения те замкнутые контуры, размеры которых не попадают в упомянутые первые заранее заданные пределы;
интерпретируют каждый из оставшихся замкнутых контуров как контур текстового символа;
находят предполагаемые строки текстовых символов по всем замкнутым контурам, интерпретированным как контуры текстовых символов;
разбивают найденные предполагаемые строки текстовых символов на наборы, интерпретируемые как вероятные слова;
сравнивают количества упомянутых контуров, интерпретированных как контуры текстовых символов, в каждом из упомянутых вероятных слов со вторыми заранее заданными пределами;
исключают из дальнейшего рассмотрения те вероятные слова, в которых количество упомянутых контуров, интерпретированных как контуры текстовых символов, не попадает в упомянутые вторые заранее заданные пределы;
сравнивают количества оставшихся вероятных слов в каждой упомянутой предполагаемой строке с третьими заранее заданными пределами;
исключают из дальнейшего рассмотрения те из упомянутых предполагаемых строк, в которых количество вероятных слов не попадает в упомянутые третьи заранее заданные пределы;
считают факт наличия оставшихся предполагаемых строк с вероятными словами обнаружением текста в упомянутом растровом изображении.
1. The method of detecting text in a two-color raster image, which consists in the fact that:
recognizing a background color in said two-color raster image;
find the boundaries of the closed loop described around each of the individual patterns of fused pixels of a color other than the background color, and remember its coordinates;
comparing the sizes of each of the aforementioned closed loops with the first predetermined limits;
exclude from further consideration those closed loops whose sizes do not fall within the aforementioned first predetermined limits;
interpret each of the remaining closed loops as the outline of a text symbol;
find the estimated lines of text characters along all closed circuits, interpreted as the contours of text characters;
break the found alleged strings of text characters into sets interpreted as likely words;
comparing the amounts of said outlines, interpreted as outlines of text characters, in each of said likely words with second predetermined limits;
exclude from further consideration those probable words in which the number of the mentioned contours, interpreted as the contours of text characters, does not fall within the said second predetermined limits;
comparing the number of remaining probable words in each said putative string with the third predetermined limits;
exclude from further consideration those of the said alleged lines in which the number of likely words does not fall within the said third predetermined limits;
consider the fact of the presence of the remaining alleged lines with likely words by detecting the text in the mentioned bitmap.
2. Способ по п.1, в котором при распознавании фонового цвета:
подсчитывают количество пикселов каждого из двух цветов упомянутого растрового изображения;
выбирают в качестве фонового цвета тот цвет из упомянутых двух цветов, который имеет большее количество подсчитанных пикселов.
2. The method according to claim 1, in which when recognizing the background color:
counting the number of pixels of each of the two colors of said raster image;
choose the background color of the above two colors that has a greater number of counted pixels as the background color.
3. Способ по п.1, в котором в процессе или после нахождения границ каждого из упомянутых замкнутых контуров заменяют цвет в рисунке слитных пикселов, лежащем в данном замкнутом контуре, на цвет фона.3. The method according to claim 1, in which, during or after finding the boundaries of each of the aforementioned closed loops, replace the color in the fused pixel pattern lying in this closed loop with the background color. 4. Способ по п.1 или 3, в котором упомянутые замкнутые контуры представляются описывающими их прямоугольниками.4. The method according to claim 1 or 3, wherein said closed loops are represented by rectangles describing them. 5. Способ по п.1, в котором нахождение упомянутых предполагаемых строк текстовых символов осуществляют с помощью следующих операций:
выбирают очередной контур текстового символа, не участвующий в какой-либо из упомянутых предполагаемых строк;
осуществляют нанизывание строки слева и справа от выбранного контура текстового символа за счет выполнения следующих операций:
производят объединение правой и левой подстрок для получения новой строки.
5. The method according to claim 1, in which the finding of the alleged lines of text characters is carried out using the following operations:
choose the next contour of the text character that is not involved in any of the alleged lines mentioned;
stringing the line to the left and right of the selected outline of the text character by performing the following operations:
combine the right and left substrings to get a new line.
6. Способ по п.5, в котором разбиение упомянутых предполагаемых строк текстовых символов на вероятные слова осуществляют с помощью следующих операций:
находят в каждой из упомянутых предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов;
строят гистограмму частот найденных расстояний;
выбирают в качестве самого частого расстояния абсциссу первого максимума построенной гистограммы;
сравнивают в каждой из упомянутых предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов с выбранным самым частым расстоянием;
разделяют в каждой из упомянутых предполагаемых строк любые два соседних контура текстового символа на вероятные слова, если расстояние между ними не меньше удвоенного упомянутого самого частого расстояния.
6. The method according to claim 5, in which the division of the mentioned alleged lines of text characters into probable words is carried out using the following operations:
find in each of the mentioned alleged lines the distances between all adjacent pairs of contours of text characters;
build a histogram of the frequencies of the distances found;
the abscissa of the first maximum of the constructed histogram is selected as the most frequent distance;
in each of the aforementioned alleged lines, comparing the distances between all adjacent pairs of contours of text characters with the selected most frequent distance;
in each of the alleged lines mentioned, divide any two adjacent contours of the text symbol into probable words, if the distance between them is not less than twice the mentioned most frequent distance.
7. Способ по п.1, в котором при распознавании фонового цвета подсчитывают в исходном изображении количество пикселов цвета, отличного от фонового, а после упомянутого исключения вероятных слов, в которых количество контуров текстовых символов не попадает в упомянутые вторые заранее заданные пределы, и предполагаемых строк, в которых количество вероятных слов не попадает в упомянутые третьи заранее заданные пределы, выполняют следующие операции:
подсчитывают в оставшемся изображении количество пикселов упомянутого цвета, отличного от фонового цвета;
вычисляют отношение подсчитанного количества пикселов упомянутого цвета, отличного от фонового цвета, к ранее подсчитанному количеству пикселов того же цвета в исходном двухцветном изображении;
исключают из дальнейшего рассмотрения изображение, если для него вычисленное в предыдущей операции отношение меньше четвертого заранее заданного предела.
7. The method according to claim 1, in which, when recognizing the background color, the number of color pixels in the original image is calculated different from the background, and after the exclusion of probable words, in which the number of contours of text characters does not fall within the said second predetermined limits, and the estimated lines in which the number of likely words does not fall within the mentioned third predetermined limits, perform the following operations:
counting in the remaining image the number of pixels of said color other than the background color;
calculating the ratio of the counted number of pixels of said color other than the background color to the previously counted number of pixels of the same color in the original two-color image;
exclude from further consideration the image if for him the ratio calculated in the previous operation is less than the fourth predetermined limit.
8. Способ обнаружения текста в растровом многоцветном изображении, заключающийся в том, что:
приводят растровое многоцветное изображение к растровому двухцветному изображению;
распознают фоновый цвет в упомянутом растровом двухцветном изображении;
находят границы замкнутого контура, описанного вокруг каждого из отдельных рисунков слитных пикселов цвета, отличного от упомянутого фонового цвета, и запоминают его координаты;
сравнивают размеры каждого из упомянутых замкнутых контуров с первыми заранее заданными пределами;
исключают из дальнейшего рассмотрения те замкнутые контуры, размеры которых не попадают в упомянутые первые заранее заданные пределы;
интерпретируют каждый из оставшихся замкнутых контуров как контур текстового символа;
находят предполагаемые строки текстовых символов по всем замкнутым контурам, интерпретированным как контуры текстовых символов;
разбивают найденные предполагаемые строки текстовых символов на наборы, интерпретируемые как вероятные слова;
сравнивают количества упомянутых контуров, интерпретированных как контуры текстовых символов, в каждом из упомянутых вероятных слов со вторыми заранее заданными пределами;
исключают из дальнейшего рассмотрения те вероятные слова, в которых количество упомянутых контуров, интерпретированных как контуры текстовых символов, не попадает в упомянутые вторые заранее заданные пределы;
сравнивают количества оставшихся вероятных слов в каждой упомянутой предполагаемой строке с третьими заранее заданными пределами;
исключают из дальнейшего рассмотрения те из упомянутых предполагаемых строк, в которых количество вероятных слов не попадает в упомянутые третьи заранее заданные пределы;
считают факт наличия оставшихся предполагаемых строк с вероятными словами обнаружением текста в упомянутом растровом изображении.
8. A method for detecting text in a raster multicolor image, which consists in the fact that:
lead a raster multicolor image to a raster two-color image;
recognizing a background color in said two-color raster image;
find the boundaries of the closed loop described around each of the individual patterns of fused pixels of a color other than the background color, and remember its coordinates;
comparing the sizes of each of the aforementioned closed loops with the first predetermined limits;
exclude from further consideration those closed loops whose sizes do not fall within the aforementioned first predetermined limits;
interpret each of the remaining closed loops as the outline of a text symbol;
find the estimated lines of text characters along all closed circuits, interpreted as the contours of text characters;
break the found alleged strings of text characters into sets interpreted as likely words;
comparing the amounts of said outlines, interpreted as outlines of text characters, in each of said likely words with second predetermined limits;
exclude from further consideration those probable words in which the number of the mentioned contours, interpreted as the contours of text characters, does not fall within the said second predetermined limits;
comparing the number of remaining probable words in each said putative string with the third predetermined limits;
exclude from further consideration those of the said alleged lines in which the number of likely words does not fall within the said third predetermined limits;
consider the fact of the presence of the remaining alleged lines with likely words by detecting the text in the mentioned bitmap.
9. Способ по п.8, в котором приведение к растровому двухцветному изображению осуществляют с помощью следующих операций:
преобразуют цвета растрового многоцветного изображения в оттенки серого;
строят для преобразованного изображения гистограмму частот оттенков серого;
находят центр тяжести построенной гистограммы;
задают порог черно-белого на уровне 3/4 расстояния от первого уровня серого до найденного центра тяжести.
9. The method of claim 8, in which the reduction to a two-color raster image is carried out using the following operations:
convert the colors of a raster multicolor image to shades of gray;
building a histogram of frequencies of shades of gray for the converted image;
find the center of gravity of the plotted histogram;
set the threshold for black and white at 3/4 of the distance from the first gray level to the found center of gravity.
10. Способ по п.8, в котором при распознавании фонового цвета:
подсчитывают количество пикселов каждого из двух цветов упомянутого растрового двухцветного изображения;
выбирают в качестве фонового цвета тот цвет из упомянутых двух цветов, который имеет большее количество подсчитанных пикселов.
10. The method according to claim 8, in which when recognizing the background color:
counting the number of pixels of each of two colors of said two-color raster image;
choose the background color of the above two colors that has a greater number of counted pixels as the background color.
11. Способ по п.8, в котором в процессе или после нахождения границ каждого из упомянутых замкнутых контуров заменяют цвет в рисунке слитных пикселов, лежащем в данном замкнутом контуре, на цвет фона.11. The method according to claim 8, in which, during or after finding the boundaries of each of the aforementioned closed loops, replace the color in the fused pixel pattern lying in this closed loop with the background color. 12. Способ по п.8 или 10, в котором упомянутые замкнутые контуры представляются описывающими их прямоугольниками.12. The method of claim 8 or 10, wherein said closed loops are represented by rectangles describing them. 13. Способ по п.8, в котором нахождение упомянутых предполагаемых строк текстовых символов осуществляют с помощью следующих операций:
выбирают очередной контур текстового символа, не участвующий в какой-либо из упомянутых предполагаемых строк;
осуществляют нанизывание строки слева и справа от выбранного контура текстового символа за счет выполнения следующих операций:
производят объединение правой и левой подстрок для получения новой строки.
13. The method of claim 8, in which the finding of the alleged lines of text characters is carried out using the following operations:
choose the next contour of the text character that is not involved in any of the alleged lines mentioned;
stringing the line to the left and right of the selected outline of the text character by performing the following operations:
combine the right and left substrings to get a new line.
14. Способ по п.13, в котором разбиение упомянутых предполагаемых строк текстовых символов на вероятные слова осуществляют с помощью следующих операций:
находят в каждой из упомянутых предполагаемых строк расстояния между всеми парами соседних контуров текстовых символов;
строят гистограмму частот найденных расстояний;
выбирают в качестве самого частого расстояния абсциссу первого максимума построенной гистограммы;
сравнивают в каждой из упомянутых предполагаемых строк расстояния между всеми соседними парами контуров текстовых символов с выбранным самым частым расстоянием;
разделяют в каждой из упомянутых предполагаемых строк любые два соседних контура текстового символа на вероятные слова, если расстояние между ними не меньше удвоенного упомянутого самого частого расстояния.
14. The method according to item 13, in which the division of the aforementioned alleged lines of text characters into probable words is carried out using the following operations:
find in each of the mentioned alleged lines the distances between all pairs of adjacent contours of text characters;
build a histogram of the frequencies of the distances found;
the abscissa of the first maximum of the constructed histogram is selected as the most frequent distance;
in each of the aforementioned alleged lines, comparing the distances between all adjacent pairs of contours of text characters with the selected most frequent distance;
in each of the alleged lines mentioned, divide any two adjacent contours of the text symbol into probable words, if the distance between them is not less than twice the mentioned most frequent distance.
15. Способ по п.8, в котором при распознавании фонового цвета подсчитывают в исходном изображении количество пикселов цвета, отличного от фонового, а после упомянутого исключения вероятных слов, в которых количество контуров текстовых символов не попадает в упомянутые вторые заранее заданные пределы, и предполагаемых строк, в которых количество вероятных слов не попадает в упомянутые третьи заранее заданные пределы, выполняют следующие операции:
подсчитывают в оставшемся изображении количество пикселов упомянутого цвета, отличного от фонового цвета;
вычисляют отношение подсчитанного количества пикселов упомянутого цвета, отличного от фонового цвета, к ранее подсчитанному количеству пикселов того же цвета в исходном двухцветном изображении;
исключают из дальнейшего рассмотрения изображение, если для него вычисленное в предыдущей операции отношение меньше четвертого заранее заданного предела.
15. The method according to claim 8, in which, when recognizing the background color, the number of color pixels in the source image is different from the background, and after the exclusion of the possible words, in which the number of contours of text characters does not fall within the said second predetermined limits, and the estimated lines in which the number of likely words does not fall within the mentioned third predetermined limits, perform the following operations:
counting in the remaining image the number of pixels of said color other than the background color;
calculating the ratio of the counted number of pixels of said color other than the background color to the previously counted number of pixels of the same color in the original two-color image;
exclude from further consideration the image if for him the ratio calculated in the previous operation is less than the fourth predetermined limit.
16. Способ выявления спама, содержащего растровое изображение, заключающийся в том, что:
осуществляют обнаружение текста в упомянутом растровом изображении по п.1 или 8;
формируют сигнатуру обнаруженного текста;
сравнивают сформированную сигнатуру с эталонными шаблонами спама, хранящимися в базе данных;
считают упомянутое растровое изображение спамом при совпадении с заранее заданной точностью сформированной сигнатуры с по меньшей мере одним эталонным шаблоном спама.
16. A method for detecting spam containing a raster image, which consists in the fact that:
detecting text in said raster image according to claim 1 or 8;
form the signature of the detected text;
comparing the generated signature with the reference spam patterns stored in the database;
consider the mentioned bitmap as spam, coinciding with a predetermined accuracy of the generated signature with at least one reference spam template.
17. Способ по п.16, в котором сигнатуру формируют на основе длин вероятных слов, оставшихся после сравнения с упомянутыми вторыми заранее заданными пределами. 17. The method according to clause 16, in which the signature is formed on the basis of the lengths of the likely words remaining after comparison with the said second predetermined limits.
RU2007140039/09A 2007-10-31 2007-10-31 Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images RU2363047C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2007140039/09A RU2363047C1 (en) 2007-10-31 2007-10-31 Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2007140039/09A RU2363047C1 (en) 2007-10-31 2007-10-31 Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images

Publications (2)

Publication Number Publication Date
RU2007140039A RU2007140039A (en) 2009-05-10
RU2363047C1 true RU2363047C1 (en) 2009-07-27

Family

ID=41019505

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2007140039/09A RU2363047C1 (en) 2007-10-31 2007-10-31 Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images

Country Status (1)

Country Link
RU (1) RU2363047C1 (en)

Cited By (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2453919C1 (en) * 2011-03-28 2012-06-20 Закрытое акционерное общество "Лаборатория Касперского" Method of detecting spam in bitmap image
RU2479028C2 (en) * 2011-03-21 2013-04-10 Федеральное государственное военное образовательное учреждение высшего профессионального образования ВОЕННО-КОСМИЧЕСКАЯ АКАДЕМИЯ им. А.Ф. Можайского Method of recognising graphic format message content
RU2632427C1 (en) * 2016-12-09 2017-10-04 Общество с ограниченной ответственностью "Аби Девелопмент" Optimization of data exchange between client device and server
RU2680358C1 (en) * 2018-05-14 2019-02-19 Федеральное государственное казенное военное образовательное учреждение высшего образования Академия Федеральной службы охраны Российской Федерации Method of recognition of content of compressed immobile graphic messages in jpeg format
RU2697737C2 (en) * 2016-10-26 2019-08-19 Федеральное государственное казенное военное образовательное учреждение высшего образования "Военный учебно-научный центр Военно-воздушных сил "Военно-воздушная академия имени профессора Н.Е. Жуковского и Ю.А. Гагарина" (г. Воронеж) Министерства обороны Российской Федерации Method of detecting and localizing text forms on images

Families Citing this family (2)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US8023697B1 (en) 2011-03-29 2011-09-20 Kaspersky Lab Zao System and method for identifying spam in rasterized images
CN110598211B (en) * 2019-09-02 2023-09-26 腾讯科技(深圳)有限公司 Article identification method and device, storage medium and electronic device

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US6470094B1 (en) * 2000-03-14 2002-10-22 Intel Corporation Generalized text localization in images
US6608930B1 (en) * 1999-08-09 2003-08-19 Koninklijke Philips Electronics N.V. Method and system for analyzing video content using detected text in video frames
US20040001634A1 (en) * 2002-06-28 2004-01-01 Microsoft Corporation Text detection in continuous tone image segments
RU2251151C2 (en) * 2002-12-17 2005-04-27 Аби Софтвер Лтд. Bitmap image analysis method
US20050281455A1 (en) * 2004-06-17 2005-12-22 Chun-Chia Huang System of using neural network to distinguish text and picture in images and method thereof

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US6608930B1 (en) * 1999-08-09 2003-08-19 Koninklijke Philips Electronics N.V. Method and system for analyzing video content using detected text in video frames
US6470094B1 (en) * 2000-03-14 2002-10-22 Intel Corporation Generalized text localization in images
US20040001634A1 (en) * 2002-06-28 2004-01-01 Microsoft Corporation Text detection in continuous tone image segments
RU2251151C2 (en) * 2002-12-17 2005-04-27 Аби Софтвер Лтд. Bitmap image analysis method
US20050281455A1 (en) * 2004-06-17 2005-12-22 Chun-Chia Huang System of using neural network to distinguish text and picture in images and method thereof

Cited By (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2479028C2 (en) * 2011-03-21 2013-04-10 Федеральное государственное военное образовательное учреждение высшего профессионального образования ВОЕННО-КОСМИЧЕСКАЯ АКАДЕМИЯ им. А.Ф. Можайского Method of recognising graphic format message content
RU2453919C1 (en) * 2011-03-28 2012-06-20 Закрытое акционерное общество "Лаборатория Касперского" Method of detecting spam in bitmap image
RU2697737C2 (en) * 2016-10-26 2019-08-19 Федеральное государственное казенное военное образовательное учреждение высшего образования "Военный учебно-научный центр Военно-воздушных сил "Военно-воздушная академия имени профессора Н.Е. Жуковского и Ю.А. Гагарина" (г. Воронеж) Министерства обороны Российской Федерации Method of detecting and localizing text forms on images
RU2632427C1 (en) * 2016-12-09 2017-10-04 Общество с ограниченной ответственностью "Аби Девелопмент" Optimization of data exchange between client device and server
RU2680358C1 (en) * 2018-05-14 2019-02-19 Федеральное государственное казенное военное образовательное учреждение высшего образования Академия Федеральной службы охраны Российской Федерации Method of recognition of content of compressed immobile graphic messages in jpeg format

Also Published As

Publication number Publication date
RU2007140039A (en) 2009-05-10

Similar Documents

Publication Publication Date Title
EP4099217B1 (en) Image processing model training method and apparatus, device, and storage medium
RU2363047C1 (en) Method of detecting text in bitmap image (versions) and method of detecting spam, containing bitmap images
CN104008384B (en) Character identifying method and character recognition device
CN104361312B (en) A kind of method and apparatus that character recognition is carried out to image
CN109343920B (en) Image processing method and device, equipment and storage medium thereof
JP7512523B2 (en) Video detection method, device, electronic device and storage medium
US11600088B2 (en) Utilizing machine learning and image filtering techniques to detect and analyze handwritten text
CN110866529A (en) Character recognition method, character recognition device, electronic equipment and storage medium
WO2021159802A1 (en) Graphical captcha recognition method, apparatus, computer device, and storage medium
US20190392606A1 (en) Object detection device, object detection method, and object detection program
KR102325347B1 (en) Apparatus and method of defect classification based on machine-learning
KR20150051711A (en) Apparatus and method for extracting skin area for blocking harmful content image
CN111461126A (en) Method, device, electronic device and storage medium for space recognition in text line
CN109583492A (en) A kind of method and terminal identifying antagonism image
RU2453919C1 (en) Method of detecting spam in bitmap image
CN114329475B (en) Training method, device and equipment for malicious code detection model
She et al. Progressive supervised pedestrian detection algorithm for green edge–cloud computing
US10521907B2 (en) Image processing apparatus, program, and radiation image capturing apparatus
CN110134924B (en) Overlapping text component extraction method and device, text recognition system and storage medium
CN110766003A (en) Detection method of fragment and link scene characters based on convolutional neural network
Maulana et al. Handwriting Classification of Sundanese Script Using LBP Feature Extraction and CNN
CN114187445A (en) Method and device for recognizing text in image, electronic equipment and storage medium
Nguyen et al. Tensor voting based text localization in natural scene images
Pramanik et al. Finding the optimum classifier: Classification of segmentable components in offline handwritten Devanagari words
Karasek et al. Genetic programming based classifier in viola-jones rapidminer image mining extension