[go: up one dir, main page]

RU2320011C1 - Method for automatic correction of red-eye effect - Google Patents

Method for automatic correction of red-eye effect Download PDF

Info

Publication number
RU2320011C1
RU2320011C1 RU2006123847/09A RU2006123847A RU2320011C1 RU 2320011 C1 RU2320011 C1 RU 2320011C1 RU 2006123847/09 A RU2006123847/09 A RU 2006123847/09A RU 2006123847 A RU2006123847 A RU 2006123847A RU 2320011 C1 RU2320011 C1 RU 2320011C1
Authority
RU
Russia
Prior art keywords
points
color
image
red
array
Prior art date
Application number
RU2006123847/09A
Other languages
Russian (ru)
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 RU2006123847/09A priority Critical patent/RU2320011C1/en
Application granted granted Critical
Publication of RU2320011C1 publication Critical patent/RU2320011C1/en

Links

Images

Landscapes

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

Abstract

FIELD: photographic equipment engineering, image processing methods, in particular, methods for automatically correcting red-eye effect.
SUBSTANCE: method includes analysis of additional information about an image; creation of at least one array for storing image point marks; for each image point a color mark is recorded into mark array, if the color of point is a typical color for red eyes and is not a typical color for human skin; filtration of one-component image; for each point of image a boundary mark is recorded into array of marks, and also filter number is recorded into array of marks; on basis of array of marks, connected areas of points are determined; for each connected area of points with consideration of neighborhood, computation of fixed row of features; on basis of features, classification of connected areas of points onto red-eye areas and false areas; connection to red-eye connected area of image points neighboring with points of given area and close in color; connection to connected area of red-eye of image points positioned inside external contour of given area; and change of color of points in connected red-eye area.
EFFECT: ensured high quality of automatic correction of red-eye effect.
10 cl, 8 dwg

Description

Заявляемое изобретение относится к области фотографической техники, а более конкретно к способам обработки изображений, в частности к методам автоматической коррекции эффекта красных глаз.The claimed invention relates to the field of photographic technology, and more particularly to methods of image processing, in particular to methods for automatically correcting red eye.

Большое количество любительских фотографий повреждено так называемым эффектом красных глаз, который часто возникает при фотографировании со вспышкой. Данный эффект значительно ухудшает впечатление от фотографии.A large number of amateur photographs are damaged by the so-called red-eye effect, which often occurs when photographing with a flash. This effect significantly impairs the impression of the photograph.

Большинство существующих инструментов коррекции красных глаз предполагают участие пользователя для локализации области красных глаз и/или выбора способа и параметров коррекции. Все существующие подходы для автоматического, т.е. без участия пользователя, включают, как минимум, 2 этапа: обнаружение областей красного глаза и коррекция этих областей. Этап обнаружения может включать в себя следующие действия: анализ дополнительной информации об изображении, сегментация областей, т.е. поиск связных областей точек, вычисление признаков, характеризующих области красных глаз, классификацию для исключения ложных областей, обнаружение лиц, обнаружение глаз, обнаружение характерного отблеска на зрачке, верификация пар глаз.Most existing red-eye correction tools require user involvement to localize the red-eye region and / or select a correction method and parameters. All existing approaches for automatic, i.e. without user intervention, include at least 2 stages: detection of red eye areas and correction of these areas. The detection step may include the following actions: analysis of additional information about the image, segmentation of areas, i.e. search for connected areas of points, calculation of signs characterizing the areas of red eyes, classification to exclude false areas, face detection, eye detection, detection of a characteristic reflection on the pupil, verification of pairs of eyes.

Основными проблемами при детектировании областей красных глаз являются следующие:The main problems in detecting red eye areas are as follows:

а. Цвета областей красных глаз могут значительно варьироваться:but. The colors of the red-eye areas can vary significantly:

от ярко оранжевого до пурпурного, от малинового до светло-фиолетового. Кроме того, существует отдельный тип эффекта красных глаз так называемые золотые глаза, которые выглядят как ярко-желтые или белые маленькие кружки.from bright orange to purple, from raspberry to light purple. In addition, there is a separate type of red-eye effect, the so-called golden eyes, which look like bright yellow or white small circles.

б. Иногда цвет областей красного глаза и цвет кожи человека получается одинаковым. Как правило, этот эффект вызван смешением красного цвета зрачка и белого цвета отблеска на зрачке, низкочастотной фильтрацией оптикой фотокамер, низкочастотной фильтрацией при JPEG сжатии, неправильным цветовым балансом.b. Sometimes the color of the areas of the red eye and the color of the skin of a person is the same. Typically, this effect is caused by a mixture of the red color of the pupil and the white color of the reflection on the pupil, low-pass filtering by camera optics, low-pass filtering with JPEG compression, and the wrong color balance.

В существующих методах сегментация областей осуществляется путем порогового отсечения в некотором цветовом пространстве: RGB (см. выложенную заявку на патент США №2004/0,228,542 [1]), Lab (см. патент США №6,873,743 [2]), YCbCr (см. выложенную заявку на патент США №2002/0,150,292 [3]). Часто пороговое отсечение осуществляют по специально вычисленному изображению, которое характеризует степень красноты (redness factor) точек изображения. Однако по причинам, изложенным выше, часто невозможно точно разделить точки, относящиеся к областям красных глаз и областям кожи человека.In existing methods, segmentation of regions is carried out by threshold clipping in a certain color space: RGB (see laid-out application for US patent No. 2004/0,228,542 [1]), Lab (see US patent No. 6,873,743 [2]), YCbCr (see laid out US patent application No. 2002 / 0,150,292 [3]). Often, threshold clipping is performed using a specially calculated image that characterizes the redness factor of the image points. However, for the reasons stated above, it is often impossible to accurately separate the points related to the areas of red eyes and areas of human skin.

Лучшие результаты сегментации получаются при применении к изображению, характеризующему степень красноты, согласованных фильтров или фильтров обнаружения границ. Так, например, в выложенной заявке на патент США №2004/0,213,476 [4] и в патенте США №6,204,858 [5] применяют симметричные согласованные фильтры, а в выложенной заявке на патент США №2004/0,114,829 [6] для обнаружения границ применяют морфологический оператор "tophat". В этих методах для обнаружения областей красных глаз разного размера требуется применение нескольких фильтров разного размера. Кроме того, данные методы хорошо детектируют только области округлой формы.The best segmentation results are obtained when applied to an image characterizing the degree of redness, matched filters or border detection filters. So, for example, in the laid out application for US patent No. 2004/0,213,476 [4] and in US patent No. 6,204,858 [5] symmetric matched filters are used, and in the laid out application for US patent No. 2004/0,114,829 [6] the morphological operator "tophat". In these methods, the detection of red eye regions of different sizes requires the use of several filters of different sizes. In addition, these methods only well detect areas of a rounded shape.

Приблизительно 70-80% фотографий людей, снятых со вспышкой, имеют отблеск на зрачке. Таким образом, отблеск является важным сопутствующим признаком эффекта красных глаз. На поиске отблеска основаны методы, описанные в выложенной заявке на патент США №2004/0,184,670 [7] и в патенте США №6,718,051 [8]. Многие источники утверждают, что на стадии коррекции желательно сохранять отблеск на зрачке, так как это улучшает впечатление от скорректированной фотографии.Approximately 70-80% of photographs of people taken with the flash have a reflection on the pupil. Thus, glare is an important concomitant symptom of red eye. The methods described in US Patent Application Laid-Open No. 2004/0,184,670 [7] and US Patent No. 6,718,051 [8] are based on the search for glare. Many sources claim that at the stage of correction it is desirable to maintain a reflection on the pupil, as this improves the impression of the corrected photograph.

Для классификации связных областей часто используют следующие признаки, указанные в [2]:For the classification of connected areas, the following features are often used, indicated in [2]:

- размеры и площадь,- dimensions and area,

- коэффициенты протяженности и округлости,- the coefficients of the length and roundness,

- коэффициент компактности,- compactness coefficient,

- локальный контраст,- local contrast,

- присутствие цветов, характерных для кожи человека,- the presence of colors characteristic of human skin,

- присутствие отблеска,- the presence of glare,

- присутствие белых точек, характерных для склеры,- the presence of white dots characteristic of the sclera,

- средние, минимальные и максимальные значения цветов.- average, minimum and maximum values of colors.

Для исключения из рассмотрения ложных областей используются как простые деревья решений, так и более сложные классификаторы, основанные на комитете простых классификаторов (см., например, выложенные заявки на патент США №2004/0,213,476 [4] и №2004/0,233,299[9]). Метод, описанный в [4], использует дополнительные признаки для обнаружения глаз. Метод, описанный в [9], использует два каскада классификаторов, обученных с помощью AdaBoost, первый каскад обнаруживает глаза, второй в области глаза детектирует область красного зрачка. Также в ряде существующих методов для уменьшения количества ложных срабатываний используется обнаружение лиц людей, основанное на алгоритме Виолы и Джонса (см. P.Viola, M.Jones, "Robust real-time object detection", 2nd international workshop on statistical and computational theories of vision - modeling, learning, computing, and sampling, 2002[10]), или на анализе областей цветов кожи человека (см. патент США №6,252,976 [11] и выложенную заявку на патент США №2003/0,202,105 [12]). Общим недостатком данных подходов является то, что они зависят от ориентации лица на изображении.To exclude false domains from consideration, both simple decision trees and more complex classifiers are used, based on a committee of simple classifiers (see, for example, laid-out patent applications US No. 2004/0,213,476 [4] and No. 2004/0,233,299 [9]) . The method described in [4] uses additional features to detect eyes. The method described in [9] uses two cascades of classifiers trained using AdaBoost, the first cascade detects the eyes, the second detects the area of the red pupil in the eye area. Also, in a number of existing methods, to reduce the number of false positives, people faces detection based on the Viola and Jones algorithm is used (see P. Viola, M. Jones, "Robust real-time object detection", 2nd international workshop on statistical and computational theories of vision - modeling, learning, computing, and sampling, 2002 [10]), or by analyzing the areas of human skin color (see US Patent No. 6,252,976 [11] and US Patent Application Laid-Open No. 2003/0,202,105 [12]). A common drawback of these approaches is that they depend on the orientation of the face in the image.

Еще одним подходом для уменьшения количества ложных срабатываний является верификация пар глаз, при которой каждой обнаруженной области ищется парная (см. [4] и патент США №6,292,5 74 [13]). Однако приблизительно на 5% фотографий есть только один красный глаз. Это происходит, например, при повороте головы или когда часть головы загорожена другими объектами. Таким образом, верификация пар не всегда применима.Another approach to reduce the number of false positives is the verification of pairs of eyes, in which each detected area is searched for a pair (see [4] and US patent No. 6,292,5 74 [13]). However, approximately 5% of photographs have only one red eye. This happens, for example, when turning the head or when part of the head is blocked by other objects. Thus, pair verification is not always applicable.

Во многих методах предварительно считывают информацию о вспышке из EXIF и осуществляют коррекцию, только если фотография получена со вспышкой (см. выложенную заявку на патент США №2003/0,044,178 [14] и патент США №6,895,112 [15]). Данный подход, несомненно, является полезным для уменьшения времени обработки и уменьшения количества ложных обнаружений.In many methods, flash information is preliminarily read from EXIF and corrected only if the photograph was taken with a flash (see US Patent Application Laid-Open No. 2003/0.044,178 [14] and US Patent No. 6,895,112 [15]). This approach is undoubtedly useful for reducing processing time and reducing the number of false detections.

Наиболее близким к заявляемому изобретению является решение [4].Closest to the claimed invention is a solution [4].

Задача, на решение которой направлено заявляемое изобретение, состоит в том, чтобы разработать усовершенствованный способ обработки изображений, позволяющий в автоматическом режиме детектировать и корректировать большое количество различных оттенков красных глаз с присутствием отблеска и без, в том числе некоторые так называемые золотые глаза. При этом новый способ должен обеспечивать высокое качество автоматического обнаружения, быть достаточно быстрым, быть применимым для любой цветовой системы и для произвольной ориентации лица на фотографии.The problem to which the claimed invention is directed is to develop an improved image processing method that automatically detects and corrects a large number of different shades of red eyes with or without glare, including some so-called golden eyes. Moreover, the new method should provide high quality automatic detection, be fast enough, be applicable to any color system and for arbitrary orientation of the face in the photo.

Поставленная задача решена за счет создания способа автоматической коррекции эффекта красных глаз на цифровых цветных изображениях, включающего в себя выполнение следующих операций:The problem is solved by creating a method for automatically correcting red-eye in digital color images, which includes the following operations:

- анализируют дополнительную информацию об изображении, при этом если вместе с изображением хранятся метаданные с информацией о вспышке, определяют, использовалась ли вспышка при фотографировании, если вспышка не использовалась, то изображение не корректируют;- analyze additional information about the image, while if metadata with information about the flash is stored with the image, it is determined whether the flash was used when photographing, if the flash was not used, the image is not corrected;

- создают, по меньшей мере, один массив для хранения меток точек изображения, равный размеру изображения, причем каждый элемент массива имеет взаимнооднозначное соответствие с точкой изображения;- create at least one array for storing labels of image points equal to the size of the image, and each element of the array has a one-to-one correspondence with the image point;

- для каждой точки изображения записывают в массив меток метку цвета, если цвет точки является цветом, типичным для красных глаз, и не является цветом, типичным для кожи человека;- for each point in the image, a color label is recorded in the tag array if the color of the point is a color typical of red eyes and is not a color typical of human skin;

- фильтруют однокомпонентное изображение, точки которого получают как функцию яркости и интенсивности компонент точек исходного цветного изображения, по меньшей мере, четырьмя ориентированными через равные углы направленными фильтрами для обнаружения границ, характерных для границ красных глаз, при этом для каждой точки изображения определяют максимальный результат фильтрации;- filtering a one-component image, the points of which are obtained as a function of the brightness and intensity of the components of the points of the source color image with at least four directional filters oriented at equal angles to detect borders characteristic of red-eye borders, and for each image point, the maximum filtering result is determined ;

- для каждой точки изображения записывают в массив меток метку границы, если максимальный результат фильтрации в этой точке больше порогового значения, а также записывают в массив меток номер фильтра, результат работы которого максимален;- for each point in the image, the border label is written to the label array if the maximum filtering result at this point is greater than the threshold value, and the filter number is recorded in the label array, the result of which is maximum;

- по массиву меток определяют связные области точек, для которых записана метка цвета или метка границы;- the connected areas of points for which a color mark or a border mark is recorded are determined by the array of marks;

- для каждой связной области точек с учетом окрестности вычисляют фиксированный ряд признаков;- for each connected region of points, taking into account the neighborhood, a fixed series of signs are calculated;

- на основе признаков классифицируют связные области точек на области красных глаз и ложные области;- based on the signs, the connected areas of the dots on the areas of red eyes and false areas are classified;

- присоединяют к связной области красного глаза точки изображения, соседние с точками данной области и близкие по цвету;- attach to the connected region of the red eye the image points adjacent to the points of the given area and close in color;

- присоединяют к связной области красного глаза точки изображения, расположенные внутри внешнего контура данной области;- attach to the connected region of the red eye, image points located inside the outer contour of this area;

- изменяют цвет точек связной области красного глаза.- change the color of the points of the connected region of the red eye.

В заявляемом способе точки красных глаз детектируют по цвету и по характерной границе двумя независимыми этапами, что позволяет детектировать больше различных оттенков красных глаз и повысить качество детектирования в целом.In the inventive method, red eye points are detected by color and by a characteristic boundary in two independent steps, which allows to detect more different shades of red eyes and improve the quality of detection as a whole.

В отличие от других методов для детектирования цветов, типичных для красных глаз, используют не пороговое ограничение в какой-либо предопределенной цветовой системе или в изображении, описывающем степень красноты цвета, а используют множества цветов, типичных для красных глаз и кожи человека, которые задаются несколькими известными аналитическими функциями или таблично.Unlike other methods for detecting colors typical of red eyes, they do not use a threshold restriction in any predefined color system or in an image describing the degree of redness of the color, but use many colors typical of red eyes and human skin, which are set by several known analytical functions or tabular.

В отличие от других методов для детектирования границ областей глаз используют не симметричные фильтры, а направленные фильтры, что позволяет детектировать области красных глаз разного размера без применения нескольких фильтров с ядрами разного размера и позволяет детектировать области красных глаз любой формы, а не только округлые.Unlike other methods, directional filters are used to detect the boundaries of the eye regions, but directional filters, which allows detecting the red-eye regions of different sizes without using several filters with nuclei of different sizes and allows detecting the red-eye regions of any shape, not just round ones.

К менее значимым улучшениям следует отнести:Less significant improvements include:

- изменение порога при детектировании границ красных глаз в зависимости от степени типичности того, что данный цвет является цветом кожи человека или цветом красных глаз;- a change in the threshold when detecting the boundaries of red eyes, depending on the degree of typicality that this color is the color of a person’s skin or the color of red eyes;

- использование при классификации признаков, основанных на результатах работы направленных фильтров детектирования границ.- use in classifying features based on the results of directional border detection filters.

Для лучшего понимания существа заявляемого изобретения оно поясняется далее с привлечением чертежей.For a better understanding of the essence of the claimed invention, it is explained below with the help of drawings.

Фиг.1. Схема основных компонентов системы, реализующей заявляемый способ.Figure 1. Scheme of the main components of a system that implements the inventive method.

Фиг.2. Алгоритм заявляемого способа.Figure 2. The algorithm of the proposed method.

Фиг.3. Таблица, задающая в цветовой системе YCbCr множество цветов, характерных для красных глаз.Figure 3. A table that defines the YCbCr color system with a variety of colors that are characteristic of red eyes.

Фиг.4. Таблица, задающая в цветовой системе YCbCr множество цветов, характерных для кожи человека.Figure 4. A table that sets the YCbCr color system to the set of colors characteristic of human skin.

Фиг.5. Таблица с данными для построения классификатора.Figure 5. A table with data for constructing a classifier.

Фиг.6. График функции изменения яркости при коррекции.6. Graph of the function of changing the brightness during correction.

Фиг.7. Пример выполнения заявляемого способа.7. An example of the implementation of the proposed method.

Заявляемое изобретение предлагает способ автоматической, т.е. без участия человека, коррекции эффекта красных глаз на цифровых изображениях. Данный способ может обрабатывать цветные изображения в любой цветовой системе. Одним из предпочтительных вариантов реализации способа является обработка изображения в цветовой системе YCbCr, которая описана в стандарте сжатия JPEG. Все численные данные, приведенные в этом описании, даны для цветовой системы YCbCr и глубины цвета 24 бит на точку (пиксел) по 8 бит на каждую компоненту цвета, но специалистам ясно, что можно пересчитать соответствующие данные для других цветовых систем и глубины цвета.The claimed invention provides an automatic method, i.e. without human intervention, red-eye correction in digital images. This method can process color images in any color system. One of the preferred embodiments of the method is image processing in the YCbCr color system, which is described in the JPEG compression standard. All the numerical data given in this description is given for the YCbCr color system and a color depth of 24 bits per dot (pixel) of 8 bits for each color component, but it is clear to specialists that it is possible to recalculate the corresponding data for other color systems and color depth.

Фиг.1 показывает основные компоненты системы, на которой данный способ может быть реализован. Работа способа управляется процессором 101, который выполняет программный код, хранящийся в памяти 102. Также в памяти 102 хранится исходное цветное цифровое изображение. Изображение анализируется и корректируется. Результат коррекции передается на устройство 103 отображения и на устройство 104 печати. Передача информации в системе осуществляется по шине 105 данных.Figure 1 shows the main components of the system on which this method can be implemented. The operation of the method is controlled by a processor 101, which executes program code stored in the memory 102. Also, the original color digital image is stored in the memory 102. The image is analyzed and adjusted. The correction result is transmitted to the display device 103 and to the print device 104. Information is transmitted in the system via data bus 105.

На фиг.2 приведена блок-схема этапов работы способа, т.е. алгоритм выполнения способа. На шаге 201 анализируют дополнительную информацию об изображении, при этом если вместе с изображением хранят метаданные с информацией о вспышке, определяют, использовалась ли вспышка при фотографировании, если вспышка не использовалась, то изображение не корректируют. Дополнительная информация об изображении или так называемые метаданные могут храниться в одном файле данных вместе с изображением в соответствии со стандартами EXIF и/или P.I.M. Если метаданные присутствуют в файле, и в них доступна информация о состоянии вспышки при регистрации данного изображения, и известно, что вспышка не использовалась, то делают вывод, что условий для возникновения эффекта красных глаз нет, красные глаза на изображении отсутствуют, способ заканчивает работу. В противном случае предполагают, что присутствие эффекта красных глаз возможно, на основании этого вывода осуществляют детектирование и коррекцию областей красных глаз.Figure 2 shows the block diagram of the stages of the method, i.e. the algorithm for performing the method. At step 201, additional image information is analyzed, if metadata with flash information is stored with the image, it is determined whether the flash was used when photographing, if the flash was not used, the image is not corrected. Additional image information or so-called metadata can be stored in a single data file with the image in accordance with EXIF and / or P.I.M. If the metadata is present in the file, and information about the state of the flash when registering this image is available, and it is known that the flash was not used, then they conclude that there are no conditions for the occurrence of red eyes, there are no red eyes in the image, the method ends. Otherwise, it is assumed that the presence of the red-eye effect is possible, based on this conclusion, the detection and correction of the red-eye regions is carried out.

На шаге 202 создают, по меньшей мере, один массив для хранения меток точек (т.н. пикселов) изображения, равный размеру изображения, причем каждый элемент массива имеет взаимнооднозначное соответствие с точкой изображения, причем для каждой точки изображения имеется возможность записать в массив меток несколько меток одновременно.At step 202, at least one array is created for storing labels of points (so-called pixels) of the image equal to the size of the image, each element of the array having a one-to-one correspondence with the image point, and for each image point it is possible to write to the array of labels multiple tags at the same time.

На шаге 203 для каждой точки изображения записывают в массив меток метку цвета, если цвет точки является цветом, типичным для красных глаз, и не является цветом, типичным для кожи человека. Множества цветов, типичных для красных глаз и кожи человека, задаются таблично, причем данные множества могут пересекаться. На фиг.3 приведен массив, который содержит данные о степени типичности того, что данный цвет является цветом кожи человека. Степень типичности задается числом от 0 до 3, где 3 означает, что данный цвет очень типичен для кожи человека, 0 - данный цвет не типичен для кожи человека, 1 и 2 означают промежуточные значения. Массив с фиг.3 показан в виде двумерной таблицы, но его следует рассматривать как одномерный массив: строка таблицы за строкой размера 128 двойных слов (двойное слово хранит 32 бита). Для кодирования степени типичности используется 2 бита. Числа в таблице приведены в шестнадцатеричной системе счисления. Для получения степени типичности skin_typicalness с помощью массива skin_typicalness_array с фиг.3 по значениям цвета Y, Cb, Cr используют следующий способ:In step 203, for each point in the image, a color mark is written to the tag array if the point color is a color typical of red eyes and is not a color typical of human skin. The sets of colors typical of red eyes and human skin are tabulated, and these sets may intersect. Figure 3 shows an array that contains data on the degree of typicality that this color is the color of human skin. The degree of typicality is set by a number from 0 to 3, where 3 means that this color is very typical of human skin, 0 - this color is not typical of human skin, 1 and 2 mean intermediate values. The array of FIG. 3 is shown as a two-dimensional table, but it should be considered as a one-dimensional array: a row of a table after a row of size 128 double words (a double word stores 32 bits). 2 bits are used to encode the degree of typicality. The numbers in the table are given in hexadecimal notation. To obtain the typicality of skin_typicalness using the skin_typicalness_array array of FIG. 3, the following method is used according to the color values Y, Cb, Cr:

Если Cr<111 или Cb<30 или Cb>174, то степень типичности равна нулю,If Cr <111 or Cb <30 or Cb> 174, then the degree of typicality is zero,

иначе:otherwise:

Cb=(Cb-30)/9;Cb = (Cb-30) / 9;

Cr=(Cr-111)/9;Cr = (Cr-111) / 9;

idx=(Cr SHL 7)OR(Cb SHL 3)OR(Y SHR 5);idx = (Cr SHL 7) OR (Cb SHL 3) OR (Y SHR 5);

skin_typicalness=(skin_typicalness _array[idx SHR 4] SHR ((idx AND 15) SHL 1)) AND 3;skin_typicalness = (skin_typicalness _array [idx SHR 4] SHR ((idx AND 15) SHL 1)) AND 3;

где SHL - арифметический сдвиг влево, SHR - арифметический сдвиг вправо, AND - побитовое логическое И, OR - побитовое логическое ИЛИ, операция [] - извлечение элемента из массива по индексу, первый элемент массива имеет индекс 0.where SHL is an arithmetic shift to the left, SHR is an arithmetic shift to the right, AND is a bitwise logical AND, OR is a bitwise logical OR, operation [] is to retrieve an element from an array by index, the first element of the array has index 0.

На фиг.4 приведен массив, который содержит данные о степени типичности того, что данный цвет является цветом красных глаз - red_typicalness. Данный массив организован аналогично массиву степени типичности цвета кожи человека, работа с данным массивом также осуществляется полностью идентично. Таким образом, метка цвета записывается в массив меток, если skin_typicalness равно нулю и red_typicalness больше единицы.Figure 4 shows an array that contains data on the degree of typicality that this color is the color of red eyes - red_typicalness. This array is organized similarly to an array of the degree of typicality of a person’s skin color, work with this array is also completely identical. Thus, the color label is written to the labels array if skin_typicalness is zero and red_typicalness is greater than one.

Следует отметить, что в рамках данного изобретения множества цветов, типичных для красных глаз и кожи человека, могут быть ограничены набором аналитических функций, причем данные множества могут пересекаться. Примером может служить набор функций для детектирования цветов кожи человека, приведенный в статье G.Gomez, E.Morales, Automatic feature construction and a simple rule induction algorithm for skin detection, proc. of the ICML Workshop on Machine Learning in Computer Vision, pp.31-38, 2002. [16].It should be noted that in the framework of this invention, the set of colors typical of red eyes and human skin may be limited by a set of analytical functions, and these sets may intersect. An example is the set of functions for detecting color of human skin, as described in G. Gomez, E. Morales, Automatic feature construction and a simple rule induction algorithm for skin detection, proc. of the ICML Workshop on Machine Learning in Computer Vision, pp. 31-38, 2002. [16].

На шаге 204 фильтруют однокомпонентное изображение, точки которого получают как функцию яркости и интенсивности компонент точек исходного цветного изображения, по меньшей мере, четырьмя ориентированными через равные углы направленными фильтрами для обнаружения границ, характерных для границ красных глаз, при этом для каждой точки изображения определяют максимальный результат фильтрации. В предпочтительном варианте реализации изобретения в качестве направленных фильтров для обнаружения границ используют отношения сумм точек соседних равного размера прямоугольных фрагментов однокомпонентного изображения, точки которого получают как функцию яркости и интенсивности компонент точек исходного изображения в соответствии со следующими формулами:At step 204, a one-component image is filtered, the points of which are obtained as a function of the brightness and intensity of the components of the points of the source color image with at least four directional filters oriented at equal angles to detect borders characteristic of red-eye borders, and the maximum filtering result. In a preferred embodiment of the invention, the directional filters for detecting boundaries use the ratio of the sums of points of neighboring equal-sized rectangular fragments of a single-component image, the points of which are obtained as a function of the brightness and intensity of the components of the points of the original image in accordance with the following formulas:

Figure 00000002
Figure 00000002

Figure 00000003
Figure 00000003

Figure 00000004
Figure 00000004

Figure 00000005
Figure 00000005

где фильтрация осуществляется по всем точкам изображения, r - номер строки, с - номер столбца, Y и Cr - компоненты изображения. Единица в числителе добавляется для предотвращения сингулярности.where filtering is performed for all points of the image, r is the row number, c is the column number, Y and Cr are the image components. A unit in the numerator is added to prevent singularity.

Следует отметить, что в качестве направленных фильтров для обнаружения границ можно использовать курсовые градиентные фильтры, описанные, например, в У.Прэтт "Цифровая обработка изображений" в 2-х томах, М., "Мир", 1982 [17], применяемые к однокомпонентному изображению, точки которого получают как функцию яркости и интенсивности компонент точек исходного изображения.It should be noted that as directional filters for detecting boundaries, course gradient filters can be used, described, for example, in U. Pratt "Digital Image Processing" in 2 volumes, M., Mir, 1982 [17], applied to a single-component image whose points are obtained as a function of the brightness and intensity of the components of the points of the original image.

На шаге 205 для каждой точки изображения записывают в массив меток метку границы, если максимальный из результатов фильтрации E1(r,c), Е2(r,c), Е3(r,c) или Е4(r,с) больше порогового значения Т, а также записывают в массив меток номер фильтра, результат работы которого максимален. Данный шаг позволяет обнаруживать точки красных глаз, цвет которых близок к цвету кожи человека, и так называемые "золотые глаза". Кроме того, данный подход позволяет на шаге 207 вычислить информативные признаки для последующей классификации областей.At step 205, for each image point is recorded in an array of labels mark boundaries, if the maximum of the filter results E 1 (r, c), E 2 (r, c), e 3 (r, c) or E4 (r, s) more than the threshold value of T, and also record the filter number in the array of labels, the result of which is maximum. This step allows you to detect points of red eyes, the color of which is close to the color of human skin, and the so-called "golden eyes". In addition, this approach allows at step 207 to calculate informative features for the subsequent classification of areas.

Пороговое значение Т не является постоянным для всех точек изображения, а увеличивается, если цвет точки является цветом, типичным для кожи человека, и уменьшается, если цвет точки является цветом, типичным для красных глаз. Используется следующее правило: если степень типичности skin_typicalness того, что данный цвет является цветом кожи человека, больше 1, то Т=1,09, иначе, если степень типичности red_typicalness того, что данный цвет является цветом красных глаз, больше 1, то Т=1,07, иначе Т=1,08.The threshold value of T is not constant for all points of the image, but increases if the color of the point is a color typical of human skin, and decreases if the color of the point is a color typical of red eyes. The following rule is used: if the degree of typicality of skin_typicalness that a given color is the color of a person’s skin is greater than 1, then T = 1.09, otherwise, if the degree of typicality of red_typicalness that this color is a color of red eyes is greater than 1, then T = 1.07, otherwise T = 1.08.

На шаге 206 по массиву меток определяют связные области точек, для которых записана метка цвета или метка границы. В наиболее предпочтительном варианте изобретения используется критерий 8-связности. Каждой точке каждой связной области присваивается номер области. Для определения связных областей точек используют один из широко известных алгоритмов заполнения области цветом, описанный, например, в J.D.Foley, A.van Dam, S.K.Feiner, J.F.Hughes "Computer graphics: principles and practice", 2nd edition, Addison-Wesley pub., 1990 [18].At step 206, the connected areas of the points for which a color mark or border mark is recorded are determined from the marks array. In a most preferred embodiment of the invention, the 8-connectivity criterion is used. Each point in each connected region is assigned a region number. To determine the regions of connected pixels using one of well-known algorithms fill color field, described for example in JDFoley, A.van Dam, SKFeiner, JFHughes "Computer graphics: principles and practice", 2 nd edition, Addison-Wesley pub, 1990. [eighteen].

На шаге 207 для каждой связной области точек с учетом окрестности вычисляют ряд признаков. Пусть (r1, c1) - координаты левого верхнего угла прямоугольника, описывающего связную область точек, (r2, c2) - координаты правого нижнего угла. Пусть p(r, c) - функция, которая равна 1, если точка с координатами (r, с) принадлежит объекту, и равна 0 в противном случае. Вычисляют следующие признаки:At step 207, for each connected region of points, taking into account the neighborhood, a number of features are calculated. Let (r1, c1) be the coordinates of the upper left corner of the rectangle describing the connected region of points, (r2, c2) be the coordinates of the lower right corner. Let p (r, c) be a function that is equal to 1 if the point with coordinates (r, c) belongs to the object and is equal to 0 otherwise. The following symptoms are calculated:

N - общее количество точек связной области.N is the total number of points in the connected region.

Nr - количество точек связной области, помеченных меткой цвета.Nr - the number of points in the connected area marked with a color label.

N1, N2, N3 и N4 - количество точек связной области, помеченных каждым из направленных фильтров.N1, N2, N3 and N4 - the number of points in the connected area marked by each of the directed filters.

Размеры описывающего прямоугольника:Description Rectangle Dimensions:

L=c2-c1; W=r2-r1.L = c2-c1; W = r2-r1.

Коэффициент компактности:Compactness factor:

Kc=N/(L×W).Kc = N / (L × W).

Коэффициент удлинения 1:Elongation Ratio 1:

Ke1=min(L, W)/max(L, W).Ke1 = min (L, W) / max (L, W).

Количество направленных фильтров, номера которых записаны в массиве меток для данной связной области точек:The number of directional filters, the numbers of which are recorded in the array of labels for this connected area of points:

М=sign(N1)+sign(N2)+sign(N3)+sign(N4).M = sign (N1) + sign (N2) + sign (N3) + sign (N4).

Отношение максимального из количеств точек области, помеченных каждым из направленных фильтров, к общему количеству точек области:The ratio of the maximum of the number of points in the region, marked with each of the directed filters, to the total number of points in the region:

Ка=max(N1, N2, N3, N4)/N.Ka = max (N1, N2, N3, N4) / N.

Коэффициент удлинения 2:Elongation Ratio 2:

Figure 00000006
Figure 00000006

где Ipq - центральные моменты порядка p+q, которые вычисляются как:where I pq are the central moments of order p + q, which are calculated as:

Figure 00000007
Figure 00000007

где (rm, cm) - координаты центра масс, которые вычисляются как:where (rm, cm) are the coordinates of the center of mass, which are calculated as:

Figure 00000008
Figure 00000008

Figure 00000009
Figure 00000009

Доля точек в окрестности связной области, цвет которых типичен для цвета кожи человека, Ks:The proportion of points in the vicinity of the cohesive region, the color of which is typical of human skin color, Ks:

Figure 00000010
Figure 00000010

Figure 00000011
Figure 00000011

Figure 00000012
Figure 00000012

Figure 00000013
Figure 00000013

Ks=max(S1+S2, S2+S3, S3+S4, S4+S1)/2,Ks = max (S 1 + S 2 , S 2 + S 3 , S 3 + S 4 , S 4 + S 1 ) / 2,

где функция ts(r, c) равна 1, если степень типичности skin_typicalness того, что данный цвет является цветом кожи человека, больше 1, и равна 0 в противном случае.where the function ts (r, c) is equal to 1 if the degree of typicality of skin_typicalness that this color is the color of human skin is greater than 1, and equal to 0 otherwise.

Доля точек в описывающем связную область прямоугольнике, цвет которых типичен для блика:The proportion of points in a rectangle describing a connected region whose color is typical of glare:

Figure 00000014
Figure 00000014

где функция tg(r, c) равна 1, если Y(r, c)>240 и Cb(r, c)>100 и Cb(r, c)<156 и Cr(r, c)>100 и Cr(r, c)<156, и равна 0 в противном случае. Средняя яркость точек связной области:where the function tg (r, c) is 1 if Y (r, c)> 240 and Cb (r, c)> 100 and Cb (r, c) <156 and Cr (r, c)> 100 and Cr ( r, c) <156, and is 0 otherwise. The average brightness of the points of the connected area:

Figure 00000015
Figure 00000015

Средняя яркость точек в окрестности связной области:The average brightness of the points in the vicinity of the connected region:

Figure 00000016
Figure 00000016

Среднее значение компоненты Cr точек в окрестности связной области:The average value of the component Cr of points in a neighborhood of a connected region:

Figure 00000017
Figure 00000017

На шаге 208 на основе признаков классифицируют связные области точек на области красных глаз и ложные области, которые далее не рассматриваются. При классификации используют каскад классификаторов. Сначала применяют несколько простых классификаторов, основанных на сравнении значений признаков с пороговыми значениями. Целью данных классификаторов является исключение очевидно ложных областей. Затем для классификации областей красных глаз применяют классификатор, основанный на взвешенном голосовании комитета простых классификаторов.In step 208, the connected areas of the dots on the red-eye and the false areas, which are not considered further, are classified based on the signs. When classifying a cascade of classifiers is used. First, several simple classifiers are used, based on a comparison of the values of the characteristics with threshold values. The purpose of these classifiers is to eliminate obviously false areas. Then, a classifier is used to classify red eye areas, based on a weighted vote of a committee of simple classifiers.

Первым простым классификатором каскада является правило: если Nr=0 или М<2, то область исключается из рассмотрения. Данное условие позволяет на порядок и более уменьшить количество анализируемых связных областей, но при этом ошибочно исключаются из рассмотрения приблизительно 3% областей красных глаз.The first simple classifier of the cascade is the rule: if Nr = 0 or M <2, then the region is excluded from consideration. This condition allows decreasing the number of analyzed connected regions by an order of magnitude or more, but approximately 3% of the red-eye regions are erroneously excluded from consideration.

Для исключения очевидно ложных областей используют следующие наборы правил, которые различаются в зависимости от общего количества точек области:To exclude obviously false areas, the following rule sets are used, which differ depending on the total number of points in the area:

если N>150 и (М<4 или Ке1<0.4 или Кс<0.3 или Ка>0.5), то область исключается из рассмотрения, иначе если N>75 и (М<3 или Ке1<0.35 или Кс<0.2 или Кс>0.9 или Ка>0.65), то область исключается из рассмотрения, иначе если Ке1<0.3 или Кс<0.2, то область исключается из рассмотрения.if N> 150 and (M <4 or Ke1 <0.4 or Ks <0.3 or Ka> 0.5), then the region is excluded from consideration, otherwise if N> 75 and (M <3 or Ke1 <0.35 or Ks <0.2 or Ks> 0.9 or Ka> 0.65), then the region is excluded from consideration, otherwise if Ke1 <0.3 or Kc <0.2, then the region is excluded from consideration.

В следующем классификаторе используют правило, основанное на антропометрических соотношениях между размерами головы и зрачка человека. Известно, что диаметр зрачка составляет до 1/15 от ширины головы в зависимости от возраста и расы человека. Предполагается, что максимальный размер зрачка получается при портретной съемке, то есть когда все поле изображения занимает голова человека. Пусть XSize -горизонтальный размер изображения, a YSize - вертикальный размер изображения. Тогда условие для исключения областей:The following classifier uses a rule based on anthropometric ratios between the size of a person’s head and pupil. It is known that the diameter of the pupil is up to 1/15 of the width of the head, depending on the age and race of the person. It is assumed that the maximum pupil size is obtained with portrait shooting, that is, when the entire head of the image is occupied by a person’s head. Let XSize be the horizontal size of the image and YSize the vertical size of the image. Then the condition for excluding areas:

если W>min(XSize, YSize)/15 или L>min(XSize, YSize)/15, то область исключается из рассмотрения.if W> min (XSize, YSize) / 15 or L> min (XSize, YSize) / 15, then the area is excluded from consideration.

Затем для классификации областей красных глаз применяют классификатор Gentle AdaBoost, основанный на взвешенном голосовании комитета простых классификаторов (см. J.Friedman, T.Hastie, R.Tibshirani. Additive logistic regression: A statistical view of boosting. The Annals of Statistics, 38(2):337-374, April 2000. [19]). Таблица на фиг.5 содержит данные для построения классификатора. Связная область считается областью красного глаза, еслиThen, the Gentle AdaBoost classifier is used to classify red eye areas, based on a weighted vote of a committee of simple classifiers (see J. Friedman, T. Hastie, R. Tibshirani. Additive logistic regression: A statistical view of boosting. The Annals of Statistics, 38 ( 2): 337-374, April 2000. [19]). The table in figure 5 contains data for constructing a classifier. The connected area is considered to be the area of the red eye if

Figure 00000018
Figure 00000018

где wl(i) равно 1, если b(i)×Feature(i)>b(i) x Th(i), и 0 в противном случае, где Feature(i) есть признак, указанный во втором столбце и i-й строке таблицы. Изменение Тр позволяет регулировать соотношение ошибок первого и второго рода. В наиболее предпочтительном варианте изобретения Тр=-0,1, при этом правильно классифицируется 97,5% областей.where wl (i) is equal to 1 if b (i) × Feature (i)> b (i) x Th (i), and 0 otherwise, where Feature (i) is the characteristic indicated in the second column and i- th row of the table. Changing Tp allows you to adjust the ratio of errors of the first and second kind. In the most preferred embodiment of the invention, Tr = -0.1, while 97.5% of the regions are correctly classified.

Следует отметить, что для данного набора признаков близкие результаты классификации дают классификаторы Real AdaBoost (см. R.E. Schapire, Y.Singer, Improved boosting algorithms using confidence-rated predictions. Machine Learning, 37(3):297-336, 1999 [20], также основанные на взвешенном голосовании комитета простых классификаторов, и классификатор, основанный на методе опорных векторов, в котором используется экспоненциальная ядерная функция V.N.Vapnik, Statistical Learning Theory, John Wiley and Sons publ., 1998 [21]).It should be noted that for this set of attributes, close classification results are obtained by the Real AdaBoost classifiers (see RE Schapire, Y.Singer, Improved boosting algorithms using confidence-rated predictions. Machine Learning, 37 (3): 297-336, 1999 [20] , also based on a weighted vote of a committee of simple classifiers, and a classifier based on the support vector method, which uses the exponential nuclear function VNVapnik, Statistical Learning Theory, John Wiley and Sons publ., 1998 [21]).

На шаге 209 присоединяют к связной области красного глаза точки изображения соседние с точками данной области и близкие по цвету. Этот шаг необходим, чтобы присоединить к связной области розовые и фиолетовые оттенки, которые часто образуются на границе красной области из-за смешения красного цвета зрачка и цветов радужной оболочки глаза и/или отблеска на зрачке. Способ присоединения следующий: вычисляют среднее значение яркости Y и среднее значение компоненты Cr для точек области Ym, Crm; если точка с координатами (r, с) не является точкой области и, по меньшей мере, 2 соседние точки принадлежат области, то вычисляется расстояние между (Y(r, c), Cr(r, c)) и (Ym, Crm), и если это расстояние меньше порога Td, то точку с координатами (r, с) помечают как присоединяемую. Все помеченные точки присоединяются в конце итерации. Выполняют несколько итераций. Если в конце итерации ни одна точка не помечена как присоединяемая, то итерации прекращают. В наиболее предпочтительном варианте реализации изобретения Td=30 и выполняют 5 итераций присоединения.At step 209, image points adjacent to the points of the given region and similar in color are connected to the connected region of the red eye. This step is necessary to attach pink and violet shades to the connected area, which are often formed at the border of the red area due to the mixing of the red color of the pupil and the colors of the iris and / or glare on the pupil. The connection method is as follows: calculate the average value of the brightness Y and the average value of the component Cr for points in the region Ym, Crm; if the point with coordinates (r, c) is not a point of the region and at least 2 neighboring points belong to the region, then the distance between (Y (r, c), Cr (r, c)) and (Ym, Crm) is calculated , and if this distance is less than the threshold Td, then the point with coordinates (r, c) is marked as joinable. All marked points are attached at the end of the iteration. Perform several iterations. If at the end of the iteration no points are marked as joinable, then the iterations are stopped. In a most preferred embodiment, Td = 30 and 5 attachment iterations are performed.

На шаге 210 присоединяют к связной области красного глаза точки изображения, расположенные внутри внешнего контура данной области. Для этого применяют алгоритм заполнения области цветом, такой же, как на шаге 206. Данный шаг необходим для присоединения к связной области точек отблеска и различных внутренних точек, цвет которых в результате шумов или JPEG сжатия исказился и перестал быть типичным для области красного глаза.At step 210, image points located inside the outer contour of the area are connected to the connected region of the red eye. To do this, apply the algorithm for filling the area with color, the same as in step 206. This step is necessary to attach to the connected area the gleam points and various internal points, the color of which as a result of noise or JPEG compression has distorted and ceased to be typical of the red eye area.

На шаге 211 непосредственно корректируют изображение, то есть изменяют цвет точек связной области красного глаза. Коррекция заключается в преобразовании точек в серый цвет, их затемнении и смешивании с исходным изображением в соответствии со следующими формулами:At step 211, the image is directly corrected, that is, the color of the dots of the connected region of the red eye is changed. The correction consists in converting the dots to gray, darkening them and mixing them with the original image in accordance with the following formulas:

Y(r, с)=f(Y(r, с))×α(r, с)+Y(r, с)×(1-α(r, с)),Y (r, s) = f (Y (r, s)) × α (r, s) + Y (r, s) × (1-α (r, s)),

Cb(r, с)=128×α(r, с)+Cb(r, с)×(1-α(r, с)),Cb (r, s) = 128 × α (r, s) + Cb (r, s) × (1-α (r, s)),

Cr(r, с)=128×α(r, с)+Cr(r, с)×(1-α(r, с)),Cr (r, s) = 128 × α (r, s) + Cr (r, s) × (1-α (r, s)),

где коррекцию осуществляют для всех точек связной области красного глаза, функция f(Y(r,c)) уменьшает яркость точки с координатами (r,с), вид функции показан на фиг.6, α(r,c)=Nn/8, где Nn - число соседних точек точки с координатами (r, с), которые относятся к данной связной области.where the correction is carried out for all points of the connected region of the red eye, the function f (Y (r, c)) reduces the brightness of the point with coordinates (r, c), the form of the function is shown in Fig. 6, α (r, c) = Nn / 8 , where Nn is the number of neighboring points of the point with coordinates (r, s) that belong to this connected region.

В отдельных вариантах реализации способа целесообразно записывать информацию об проведенной коррекции красных глаз в метаданные с целью предотвращения повторной обработки одного и того же изображения.In certain embodiments of the method, it is advisable to record information about the red-eye correction performed in the metadata in order to prevent reprocessing of the same image.

На фиг.7 показан пример коррекции: 7.1 - исходное изображение, 7.2 - скорректированное изображение.Figure 7 shows an example of correction: 7.1 is the original image, 7.2 is the corrected image.

Предложенный метод предназначен для реализации в различных устройствах, регистрирующих, отображающих или печатающих фотографии, или в программном обеспечении для редактирования и обработки изображений. В частности, возможно применение данного способа в фотопринтерах и МФУ, имеющих возможность сканировать и копировать фотографии, в цифровых фотокамерах, мобильных телефонах, оборудованных цифровыми камерами со вспышкой, в камкордерах (т.е. видеокамерах), оборудованных вспышкой, в электронных фоторамках, предназначенных для хранения и показа цифровых фотографий, в фотокиосках, в цифровых фотолабораториях, в программном обеспечении для редактирования и обработки изображений.The proposed method is intended for implementation in various devices that register, display or print photos, or in software for editing and image processing. In particular, it is possible to use this method in photo printers and MFPs that can scan and copy photos, in digital cameras, mobile phones equipped with digital cameras with flash, camcorders (i.e. video cameras) equipped with flash, in electronic photo frames designed for storing and displaying digital photographs, in kiosks, in digital photo laboratories, in image editing and processing software.

Claims (10)

1. Способ автоматической коррекции эффекта красных глаз на цифровых цветных изображениях, включающий в себя выполнение следующих операций:1. A method of automatically correcting red eye in digital color images, including the following operations: анализируют дополнительную информацию об изображении, при этом если вместе с изображением хранятся метаданные с информацией о вспышке, определяют, использовалась ли вспышка при фотографировании, если вспышка не использовалась, то изображение не корректируют;analyze additional information about the image, while if metadata with information about the flash is stored with the image, it is determined whether the flash was used when photographing, if the flash was not used, the image is not corrected; создают, по меньшей мере, один массив для хранения меток точек изображения, равный размеру изображения, причем каждый элемент массива имеет взаимнооднозначное соответствие с точкой изображения;creating at least one array for storing image point labels equal to the size of the image, wherein each element of the array has a one-to-one correspondence with the image point; для каждой точки изображения записывают в массив меток метку цвета, если цвет точки является цветом, типичным для красных глаз, и не является цветом, типичным для кожи человека;for each point in the image, a color label is written to the tag array if the color of the point is a color typical of red eyes and is not a color typical of human skin; фильтруют однокомпонентное изображение, точки которого получают как функцию яркости и интенсивности компонент точек исходного цветного изображения, по меньшей мере, четырьмя ориентированными через равные углы направленными фильтрами для обнаружения границ, характерных для границ красных глаз, при этом для каждой точки изображения определяют максимальный результат фильтрации;filtering a one-component image, the points of which are obtained as a function of the brightness and intensity of the components of the points of the source color image, by at least four directional filters oriented at equal angles to detect borders characteristic of red-eye borders, and for each image point, the maximum filtering result is determined; для каждой точки изображения записывают в массив меток метку границы, если максимальный результат фильтрации в этой точке больше порогового значения, а также записывают в массив меток номер фильтра, результат работы которого максимален;for each point in the image, a border label is written to the label array if the maximum filtering result at this point is greater than the threshold value, and the filter number is recorded in the label array, the result of which is maximum; по массиву меток определяют связные области точек, для которых записана метка цвета или метка границы;by the array of labels, the connected areas of points are determined for which a color label or border label is recorded; для каждой связной области точек с учетом окрестности вычисляют фиксированный ряд признаков;for each connected region of points, taking into account the neighborhood, a fixed series of features is calculated; на основе признаков классифицируют связные области точек на области красных глаз и ложные области;on the basis of signs, the connected areas of points on the areas of red eyes and false areas are classified; присоединяют к связной области красного глаза точки изображения, соседние с точками данной области и близкие по цвету;attach to the connected region of the red eye dots of the image adjacent to the dots of this region and close in color; присоединяют к связной области красного глаза точки изображения, расположенные внутри внешнего контура данной области;attach to the connected region of the red eye image points located inside the outer contour of this region; изменяют цвет точек связной области красного глаза.change the color of the dots of the connected area of the red eye. 2. Способ по п.1, отличающийся тем, что множества цветов типичных для красных глаз и кожи человека задают известными аналитическими функциями.2. The method according to claim 1, characterized in that the set of colors typical of red eyes and human skin is set by known analytical functions. 3. Способ по п.1, отличающийся тем, что множества цветов типичных для красных глаз и кожи человека задают таблично.3. The method according to claim 1, characterized in that the set of colors typical of red eyes and human skin set table. 4. Способ по любому из пп.2 и 3, отличающийся тем, что множества цветов являются пересекающимися.4. The method according to any one of claims 2 and 3, characterized in that the plurality of colors are intersecting. 5. Способ по п.1, отличающийся тем, что в качестве направленных фильтров для обнаружения границ используют курсовые градиентные фильтры.5. The method according to claim 1, characterized in that the directional filters for detecting boundaries use directional gradient filters. 6. Способ по п.1, отличающийся тем, что в качестве направленных фильтров для обнаружения границ используют отношения сумм точек соседних равного размера прямоугольных фрагментов.6. The method according to claim 1, characterized in that the ratio of the sums of points of neighboring equal-sized rectangular fragments are used as directional filters for detecting boundaries. 7. Способ по п.1, отличающийся тем, что при сравнении результатов фильтрации с пороговым значением данное пороговое значение увеличивают, если цвет точки является цветом типичным для кожи человека, и уменьшают, если цвет точки является цветом типичным для красных глаз.7. The method according to claim 1, characterized in that when comparing the filtering results with a threshold value, this threshold value is increased if the point color is a color typical of human skin, and reduced if the point color is a color typical of red eyes. 8. Способ по п.1, отличающийся тем, что для каждой связной области точек вычисляют следующие признаки:8. The method according to claim 1, characterized in that for each connected area of the points calculate the following features: размеры описывающего прямоугольника;dimensions of the describing rectangle; общее количество точек связной области;total number of points in the connected area; количество точек связной области помеченных меткой цвета;the number of points in the connected area marked with a color label; количество точек связной области, помеченных каждым из направленных фильтров;the number of points in the connected area marked with each of the directed filters; коэффициент компактности;compactness factor; количество направленных фильтров, номера которых записаны в массиве меток для данной связной области точек;the number of directional filters, the numbers of which are recorded in the array of labels for this connected area of points; отношение максимального из количеств точек области, помеченных каждым из направленных фильтров, к общему количеству точек области;the ratio of the maximum of the number of region points marked with each of the directed filters to the total number of region points; коэффициент удлинения;elongation coefficient; доля точек в окрестности связной области, цвет которых типичен для цвета кожи человека;the proportion of points in the vicinity of the cohesive region, the color of which is typical of the color of human skin; доля точек в описывающем связную область прямоугольнике, цвет которых типичен для блика;the proportion of points in a rectangle describing a connected region whose color is typical of glare; средняя яркость точек связной области;average brightness of the points of the connected area; средняя яркость точек в окрестности связной области;average brightness of points in the vicinity of a connected region; среднее значение компоненты Cr точек в окрестности связной области.average value of the component Cr of points in a neighborhood of a connected region. 9. Способ по п.1, отличающийся тем, что для классификации связных областей точек применяют каскад классификаторов, в котором используют, по меньшей мере, один классификатор, основанный на методе опорных векторов;9. The method according to claim 1, characterized in that for the classification of the connected areas of the points, a cascade of classifiers is used, in which at least one classifier is used, based on the support vector method; 10. Способ по п.1, отличающийся тем, что для классификации связных областей точек применяют каскад классификаторов, в котором используют, по меньшей мере, один классификатор, основанный на взвешенном голосовании комитета простых классификаторов.10. The method according to claim 1, characterized in that for the classification of the connected areas of the points, a cascade of classifiers is used, in which at least one classifier is used, based on a weighted vote of a committee of simple classifiers.
RU2006123847/09A 2006-07-05 2006-07-05 Method for automatic correction of red-eye effect RU2320011C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2006123847/09A RU2320011C1 (en) 2006-07-05 2006-07-05 Method for automatic correction of red-eye effect

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2006123847/09A RU2320011C1 (en) 2006-07-05 2006-07-05 Method for automatic correction of red-eye effect

Publications (1)

Publication Number Publication Date
RU2320011C1 true RU2320011C1 (en) 2008-03-20

Family

ID=39279887

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2006123847/09A RU2320011C1 (en) 2006-07-05 2006-07-05 Method for automatic correction of red-eye effect

Country Status (1)

Country Link
RU (1) RU2320011C1 (en)

Cited By (9)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2374688C1 (en) * 2008-04-10 2009-11-27 Корпорация "САМСУНГ ЭЛЕКТРОНИКС Ко., Лтд." Method for improvement of digital image quality on basis of metadata
US8786735B2 (en) 2011-03-21 2014-07-22 Apple Inc. Red-eye removal using multiple recognition channels
US8811683B2 (en) 2011-06-02 2014-08-19 Apple Inc. Automatic red-eye repair using multiple recognition channels
US8818091B2 (en) 2011-03-21 2014-08-26 Apple Inc. Red-eye removal using multiple recognition channels
US8837785B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
US8837827B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
US8837822B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
RU2535482C2 (en) * 2010-02-08 2014-12-10 Тенсент Текнолоджи (Шэньчжэнь) Компани Лимитед Method and apparatus for editing with image optimisation
RU2547703C2 (en) * 2010-06-28 2015-04-10 Нокиа Корпорейшн Method, apparatus and computer programme product for compensating eye colour defects

Citations (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2250499C1 (en) * 2003-11-17 2005-04-20 Иванов Александр Львович Method for computer recognition of objects

Patent Citations (1)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2250499C1 (en) * 2003-11-17 2005-04-20 Иванов Александр Львович Method for computer recognition of objects

Cited By (9)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2374688C1 (en) * 2008-04-10 2009-11-27 Корпорация "САМСУНГ ЭЛЕКТРОНИКС Ко., Лтд." Method for improvement of digital image quality on basis of metadata
RU2535482C2 (en) * 2010-02-08 2014-12-10 Тенсент Текнолоджи (Шэньчжэнь) Компани Лимитед Method and apparatus for editing with image optimisation
RU2547703C2 (en) * 2010-06-28 2015-04-10 Нокиа Корпорейшн Method, apparatus and computer programme product for compensating eye colour defects
US8786735B2 (en) 2011-03-21 2014-07-22 Apple Inc. Red-eye removal using multiple recognition channels
US8818091B2 (en) 2011-03-21 2014-08-26 Apple Inc. Red-eye removal using multiple recognition channels
US8837785B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
US8837827B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
US8837822B2 (en) 2011-03-21 2014-09-16 Apple Inc. Red-eye removal using multiple recognition channels
US8811683B2 (en) 2011-06-02 2014-08-19 Apple Inc. Automatic red-eye repair using multiple recognition channels

Similar Documents

Publication Publication Date Title
CN108446617B (en) Side face interference resistant rapid human face detection method
US11790499B2 (en) Certificate image extraction method and terminal device
Ke et al. The design of high-level features for photo quality assessment
US8929680B2 (en) Method, apparatus and system for identifying distracting elements in an image
EP0635972B1 (en) Automated detection and correction of eye color defects due to flash illumination
WO2017101626A1 (en) Method and apparatus for implementing image processing
CN114565675A (en) A method for removing dynamic feature points in the front end of visual SLAM
KR20180065889A (en) Method and apparatus for detecting target
CN108537155A (en) Image processing method, device, electronic equipment and computer readable storage medium
CN102024144A (en) Container number identification method
CN103902958A (en) Method for face recognition
CN112862832B (en) Dirt detection method based on concentric circle segmentation positioning
CN108830175A (en) Iris image local enhancement methods, device, equipment and storage medium
CN110688926B (en) Subject detection method and device, electronic device, computer-readable storage medium
WO2020248848A1 (en) Intelligent abnormal cell determination method and device, and computer readable storage medium
WO2021139197A1 (en) Image processing method and apparatus
RU2320011C1 (en) Method for automatic correction of red-eye effect
CN110008943A (en) A kind of image processing method and device, a kind of calculating equipment and storage medium
CN118608926A (en) Image quality evaluation method, device, electronic device and storage medium
Li et al. UStark: underwater image domain-adaptive tracker based on Stark
US20170293818A1 (en) Method and system that determine the suitability of a document image for optical character recognition and other image processing
RU2324225C1 (en) Method for automatic red eye correction
Ghosal et al. A geometry-sensitive approach for photographic style classification
US20060010582A1 (en) Chin detecting method, chin detecting system and chin detecting program for a chin of a human face
CN114359764A (en) A method, system and related equipment for identifying illegal buildings based on image data

Legal Events

Date Code Title Description
MM4A The patent is invalid due to non-payment of fees

Effective date: 20200706