ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio...

274
ESCUELA POLITÉCNICA NACIONAL ESCUELA DE INGENIERÍA PROCESAMIENTO DIGITAL DE IMÁGENES UTILIZANDO LA TRANSFORMADA DE HOUGH PROYECTO PREVIO A LA OBTENCIÓN DEL TITULO DE INGENIERO EN ELECTRÓNICA Y TELECOMUNICACIONES FABIÁN WLADIMIRO BASANTES MORENO DIRECTORA: Ing. MARÍA SOLEDAD JIMÉNEZ, MSc. Quito, Abril 2004

Transcript of ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio...

Page 1: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ESCUELA POLITÉCNICA NACIONAL

ESCUELA DE INGENIERÍA

PROCESAMIENTO DIGITAL DE IMÁGENES UTILIZANDO LATRANSFORMADA DE HOUGH

PROYECTO PREVIO A LA OBTENCIÓN DEL TITULO DEINGENIERO EN ELECTRÓNICA Y TELECOMUNICACIONES

FABIÁN WLADIMIRO BASANTES MORENO

DIRECTORA: Ing. MARÍA SOLEDAD JIMÉNEZ, MSc.

Quito, Abril 2004

Page 2: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

DECLARACIÓN

Yo, Fabián Wladimiro Basantes Moreno, declaro que el trabajo aquí descrito es

de mi autoría; que no ha sido previamente presentado para ningún grado o

calificación profesional; y, que he consultado las referencias bibliográficas que

se incluyen en este documento.

La Escuela Politécnica Nacional, puede hacer uso de los derechos

correspondientes a este trabajo, según lo establecido por la Ley de Propiedad

Intelectual, por su Reglamento y por la normatividad institucional vigente.

Fabián Wladimiro Basantes Moreno

Page 3: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CERTIFICACIÓN

Certifico que el presente trabajo fue desarrollado por el Sr. Fabián Wladimiro

Basantes Moreno, bajo mi supervisión.

Ing. Ijrlaría Soledíd Jmíénez, MSc.

DIRECTORA DEL PROYECTO

Page 4: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

DEDICATORIA

Este trabajo lo dedico con mucho cariño y afecto a:

Dios, por haberme permitido llegar a completar esta meta, tan anhelada por mí y

esperada por mis padres. Por haberme dado los padres, hermanos, los amigos y los

compañeros de aula que siempre han tenido las palabras precisas en los momentos

justos. Por hacerme sentir siempre Su Presencia en los momentos alegres como en ios

difíciles.

Mis padres, Alberto y Guadalupe que, con mucho amor, fe, paciencia, me han otorgado el

mejor regalo que puede aspirar a recibir un hijo: la educación. Porque nunca me han

abandonado en mis instantes más tristes y siempre confiaron en mí. Que los sufrimientos

de ellos sean compensados con la alegría tan inmensa de este momento.

Mis hermanos: Marco, Beto y Roberto que siempre estuvieron prestos a darme apoyo y

soporte y que, a pesar de mis desplantes, a veces de niño mimado, nunca me dieron la

espalda y siempre estuvieron conmigo.

Mi sobrino, Alberto Daniel Basantes Arias, y mi ahijada, Gabriela Proaño Pazmiño,

porque en ellos encontré la voz de esperanza de los hijos que, algún día, Dios me dará

para cuidar.

Ximena Cordero Sosa, que me brindó apoyo y ánimo en los momentos más duros de

este trabajo. Que, a pesar de mis errores, estuvo conmigo en los momentos más difíciles

de este año y nunca desconfió de mí; que tiene palabras de aliento en los instantes tristes

y en los momentos alegres y, en cualquiera de ellos, me da cariño, afecto y comprensión.

Al Silencioso Voto de Confianza que recibí de toda mi familia, de mi mamá en particular,

Directora de Tesis, amigos, profesores y de aquellas personas especiales que me

acompañaron en este tiempo, sobretodo de Ximena, Lorena y Adriana.

Page 5: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

AGRADECIMIENTO

A la Ing. María Soledad Jiménez por la paciencia que tuvo al dirigirme la tesis, por sus

"haladas de orejas" cuando yo desaparecía y su constante guiar mi camino hacia la

consecución de esta meta. Nada fue tan importante en este tiempo como el silencioso voto de

confianza que recibí de mi mamá, Usted y de otras personas muy especiales.

A los Ingenieros Carlos Egas, Carlos Herrera, Tarquino Sánchez, Ramiro Morejón por

haberme brindado la confianza para darme un sitio para trabajar mi tesis, colaborar con ellos

en la creación de los Programas de Postgrado, el Centro de Transferencia, Academia Cisco,

Proyecto Microsoft y prepararme para el futuro. Nunca olvidaré las palabras de apoyo, aliento

y consejo que recibí cuando más necesité.

A los Ingenieros Pablo Hidalgo y Fernando Flores y Dr. Iván Bernal que me dieron soporte en

los instantes en los cuales yo solicité su apoyo y experiencia para terminar este trabajo.

A la Sra. María Elena Aguirre C., Sra. Guadalupe Buenaño de Bedoya y Sra. Mariana de

Coronel por estar pendientes de mi evolución en mi paso por la Facultad de Ingeniería

Eléctrica, darme palabras de aliento y consejo en estos años que han sido los mejores de mi

vida.

A Santiago Yepes por su palabra de apoyo y consejo en los momentos difíciles de la carrera y

también en los momentos de triunfo.

A todos mis profesores de la Politécnica por darme una parte de sus conocimientos, no solo a

mí sino a todos los que estuvimos en sus cátedras.

A Antonio Proaño y Lorena Pazmiño de Proaño por ser mis amigos durante todo mi paso por

la Politécnica dentro y fuera de ella; porque nunca me dejaron solo y siempre estuvieron

conmigo en todo momento, tanto para celebrar los éxitos, como para soportar los fracasos.

A Fernando Carrera, Fernando Vásquez, William Reinoso, José Antonio Pazmiño, Mayra

Rodríguez, Marina Hidalgo, Evelyn Arias, Irene Fabara y a todos mis amigos y compañeros de

aula y trabajo que a través del correo o en los pasillos de la Facultad me apoyaron y

acompañaron en este largo período.

A Adriana Molina, Alexandra Arias, Catalina Aviles, Isabela Astudillo, Paulina Erazo, Verónica

Jiménez, Nubia Pazrniño, Verónica Nolivos, Antonio Redín, David Bravo, Fernando Ibarra,

Xavier Zurita y a todos aquellos amigos que me acompañaron y que compartieron momentos

gratos, agradables y de los otros durante este período de ejecución de mi tesis. Gracias por

haberme dado palabras de aliento y ánimo cuando me vieron desfallecer y compartir conmigo

cada uno de los instantes alegres y tristes.

A los amigos por haber sido eso... mis amigos.

A todos aquellos que tuvieron la suerte, o la mala suerte, de haber sido mis alumnos, mientras

fui Ayudante de Laboratorio.

Page 6: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ÍNDICE

Página

DECLARACIÓN i

CERTIFICACIÓN ii

DEDICATORIA iii

AGRADECIMIENTO iv

ÍNDICE v

PRESENTACIÓN ix

RESUMEN xi

CAPÍTULO 1: INTRODUCCIÓN AL PROCESAMIENTO

DIGITAL DE IMÁGENES 1

1.1 FUNDAMENTOS DE PROCESAMIENTO DIGITAL DE

IMÁGENES 2

1.1.1 Definiciones básicas de imagen 2

1.1.2 Imagen digital 4

1.1.3 Etapas del procesamiento digital de imágenes 8

1.2 LOS PROBLEMAS DEL PROCESAMIENTO DE IMÁGENES 11

1.2.1 Modelado y representación de la imagen 12

1.2.2 Ampliación y mejoramiento de la imagen 14

1.2.3 Restauración de la imagen 14

1.2.4 Análisis de la imagen 15

1.2.5 Reconstrucción de la imagen desde proyecciones 15

1.2.6 Compresión de datos de la imagen 16

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 7: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ÍNDICE - VI -

1.3 ELEMENTOS DE LOS SISTEMAS DE PROCESAMIENTO DE

IMÁGENES 17

1.3.1 Adquisición de imágenes 17

1.3.2 Almacenamiento 17

1.3.3 Procesamiento 19

1.3.4 Presentación 20

CAPÍTULO 2: TRANSFORMADAS DE LA IMAGEN 21

2.1 INTRODUCCIÓN 21

2.2 LAS TRANSFORMADAS DE LA IMAGEN 22

2.2.1 La Transformada de Fourier 23

2.2.2 La Transformada discreta coseno 34

2.2.3 La Transformada discreta seno 37

2.2.4 La Transformada Walsh 38

2.2.5 La Transformada Hadamard 41

2.2.6 Otras transformadas de la imagen 43

CAPÍTULO 3: TRANSFORMADA DE HOUGH 45

3.1 INTRODUCCIÓN 45

3.2 FUNDAMENTOS DE LA TRANSFORMADA DE HOUGH 47

3.2.1 Principios matemáticos de la Transformada de Hough 49

3.2.1.1 Generalidades de la ecuación de la línea recta 49

3.2.1.2 Principios del Plano de la Transformada de Hough 53

3.2.1.3 Definición formal de la Transformada de Hough 56

3.2.1.4 La Transformada de Hough en función de la pendiente y la ordenada en el

origen 58

3.2.1.5 La Transformada de Hough en función de la ecuación normal de la línea recta

(Parametrización normal) 60

3.2.1.6 La Transformada de Hough para elipses, círculos y otras curvas 61

3.2.1.7 Semejanzas y diferencias: el método pendiente - intercepto en el eje y versus el

método de parametrización normal 68

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 8: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ÍNDICE - vü -

3.3 ALGORITMOS TÍPICOS DE LA TRANSFORMADA DE HOUGH 70

3.3.1 Principios del análisis de la Transformada de Hough 71

3.3.2 La Transformada de Hough estándar 73

3.3.2.1 Algoritmo de la Transformada de Hough estándar para el método de

parametrización pendiente - intercepto 74

3.3.2.2 Algoritmo de la Transformada de Hough estándar para el método de

parametrización normal o p - 9 80

3.3.3 La Transformada de Hough Aleatoria 85

3.3.4 Otros métodos de la Transformada de Hough 88

3.4 APLICACIONES FUNDAMENTALES DE LA TRANSFORMADA

DE HOUGH 89

CAPÍTULO 4: DISEÑO E IMPLEMENTACIÓN DEL

ALGORITMO Y ANÁLISIS DE RESULTADOS 91

4.1 INTRODUCCIÓN 91

4.2 IMPLEMENTACIÓN DEL ALGORITMO DE CÁLCULO DE LA

TRANSFORMADA DE HOUGH 92

4.2.1 Herramientas de programación 92

4.2.2 Pasos previos del diseño del Algoritmo de cálculo de la Transformada de

Hough 95

4.2.2.1 La importancia de la aplicación de la imagen a transformar 95

4.2.2.2 Tipo de gráfico de entrada 97

4.2.2.3 Binarización de la imagen. Selección del método de binarización 98

4.2.3 Diseño del Algoritmo de cálculo de la Transformada de Hough. 101

4.2.3.1 Algoritmo de cálculo considerando sólo líneas rectas 103

4.2.3.2 Algoritmo de cálculo considerando sólo curvas 108

4.2.3.3 Algoritmo de cálculo generalizado 111

4.2.3.4 Tiempos de cómputo, complejidad de cálculo y tamaño del archivo de grabación 115

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 9: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ÍNDICE - viÜ -

4.3 ANÁLISIS DE RESULTADOS 118

4.3.1 Requerimientos del sistema 118

4.3.2 Resultados para líneas rectas puras 118

4.3.3 Resultados para líneas curvas puras 126

CAPÍTULO 5: CONCLUSIONES Y RECOMENDACIONES 131

5.1 EL FUTURO DE LA TRANSFORMADA DE HOUGH 131

5.2 CONCLUSIONES 133

5.3 RECOMENDACIONES 136

5.3.1 Procesamiento de Imágenes 137

5.3.2 Informática y Procesamiento de señales 139

5.3.3 Laboratorios afines con el Procesamiento de Señales 141

5.3.4 La perspectiva de esta investigación 143

BIBLIOGRAFÍA 144

ANEXOS

A ARTÍCULOS SOBRE LA TRANSFORMADA DE HOUGH

B LA TRANSFORMADA RADON

C AYUDAS DEL MATLAB

D LISTADOS DEL PROGRAMA

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 10: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

PRESENTACIÓN

La necesidad de procesar una imagen, con el fin de obtener alguna característica

especial de la misma, es una actividad que, desde la segunda mitad del siglo XX,

ha sido un polo de investigación científica de la humanidad. El auge de la guerra

fría, los lanzamientos espaciales, las fotografías por rayos X, infrarrojos, las

primeras fotografías por satélite y las investigaciones en el campo de la física

aplicada y la medicina, entre otros, han sido los principales motivos por los cuales

el procesamiento de imágenes y fotografías ha tomado importancia. Este ha sido

el detonante para que muchos investigadores desarrollen técnicas para mejorar la

gráfica y con ello permitir una mejor comprensión de la misma y poder interpretar

con mayor precisión los resultados que arroje el análisis que se haga de ella.

Una de las técnicas que ha sido objeto de la investigación en el campo del

procesamiento de la imagen ya capturada es la Transformada de Hough. Esta

técnica nace en plena guerra fría pero no dentro de la investigación militar, sino

dentro de la física aplicada. Paul Hough era parte de un equipo que estudiaba la

trayectoria de las partículas atómicas en una cámara de burbujas. En 1962, con el

aval de IBM presenta a la United States Patent Office un documento donde

detalla su investigación y conclusiones, las cuales quedaron registradas como

una patente de los Estados Unidos de libre distribución [31].

A partir de aquel trabajo, algunas investigaciones se desarrollaron tomando como

objetivo, o como base, el trabajo de Paul Hough. Uno de ellos permitió un

despegue de la Transformada: "Use ofthe Hough Transformaron to Detect Lines

and Curves in Pictures", de Duda y Hart [41]. En este trabajo se complementa la

idea original de la patente y otro que sistematizaba la parametrización de la

Transformada de Hough. Duda y Hart presentan otra forma de trabajar con la

Transformada de Hough requiriendo la ayuda de la forma normal de la ecuación

de la línea recta.

Este trabajo fue el detonante y la base de la mayoría de trabajos posteriores

sobre la Transformada de Hough. Muchas de las investigaciones sobre el campo

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 11: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

PRESENTACIÓN - X

se sustentan en el método de parametrización presentado por Duda y Hart, pero

adicionalmente, tratan de presentar nuevos métodos para la utilización de la

Transformada.

A partir del trabajo de Duda y Hart, y del lanzado por Kittler e lllingworth en 1982,

el estudio y aplicación de la Transformada de Hough ha alcanzado un interesante

repunte. Súmese a aquello el mejoramiento de los sistemas informáticos y de

adquisición de las imágenes, el impulso para los investigadores se ha

multiplicado, lo cual es evidente por la cantidad de trabajos adicionales e

investigaciones que se han dado desde la década del 80, pero ya no solo para la

física aplicada sino para la medicina y la robótica. En los últimos años, los

estudios de la Transformada de Hough ya no solo se enfocan en el

perfeccionamiento de técnicas orientadas a las ramas ya mencionadas, sino que,

además, se ha ampliado el campo de aplicación de la Transformada de Hough

orientándola al ámbito de la detección de características en imágenes

geocientíficas, provenientes de satélites, fotografías aéreas y reconocimiento de

patrones definidos en una gráfica determinada.

Queda de más resaltar que este Proyecto de Titulación no pretende ser un

estudio completo de la Transformada de Hough con todas sus variantes. A lo

largo de la recopilación realizada en este trabajo, se notó que, si bien es cierto

que la base matemática y de procesamiento entre las distintas técnicas de

aplicación de la transformada son similares, para llegar al objetivo final es

necesario definir las áreas de influencia del resultado final. Es por ello que no se

desarrolló un procedimiento orientado a una aplicación específica para su

implementación.

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 12: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

RESUMEN

Una de las técnicas de procesamiento intermedio de imágenes, cuyo desarrollo

ha sido muy acelerado en la última década, se presenta en este trabajo. La

Transformada de Hough nace de un estudio de la trayectoria de las partículas

subatómicas dentro de una cámara de burbujas en el año 1962. A partir de esa

fecha, varios trabajos se han desarrollado con el propósito de aplicar esta técnica

en el procesamiento intermedio de una imagen digital.

Este estudio, sin llegar a ser un trabajo completo sobre las potencialidades de la

Transformada de Hough, intenta ser una base para la comprensión y posterior

profundización en este aspecto. Durante este trabajo se abordará una

introducción sobre el procesamiento de imágenes (Capítulo I), un estudio rápido

acerca de las distintas transformadas de imagen (Capítulo II). El Capítulo III

abordará los temas relacionados con la Transformada Directa de Hough, mientras

en el Capítulo IV se presentarán algunas consideraciones de diseño y esquemas

de los algoritmos que servirán para resolver los tres problemas que la

Transformada de Hough aborda en la actualidad: procesamiento de líneas rectas,

procesamiento de curvas y procesamiento de imágenes con cualquier patrón de

curvas. Adicionalmente, al finalizar el Capítulo IV se analizarán los resultados que

se obtienen al aplicar la Transformada de Hough en una imagen.

El Capítulo V servirá para tratar de mirar hacia el futuro de la Transformada e

intentar descubrir el horizonte que tendrá en unos años. Para finalizar este

Capítulo, se plantearán las conclusiones que se han obtenido de este trabajo y de

su investigación, para establecer algunas recomendaciones que se consideran

valiosas.

Adicionalmente, en los Anexos se incluyen algunos trabajos sobre la

Transformada de Hough, entre ellos se hallan la patente de Paul V. Hough que

dio origen a la transformada, el artículo de Duda y Hart que permitió un cambio de

enfoque de la misma y algunos artículos recientes sobre el tema, que permitirán

completar el análisis y las perspectivas de esta herramienta.

Page 13: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1

INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DEIMÁGENES

Hoy en día, la imagen es una de las preocupaciones tecnológicas del ser humano.

De hecho, la imagen obtenida por métodos electrónicos es considerada como una

herramienta fundamental en el diagnóstico de problemas médicos, ambientales,

geofísicos, geotécnicos y otras áreas relacionadas con las Ciencias Naturales.

Una imagen, obtenida electrónicamente, puede provenir, por ejemplo, de una

cámara fotográfica, un complicado sistema de rayos X o rayos infrarrojos, o de los

ojos de un satélite en órbita alrededor de un planeta. La información, recopilada

por estas fuentes electrónicas, se ve alterada por un procesamiento interno del

sistema, que introduce ruido a las mismas y distorsiona, a veces de manera

grosera, el resultado final. Es por ello el interés de la comunidad científica mundial

en mejorar los sistemas de procesamiento digital de imágenes y en encontrar

métodos matemáticos y computacionales que permitan, sobre la base de un

hardware, minimizar el efecto del procesamiento sobre una imagen previamente

capturada.

Un punto que se debe resaltar es que, para el resto de este estudio, se

considerará que la imagen ha sido ya previamente capturada en un formato

específico y de allí se procederá a estudiar su comportamiento.

La imagen es producto de la estimulación visual de un objeto. Es por ello que,

para poder "observar un objeto", dentro del ojo empieza un procedimiento de

reconocimiento que involucra el funcionamiento de cientos de millones, por no

decir de billones, de células cerebrales encargadas de procesar esa información

para convertirla en lo que se llama la "imagen".

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 14: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 2 -

1.1 FUNDAMENTOS DE PROCESAMIENTO DIGITAL DEIMÁGENES

Para comenzar con el estudio del procesamiento digital de imágenes se

debe primero centrar en el estudio de la imagen como producto de la

abstracción de una realidad por parte del sentido de la vista. Una vez que

se hayan establecido los primeros conceptos sobre la imagen, se deben

plantear los pasos a seguir dentro del procesamiento digital de imágenes.

En este proceso, se expondrá las definiciones básicas de imagen, un

resumen de los distintos procesos intermedios que se tienen que realizar

para procesar una imagen y los criterios básicos que permiten realizar el

procesamiento de una imagen con una determinada transformada.

1.1.1 DEFINICIONES BÁSICAS DE IMAGEN

La imagen se define como el conjunto de señales visuales que provienen

de un objeto y que permiten hacer una abstracción de sus características

geométricas. Es decir, la imagen es la forma como el sentido de la vista

percibe un determinado objeto; así, la forma como la especie humana

percibe un cubo puede o no ser la misma como la percibe un insecto, un

primate o una serpiente.

La imagen sirve, en primera instancia, para distinguir las características

geométricas y puede ayudar a la estimación de las características físicas,

tales como volumen, masa, etc. Una de las características físicas que, por

aumentar complejidad, se desechará en este estudio es el color y solo se

analizará la imagen desde el punto de vista monocromático, es decir, como

producto de la variación de la intensidad de luz, desde el blanco hasta el

negro, en una escala de grises.

Las imágenes, en general, son señales que tienen características muy

especiales. En primera instancia, son una medida de un parámetro en

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 15: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 3 -

función del espacio (distancia), cuando se ha estado acostumbrado a tener

señales que relacionan una característica en función del tiempo. Segundo,

la imagen contiene gran cantidad de información. De hecho, los sistemas

actuales de grabación permiten tener un segundo de imagen de video en

algunos cientos de kilobytes (o decenas de megabytes). Tercero, el juicio

final de la calidad de !a imagen dependerá siempre del concepto subjetivo

de la percepción del visor humano. Estas características particulares, han

convertido al procesamiento de imágenes en un tema especial del

Procesamiento Digital de Señales [22].

Las imágenes son una descripción de cómo un parámetro varía sobre una

superficie. Por ejemplo, las imágenes estándar, que son las que se

aprecian, resultan de la variación de la intensidad de luz sobre un plano

bidimensional. Pero, la luz no es el único parámetro que se usa en la

descripción de una imagen científica. Por ejemplo, se puede usar la

temperatura de una superficie para dibujar una imagen, la emisión de rayos

X para dibujar una galaxia. Una cosa muy distinta es que estas "imágenes"

sean convertidas en gráficas convencionales (imágenes luminosas) para el

análisis humano.

Al hablar de una imagen, se piensa en un conjunto de puntos que forman

un arreglo bidimensional el cual tiene características especiales. Estas

características especiales están ligadas expresamente a aquellos

parámetros físicos que varían en función del espacio y que, al convertirse

en señales visuales, estimulan el sentido de la vista. Los parámetros físicos

que determinan que un objeto pueda ser apreciado o no por el ojo, y, de

hecho, por cualquier instrumento sensor, son el brillo1 y la luminancia2.

En general, la imagen monocromática se define como una función

bidimensional de intensidad de luz f(x, y), donde x e y representan las

coordenadas espaciales y el valor de f en un punto cualquiera (x, y) es

Brillo: Se define el brillo como el nivel de gris de una imagen monocromáticaLuminancia: Cuando el flujo luminoso incide sobre una superficie se dice que ésta ha sido iluminada. La luminancia se define comoel flujo luminoso por unidad de superficie. La unidad de la luminancia es el lux, equivalente a un lumen por metro cuadrado [29].

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 16: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES — 4 —

proporcional al brillo (o nivel de gris) de la imagen en ese punto. La

convención de ejes que se aplica en el estudio de los sistemas de

procesamiento de imágenes se muestra en la Figura 1.1

Origen(0,0)

Figura 1.1: Convenio de ejes utilizado para la representación digital de imágenes [6]

1.1.2 IMAGEN DIGITAL

Una imagen digital es una matriz de números que representan valores de

iluminación en puntos regularmente espaciados de la imagen de una

escena. A este punto se lo denomina elemento de imagen o, más

comúnmente, pixel o peí (picture element), y sus valores se denominan

niveles de gris [22]. Este punto, en principio, es el resultado de una función

no discreta de las coordenadas (x, y); en consecuencia, es de suponer que

este punto, para someterlo a un proceso de análisis digital, deberá pasar

por un proceso de digitalizacion. Este proceso de digitalizacion debe pasar

por algunas etapas ya descritas ampliamente en muchas publicaciones,

pero aquí, se mencionarán algunas características de este proceso de

digitalizacion de una imagen bidimensional.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 17: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 5 -

La Figura 1.2 plantea una idea bastante ilustrativa de la estructura de una

imagen digital. La imagen, del planeta Venus, fue obtenida por medio de

señales de radar. La imagen, aquí representada, es un arreglo

bidimensional de 40000 muestras de 200 muestras por fila y 200 muestras

por columna. Cada muestra es lo que se define como píxel y, en este

ejemplo es un número entero entre O y 255. Cada uno de estos valores

está asociado a una escala de grises, donde O es el negro y 255 es el

blanco; los valores intermedios son tonalidades de gris.

Las imágenes tienen toda su información codificada en el dominio

espacial, el equivalente al dominio del tiempo. Esto quiere decir, o

significa, que "el espaciamiento y el número de píxeles se determinan por

el menor número de características que se necesitan para parecerse en

comparación con el ajuste formal de algún teorema del muestreo. Se puede

decir que el efecto de aliasinff* puede aparecer en imágenes, pero,

generalmente, se piensa que es un inconveniente antes que un problema

mayor" [23].

Una imagen digital típica se compone de alrededor de 500 filas por 500

columnas, esta calidad es común en computadoras personales, televisión y

en la investigación científica general. Las imágenes de menor resolución

(250 x 250) han sido desechadas por la pobre resolución que presentan.

En el caso de nuevas tecnologías, se añaden un mayor número de píxeles.

Las resoluciones más altas (por ejemplo 1000 x 1000) se consideran

excepcionalmente buenas y es el nuevo objetivo de estandarización en las

computadoras personales, en la televisión de alta definición y en las

películas de 35 mm; así mismo existen otras aplicaciones que están

requiriendo una alta resolución, como son las imágenes de rayos X, las

fotografías espaciales y los anuncios en revistas.

3 Aliasing: El efecto de aliasing o espectro plegadizo (doblamiento) se denomina a la sobreposición espectral o inversión de cola [4]

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 18: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -6-

Columii155 160 165

(a) (b)

Coluran150 155 160 165

183.

ISí.

194

1S4

202

203

174

143

164

175

172

156

154

144

140

135

183

195

196

212

215

208

149

137

165

187

184

191

163

150

151

143

181

190

198

200

2Ü3

166

143

147

159

193

179

196

175

143

150

151

184

195

201

204

179

159

151

15.1

179

1S1

15.?

159

165

162

185

179

177

191

206

201

165

160

156

150

i8s167

158

167

207

215

215

213

200

205

209

202

165

168

148

140

159

151

172

195

211

212

214

216

200

216

215

214

199

166

146

121

126

162

163

178

197

211

210

214

189

206

216

214

207

15?

125

133

134

182

207

2*33

201

209

210

191

159

174

199

214

202

174

118

157

150

192

205

214

201

197

211

201

135

153175

205

20S

211

203

1W

1.99

175

U8

201

199

198

209

205

94

112

140

173

197

204

208

203

174

129

127

143

138

133

135

138

105

80

77

102

129

158

162

164

119

60

63

101

79

71

m61

160

134

106

84

73

69

81

94

100

88

56

69

76

69

45

59

174

157

142

120

112

79

58

56

41

47

43

38

67

77

69

61

191

174

no134

131

127

mi66

41

37

42

44

51

63

66

77

1%

196

186

159

146

143

125

m58

50

55

52.

53

53

60

63

(c)

Figura 1.2: Estructura de una imagen digital [22]

Imagen digitalizada del planeta Venus. En esta imagen, el arreglo es de 200 filas por 200columnas (a), cada pixel está asociado a un número entre O y 255. (b) Sección ampliada de(a). El valor de cada píxel fue asociado a un nivel de energía de la microonda reflejada (c). Laimagen en escala de grises se forma asignando un valor entre O a 255 para diferentes tonosde gris.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 19: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 7 -

Sin embargo, a mayor cantidad de píxeles, los problemas de manejo de la

señal aumentan. Uno de ellos es el almacenamiento. En el caso de las

imágenes, un segundo de imagen requiere mil veces más espacio de

almacenamiento que el mismo tiempo de audio. "La transmisión de una

imagen de 500 x 500 a través de un módem de 33.6 kbps requerirá cerca

de un minuto. Si se requiere transmitir esa misma imagen, con el doble de

resolución, los problemas se cuadruplican" [23].

Es común usar para procesamiento de imágenes 256 niveles de gris

(niveles de cuantización), lo cual implica un byte por píxel. Esto es

conveniente por muchas razones; una de ellas es la facilidad de la

administración de los datos, o, mejor dicho, la capacidad de

almacenamiento en los equipos de computación. Otra razón es la que un

mayor número de píxeles compensa de alguna manera la limitación de los

procesos de cuantización. Pero, la más importante, tiene que ver con la

capacidad del ojo humano para percibir las imágenes por medio del brillo.

Una imagen presentada a un observador humano no se mejorará si se

usan más de 256 niveles de cuantización.

Sin embargo, algunas imágenes necesitan ser almacenadas con más de

ocho bits por píxel. Muchas de las imágenes encontradas en

procesamiento digital representan parámetros no visuales. El punto es que

el ojo humano podría ver toda la información en los niveles más finamente

espaciados.

El valor de cada píxel en una imagen digital representa una pequeña región

en la imagen continua digitalizada y contiene información sobre una

pequeña área de la imagen, dependiendo de la grilla de muestreo. Esta

región de la imagen continua que contribuye al valor del píxel se denomina

apertura de muestreo. El tamaño de la apertura dependerá de la

aplicación en la cual se utilizará un sistema particular de imagen: en los

microscopios, la apertura dependerá de las cualidades ópticas y la longitud

de onda de la luz, la cámaras electrónicas están limitadas por la difusión

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 20: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 8 -

aleatoria de los electrones en el sensor de imagen. En muchos casos, la

grilla de muestreo se hace, aproximadamente, igual a la apertura de

muestreo del sistema. La resolución de la imagen se verá limitada

principalmente por la más grande de las dos.

Aunque el tamaño de la imagen digital varía según la aplicación, como ya

se ha visto muy someramente en líneas anteriores, una regla muy común

es tomar matrices cuadradas con tamaños y números de niveles de gris

que sean potencias enteras de 2. Un ejemplo muy común es el de la

televisión de imagen monocromática, que es una matriz de 512 x 512

puntos con 128 niveles de gris.

1.1.3 ETAPAS DEL PROCESAMIENTO DIGITAL DE IMÁGENES.

El tratamiento digital de imágenes no solo comprende una aplicación en

particular de software, envuelve tanto aplicaciones varias de software, así

como el hardware que se utilizaría para capturar y procesar la imagen, con

un software diseñado para ser aplicado en él. Sin embargo, la computadora

se ha convertido en la herramienta, por decirlo así, casi estándar para los

sistemas de procesamiento de imágenes. Con esto no se quiere desechar

a las tarjetas de procesamiento digital de señales (DSP), las cuales han

tenido un considerable mejoramiento y se han convertido en otra

herramienta más del procesamiento de imágenes.

En un sistema de procesamiento de imágenes, se distinguen seis etapas,

las cuales se ilustran en diagrama de bloques en la Figura 1.3.

La primera etapa de cualquier sistema de tratamiento digital de imágenes

es la adquisición de la imagen. Durante el proceso de adquisición de

imagen, se utilizará un elemento sensor, cuyas características estarán

fijadas por el tipo de señales que se requieren graficar; por ejemplo, si se

requiere captar la imagen de una bacteria, el sistema de adquisición deberá

tener como característica la óptica y la longitud de onda de la luz, si se va a

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 21: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -9-

capturar una imagen de video, se requerirá de una cámara de video, etc.

Obviamente, si la imagen adquirida no se halla en formato digital, se

requerirá pasar esta señal a través de un sistema convertidor analógico -

digital para digitalizarla.

Representación ydescripción

ir

Base de conocimiento

\

Reconocimientoe interpretación

Figura 1.3: Etapas fundamentales del procesamiento digital de imágenes |

Una vez que se ha adquirido la imagen, se debe tomar en cuenta que en

este proceso pueden ocurrir alteraciones que pueden afectar la calidad de

la imagen digital final (ruido, aliasing, errores en la digitalización). Por ello

existe la etapa de preprocesamiento, en donde se tratará de mejorar la

imagen obtenida de manera que las posibilidades de éxito para los

procesos posteriores se incrementen. Dentro de estas técnicas de

preprocesamiento están la mejora del contraste, eliminación del ruido, etc.

La siguiente etapa involucra uno de los procesos más importantes del

procesamiento de la imagen, la segmentación involucra la división de la

imagen original en sus partes constitutivas u objetos. Esta es la parte más

difícil del procesamiento. Si la segmentación de una imagen no es buena o

es demasiado tosca, el procedimiento siguiente dilatará la solución

satisfactoria del problema. Si, en cambio, la segmentación es muy débil o

errática, a la larga ocurrirá un fallo.

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 22: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -10-

Luego del proceso de segmentación, el resultado son los datos del píxel en

bruto, que significan, ya sea el contorno de una región, o bien todos los

puntos de una región determinada. Cualquiera sea el significado de los

datos, éstos deberán pasar a una computadora para su procesamiento. La

siguiente decisión es algo más compleja, pues se debe escoger si los datos

obtenidos servirán para representar un contorno o una región de una

imagen. Obviamente, esta selección dependerá en gran medida del interés

que se tenga en el tratamiento posterior de la información obtenida: si el

interés principal es estudiar el exterior de una figura o imagen, los datos

obtenidos significarán contornos de una región; si, en cambio, el interés

radica en el estudio de la estructura interna de una región, los datos

representará información del interior de la región. Pero, en algunas

aplicaciones, ambas necesidades coexisten, por ejemplo, las que tengan

que ver con el reconocimiento de caracteres, donde es necesario aplicar un

procedimiento basado en la forma del contorno, la estructuración de la

imagen y otras propiedades internas.

Pero esta selección es tan solo una parte de la solución para transformar

los datos de píxel en bruto a una forma adecuada para ser tratados en una

computadora. Deberá, adicionalmente, desarrollarse un método, o

especificar uno existente, para describir los datos de forma que se resalten

los rasgos de interés. Este paso es la descripción de objetos y debe

hacerse paralelamente a la representación de los objetos, para así permitir

la diferenciación entre un objeto y otro.

El reconocimiento de objetos es el último procedimiento dentro de este

proceso. Junto a él, debe desarrollarse la interpretación del objeto. El

reconocimiento "es el proceso que asigna una etiqueta a un objeto

basándose en la información proporcionada por sus descriptores" [6]. La

interpretación, mientras tanto, será el asignar significado a un conjunto de

objetos reconocidos.

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 23: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -11-

Pero, además se debe siempre tener en cuenta una comparación

importante con el conocimiento adquirido sobre un objeto que se va a

estudiar. Por ello es muy importante tener una base de conocimiento, la

cual permitirá relacionar los resultados obtenidos a lo largo del proceso

anterior con un objeto real. Esta base de conocimiento estará codificada en

algún sistema de almacenamiento al cual se deberá tener un rápido

acceso. Sin embargo, no hay que perder de vista que este conocimiento

puede ser muy simple o muy complejo, dependiendo del procesamiento

que se haya realizado a la imagen.

1.2 LOS PROBLEMAS DEL PROCESAMIENTO DE IMÁGENES

Son varios los problemas que un desabollador de sistemas de

procesamiento de imágenes debe afrontar:

1. Modelado y representación de la imagen

2. Ampliación de la imagen

3. Restauración de la imagen

4. Análisis de la imagen

5. Reconstrucción de la imagen

6. Compresión de la imagen.

Cada uno de estos problemas involucra una serie de aplicaciones y

estrategias para hacerlos frente, las cuales tendrán una interrelación muy

estrecha y, muchas veces, la solución de un problema implica el

aparecimiento, o desaparición de otros. Supóngase que se quiere

interpretar los resultados de la captura por rayos X de un asteroide en el

espacio. Primero se deberá escoger un método para representar la imagen;

pero este, involucrará que la imagen se vea afectada por ruido de

procesamiento, así como el ruido interestelar propio. Para ello se deberá

analizar la imagen obtenida para saber cuáles datos capturados o

representados por el paso anterior pertenecen al asteroide y cuáles son

producto del ruido. Una vez que se ha analizado la imagen, se deberá

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 24: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 12 -

reconstruir la imagen con los nuevos datos para así, poder poner en

consideración de los científicos la imagen del asteroide.

Pero no siempre todos los problemas están presentes. Se ha visto en el

análisis anterior que solo algunos de los problemas pueden complicar un

estudio de procesamiento de imagen. En muchas ocasiones, es de interés

para todos que las fotos de la infancia o de los padres se mantengan

invariables en el tiempo. Sin embargo, el paso del tiempo deteriora la foto:

los colores, si los hay, se pierden, las imágenes se deterioran y tienden a

desaparecer, etc. Para cualquier investigador, el sueño es que esa imagen,

por más que pase el tiempo no se altere y, es más, desea que la imagen

sea tan o más nítida que cuando la foto fue tomada. El investigador deberá

sopesar cual de esos problemas (pérdida de nitidez, desgaste, etc.) es el

más relevante, anular su efecto nocivo y, recuperar la imagen sin que se

haya alterado significativamente.

1.2.1 MODELADO Y REPRESENTACIÓN DE LA IMAGEN.

En general, la imagen es una función bidimensional que lleva información.

Los modelos de imagen dan una interpretación lógica o cuantitativa de las

propiedades de la función.

Uno de los puntos más importantes a considerarse en la representación de

una imagen es la fidelidad del criterio tomado para medir la calidad de una

imagen o del desempeño de una técnica de procesamiento. La selección

de un adecuado criterio de fidelidad ayuda en el diseño de un sensor de

imagen, porque dirá qué variables pueden ser medidas con mayor

precisión. La Tabla 1.1 relaciona el parámetro físico de la imagen a

estudiar, el aparato que evalúa la señal y la imagen obtenida a través de

ese procedimiento.

El requerimiento fundamental para el procesamiento digital es que una

imagen se halle cuantizada y muestreada. La tasa de muestreo, definida

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 25: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -13-

como el número de muestras por unidad de área, tiene que ser

suficientemente grande para preservar la información útil en una imagen.

Una explicación más profunda al respecto se verá más adelante y también

se lo encuentra en la literatura asociada a procesamiento digital de señales

o transmisión digital de señales.

Característica

Luminancia de objetos en una escena

Absorción de características del tejidohumano

Reflexión de ondas electromagnéticas

Variación de temperatura en una región

Variación del campo gravitacional en unárea determinada

Aparato sensor deimagen

Cámara de fotos ode video

Aparato Rayos X

RADAR

Cámara infrarroja

Satélite

Imagen obtenida

Fotografía o video

Placa de Rayos X. TomografíaAxial Computarizada

Sección transversal de un objetivo

Imagen infrarroja

Imagen geográfica

Tabla 1.1: Relación entre las características de un cuerpo y las imágenes obtenidas [9]

Un método clásico para la representación de una señal es por la expansión

de una serie ortogonal, como la de Fourier. Para imágenes, la

representación análoga es posible por medio de funciones ortogonales

bidimensionales llamadas bases de la imagen. Para imágenes

muestreadas, las bases de la imagen pueden ser determinadas por medio

de matrices unitarias llamadas transformadas de la imagen. La imagen se

obtendrá por medio de la combinación lineal de las bases de la imagen.

Muchas características de la imagen, tales como: la frecuencia espacial, el

contenido, ancho de banda, espectro de potencia, extracción de

características y otras, se pueden estudiar por medio de algunas

expansiones.

Otro método es el modelo estadístico, donde la imagen se describe como

una parte de un ensamble, caracterizado a veces por sus funciones de

covarianza y media. Esto permite desarrollar algoritmos que son útiles para

una clase o un conjunto de imágenes mejor que para una imagen sola.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 26: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -14-

1.2.2 AMPLIACIÓN Y MEJORAMIENTO DE LA IMAGEN

En el mejoramiento y ampliación de la imagen, el objetivo es acentuar

ciertas características de la imagen para el posterior análisis o para la

exhibición de la imagen. Dentro de las características a acentuar están: el

contraste, ampliación de bordes, pseudocoloración, filtrado de ruido y

magnificación. El mejoramiento de imagen es utilizado en extracción de

características, análisis de imágenes y exhibición de información visual. El

proceso de ampliación, por sí mismo, no incrementa la información

contenida en los datos, sólo enfatiza ciertas características específicas de

la imagen.

Las imágenes pueden perder calidad debido a un proceso fotográfico

imperfecto de los dispositivos de exhibición, pobre contraste, desigual

distribución de grises, canales con ruido, ruido sal y pimienta, ruido de

cuantización. La naturaleza de la imperfección determina la variedad de

técnicas de mejoramiento.

Las técnicas de mejoramiento y ampliación de la imagen, como

ensanchamiento del contraste, mapean un nivel de gris dentro de otro nivel

de gris, por medio de una transformación predeterminada. Otras técnicas

de mejoramiento y ampliación realizan operaciones entre vecinos como la

convolución, operaciones de transformada, como en la transformada

discreta de Fourier, etc.

1.2.3 RESTAURACIÓN DE LA IMAGEN.

La restauración de la imagen se refiere a remover o minimizar las

degradaciones conocidas en una imagen. Esto incluye filtrado de ruido,

corrección de la distorsión geométrica o no linealidad debido al sensor,

hacer lo más nítida posible una imagen borrosa, debido a las limitaciones

del sensor o su medio ambiente.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 27: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -15-

Uno de los resultados fundamentales en la teoría de filtrado usado

comúnmente para la restauración de la imagen se conoce como el filtro de

Wiener. Este filtro es una técnica de restauración de imágenes con

presencia de imágenes borrosas así como de ruido. La respuesta de

frecuencia de este filtro adquiere un compromiso entre el filtro pasabajos de

ruido y un filtro inverso pasaaltos, y da como resultado un filtro pasabanda

[9].

Existen otros métodos de restauración de imágenes que la bibliografía

sobre procesamiento digital de señales e imágenes trata. Alguno de ellos

se lo verá más adelante, conforme avance este trabajo.

1.2.4 ANÁLISIS DE LA IMAGEN.

El análisis de la imagen está relacionado con hacer mediciones

cuantitativas de una imagen para producir una descripción de ella. Dentro

del análisis de la imagen, se encuentra lo que es el reconocimiento de

patrones, la extracción de alguna característica que va a servir para

estudiar detenidamente la imagen. Este tema se lo abordará con más

profundidad en el Capítulo 3, donde se estudiará, específicamente la

Transformada de Hough, objetivo de esta proyecto.

1.2.5 RECONSTRUCCIÓN DE LA IMAGEN DESDE PROYECCIONES.

Esta es una clase especial del problema de restauración de imagen, donde

un objeto multidimensional, en ocasiones, se reconstruye a partir de

muchas proyecciones unidimensionales. Este procedimiento es muy

aplicado en estudios donde se obtienen imágenes producidas por una

radiación penetrante a través de un objeto.

Este es un tópico que surge independientemente en algunas disciplinas

científicas, como la medicina, la radio astronomía, la investigación sísmica,

el microscopio electrónico y la interferometría óptica. La reconstrucción de

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 28: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 16 -

imágenes a partir de proyecciones se ha estudiado por un gran número de

científicos con distintos puntos de vista.

Matemáticamente, los problemas de reconstrucción de imágenes se

resuelven usando la teoría de !a Transformada Radón, ligada a la

transformada de Hough, que está asociada a muchos algoritmos de

reconstrucción.

1.2.6 COMPRESIÓN DE DATOS DE LA IMAGEN.

El monto de información asociado con una información visual es muy

grande. Esto implica que el guardar la información visual requerirá de una

enorme capacidad de almacenamiento. Sin embargo, la capacidad de

almacenamiento es muy relativa, ya que se debe tener también en cuenta

los tiempos de acceso, los cuales son, usualmente, inversamente

proporcionales a la capacidad. Por ello, el almacenamiento y/o la

transmisión de una imagen a través de un sistema de comunicaciones

requieren de una gran capacidad de almacenamiento en las unidades de

grabación y/o ancho de banda de los canales de transmisión, lo cual sería

muy costoso. Las técnicas de compresión de imágenes se relacionan con

la reducción del número de bits requeridos para almacenar o transmitir

imágenes sin pérdidas apreciables de información.

Es fácil inferir donde se presenta este problema: cuando se transmiten

señales de televisión, imágenes de satélite, radar, sonar, aéreas,

teleconferencias, comunicación de computadoras, etc.; los problemas de

almacenamiento se dan cuando se guarda información proveniente de

documentos orientados a la educación, medicina, o ciencias aplicadas que

necesitan interpretar un gran conjunto de detalles provistos por una imagen

obtenida de una fuente.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 29: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -17-

1.3 ELEMENTOS DE LOS SISTEMAS DE PROCESAMIENTO

DIGITAL DE IMÁGENES

Para realizar el procesamiento de una imagen se necesitarán los siguientes

elementos:

Para adquisición de imágenes

Para almacenar las imágenes

Para tratar imágenes

Para comunicar y transmitir las imágenes

Para presentar las imágenes

1.3.1 ADQUISICIÓN DE IMÁGENES.

Son los equipos y aparatos necesarios para tomar una característica del

objeto a ser analizado y convertirlo en imagen. Este es el primer paso y en

él intervienen dos elementos: el dispositivo físico sensible a una

determinada banda del espectro de energía electromagnética y que

produzca una señal eléctrica de salida proporcional al nivel de energía

detectado. El segundo, denominado digitalizador, se encarga de

transformar la señal de salida del sistema a formato digital.

1.3.2 ALMACENAMIENTO

Una señal de 8 bits y de 1024 x 1024 píxeles necesita un millón de bytes

de memoria. De esta manera, la capacidad de almacenamiento adecuada

para un sistema de tratamiento digital se convierte en un reto para los

diseñadores pues ellos deberán proporcionar los parámetros para

determinar dicha capacidad.

El almacenamiento digital de aplicaciones de procesamiento de imágenes

cae en tres categorías básicas:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 30: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES -18-

a) A corto plazo, que se lo utilizará durante el procesamiento. Para esto se

utilizará la memoria de la computadora o unas tarjetas especiales,

denominadas memorias temporales, que tienen un rápido acceso.

b) En línea, para una reutilización rápida. Se usarán los discos magnéticos

o los de computadora o los magneto - ópticos.

c) En archivo, cuando los datos no se los utiliza frecuentemente. Se

usarán las cintas magnéticas y los CDROMs.[6]

Comunicación

Adquisiciónde la imagen

Scanner

Video

Televisión

Impresora

Computadora

Presentación

Discos ópticosDiscos flexibles

Cintas magnéticas y D¡scos éticos

de video

Figura 1.5: Elementos funcionales de un sistema de procesamiento digital de imágenes[6]. Los componentes de cada cuadro son solo ejemplos de los equipos quepueden ser utilizados en cada fase.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 31: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 19 -

1.3.3 PROCESAMIENTO

El procesamiento de imágenes requerirá de procedimientos que

normalmente se expresan en forma de algoritmos. En este caso, la mayor

cantidad de funciones se las desarrolla vía software. El hardware debe ser

considerado de tal manera que la velocidad de procesamiento del hardware

permita realizar un rápido procesamiento de la imagen.

En la actualidad, la mayoría de sistemas de procesamiento de imágenes

son netamente software capaz de correr en computadores personales. En

algunos casos, y gracias al auge del Internet y las computadoras, el

software es barato o de versión libre. Los investigadores deben hacer las

dos cosas: diseñar el hardware y el software asociados a un sistema de

procesamiento de imágenes.

Pero, una cosa que se debe tener presente, es que algunas de las

aplicaciones de procesamiento de imágenes se diseñaron para resolver un

problema específico. Cuando uno se encuentra con este inconveniente se

enfrentará al dilema de adaptar el programa a su necesidad o desarrollar

otro para su aplicación estricta. Ambas son soluciones viables de realizar,

sin embargo, hay que analizar si la aplicabilidad de la solución es

conveniente para el usuario.

1.3.4 PRESENTACIÓN

Para muchos, uno de los éxitos de cualquier sistema de tratamiento digital

de imágenes es la forma como los datos pueden ser presentados. A veces,

los resultados obtenidos no sólo interesan a un investigador, sino que

interesan a varias personas. De allí, la forma de presentación juega

papeles importantes. Se puede inferir, que dependerá mucho de la

necesidad de analizar los resultados y a quienes interesa la información

para ponerla en pantalla, en impresora, o en archivo.

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 32: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 1: INTRODUCCIÓN AL PROCESAMIENTO DIGITAL DE IMÁGENES - 20 -

Dentro de estos casos se halla la imagen de televisión. No tiene mucho

sentido que una imagen de un programa en vivo, sea impresa en papel y

luego distribuida a los espectadores. A más de un inútil desperdicio de

recursos, se puede decir que es una idea absurda.

Una vez que se ha planteado un entorno muy simple del procesamiento de

imágenes, a continuación se estudiará las herramientas matemáticas

comunes del procesamiento de imágenes: las transformadas. Luego, y una

vez establecida la utilidad de cada transformada, se realizará el estudio de

la Transformada de Hough, objetivo de este trabajo, en conjunto con

algunos detalles de lo que es la digitalización y muestreo de imágenes, y la

utilidad de esta transformada en la solución de algún problema específico

de procesamiento de imágenes.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 33: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2

LAS TRANSFORMADAS DE LA IMAGEN

2.1 INTRODUCCIÓN

Como se indicó en el Capítulo precedente, la imagen es una función

bidimensional de la intensidad de la luz. Esto es, que cualquier expresión

que trate de relacionar una imagen, debe tener en consideración las

coordenadas espaciales que un punto de la imagen tiene con respecto a un

sistema predeterminado de referencia1.

Para que esta imagen pueda ser estudiada, comprimida, tratada, filtrada y

afectada por cualquier otro procesamiento de tipo digital, se la debe

convertir en una función discreta o, propiamente, debe pasar a través de un

sistema que la convierta en un conjunto de unos y ceros agrupadas en

conjuntos de n bits.

Si se desea que la imagen monocromática, de formato continuo, sea

digitalizada se deberá hacerla pasar por un sistema convertidor de

analógico a digital. Este sistema deberá tener en consideración el teorema

del Muestreo2, cuya aplicación es fundamental en el estudio de los

sistemas de procesamiento digital de señales.

Adicionalmente, la imagen, en sí mismo, es bastante compleja de analizar.

Para simplificar su estudio, se utiliza el criterio de la transformada de una

función. El principio de una transformada es convertir una función,

perteneciente a un espacio vectorial, en otra función del mismo espacio o

de otro espacio, por medio de varias funciones denominadas bases del

espacio vectorial.

1 Véase ia convención de coordenadas para una imagen en la Sección 1.1.12 Teorema del Muestreo: "Una señal ¡imitada en banda, que no contiene componentes espectrales mayores que ia frecuencia fm (Hz),

está determinada en forma única por sus valores en intervalos uniformes menores de «y ~ segundos"¿'

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 34: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 22 -

En la bibliografía de procesamiento de señales [9], así como de

Matemáticas Avanzadas se hace referencia a los principios de las

transformadas de función, por tal motivo, no se hará un estudio a

profundidad de los fundamentos de las transformadas de función, y más

bien se enfocará el estudio a las principales transformadas de la imagen.

Sin embargo, el objetivo de este trabajo no es analizar a profundidad el

comportamiento de cada una de las transformadas de la imagen. En

consecuencia, el trabajo se centrará en enunciar las particularidades de las

mismas y algunas características que servirán en los Capítulos siguientes

al compararlas en su desempeño con la transformada de Hough.

2.2 LAS TRANSFORMADAS DE LA IMAGEN

El término transformada está asociado a una relación matemática que

permite expresar una función definida en un espacio vectorial Ü^Tde base

canónica conocida <v-i, v2l .... vn>, como una combinación lineal de otra

base canónica, del mismo espacio vectorial, o de otro espacio vectorial <?¿.

Matemáticamente, se puede decir que:

: X = av! + bv2 + cv3 + ..... +jvn (2-1)

donde V es el vector de elementos: v1( v2, v3 ..... vn; y a, b, c, .... j son

escalares.

El término transformadas de la imagen se refiere, usualmente, a una clase

de matrices unitarias utilizadas para representar imágenes digitalizadas.

Así como una señal unidimensional puede ser representada por una serie

ortogonal de funciones base, una imagen puede expandirse en términos de

un grupo discreto de arreglos básicos llamados bases de la imagen. Estas

bases de la imagen pueden generarse por matrices unitarias;

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 35: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 23 -

alternativamente, una imagen dada N x N píxeles puede ser vista como un

vector N2 x 1. Una transformada de imagen provee un grupo de

coordenadas o base vectorial para un espacio vectorial [9].

Las principales transformadas de la imagen, y que se harán referencia en

este trabajo, son:

a. Transformada de Fourier

b. Transformada discreta coseno

c. Transformada discreta seno

d. Transformada Walsh

e. Transformada Hadamard

Adicionalmente, se tiene a la Transformada Radon, cuyo estudio se lo

incluirá dentro de los anexos a este trabajo.

2.2.1 LA TRANSFORMADA DE FOURIER

La Transformada de Fourier es una de las herramientas más utilizadas en

el campo del procesamiento de señales. La mayoría de análisis de señales

han sido desarrollados gracias a las propiedades de esta herramienta [3, 6,

9, 23].

Para el caso unidimensional, la Transformada de Fourier de una función

f(x), que se denota como^{f(x)}, o F(u), se define como:

00

= F(u) = Jf(x)e-]2rtuxdx ; j = v^l (2 - 2)

Esto muestra que la Transformada de Fourier de cualquier función tendrá,

en el caso más general, una forma compleja así:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 36: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 24 -

F(u) = Re(u)+jlm(u) (2-3)

Donde Re(u) e Im(u) son las partes real e imaginaria de la Expresión (2 -

2). La forma más conveniente de utilizar la transformada de Fourier es la

forma polar de la misma así:

^{f(x)} = F(u)=|F(u)|ej*(u) (2-4)

Donde |F(u)| recibe el nombre de espectro de Fourier de f(x) y (|>(u), es el

ángulo de fase3. Al cuadrado del módulo de la transformada de Fourier se

le conoce como espectro de potencia de f(x), o, densidad espectral de

potencia de f(x) [6].

Al valor de u de F(u) se lo conoce como variable de frecuencia. Esta

designación se la hace debido a que el término exponencial de la

representación polar de la transformada de Fourier representa el ángulo de

fase expresado en radianes, según Ea fórmula de Euler4 [6].

La transformada inversa de Fourier se define como:

= f(x) = F^e^du ; j = ,' í (2 - 5)

Para el caso bidimensional, la transformada de Fourier y la transformada

inversa de Fourier se expresan como:

Se define como módulo y ángulo de fase de una función compleja a:

F(U)

eJ2;tux =

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 37: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 25 -

, y)} = F(U, V) = | Jf (x, yje-^x^'dxdy ; j = -;-1 (2 - 6)-W- 00

oo oo

1{F(u, v)} = f(x, y)= JjFCu^e^^dudv; j = V- 1 (2-7)

Propiedades de la Transformada de Fourier [9, 23]

a. Frecuencia espacial. Si f(x, y) representa la luminancia y (x, y) las

coordenadas espaciales, (u, v) son las frecuencias espaciales que

representarán los cambios de luminancia con respecto a distancias

espaciales. Las unidades de (u, v) son recíprocas de (x, y).

b. Unicidad. Para una función continua f(x, y), existe una única

transformada de Fourier F(u, v).

c. Separabilidad. Por definición, el núcleo de la transformada de Fourier es

separable, así que se puede escribir como una transformada separada

en x e y, así:

CO 00

y)} = F(u, v) = f ff(x,y)e-i2"<ux'dx -J2;n(vy)dy; j=^Cí (2_8)

Lo que significa que la transformada bidimensional puede realizarse por

una sucesión de transformadas unidimensionales según cada una de

sus coordenadas espaciales.

d. Respuesta de frecuencia y valores propios de sistemas invariantes

desplazados. Una propiedad fundamental de las funciones propias de

un sistema lineal invariante en el tiempo es que sus funciones propias5

están dadas por el exponencial complejo eH27t(ux + \, en cualquier

sistema invariante, para cualquier valor de u y v, la salida de un sistema

lineal invariante sería:

' funciones propias de un sistema se definen como una función de entrada que aparecen a la salida con un cambio posible solo en laamplitud. Esto significa que la función de salida es una combinación lineal de la función de entrada.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 38: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 26 -

00

g(x, y) = Jh(x-x\y-y')ej2*(uxl+^'Wdy' (2 - 9)—00

Al realizar el cambio de variables x" = x-x(, y=y -y ; y, simplificando el

resultado, se obtiene:

G(x, y) = H(u, v) ei27t(ux + vy) (2 - 10)

La función H(u, v), que es la transformada de Fourier de la respuesta a

un impulso, se denomina respuesta de frecuencia del sistema.

e. Teorema de convolución. La transformada de Fourier de la convolución

de dos funciones es el producto de las transformadas de las funciones.

g(x, y) = h(x, y) • f(x, y) o G(u, v) = H(u, v) F(u, v) (2-11)

Donde • representa la operación de convolución.

Análogamente, se puede llegar a establecer que la transformada de

Fourier del producto de dos funciones es igual a la convolución de sus

transformadas de Fourier.

f. Producto interno. El producto interno de dos funciones es igual al

producto interno de sus transformadas de Fourier

00 00 00 cO

J Jf (x, y) h * (x, y) dx dy = J f F(u, v) H * (u, v) du dv (2-12)—00-00 —00—00

Cuando f = h, el producto interno toma la forma de la fórmula de

conservación de la energía de Parsevaf, es decir que, la energía total

en la función, es la misma que en su transformada de Fourier [9, 23].

6 Teorema de Parseval [4]:oo W oo oo

r= f [|f(x,y)2dxdy= f fF(u,v)2 dudv— OO—00 —eo—M

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 39: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -27-

La Transformada Discreta de Fourier [3, 6]

Cuando una función continua se ha discretizado, el resultado obtenido es

una sucesión de la forma:

{f(xo), f(x + Ax), f(x + 2Ax)t .... f(x + [N -

la cual se obtiene luego de hacer pasar la función continua por un sistema

de muestreo que cumple las condiciones del Teorema del Muestreo y Ax,

son los intervalos donde son tomadas las muestras (Figura 2.1) [6].

Figura 2.1: Muestreo de una función continua

Si se hace una analogía con el caso continuo: los símbolos de integrales se

reemplazan por sumatorios y los valores de x serán discretos. De esta

forma se obtiene el par de transformadas unidimensionales discretas:

F(u) =x=0

(2-12)

Será la transformada discreta unidimensional de Fourier directa, mientras

que:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 40: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 28 -

N-1 -2nlix

/ ' \")" v — n *i o M "i /«-» *< ^ \¿ x - 0 , 1,2,..., N-1 (2-14)

Será la transformada discreta unidimensional de Fourier inversa.

Los valores u = O, 1, 2,..., N - 1 de la transformada discreta de Fourier

corresponden a las muestras de la transformación continua en los valores

O, Au, 2Au,..., (N - 1) Au. En otras palabras, F(u) representa F(uAu). Esta

notación es similar a la utilizada para la función discreta f(x), con la

salvedad de que ahora las muestras comienzan desde el origen del eje de

frecuencias. Los términos Au y Ax se relacionan mediante la Expresión:

AU = --- /o H c\x (2-15)

El par de transformadas discretas bidimensionales de Fourier es, de

manera análoga:

' (2-16)x=0 y=0 v '

Será la transformada discreta bidimensional de Fourier directa, mientras

que:

N~1 N~1 • L* vt\ * (2 — 17)

U=0 v=0 x '

x = 0,1,2 M-1;y = 0, 1,2,..., N-1

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 41: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 29

Será la transformada discreta bidimensional de Fourier inversa.

Se debe considerar que si, en el caso de una función continua

unidimensional, el muestreo se lo hacia solo en un eje, para el caso

bidimensional el muestreo se lo hace en los dos ejes, con lo cual se obtiene

una cuadrícula de muestreo, con divisiones de ancho Ax e Ay, en los ejes x

e y respectivamente. Los comentarios respecto al muestreo en el caso

unidimensional son plenamente aplicables en el caso bidimensional. En

consecuencia, los valores de Au y Av, en función de sus correspondientes

Axe Ay, serán:

Au = —— Ax * O /o ^ o\x (2-18)

1Av = —— Ay * O /o * n\y y (2-19)

Cuando en las imágenes se hace un muestreo con los mismos valores de

M y N (distribución cuadrada), las expresiones (2 - 16) y (2 - 17) quedan:

\ Ny)e (2-20)

u=0 v=0

u;v = 0, 1,2, ...,N-1

x=0 y=0

x, y = 0,1, 2 N-1

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 42: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 30 -

De manera común, las imágenes se digitalizan en matrices cuadradas,

pero no se debe olvidar que, para el caso más general, se debe asumir que

las imágenes son del tipo rectangular [6, 9].

Las otras características de la transformada de Fourier, tales como

espectro de Fourier, ángulo de fase y espectro de potencia, se calculan de

manera análoga al procedimiento propuesto para funciones continuas, con

la diferencia de que el análisis se lo hará con variables discretas.

La propiedad de separabilídad de la transformada tridimensional de Fourier,

caso discreto

La transformada discreta bidimensional de Fourier es una imagen {u(x, y)}

de orden N x N es una transformada separable [3, 6, 9] que se define

como:

(2 - 22)x=0 y=0

u;v = 0, 1,2 N-1

u=0 v=0

x, y =0,1, 2,..., N-1

En ambos casos, tanto la transformada directa como la inversa de Fourier

se pueden escribir como:

1 N-1 N-1

F(u,v) = — ££N x=Q y=Q

u;v = 0, 1,2, ..., N-1

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 43: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -31-

Y

N-1 N-1

f(x.Y) = ££F(u,v)h(x,y,u,v) (2 - 25}u=0 v=0 V '

x, y = 0,1,2 ..... N-1

Los términos de g(x, y, u, v) y h(x, y, u, v) se denominan núcleos de la

transformada directa e inversa respectivamente.

Si un núcleo es separable, debería cumplir la condición de que:

g(xí y, u, v) = g^x, y)g2(u,v) (2 - 26)

Si en la Ecuación (2 - 26), 91 es igual a g2, se está frente al caso de que el

núcleo es simétrico7.

Analizando la Expresión (2 - 20). El núcleo de la transformada directa de

Fourier es:

g(x, y. u, v) = ¿e » > (2-27)

Por propiedades de la función exponencial, el miembro izquierdo puede ser

dividido en dos, con lo cual la Expresión (2 - 27) queda como:

g(x,y,u,v)= Ñ e - T (2-28)\'N A/N

De donde se puede observar que el núcleo de la Transformada discreta

bidimensional de Fourier es separable y además es simétrico, pues:

7 Para el caso de la transformada inversa, las condiciones expuestas hasta este punto son aplicables

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 44: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 32 -

g(x, y, u, v) = g^x. u)gi(y, v) (2 - 29)

1 -Donde: g^u^-e y g 1 ( v , y ) ^ e

Por lo tanto, una transformada de núcleo separable puede ser calculada en

dos etapas utilizando, para cada etapa, una transformada unidimensional.

Este desarrollo resulta muy valioso. Un análisis muy profundo puede llevar

a deducir que, la principal ventaja de la propiedad de separabilidad radica

en que F(u, v) o f(x, y) pueden ser calculados con dos pasos aplicando

sucesivamente la transformada de Fourier unidimensional directa o inversa.

Si la Ecuación (2 -22) se expresa como:

(2~30)x=0

Donde:

F(x,v) = (2-31)

Para cada valor de x, la expresión dentro de los corchetes de la Ecuación

(2 - 31) es una transformada unidimensional de Fourier, con valores de

frecuencia v = O, 1,..., N- 1. Por lo tanto, la función bidimensional F(x, v) se

obtiene tomando una transformada a lo largo de cada fila y multiplicando

por N. El resultado buscado, F(u, v), se obtiene entonces aplicando una

transformada a lo largo de cada columna de F(x, v), según la ecuación

(2 - 30). El procedimiento se resume en la Figura 2.2, el cual se puede

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 45: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -33-

conmutar, es decir, primero se puede extraer la transformada a las

columnas de f(x, y) y luego a las filas de este resultado. Este análisis se

extiende a la solución de la transformada inversa.

(0,0) (0,0}

Transformadas de filaMultiplicación porN Rx, v)

{O, 0),

Transformadas decolumna F(U,V)

Figura 2.2: Obtención de la transformada de Fourier bidimensional como una serie de

transformadas unidimensionales [6, 9]

Pero este análisis es posible expresarlo como matrices. Si el núcleo de la

transformada discreta g(x, y, u, v) es separable, la Ecuación (2 -23) se

puede expresar como:

D = AFA (2 - 32)

Donde D es la transformada N x N resultante para valores (u, v) en el

intervalo discreto de O a N - 1; A es una matriz N x N de transformación

simétrica con elementos a¡j = g(i, j) y F es la matriz imagen N x N.

Si B es la matriz de transformación inversa, se halla la transformada

inversa por medio de la Expresión:

B D B = B A F A B (2 - 33)

Sea B = A , entonces:

BDB = F (2 - 34)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 46: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 34 -

Es importante resaltar la propiedad de separabilidad de varias de las

transformadas que se presentarán a continuación, pues se las puede

expresar de forma similar a (2 -33) y (2 - 34).

Algo igualmente importante de resaltar es que si las matrices de

transformación obtenidas en el análisis anterior también son separables, es

decir, se las puede separar en matrices con menor cantidad de entradas

que las matrices originales (matrices de dispersión), el número de

operaciones puede reducirse de N4 a 2N3 [9]. Sin embargo, una

descomposición adecuada de la transformada de Fourier unidimensional,

puede reducir la cantidad de operaciones de N2 a N Iog2 N [6]. La cantidad

de operaciones para la transformada bidimensional dependerá del número

de pasadas sucesivas de la transformada unidimensional, según se indicó

en esta sección.

El método descrito en el párrafo anterior da origen al concepto de la

Transformada Rápida de Fourier (FFT: Fast Fourier Transform); la

aplicación del procedimiento para encontrar la transformada inversa, dará

origen a la Transformada Rápida Inversa de Fourier (IFFT: Inverse Fast

Fourier Transform), cuya aplicación puede arrojar reducciones en el tiempo

de cálculo de 50 minutos, usando la Ecuación (2 -13), a 5 segundos con la

aplicación del algoritmo de la FFT [6]8.

2.2.2 LA TRANSFORMADA DISCRETA COSENO [3, 6, 9,30]

Matemáticamente, la Expresión que define la transformada discreta coseno

(DCT: Discreto Cosine Transform), de manera unidimensional, es:

S=í rí2x+iw~Vf(x)cosr ; u = 0, 1,2,..., N-1 (2-35)Z^ v ; i 2N . . . i \* **>)x=0 L

8 Esta comparación se la hace considerando solo la Transformada unidimensional. Para el caso bidimensional, la reducción tambiénsurtirá efecto en la misma magnitud.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 47: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN •35-

Y la forma inversa de la transformada es:

N-1

u=02N

(2 - 35)

Donde a(u) se define como:

a(u) =

para u = O

para u = 1, 2,...,N-1

(2 - 36)

La transformada coseno bidimensional se define como:

N-1 N-1C(u, V) = a(u) ct(v) V V f (X, y) eos

x=0 y=0

u,v = 0,1,2 N-1

2Neos

(2y+l)v7t2N (2 - 37)

Y

N-1 N-1

f (x, y) = a(u) a(v) C(u, v) eosu=0 v=0

2Neos

2N (2 - 38)

Y a(u), a(v) vienen dados por la Expresión (2 - 36). Nótese que esta

transformada cumple con el criterio de separabilidad analizado

anteriormente.

Esta transformada es muy utilizada en compresión de imágenes. La Figura

2.3 muestra una imagen monocromática y el gráfico del logaritmo de su

transformada coseno.

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 48: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -36-

Transdmnada Qtanli COIMWImagan bn*: V w«mls.|pg

Figura 2.3:

(a) (b)

(a) Una imagen monocromática; (b) logaritmo de su transformada discreta coseno

Propiedades de la Transformada discreta coseno

1. La transformada coseno es real y ortogonal9.

2. La transformada coseno no es la parte real de la transformada de

Fourier.

3. La transformada coseno es una transformada rápida.

4. La transformada coseno tiene una excelente compactación de energía

para datos con alta correlación.

5. La base vectorial de la transformada coseno (filas de C) son los

vectores propios de la matriz tridiagonal simétrica Q, definida como:

1-ot -a O O-a 1 -a OO -a 1 -aO O -a 1-a

(2 - 39)

Con a definida por la Ecuación (2 - 36).

Una matriz es ortogonal si: A = A* -^ A"1 = AT

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 49: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 37 -

2.2.3 LA TRANSFORMADA DISCRETA SENO [9]

La matriz de transformada discreta seno de una función u(n)

unidimensional, denotada como 4* = {\j/(k, n)}, se define como:

O < k, n < N - 1 (2 - 40)

El par de transformadas seno de una secuencia unidimensional, se define

como:

n=0

O < n < N - 1 (2-42)

El par de transformadas bidimensionales seno de una imagen N x N, en

forma matricial, corresponde a:

D = ¥FY (2-43)

Donde D es la transformada de la imagen original, F la imagen y ¥ la

matriz transformada discreta seno. La transformada inversa será:

F = XPD4/ (2-44)

Propiedades de la Transformada discreta seno

1. La transformada seno es real, simétrica y ortogonal, esto es:

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 50: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -38-

= \J/ — \Lf I — (2 - 45)

2. La transformada seno no es la parte imaginaria de la transformada

discreta de Fourier.

3. La transformada seno es una transformada rápida. La transformada de

un vector de N elementos se puede calcular en N log2N operaciones.

4. La base vectorial de la transformada seno son los vectores propios de la

matriz simétrica tridiagonal de Toeplitz.

Qr =

1 -ct O O

-a 1 -a OO -a 1 -aO O -a 1

(2 - 46)

Con a definida por la Ecuación (2 - 36).

2.2.4 LA TRANSFORMADA WALSH [3, 6]

Si N = 2n, la transformada discreta de Walsh de una función f(x) se obtiene

substituyendo el núcleo

(2 - 47)i=o

En la Ecuación:

N-1

= £f(x)g(x,u)x=0

(2 - 48)

Con lo cual se obtiene:

N-1 n-1

' x=0 ¡=0

(2 - 49)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 51: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN -39-

Donde bk(z) es el k - ésimo bit en la representación binaria de z, es decir

que si n = 4, z =5 (0101, en binario), b0(z) = 1, bi(z) = O, b2(z) = 1, b3(z) = 0.

La Tabla 2.1 relaciona los valores de g(x, u), sin incluir el término constante

1/N, para N = 8. La matriz que forma el núcleo de transformación de Walsh

es simétrica con filas y columnas ortogonales. Esto lleva a la conclusión de

que el núcleo inverso es idéntico al núcleo directo, salvo por el factor

constante.

n-1

(2 - 50)¡=0

Entonces:

N-1 n-1

(2-51)u=0 j=0

Una diferencia entre la Transformada Walsh y Fourier es que Fourier se

basa en términos trigonométricos, mientras que Walsh se centra en un

desarrollo en series de funciones básicas de valores +1 o -1.

\x" \1

2

3

4

5

6

7

0 1 2 3 4 5 6 7

+ + + + + + + +

+ + + + - - - -

+ + . . + + - -

+ + - - - - + -H

+ - + . + . + -

+ - + . . + - +

+ - - + + - - +

+

Tabla 2.1: Valores del núcleo de la transformación de Walsh unidimensional. N = 8 [3]

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 52: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 40 -

=o

Los núcleos de las transformadas bidimensionales de Walsh, directa e

inversa, vienen dados por las relaciones:

(2 - 52)

h(x,y,u,v) = ( - i ) « x « - i - . u i y » - i - . v (2 _ 53)N ¡=o

Como se puede apreciar, los núcleos de las transformadas directa e

inversa son idénticos, por tal motivo, las transformadas directa e inversa de

Walsh son iguales, es decir:

, N-1 N-1 n-1

wiu v^= - Wffx V)TTí-iil-Ui^;o'i-i-KUJ+ü|VyjDri-i-ilV); n _ ^A\V^ M j¿_j^j ^ *'yl iv * \¿- '3**)

x=0 y=0 í=0

N-1 N-1 n-1

-|lv" (2 - 55)' U=0 V=0 Í=Q

En consecuencia, cualquier algoritmo usado para calcular la transformada

directa, servirá para calcular la transformada inversa.

Los núcleos de la transformada Walsh son simétricos y separables, esto los

hace similares a sus pares de la transformada de Fourier, por lo que, para

encontrar los valores de las transformadas directa e inversa se puede

aplicar por repetidas ocasiones la transformada unidimensional de Walsh y

obtener el mismo resultado. Entonces:

g(x, y, u, v) = gi(x,u)g2(y,v) = h1(x,u)h2(y,v)

g(x,y,u,v) =n-1

¡=0(2 - 56)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 53: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 41 -

2.2.5 LA TRANSFORMADA HADAMARD [3, 6, 9]

La transformada de Hadamard discreta tiene como núcleo:

(2 - 57)IN

Donde el sumatorio del exponente se lo realiza en aritmética binaria y bk(z)

es el k - ésimo bit de la representación binaria10 de z. La sustitución de la

Ecuación (2 - 57) en la Ecuación (2 -48) da la siguiente Expresión para la

transformada Hadamard:

(2-58)

Donde N = 2 y u toma valores discretos de O a N - 1 .

Como en el caso anterior, el núcleo de Hadamard forma una matriz de filas

y columnas ortogonales, condición que también la cumple el núcleo de la

transformación inversa, que sería igual a la directa pero no tiene el valor

1/N, así:

(2-59)

Con lo que, la transformada inversa de Hadamard será igual a:

N-1 IM•F/»*-\^ i_in/i ¡\i -A/ D¡(x)b¡(u) • \ — f\ o kl «i ff\) = > Ha(u)^-ij IV IV , x — u, i, ¿,..., IN — i (¿ — 60)

U=0

La Tabla 2.2 muestra la matriz de valores generada por el núcleo de la

transformada unidimensional, para N = 8, donde el término constante se ha

obviado por simplificación. Nótese que si bien las entradas son similares a

1 Véase la explicación del tema en la sección 2.2.5

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 54: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN 42

la transformada de Walsh, el orden de las filas y columnas es diferente, y

esta diferencia solo se da cuando N = 2n.

V\12

3

4

5

6

7

0 1 2 3 4 5 6 7*

+ + + + + + + +

+ + + + - - - -

+ -f - - + +

+ + - - - - 4- +

+ - + - + - + -

+ - + - - + - +

+ - - + + - - +

+

Tabla 2.2: Valores del núcleo de la transformación de Hadamard unidimensional. N = 8 [3]

Nótese que los núcleos bidimensionales serán similares a sus

correspondientes unidimensionales, esto es:

ha(x,y,u,v) = (_

(2-61)

(2 - 62)

Y nuevamente, las transformadas bidimensionales serán

Ha(u,v) =x=0 y=Q

f (*' y > =u=0 v=D

(2 - 63)

(2 - 64)

Las operaciones del sumatorio del exponente, igual como en el caso

unidimensional, deberán realizarse en aritmética binaria.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 55: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 43 -

Al igual que las transformadas anteriores, el núcleo de la transformada de

Hadamard es separable y simétrico, en consecuencia:

g(x, y, u, v) = g1(x,u)g2(y,v) = hai(x,u)ha2(y,v)

g(x,y.u,v) = (2-65)

Lo que conduce a intuir que la transformada bidimensional de Hadamard se

puede obtener por medio de la aplicación sucesiva del algoritmo de la

transformada unidimensional.

La mayoría de las imágenes obtenidas se muestrean a N = 2n por fila o

columna. En la literatura es común observar que las transformadas de

Walsh y Hadamard se entremezclan y en ocasiones se utiliza el término

Walsh - Hadamard para referirse a cualquiera de ellas. De hecho, se dice

que los vectores base de la transformada de Hadamard se obtienen de

funciones llamadas funciones Walsh [9].

2.2.6 OTRAS TRANSFORMADAS DE IMAGEN [9, 10]

En la literatura se pueden encontrar otras transformadas de imagen muy

útiles y que se emplean para realizar procesamiento de imágenes. En este

estudio, únicamente se las mencionará pero no se las estudiará a fondo, ya

que no es objeto de este trabajo.

A pesar de ello, existen dos transformadas que, por su interrelación se las

estudiará más adelante: la una es la Transformada Hough, objeto de este

estudio, y la otra es la Transformada Radon. Estas dos transformadas

merecerán un estudio aparte.

Las transformadas de la imagen que se mencionarán son:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 56: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 2: TRANSFORMADAS DE LA IMAGEN - 44 -

Transformada Haar [9]. Transformada muy rápida. Se la utiliza en el

estudio de la extracción de características, codificación y problemas del

análisis de la imagen. La compactación de la energía es considerable.

Transformada Slant [9]. Transformada rápida. Útil para codificación de

imágenes. Tiene una muy buena compactación de energía para imágenes.

Transformada Karhunen - Loeve [9, 10]. Es óptima de muchas maneras.

No tiene un algoritmo rápido, utilizada en evaluación de desempeño y para

encontrar límites de funcionamiento. Útil para pequeños tamaños de

imágenes; tiene una mejor compactación de energía en el sentido de la

media cuadrática sobre un ensamble.

Transformada Karhunen - Loeve Rápida [9]. Utilizada para diseño

rápido, técnicas de procesamiento recursivo de bloques, incluyendo

técnicas adaptivas. Su desempeño es mejor que las técnicas de

procesamiento independiente bloque por bloque.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 57: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3

LA TRANSFORMADA DE HOUGH

3.1 INTRODUCCIÓN

Uno de los puntos de estudio del Procesamiento de Imágenes es, como se

indicó en el Capítulo 1, la segmentación de la imagen para la identificación

de características de una parte de ella o de todo el conjunto. Este paso, la

segmentación, está ubicado en el nivel intermedio del procesamiento de

imágenes, pues, el grado de complejidad que tiene el proceso, y los

tiempos de cálculo o de computación son, relativamente, altos y

dependerán de la precisión que se quiera dar al tratamiento [7].

Dentro del análisis de la imagen, la segmentación de imágenes se

convierte en el primer paso. La segmentación de una imagen consiste en

dividir a la imagen en sus partes constituyentes u objetos; este proceso de

subdivisión de la imagen siempre dependerá del problema que se va a

resolver: para unas aplicaciones o investigaciones, será, por ejemplo, útil

ubicar a una persona en el centro de un paisaje o quitar a la persona de un

paisaje. Para poder hacer esto, se debe identificar claramente al contorno

de la persona para poder quitarla de la imagen original.

Una vez que se han detectado las características de la imagen, mediante la

segmentación, el siguiente proceso consiste en dar una representación a

los píxeles segmentados. Para realizar esto se tienen dos alternativas:

representar la imagen con los píxeles del contorno (características

externas), o hacerlo con los píxeles internos del segmento (características

internas). La primera alternativa se usa cuando lo importante, o el objeto de

estudio, se centra en la forma y la segunda alternativa cuando el interés

radica en el color de la imagen.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 58: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 47 -

Satelitales, la Investigación médica en Imagenologfa (Técnicas ligadas a

los Rayos X, la tomografía axial computarizada, el microscopio electrónico)

y al control de movimiento de robots por sensores, sin descuidar sus

aplicaciones en otras áreas del conocimiento humano como pueden ser los

sistemas de seguridad por medio del reconocimiento de patrones dactilares

o de determinada característica física de un elemento.

3.2 FUNDAMENTOS DE LA TRANSFORMADA DE HOUGH

La Transformada Hough fue lanzada en la década de 1962 por Paul. V. C.

Hough en un artículo que se tituló UA method and Means for Recognizing

Complex Patterns", y, hoy en día, se ha convertido en "una de las patentes

más citadas en la literatura del procesamiento de imágenes" [24]. Por ello,

su estudio se ha profundizado y sus aplicaciones giran en torno al

reconocimiento de bordes y perfiles, con orientación a la Imagenología, el

estudio geográfico por medio de imágenes obtenidas del satélite y la

segmentación de las imágenes, aunque, en sus orígenes, se la enfocó al

estudio de las partículas subatómicas que se desplazan a través de un

campo visual [31]. El texto completo de este documento se lo puede

encontrar en el Anexo A.

La Transformada Hough propone una forma de incorporar el conocimiento

previo en la transformada, con el objeto de reducir el costo computacional.

En un principio se la definió para estudiar líneas con una pendiente y un

parámetro de offset, pero, también se la está estudiando bajo el criterio de

la ecuación normal de la recta. Este criterio ha ganado terreno en el

desarrollo de algoritmos expuestos para este problema y de hecho, se lo ha

aplicado en estudios de detección de contornos de imágenes satelitales y

para el procesamiento de imágenes relacionadas con la medicina [5, 6, 7,

8, 13-16, 24,44].

La idea principal, sobre la que gira la Transformada de Hough es que "para

un punto dado en un segmento de línea, en la gráfica 108 (Ver Fig. 3.1), se

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 59: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -48-

dibuja una línea en el plano transformado..." [31]; es decir, se transformará

cada píxel de la imagen individualmente, en el parámetro de dominio a una

línea en el plano de la transformada. Esto implicará que la transformada de

Hough convertirá un punto en una línea, según se explicará en el análisis

que sigue en este Capítulo.

Figura 3.1: Figura 1 de la Patente que dio origen a la transformada de Hough [31]

"Es difícil, desde un punto de vista histórico, establecer que motivó el

desarrollo de la Transformada de Hough. Esto fue como una nueva idea y

no fue motivado por resultados..." [24]. Hay autores que piensan que la

transformada Hough nació de la nada, sin embargo, como se mencionó

anteriormente, la importancia de la transformada está en que es una

herramienta muy valiosa para lo que es la detección de bordes,

segmentación y como base para el reconocimiento de patrones de imagen.

Algunos de los estudios que se presentan como referencia, recalcan el

hecho de que sus trabajos se sustentan en la transformada de Hough y

sostienen la importancia de la misma. Además, el mismo P. V. C. Hough

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 60: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 49 -

manifiesta, en la introducción de la patente, que este invento se relaciona

con el reconocimiento de patrones complejos y "más específicamente

como un método y medio para máquinas de reconocimiento de líneas

complejas en fotografías u otras representaciones pictóricas" [31].

Sin embargo, y a pesar de los trabajos que se han hecho sobre el

particular, "la transformada de Hough no es una herramienta mágica..."2. Se

ha mencionado algunos de sus campos de aplicación y se ha mencionado

su ámbito de desarrollo, en lo que resta del trabajo se tratará de analizar su

desempeño como herramienta para el procesamiento integral de imágenes

digitales monocromáticas.

3.2.1 PRINCIPIOS MATEMÁTICOS DE LA TRANSFORMADA DE HOUGH.

La Transformada de Hough es una expresión que relaciona un punto en el

plano XY con una recta en el plano del parámetro. La pregunta que se

debería contestar es ¿cómo es que un punto puede transformarse en una

recta? La respuesta no es otra que el método de transformación a seguir, o

la transformada a aplicar, la cual debe estar relacionada con la línea recta

en alguna de sus formas conocidas. Por ello se debe establecer los

principios fundamentales de la línea recta en la Geometría Analítica.

3.2.1.1 Generalidades de la ecuación de la línea recta [31,32]

Euclides, gran matemático griego del siglo III A. C., manifestó que "por dos

puntos ubicados en un mismo plano, solo podrá pasar una recta y nada

más que una". Este principio, junto a aquel postulado de las paralelas, son

el pilar fundamental de la hoy conocida "Geometría Euclidiana". De esta

geometría y la mezcla con la matemática de Descartes o cartesiana, nace

la tan conocida "Geometría Analítica", que no es más que la aplicación de

los postulados de Geometría al plano cartesiano.

1 La referencia es una frase que el Dr. Hideaki Goto de la Universidad de Tohoku, Sendai, Japón, escribió en un e-mail, cuando le pedíun consejo sobre el trabajo (Nota del autor).

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 61: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 50 -

La distancia entre dos puntos colineales, ubicados en un mismo eje, es:

d = x? — Xi (3 — 1)

Si los puntos están ubicados en el eje horizontal y:

dy = y2-yi (3-2)

Si están ubicados en el eje vertical.

La tangente del ángulo de inclinación de una recta, que pasa por los puntos

(XL yi) y (X2, y2>, respecto al eje horizontal, conocida como pendiente de la

recta (m) (Fig. 3.2 (a)), se define por la Expresión (3 - 3):

(3-3)Y VA2 A1

Si se desea encontrar la pendiente de una recta (Fig. 3.2 (b)), dado un

punto genérico P(x, y) y un punto de la recta conocido Q(XI, yi), se deberán

reemplazar los valores de P y Q en la Ecuación (3 - 3), de la siguiente

manera:

— v¿i (3-4)

_ v1

Y de ahí:

y - yi = mx - mxi (3 - 5)

Si la suma de mxi + y-i es un número real, se la puede reemplazar por

medio de un valor b, así:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 62: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -51-

y = mx + b (3-6)

Que es la ecuación de una recta de pendiente m que corta al eje y en el

valor b, que puede ser mayor o menor que cero.

(a) (b)

Figura 3.2: (a) Cálculo de la pendiente de una recta

(b) Cálculo de la ecuación de una recta dada la pendiente y el valor de b

La Ecuación que se acaba de encontrar es de mucha utilidad para el

estudio de la transformada Hough, sin embargo, se necesita encontrar otra

ecuación que también se aplica en el estudio de esta transformada. Esta

ecuación es la ecuación normal de la línea recta.

La Ecuación (3 - 6) se puede reescribir como:

- m x + y - b = 0 (3-7)

La forma general, de la Ecuación (3 - 7) sería:

Ax + By + C = O (3-8)

A CDonde: m = —, b = —. La Expresión (3 - 8) se conoce como la

ecuación general de la línea recta.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 63: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -52-

Pero, hay aplicaciones en las cuales la ecuación general y la ecuación de

pendiente no son aplicables o complican la solución de un problema. En

estos casos, es necesario la utilización de la ecuación normal de la línea

recta.

Tómese como referencia la Figura 3.3(a). La distancia de un punto a una

recta está definida como:

Ax1 + By1 + C

VA2+B2(3-9)

Donde A, B, C son los coeficientes de la ecuación general de la recta y

yi son las coordenadas del punto que se va a estudiar.

(a) (b)

Figura 3.3: (a) Parámetros para hallar la distancia de un punto a una recta(b) Parámetros de cálculo de la ecuación normal de una recta [32, 33]

Si el punto P(xi, yO es el origen de coordenadas, la Ecuación (3 - 9) se

reduce a:

*=? (3-10)

Despejando C de la Ecuación (3 - 10) y dividiendo los términos de la

Ecuación (3 - 8) para VA2+B2 , se obtiene:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 64: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -53-

A BX+-T y-p = o2 + B2 ^/A27B7

A BDonde: ¡ = cos0. . =sen9, y 0 es el ángulo formado

entre el eje de las x y la perpendicular trazada desde el origen de

coordenadas a la recta Ax + By + C. De esta manera, la Ecuación (3-11)

toma la forma:

ysen0-p = 0 (3-12)

Que es la forma de la ecuación normal de la recta. El valor de 0 está

comprendido entre O y TI, mientras que p es un valor positivo.

La ecuación normal de la recta y la ecuación de la recta dada la pendiente

y la ordenada en el origen son las dos herramientas principales que se

utilizan para la aplicación de la transformada de Hough.

Hay otras formas de la ecuación de la línea recta, pero por este momento

se las dejará a un lado, pues no es objeto de este estudio la profundización

del análisis de la línea recta y sus ecuaciones.

3.2.1.2 Principios del Plano de la Transformada de Hough

Paul V. C. Hough define, en su trabajo que desembocó en la Transformada

de Hough, los parámetros fundamentales de definición del plano

transformado [31(Columna 1, Párrafo 56 a Columna 2, Párrafo 34)]. En

este contexto se definen 3 puntos principales:

1. Por cada punto, elemento de una línea, se obtendrá una recta en el

plano transformado.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 65: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 54 -

2. Para un punto de una línea en la parte superior de la framelet 108 (Ver

Fig. 3.1), la línea en el plano transformado está inclinada 45° a la

derecha; un punto en la horizontal de la misma framelet aparecerá

como una vertical en el plano transformado; un punto de una línea en la

parte inferior déla misma framelet, se representará por una línea

inclinada 45° a la izquierda en el plano transformado. Es decir, la línea

en el plano transformado tendrá una inclinación con la vertical que es

proporcional al desplazamiento vertical del punto en el segmento de

línea horizontal 109 en la framelet 108.

3. Se construye cada línea en el plano transformado de manera que tenga

un cruce con la línea horizontal 101 en la imagen 100 igual a la

coordenada horizontal de su punto respectivo del segmento de línea en

la/ra/r?e/eM08.

Si una serie de puntos en una framelet, reposan en una línea recta, las

líneas correspondientes de la transformada se intersecarán en un punto el

cual se llamará nudo 112 (Figura 3.1). Esto es, además, de que las

coordenadas rectangulares del nudo 112 en la gráfica 100 tengan las

siguientes propiedades:

1. Las coordenadas horizontales de los nudos 112 son iguales a las

coordenadas horizontales en la framelet 108 en la cual, los segmentos

de líneas rectas 102, 104 y 106 interceptan la línea media 109 de la

framelet 108.

2. La coordenada vertical de los nudos 112, relativa a la línea horizontal

101 de la gráfica 100, es proporcional a la tangente del ángulo entre los

segmentos de línea recta 102, 104 y 106 y la vertical. Así, las

coordenadas de los nodos 112 en el plano transformado 102A, 104A y

106A dan como resultado las pendientes y los interceptes de los

segmentos 102, 104 y 106 en la gráfica 108.

3 Framelet: Una framelet se la define como una parte de una figura que está incluida en un texto. En la Figura 3.1, lasframelets sedefinen como las panes de la figura: 108 la parte superior del gráfico y 100 la parte inferior de la misma

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 66: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 55 -

Como se mencionó en Capítulos anteriores, la imagen se la trata como un

conjunto de píxeles dentro de una región limitada. Lo ideal es que dicho

espacio sea definido como un plano en el espacio euclideano4, el cual es

un cuadrado y se lo denominará "la región de imagen continua". Se

asumirá que los lados de este cuadrado son paralelos a los ejes

coordenados x - y.

Una vez que se ha establecido las características de la región de imagen a

estudiar, se debe establecer ciertas definiciones acerca de los puntos de

imagen contenidos en la región, su definición matemática y algunos otros

convenios sobre su muestreo.

Sea (x, y) un punto de la imagen a estudiar, As es un intervalo de longitud

entre píxeles, el cual es un valor entero. Así, se puede afirmar que un punto

de una imagen, denotado como (x,y), se lo puede hallar al aplicar las

expresiones:

x =

y As 2

xAs (3-13)

xAs (3-14)

Donde [ J, es el operador piso5, As es el intervalo de cuantización de la

imagen y 5x es el error de cuantización6 en x, que se define como 8x =

x - x. Se puede llegar a establecer que |6x| < As/2 y |8y| < As/2.

Otro punto importante es el establecer que los bordes de la región de

imagen seleccionada son iguales a 2NAs, donde N es un número entero.

La cantidad de píxeles en los bordes de una imagen será igual a (2N + 1).

4 El espacio euclideano es el tan conocido espacio cartesiano y está representado por el plano x - y - z, donde el plano x - y es unsubconjunto del mismo.

s El operador piso: se define como el máximo entero menor a una cantidad, esto es: | z | U n i n < Z < n + 1

6 Para el caso de 6y, el error de cuantización en y, este se definirá como: Sy = y - y

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 67: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 56 -

En general, dentro del espacio euclideano, la imagen será un subconjunto

discreto del mismo, en donde los puntos de la imagen están distanciados

uno de otro en intervalos finitos discretos. En este punto se debe

mencionar que la imagen, en si mismo, es un conjunto continuo de puntos,

pero para el estudio de fa transformada de Hough se establecerá que se

halla en este espacio discreto.

3.2.1.3 Definición formal de la Transformada de Hough [17].

Para 1992, Princen, lllingworth y Kittler hacen público un artículo en Journal

of Mathematics Imaging Vision, Vol. 1 que se titula "A formal definition of

Hough Transform: properties and relationships". En este artículo se da una

definición formal de la Transformada de Hough. En algunos de los artículos

que sustentan este trabajo se hace referencia a este documento, que junto

al trabajo de lllingworth y Kittler "A survey of the Hough Transfom?", son

una herramienta fundamental en el estudio de la Transformada de Hough.

Sea un punto X (x, y) en el espacio de la imagen, Q = (coi, ..... , «N) un punto

en el espacio parámetro y f(X, Q) = O la función que parametriza un

conjunto de curvas. El conjunto de puntos del contorno de la imagen,

s = {Xi, ...... , Xn}, se representa como la suma de las funciones delta en las

localidades de los píxeles:

= ¿8(X-Xj) (3-15)

Se notará como Cn a una celda en el espacio parámetro centrada en Q. Un

análisis de tales celdas permiten hacer la discretización del espacio

parámetro. Se define:

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 68: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 57 -

í1 si ÍA: f x-A) = 0} n Cn * 0i v . / i Q (3-16)|0 otro valor v ;

Así que, p(X, Q) es uno, si cualquier curva en el espacio de parámetro pasa

a través de X en el espacio de la imagen. La transformada de Hough puede

escribirse como:

H(n)=Jp(X.n)l(X)dX (3-17)

O

(3-18)

, además, es el número de píxeles de imagen de cualquier curva que

pasan a través de Cn. La definición es correcta para el método del

acumulador que es típicamente usado para implementar la transformada de

Hough. Los métodos del acumulador, discretizan el espacio de parámetro

en celdas y mantienen un contador para cada celda. Los métodos para

hallar la Transformada de Hough se discutirán más adelante en el presente

trabajo.

Es claro el hecho de que no existe un solo método para hallar la

transformada de Hough de una imagen. Lo primero que se debe encontrar

son los distintos métodos de parametrización de la imagen para, de esta

manera, hallar la forma más adecuada de encontrar la Transformada de

Hough de una imagen.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 69: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 58 -

3.2.1.4 La Transformada de Hough en función de la pendiente y la ordenada en el

origen.

En general, dentro del espacio euclideano, una función puede definirse

como:

F(x, y;u, v) = 0 (3-19)

Donde x, y, u y v son variables. Se establecerá que la función aquí

presentada es continua y que cualquiera de sus variables puede ser

expresada como una función de las otras tres, es decir, por ejemplo:

u = Fu(x,y,v) (3-20)

Al iniciar este acápite se estableció que la transformada de Hough está

ligada a la relación que existe entre un punto y una línea recta, es por ello,

que en un principio se estableció las distintas ecuaciones de la linea recta.

En los primeros trabajos acerca de la transformada [41], quedó claro que la

primera parametrización, necesaria para la aplicación y estudio de la

transformada de Hough, era la ecuación de la línea recta en función de la

pendiente y la ordenada en el origen, esto es:

v = Fv(x, y, u)

y= mx + b (3-21)

b = -mx + y (3 - 22)

Donde b es la ordenada en el origen y m es la pendiente de la recta (ver

Fig 3.2(b)). El punto (x, y) pertenece al borde de la imagen a ser estudiada.

Según la Expresión (3 - 22), no existirá una sola recta que pase por un

punto definido (x, y), sino que, como lo menciona el postulado de Euclides,

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 70: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -59-

pasará un número infinito de rectas, donde lo que las diferenciará una de

otras será el valor de la pendiente (Fig. 3.4(b))

Una de las ventajas que presenta este método de parametrización es que

cualquier punto puede ser convertido en una línea recta. La desventaja

radica en el hecho de que es difícil parametrizar una línea que es

perpendicular al eje x, ya que no existe la tangente de 90°; en otras

palabras, el espacio de parametrización bidimensional pendiente -

intercepto es infinito, lo cual dificulta la aplicación de la técnica [41].

(a)

(b)

Figura 3.4: (a) Gráfica de la función y(x) = x + 2. (b) Las rectas bj(m) se intersecan en el punto(1,2). En este conjunto de gráficas se observa el efecto de la Transformada de Houghen una recta y en su transformada en el espacio de Hough.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 71: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 60 -

El efecto analizado en el párrafo anterior es una de las causas por las

cuales este método de parametrización no haya sido popularizado, aunque

se ha intentado desarrollar métodos para la aplicación [24].

3.2.1.5 La Transformada de Hough en función de la ecuación normal de la línea

recta (Parametrización normal).

Para 1972, Duda y Hart [41] trabajaron en la transformada de Hough y en

los trabajos de Rosenfeld sobre el tema y determinaron un método que,

basado en la transformada de Hough, utiliza otro tipo de parametrización

de la línea recta enfocado en el método de la ecuación normal de la línea

recta.

En la Expresión (3-12) se estableció la forma de la ecuación normal de la

línea recta, de esta ecuación nació la forma de parametrización definida por

Duda y Hart en su artículo "Use the Hough Transformation to detect Unes

and curves in pictures". Esta forma de parametrización y estudio de la

transformada de Hough se volvió en la más popular de las formas de

aplicación de este método en los años siguientes.

Una de las razones por las cuales este método se convirtió en el más

usado es que, para este caso, la transformada de Hough es limitada y

finita. Esto se debe a que la ecuación normal de la recta determina valores

restringidos en el ángulo (O y TI) y valores positivos en p.

La Figura 3.5 muestra la aplicabilidad del método de Duda y Hart. En la

Figura 3.5 (a) se observa la gráfica de la ecuación y = x + 2 con los

parámetros conocidos x - y. La distancia de esta recta al origen de

coordenadas está dada según la Ecuación (3 - 9), donde (x, y) serán (O, 0)

y el resultado es p = 1.414 con un ángulo 0 de 135° o 2.356 rad. En la

gráfica (b) se puede observar que las distintas sinusoides se cortan en ese

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 72: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 61 -

punto en particular. Como conclusión se establece que el punto de

intersección de una familia de sinusoides de la forma p = x eos 0 + y sen 0

(donde 0 es menor a n) representa a las coordenadas, en el espacio p - 0,

de la distancia y la inclinación de una recta que pasa por los puntos (x, y).

El recíproco de esta propiedad se cumple exactamente, es decir, los puntos

que pertenecen a una recta Ax + By + C = O tendrán el mismo valor de p y

G.

Propiedades de la parametrización normal

1. Un punto en el plano euclideano, corresponde a una sinusoide en el

plano parametrizado.

2. Un punto en el plano parametrizado representa a una línea recta en el

plano euclideano.

3. Los puntos que reposan sobre una misma línea recta corresponden a

curvas que cruzan en un punto común en el plano parametrizado.

4. Los puntos que reposan sobre una misma curva corresponden a líneas

que atraviesan el mismo punto en el plano euclideano.

Estas propiedades pueden analizarse de manera rápida si se toma en

consideración la Figura 3.5 (a) y (b), en la cual se visualiza el

comportamiento de un grupo de puntos que pertenecen a una misma recta

(Fig. 3.5 (a)) en el plano parametrizado (Fig. 3.5 (b)).

3.2.1.6 La Transformada de Hough para curvas, circunferencias y elipses.

Si bien es cierto, el método de la transformada de Hough fue lanzado para

líneas rectas, éste se puede aplicar a cualquier curva por medio de la

aproximación a una línea recta, utilizando para el efecto la ampliación de la

zona de estudio, o de la división en segmentos lo suficientemente

pequeños de la curva a estudiar (Fig. 3.6)

F. WLAOIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 73: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -62-

(a)

.9996275,

(b)

-5.826189, -6

Figura 3.5: (a) Gráfica de la función y(x) = x + 2. (b) Gráfica de la ecuación p = x cosO + y sene, paravalores de (x, y) pertenecientes a la recta y = x + 2. El punto donde se intersecan lassinusoides será el valor de p y 6 tales que representan la distancia de la recta y = x + 2 alorigen de coordenadas y la inclinación de la misma al eje x

En estos métodos se puede inferir algunos puntos interesantes; A medida

que la zona ampliada sea mayor, la línea recta sería más clara (Fig. 3.6

(b)), pero eso implicaría una mayor cantidad de cálculos como se lo

demostrará más adelante. Si se hace por método reticular7 (Fig, 3.6 (c)), a

La retícula se define como una zona, preferiblemente cuadrada, dividida por cuadrados más pequeños, en donde n es el número decuadrados en los cuales se dividirá la retícula.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 74: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -63

medida que la retícula se haga más y más pequeña (aumenta el valor de

n), la línea recta se hará más clara (Fig 3.6 (d)), pero, al igual que lo

anterior, aumentará el grado de complejidad del algoritmo de Hough y el

tiempo de cálculo utilizado para resolver el mismo crecerá.

(a)

s;

(c) (d)

Figura 3.6: (a) Circunferencia, (b) Zona ampliada del cuadrado mostrado en (a). En esta zona sepuede apreciar que la región puede ser asemejada a una línea recta, en donde sepuede aplicar cualquiera de las parametrízaciones de Hough. (c) La mismacircunferencia mostrada en (a) pero ahora afectada por una retícula, (d) Ampliación dela retícula en la zona mostrada por la circunferencia pequeña. Nótese que en (d) larecta es más notoria que en (b)

Duda y Hart [41] presentaron, como parte de su investigación que derivó en

el método de parametrización normal, una forma de parametrizar las

elipses y circunferencias de tal manera que se pueda aplicar la

transformada Hough sin necesidad de recurrir a los métodos de retícula y

ampliación de secciones.

Antes de profundizar el estudio de la Transformada de Hough para

circunferencias y elipses, se debe recordar algunas características

matemáticas de la elipse y la circunferencia.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 75: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 64 -

Generalidades acerca de la circunferencia y la elipse [32], [33]

La circunferencia y la elipse son parte de la familia de las cónicas cuya

ecuación general es de la forma:

Ax2 + Bxy + Cy2 + Dx + Ey + F = O (3 - 23)

Donde, para el caso de una circunferencia, A = C = 1, B =0 ,D = -2h,

E = -2k, F = h2 + k2 + r2, h y k, son las coordenadas del centro de la

circunferencia y r es el radio de la circunferencia. En el caso de la elipse,

los valores de A y B son positivos. En cuanto al término B, éste representa

un término de rotación con el eje x.

En una circunferencia, la ecuación general es de la forma:

x2 + y2 + Dx + Ey + F = O (3-24)

Donde D, E y F tienen las relaciones indicadas anteriormente. Pero, la

ecuación más familiar de la circunferencia es la ecuación canónica, que

tiene la forma:

(x-h)2 + (y-k)2 = r2 (3-25)

Donde (h, k) son las coordenadas del centro de la circunferencia y r es el

radio de la misma (Fig. 3.7). La Ecuación (3-21) se la puede expresar de

la forma:

(x^h)l + (y^k)l = 1 (3_26)

En este punto se puede indicar que el valor de r deberá ser mayor que

cero.

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 76: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -65

0,0)

Figura 3.7: Circunferencia de centro (h, k) y radio r [32, 33]

En cuanto a la elipse, la ecuación más conocida es la ecuación canónica

de la misma, que tiene la forma:

(x-h)2 (y-k)2

a2 b2(3 - 27)

Donde (h, k) son las coordenadas del centro de la elipse, a es el valor del

semieje horizontal (o el semieje mayor) y b el valor del semieje vertical (o

semieje menor) y estos valores siempre serán mayores que cero.

TETO) f¡

Figura 3.8: Elipse de centro (h, k), eje mayor 2a, eje menor 2b. [32, 33]

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 77: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 66 -

Un análisis rápido de las Ecuaciones (3 - 26) y (3 - 27) lleva a la

conclusión de que las ecuaciones son similares y que la expresión de la

elipse resulta el caso más general de las ecuaciones canónicas de estas

dos cónicas.

El problema de la parametrización de la elipse y de la circunferencia,

entonces, se verá limitado al ámbito de determinar el valor de los centros y

los ejes de las curvas.

Parametrización de la circunferencia [17]

La parametrización estándar para una circunferencia es (h, k, r), donde (h,

k) son las coordenadas del centro de la circunferencia y r es el radio de la

misma. La circunferencia está dada por las soluciones a la Ecuación

(3 -25).

Si se conocen tres puntos (xi, yO, (x2, ¥2) y (*3, Ys)* las coordenadas del

centro de la circunferencia (h, k) estarán dadas por la solución del sistema:

h]_ [X l-x3 ^-xJLxj + y j -x j -y?] (3 - 28)

k x 2 - X y - y - y 2 ~ y i x 3 - X i

Y el radio de la circunferencia será:

(3-29)

Para la parametrización de Hough, los valores a utilizar son (h, k, d), donde

d es la distancia desde el centro del círculo a la línea que une dos puntos

definidos y (h, k) son las coordenadas del centro de la circunferencia. Si se

escoge d > O, el centro de la circunferencia quedará a la derecha del

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 78: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 67 -

segmento, caso contrario quedará a la izquierda. En este caso, se puede

reparametrizar la curva en una sola variable que sería d. En consecuencia,

la curva de Hough será una línea recta en el plano parámetro.

Parametrízación de la elipse [17]

La parametrización de una elipse se ha realizado sobre la base de los

datos (h, k, a, b, 0); donde (h, k) son las coordenadas del centro de la

elipse, a y b son los datos del semieje mayor y menor, O es el valor del

ángulo existente entre la horizontal y el semieje mayor. Según Olson [17],

la parametrización de una elipse puede encontrarse según un

procedimiento desarrollado por Forbes8. Este procedimiento parte de la

definición de cinco puntos (x, y) que se suponen elementos de una elipse,

los cuales se reemplazan en la ecuación:

x2 + y2 - U(x2 - y2) - 2Vxy - Rx - Sy - T = O (3-30)

Donde las incógnitas serán los términos (U, V, R, S, T), que generan un

sistema de ecuaciones lineales 5 x 5 que se resuelve por cualquiera de los

métodos matemáticos conocidos. Para resolver el sistema, en función de

los parámetros (h, k, a, b, 6) se aplicarán las siguientes relaciones:

(3-31)

(3-32)

= (sen(29))í| l (3-33)V l + e )

R = 2h(1-U)-2kV (3 - 34)

S = 2k(1 + U)-2hV (3-35)

2aV hR kS /o

8 Forbes, A. B.: Fitting an ellipse io data, Report NPL-DITC 95/87, National Physical Laboratory, Dec. 1987 (Cita presentada en [17])

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 79: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 68 -

Donde e se define como la excentricidad de una curva9.

3.2.1.7 Semejanzas y diferencias: el método de la pendiente - intercepto eje y

vcrsus el método de parametrización normal.

Luego de haber mostrado las características principales de la transformada

de Hough en sus dos parametrizaciones básicas, es interesante hacer un

primer análisis de las semejanzas y diferencias que presentan ambos

métodos.

• Ambos constituyen métodos de parametrización con respecto a la línea

recta. Ésta es la base y el origen de la transformada Hough: establecer

una relación de parametrización entre un punto y una figura geométrica.

• Ambos consisten en establecer un conteo de eventos o votos para

establecer la ubicación más probable de un punto dentro de una

imagen. Este punto se lo aclarará en el siguiente acápite, cuando se

hable más específicamente de la forma del algoritmo para el trabajo con

la Transformada.

• La parametrización original de la transformada de Hough establecía la

utilización de la ecuación de la línea recta en función de la pendiente y

del punto de corte con el eje y. Cuando se la empezó a aplicar en el

reconocimiento de patrones y detección de bordes de imágenes

obtenidas en tomas de rayos X o en las primeras imágenes de satélite,

se empezó a notar un severo problema: Este método de

parametrización no estaba acotado, pues la pendiente de una recta

vertical es infinita, por lo tanto los parámetros necesarios, para hacer el

análisis de este caso por el método antes indicado, eran

indeterminados. Casi diez años después, Duda y Hart [41] proponen un

nuevo método de parametrización del plano usando la ecuación normal

La excentricidad de una curva es el grado en el cual ésta difiere de una circunferencia. La excentricidad de una elipse es menor queuno. La excentricidad de una circunferencia es 1 [32, 33].

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 80: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 69 -

de la línea recta. Esto ya se lo explicó en el acápite anterior; además, se

puede deducir que, para el caso más crítico (línea perpendicular al eje

horizontal), la ecuación normal de la línea recta no es infinita pues en

ese caso, el valor del parámetro no es infinito10. Ésta es la diferencia

fundamental entre estos dos métodos y ha hecho que el método de

parametrización de Duda y Hart sea más popular, o más utilizado, que

el propuesto en un principio por el análisis de Hough.

• Para el caso del método de parametrización normal se debe hablar de

una frecuencia de parametrización, la cual estaría ligada al valor del

ángulo 9, lo que no se presenta en el caso del método original. Sin

embargo, para evitar cualquier confusión, se debe analizar muy

detenidamente el significado real del valor de 0 y de p en el desempeño

de la transformada de Hough. En otras transformadas, como puede ser

la de Fourier, el valor del ángulo está relacionado con Ea frecuencia de

la señal o los armónicos de la señal. A partir de este valor se pueden

establecer los requerimientos de los filtros y los muestreadores para la

imagen. En las siguientes páginas se analizará el significado de los

valores de los parámetros de la transformada de Hough.

Nótese que aún no se puede estimar absolutamente nada sobre los

algoritmos de resolución de la transformada de Hough debido a que

todavía no se ha planteado ningún algoritmo sobre el mismo. A pesar de

ello, se debe pensar que la complejidad computacional de las soluciones es

muy alta pues, como se mencionó anteriormente, éste es un procedimiento

que cuenta las veces que un punto tiene unas coordenadas determinadas

en un plano parámetro.

Lo anotado anteriormente es el "punto débil" de la Transformada de Hough.

Muchos de los trabajos presentados en la bibliografía exhiben esta

debilidad. A pesar de ello, la transformada de Hough, es una herramienta

Nótese que la ecuación x eos 0 + y sen 0 - p = O, para este caso (0 = 90°) tomará el valor de y = p, en consecuencia, el valor de (p,0)está definido y es finito.

F. WLADIMIRO BASANTES M PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 81: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 70 -

de uso común en el procesamiento de imágenes, como se indicó al iniciar

este Capítulo.

3.3 ALGORITMOS TÍPICOS DE LA TRANSFORMADA DEHOUGH

Al iniciar este Capítulo se recalcó que la Transformada de Hough es una

herramienta muy utilizada en el procesamiento de imágenes, en lo que

tiene que ver con el reconocimiento de bordes y patrones de imágenes y es

precisamente sobre este campo donde todo el desarrollo de la teoría se ha

enfocado.

Desde la aparición de la patente, en 1962, los primeros caminos de

investigación se dieron para encontrar la forma de calcular la transformada

de Hough con un bajo costo computacional. El primer trabajo relacionado a

este tópico fue desarrollado por A. Rosenfeld11, en 1969, en el cual se dan

los parámetros para el análisis del método de Hough utilizando el análisis

de la recta en función de la pendiente - intercepto vertical. Tres años más

tarde R. Duda y P. Hart [41], utilizan este primer trabajo de Rosenfeld y

proponen el método de parametrización normal junto con las bases del

método de parametrización de curvas. Este trabajo fue la base para el

futuro desarrollo de todo lo relacionado con la transformada de Hough

incluyendo el actual análisis de errores de cuantización [7], [8], intervalos

de muestreo [8], [26], etc.

Sobre este tema, se han desarrollado algunos métodos. El primer método

es la aplicación de la transformada de Hough sin cambios. A este método

se lo conoce como la Transformada Estándar de Hough. Un segundo

método es una optimización del método estándar.

Otros métodos comunes que se encuentran en la literatura son:

- el método probabilístico

11 Rosenfeld, A.: PICTURE PROCESSING BY COMPUTER, Academic Press, San Diego, 1969

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 82: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 71 -

- El método aleatorio o randómico

- El método de descomposición de bloques

- El método forzado o restringido.

Se hará una breve exposición de cada uno de los métodos, así como un

algoritmo para el desarrollo de cada uno de ellos.

3.3.1 PRINCIPIOS DEL ANÁLISIS DE LA TRANSFORMADA DE HOUGH.

Una vez que se ha definido matemáticamente la Transformada de Hough,

es prudente establecer ciertos parámetros adicionales que se utilizan en el

análisis de la misma.

Este es un método que se utiliza solo en forma discreta, es decir, una vez

que se ha establecido la forma de parametrización, y se ha obtenido uno de

los valores del parámetro, entonces, los otros parámetros para la figura se

obtienen por rastreo total de los otros parámetros con números discretos

para todos los puntos característicos (como pueden ser puntos de borde)

de la figura. Cada número en el dominio del parámetro definido deberá ser

sustituido para todo parámetro a ser rastreado.

Los intervalos de muestreo deberían ser, o por lo menos es deseable que

lo sean, muy pequeños para el rastreo de parámetros con el fin de reducir

los errores en los parámetros. Sin embargo, al disminuir el tamaño de los

intervalos de muestreo se incrementa el uso de la memoria del computador

y del costo computacional12.

En Ja transformada de Hough se utiliza una técnica para determinar los

valores en los cuales se puede encontrar un píxel. Esta técnica es la de

voto. Un voto es el número de veces que un parámetro se repite en un

conjunto de puntos dentro de una celda determinada en el espacio

12 El costo computacional se relaciona con el tiempo en el cual un computador realiza un proceso.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 83: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 72 -

paramétrico y la fortaleza del parámetro se mide por el mayor número de

votos en la celda [8].

En la transformada de Hough, los votos se distribuyen alrededor de un

máximo local, inclusive para una entrada ideal, como una línea definida por

parámetros continuos. Esta propiedad está fuertemente relacionada con la

parametrización, los intervalos de muestreo del parámetro y el arreglo de

celdas en el espacio parámetro.

En la Sección 3.2.1.2 se presentaron qué características deben reunir el

plano transformado y el muestreo de las imágenes a ser procesadas. Una

vez que se han establecido los diferentes métodos de parametrización de

la Transformada de Hough y las características específicas del

procesamiento (muestreo y plano transformado), queda por el analizar la

región discreta de la imagen.

Obviamente, debe quedar claro que encontrar las líneas discretas en una

región discreta de la imagen es lo mismo que obtener los parámetros

(UQ, VQ) para la línea. Considere puntos continuos muestreados en una

figura continua. Si el ángulo entre el eje x y la línea tangente en una región

local en una figura continua está en el intervalo [-%, %], los puntos

continuos muestreados se definen como la intersección de la figura y la

línea recta x = t • As (i entero), que es paralela al eje y. Por otro lado, los

puntos muestreados se definen como la intersección entre la figura y la

recta paralela al eje x, y = t • As, donde t es un entero. Los puntos (x¡, y¡)

representarán los i-ésimos puntos continuos muestreados y

(x^) denotarán su valor cuantificado. Uno de los valores del error de

cuantización (6x¡ = x¡ - x¡ paralelo a x ó, 5x¡ = y¡ - y¡ paralelo a y) es cero

para un punto discreto de muestreo, esto implica que ambos errores no van

a ser cero al mismo tiempo.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 84: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 73 -

Una figura se representa solo por el conjunto de puntos muestreados

discretos {(^.y,) | i= 1, 2, .... n}; los parámetros para la figura son

desconocidos. Estos puntos, ya definidos en líneas anteriores, serán

obtenidos por métodos que se definirán en las siguientes secciones.

3.3.2 LA TRANSFORMADA DE HOUGH ESTÁNDAR.

Esta transformada nace de la aplicación directa del criterio de Hough, sea

por el método de parametrización normal ó por el método de

parametrización intercepto - pendiente. Este método es el más básico de

todos y se sustenta, como ya se mencionó, en la aplicación directa de la

transformada.

Sea u, el parámetro de rastreo, ük j el k-ésimo punto muestreado de u, y

Au el intervalo de muestreo de u. De la misma forma, vmi representará el

m-ésimo punto muestreado de v y Av el intervalo de muestreo de v. El

primer paso del procedimiento es generar un acumulador celda(k, m), que

almacenará los votos, en cada uno de los puntos muestreados (ük,vm) de|

espacio del parámetro. Para cada punto (x¡,y,)en la figura discretizada y

para todos los ük f se calcula el valor vik = F(x¡<y¡'ük)[8].

El valor cuantizado de v¡k está dado por la Expresión:

V 1_ÜL_|__Av 2

•Av (3-37)

Al variar i y k, los votos son acumulados en la correspondiente celda(k,m).

Finalmente, un máximo local de los votos se encuentra entre las celdas.

Los parámetros estimados para la figura están dados por las coordenadas

correspondientes (uk'^m) en el espacio de parámetro [8].

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 85: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -74

Una vez que se ha establecido los parámetros para el análisis de la

Transformada de Hough Estándar, se pondrán a consideración algunos

algoritmos básicos para el estudio de la transformada, sin olvidar que hay

dos formas de parametrización de la línea recta: punto - intercepto y

normal.

3.3.2.1 Algoritmo de la Transformada de Hough para el método de

parametrización pendiente - intercepto.

Existen dos maneras de resolver la Transformada de Hough: la una es por

medio de un algoritmo estándar y la otra por la optimización del algoritmo

estándar.

El algoritmo general de la Transformada de Hough es producto de la

aplicación directa del método original. Este algoritmo se lo puede encontrar

en la literatura del tema, pero aquí se presentará una de las formas del

mismo [24].

Algoritmo 1: La Transformada de Hough [24]

Haga ghough(h, k) = O para todo (h, k)

Para i = O a I -1

Para j = O a J -1

gvalor = g(i,j)

Si gvalor * O entonces

Para k = O a K - 1

b = y(j)-m(k).x(¡)

h = redondeo[(b - bmin)/delta_b]

S i h > O y h < H entonces

ghough(h, k) = ghough(h, k) + gvalor

Fin Si

Fin lazo para

Fin Si

Fin lazo para

Fin lazo para

//Inicializa el espacio de Hough

/A/alores de x

//Valores de y

//Almacena en una sola variable

//Solo considera los píxeles no nulos

//Todos los valores de m

//Calcula el b

//Encuentra la muestra correcta

//Verifica si la muestra es válida

//Actualiza el dominio parámetro

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 86: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -75-

Fin

El Algoritmo 1 describe el núcleo de la Transformada de Hough. Si se

analiza con detenimiento el algoritmo, se entenderá el por qué se utiliza el

método de parametrización (p - 0). Nótese que para cada píxel no nulo en

la imagen y para cada valor de m^ se debe calcular un valor de b que, en

este caso, es producto de redondear el valor del vecino más cercano.

Uno de los principales inconvenientes del método estándar de Hough es el

tiempo que demora el computador en realizar las operaciones necesarias

para calcular la respuesta de este problema. Una alternativa para reducir el

costo computacional en el procesamiento de imágenes con la transformada

de Hough es optimizando el algoritmo anterior.

Para poder realizar un análisis de cómo resolver o cómo realizar la

detección de líneas utilizando la transformada de Hough en el espacio b -

m13, de una manera óptima, se deberán establecer algunas fórmulas

adicionales que permitirán el cálculo de la Transformada.

Se define la ecuación de mapeo continuo utilizando parámetros discretos

como:

i mmin)Xi-bmin =

Ab ^

Donde: K = -:Ab " Ab

Esta es la representación del método de parametrización intercepto - pendiente.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 87: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -76-

= y(¡)-m(k)x{i)h = redondeo[(b - b minydelta b]

ghough(h, k) ~ ghoughíh, k) + gvalor

Figura 3.11: Diagrama de flujo del Algoritmo 1.

Si la aproximación del vecino más cercano es aplicada, entonces se puede

establecer que, los valores de h que corresponden a parámetros que están

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 88: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -77-

dentro de un dominio de parámetro discreto truncado, pueden calcularse

utilizando las siguientes relaciones:

kmin = max 0,

nu,

C+-12

K

12 ^K

SÍ K > 0

H---C C+-9 9^ < k < ^- s¡ K < O

H-~-¿K-1,

y km a x=minK- '

(3 - 39)

SÍ K >0

si K <0

La Ecuación (3 - 39) se usa para asegurar que los píxeles considerados

estén dentro de la imagen estudiada. En el Algoritmo 2 se muestra una

implementación de la Transformada de Hough para la parametrización b -

m tomando en cuenta la optimización propuesta.

Algoritmo 2: La Transformada de Hough Optimizada [24]

Haga ghough(h, k) - O para todo (h, k)

Para i = O a I -1

Para j = O a J -1

gvalor = g(i,j)

Si gvalor * O entonces

kappa = -x(i) • delta_m/delta_b

zeta = (y(j) - x(m) • m_min - bmin)/delta_b

Calcular k_min y k_max de la Ecuación 3-45

Para k = k_min a k_max

h = redondeo[kappa • k + zeta]

ghough(h, k) = ghough(h, k) + gvalor

Fin lazo para

Fin Si

Fin lazo para

Fin lazo para

Fin

//Inicializa el espacio de Hough

/A/alores de x

/A/alores de y

//Almacena en una sola variable

//Solo considera los píxeles no nulos

//Calcula la pendiente digital

//Calcula el intercepto digital

//Todos los valores de m

//Encuentra la muestra correcta

//Actualiza el dominio parámetro

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 89: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 78 -

Este algoritmo se usa para que los píxeles de la imagen que son diferentes

de cero sean transformados. Para imágenes no binarias (valores de punto

flotante), puede considerarse un nivel de umbral, pero con la condición de

que el valor de umbral está fuertemente relacionado, o tiene una fuerte

dependencia, con la naturaleza de la imagen.

Una vez que se ha establecido la forma de calcular la transformada de

Hough, hay que encontrar la forma de muestrear, o tomar las muestras de

la imagen. En los trabajos de H. Goto y H. Aso [7, 8], así como en el de P.

Toft [24] se puede hallar las formas de realizar el muestreo tanto en el caso

general, como en el caso de la transformada de Hough para el espacio b -

m.

La transformada de Hough tiene una dificultad cuando el muestreo se lo

hace de manera muy densa, pero funciona adecuadamente si el muestreo

de un parámetro es tosco y difuso. Este problema puede ser analizado de

alguna manera si se estudia el comportamiento de los píxeles vecinos en

una imagen. Se puede establecer, tomando como base la Ecuación 3 - 38,

que una banda de puntos de una imagen está mapeada en el mismo vector

parámetro

Tin- (3-40)Ab

jAy + ymin-mk(iAx + xmin)-bh (3-41)Ab

J Ab2 Ay '

Ax m x + b — vDonde: ct = m,— y B= k min —^nin-, Ax y Ay son los intervalos de

Ay Ay

muestreo en x e y respectivamente, mk es la pendiente en el punto k -

¿simo, bh el intercepto en el punto h - ésimo. El diagrama de flujo del

algoritmo 2 se muestra en la Figura 3.12

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 90: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -79-

INICIO

! ghough(h, k) = O, paratodo (h, k)

< 0<KM >

gvalor = g(¡. j)

' gvalor f O >

kappa = (-x(i) * della_m)/delta_bzela = (y(i) - x{i)"m__m¡n - b_m¡n)/della_b

Cálculo da kjnin y k_max

NOk min < k < k max

h = redondeofkappa'k + zetagtiough(h, k) = ghough(h, k) + gvalor

y

(' FIN SI H

( FIN PARA)

(FIN PARA>-

FIN

Figura 3.12: Diagrama de flujo del Algoritmo 2.

El resultado más importante de esta deducción es que todos los píxeles

que se encuentran alrededor de la línea discreta j = ai + p con un ancho de

banda igual a ~, medido en píxeles, y que se hallan en la dirección de j,

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 91: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 80 -

se mapearán en el mismo punto (h, k) en el dominio discreto del parámetro.

Supóngase que el ancho de banda seleccionado sea de ^= 0.1 (muestreo

muy fino), esto querrá decir que cada punto del espacio euclideano, tendrá

10 puntos en el espacio de Hough. Estadísticamente, sólo el décimo píxel

de la línea digital contribuirá para el análisis de Hough. Si se analiza que

para un muestreo muy brusco, por ejemplo Ab = 6Ay, en cambio, se tiene

que para un mismo punto en el espacio de Hough, y un valor dado de x¡, de

cada seis píxeles de la imagen en el espacio euclideano, se tendrá un

punto en el espacio de Hough. De este análisis, la recomendación es que

los intervalos de muestreo, tanto en el espacio euclideano como en el

espacio de Hough se tomen como: Ab = Ay.

Si bien es cierto, como se ha especificado en líneas anteriores, que el valor

de Ab no debe ser seleccionado muy pequeño, el análisis para la elección

de Am es algo distinto. Un criterio es que la pendiente digital en la

Ecuación (3 - 38), no sea mayor a 1, con el fin de evitar que el píxel quede

dentro de una línea perforada en el dominio discreto del parámetro, como

se muestra en la Ecuación (3 - 43)

KAb

< 1 => Am< Ab 2Ab

max x (M-1)Ax (3 - 43)

3.3.2.2 Algoritmo de la Transformada de Hough para el método de

parametrización normal o p - 9.

Luego del análisis presentado en la sección 3.2,1.5, ha quedado

establecido que el núcleo de la transformada de Hough, para esta forma de

parametrización, es un conjunto de sinusoides cuyo algoritmo no se

diferenciará en mucho del Algoritmo 1 presentado en la sección 3.3.2.1.

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 92: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -81-

Afgorítmo 3: La Transformada de Hough normal [24]

Haga ghough(r, t) = O para todo (r, t)

Para i = O a I - 1

Para j = O a J -1

gvalor = g(i, j)

Si gvalor * O entonces

Para t = O a T - 1

rho = x(i)cos(theta) + yQ)sen(theta)

r = redondeo[(rho - rho_min)/delta_rho]

Si r £ 0 y r < R entonces

ghough(r, t) = ghough(r, t) + gvalor

Fin Si

Fin lazo para

Fin Si

Fin lazo para

Fin lazo para

Fin

//Inicializa el espacio de Hough

/A/alores de x

/A/alores de y

//Almacena en una sola variable

//Solo considera los pixeles no nulos

//Todos los valores de theta

//Calcula el rho

//Encuentra la muestra correcta

//Verifica si la muestra es válida

//Actualiza el dominio parámetro

El diagrama de flujo para el Algoritmo 3 se muestra en la Figura 3.13.

El algoritmo 3, como está planteado, puede ser optimizado por medio de

algunas variantes al algoritmo original; éstas son:

1. Se aprovecha que el principal mapeo puede ser definido por cuatro

vectores conteniendo los valores relativos de x e y y los posibles valores

del coseno y del seno de 0t.

xrel(i) - - - yrel(j) = - - rhooff = anAp Ap Ap

costheta(t) = cos6t y sentheta(t) = sen6t

(3 - 44)

(3 - 45)

Estos arreglos se calculan una sola vez y se usan en el lazo t, luego, se

evitan cálculos adicionales de seno y coseno, como se muestra en la

siguiente Ecuación:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 93: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -82-

r = [xrel(i)costheta(t) + yrel(j)sentheta(t)] (3 - 46)

rho = x(i) cos(thela) + y(i) sen(theta)r = redondeo{(rho - rho_nmn)/delta_rtio)

ghough{r, I) = ghough(r, l) + gvalor

í FIN SI ''

( FIN SI

I FIN

Figura 3.13: Diagrama de flujo del Algoritmo 3.

2. Al igual que en el problema presentado en el análisis del algoritmo

anterior, hay que garantizar que el valor, en este caso, de r esté dentro

de la imagen. La solución a este problema puede ser incorporar en el

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 94: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 83 -

diseño del parámetro discreto, simplemente incrementando R, el

número de muestras en la dirección de p a cumplir.

Pm¡n= ¿~AP

.os t + y sen t-Pmin <R

Ap J

D

max ' 'XÍ.YJ

xjcos9t + yjsen0t =maxyx¡ +yj =V2|xm¡n <—Ap => (3-48)i '* j ¿,

R> —V2(M-1) (3-49)Ap

En donde se usa la relación: xm¡n = -Ax

3. Esta variación es similar al caso anterior, solo que se calcularán dos

matrices a partir de los cálculos efectuados en el caso 1.

xc(i, t) = xrel(i) costheta(t) e ys(j, t) = y(j) sentheta(t) - rhooff (3 - 50)

Por tanto, para el mapeo puede usarse simplemente la Expresión:

r = xc(i,t) + ys(j,t) (3-51)

Una reducción del costo computacional puede alcanzarse por medio de

truncar el número de cifras flotantes en los números hallados por el

cálculo y aplicar la usual regla de que cualquier valor cuya cifra decimal

sobrepase el 0.5 debe subir a su valor inmediato superior.

Esta técnica de optimización requerirá dos matrices y la carga

computacional baja sensiblemente si se usan las tablas almacenadas

varias veces. Esto no ocurre si se utilizó un conjunto de píxeles no nulos

por una sola vez; para el siguiente grupo de píxeles deberá realizarse el

mismo cálculo, con lo cual el procedimiento se hace muy pesado.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 95: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH -84-

Al igual que en el caso anterior, se necesita establecer un procedimiento de

muestreo de la imagen original para llevarla al espacio de Hough p - 0. En

principio, las expresiones que se hallarán serán bastante similares a las

encontradas en el caso anterior.

La expresión para el vecino más cercano se da en la Ecuación:

ÍCOS0t

X

-

+ jsen0

COS0t +

ÍPmin

1 1

yisen0t -pmjn

Ap Jy r = [r*]

— • Y (t*n*+C\- ^pn A ^ ^\min^us»ot + 5>enut;

AX )

12

Ap

Ax

(3

(3

-52)

-53)

Las expresiones anteriores muestran que la transformada de Hough mapea

todos los píxeles de la imagen que caen en un ancho de banda |^en el

mismo punto en el plano parámetro. El ancho está medido en píxeles

perpendiculares a la línea. Esto significa que Ap debe ser lo

suficientemente grande y no menor que Ax, es decir:

A p > A x (3 - 54)

En lo referente a A0, el análisis es muy similar al que se hizo para definir el

intervalo de muestreo Ax en el caso anterior. En tal razón:

max A 6 < 1 maxAp

-A0 A0<V2 Ap

M-1 Ax(3 - 55)

Este cálculo debe garantizar que el pixel muestreado estará dentro de un

segmento válido de línea y que no va a caer en un sitio de la línea en la

cual no existe definición.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 96: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 85 -

3.3.3 LA TRANSFORMADA DE HOUGH ALEATORIA.

Se ha mencionado varias veces durante este Capítulo que una de las

debilidades de la Transformada de Hough es el tiempo que consume en

realizar los cálculos necesarios y la gran cantidad de memoria que requiere

para almacenar los datos hallados esto debido a que el acumulador tiene

un crecimiento exponencial a medida que aumenta el número de

parámetros.

La transformada de Hough Aleatoria (RHT, Random Hough Transform) es

una de las soluciones presentadas para resolver estos problemas. Esta

variación a la transformada de Hough fue presentada por Xu, Oja y

Kultanen en el artículo "A new curve detection method: Randomized Hough

Transform (RHT)" en la revista Pattern Recognition Letters N° 11(5) en

1990 y es el método más simple de la Transformada de Hough

Probabilística.

La Transformada de Hough aleatoria tiene por objetivo obtener, a partir de

dos puntos de borde de una imagen binaria un pequeño subconjunto de

puntos seleccionados aleatoriamente, a partir de los cuales se hará un

mapeo de la imagen para un nuevo espacio de parametrización de la curva

estudiada.

El método RHT está basado en el hecho de que un único punto en el nuevo

espacio de parametrización puede ser determinado a partir de un pequeño

subconjunto de puntos de borde de la imagen original. El tamaño de este

subconjunto depende exclusivamente de la complejidad de las curvas a ser

detectadas. Para el caso de líneas rectas, un punto de acumulación en el

nuevo espacio de parametrización puede ser obtenido a partir de dos

puntos de borde de la imagen binaria original. Estos pares de puntos (x¡, y)

pueden ser escogidos aleatoriamente. En seguida, el punto (x¡, yj) es usado

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 97: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 86 -

para el cálculo de la ecuación de la recta y la celda A(x¡, y) es almacenada

en una tabla de acumulación. Se ejecuta una RHT para descubrir los

valores de la tabla de acumulación que son mayores o iguales a un valor

considerado mínimo.

Los métodos probabilísticos de la Transformada de Hough se diferencian

en el tipo de dato aleatorio que consideran para el análisis de la imagen.

Par el caso de la transformada de Hough aleatoria, el método detecta todas

las instancias de una curva particular p - dimensional en una imagen

binaria.

El algoritmo que permite el cálculo de la transformada aleatoria de Hough

se lo puede apreciar en el siguiente listado:

Algoritmo 4: La Transformada de Hough Aleatoria

1. Crear el conjunto E de todos los puntos del contorno en el contorno detectado de la imagen

binaria

2. Seleccionar aleatoriamente los p puntos (ei, 62, , ep) de E.

3. Resolver para los parámetros (0) de la curva en el espacio de la imagen, definidos por los

puntos seleccionados.

4. Incrementar la celda apropiada, A(9), en el arreglo acumulador.

5. Si la A(0) excede un umbral predefinido í, entonces la curva parametrizada por 6 es detectada.

Cuando esto ocurre, los puntos que pertenecen a la curva se remueven de E y se reinicializa el

acumulador.

6. A pesar de haberse detectado una curva, verificar que se cumple o no una condición de parada.

Si no se cumple, retornar al paso 2.

Las partes principales del algoritmo 4 y de cualquier algoritmo PHT14 son:

un mecanismo de muestreo (pasos 2 - 3) y un método de detección de

picos en el acumulador de votos (pasos 4 - 5).

El mecanismo de muestreo define una distribución de muestras en el

espacio continuo del parámetro 0. Sin embargo, cualquier mecanismo de

14 PHT: Probabilistic Hough Transform

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 98: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 87 -

muestreo es discreto por naturaleza. De esta manera, se puede visualizar

el mecanismo de muestreo como la definición de un espacio de muestreo

Q d 0 y una distribución de muestras (función de probabilidad de masa),

g(9), en Q. En RHT, el mecanismo de muestreo es la selección de p puntos

(ti\. Así, si hay K= p - uplas de puntos y 6¡ es el

\PJ

parámetro para la i - ésima p - upla, entonces Q = {61 , 0|<} y la

distribución de muestras puede escribirse como:

(3-56)

Si todos los 6'¡ son únicos, entonces g(0) es una distribución uniforme en

Q, es decir:

g(6*) = - 9* e O (3-57)K

Las curvas que se presentan en la imagen deberían corresponder a

regiones en 0 que tienen relativamente una gran probabilidad bajo g. El

método de detección de picos de la RHT se consigue por medio de agrupar

los valores muestreados del parámetro en celdas dentro del acumulador y

compararlos con un valor umbral.

Aplicar la RHT no es recomendable si se lo hace a curvas no lineales con

respecto a sus parámetros. En este caso están involucrados la elipse y el

círculo. Un análisis de este problema se encuentran en los trabajos de

McLaughlin15, Yuen, lllingworth y Kittler16 [26].

IJ McLAUGHLIN, R. A.: RANDOMIZED HOUGH TRANSFORM: IMPROVED ELLIPSE DETECTION WTTH COMPARÍSON..Pattem Recognition Letters 19(3 - 4), Pag, 299 - 305. 1998.

16 YUEN, H; ILLINGWORTH, J.; KITTLER, J: DETECT1NG PARTIALLY OCCLUDED ELLIPSES USING THE HOUGHTRANSFORM. Image and Vision Computing. 8 (1), Pag. 71 - 77. 1989.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 99: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH

El principal problema al cual debe enfrentarse este método es que el

desempeño de la RHT no es bueno en imágenes ruidosas o complejas. Las

nuevas RHT se han propuesto reducir este inconveniente para mejorar el

desenvolvimiento de la RHT. Una de las variaciones que se están

implementando a la RHT, y de hecho la más simple, es la RHT con un

criterio de distancia a un punto.

Algunas variaciones de este método son la transformada de Hough

aleatoria dinámica y con ventana aleatoria. Sin embargo han habido

algunos trabajos adicionales sobre esta variación de la transformada que

constan en la bibliografía incluida en este trabajo.

3.3.4 OTROS MÉTODOS DE LA TRANSFORMADA DE HOUGH.

Hay varios métodos de la Transformada de Hough que han aparecido,

todos ellos movidos por el interés de hacerla más versátil, más eficiente y,

sobretodo, hacerla más rápida, computacionalmente hablando.

Cada uno de los métodos que han aparecido, inspirados en el trabajo

original de Hough y en la implementación presentada por Duda y Hart,

nacen de la necesidad de aplicarlos a una problema previamente creado.

Por ejemplo, la Transformada de Hough por importancia de muestro nace

para mejorar el desempeño de la transformada de Hough probabilística.

Algunos de los métodos de aplicación de la Transformada de Hough que se

mencionarán son:

- Transformada de Hough Adaptiva, que apareció por primera vez en el

trabajo de J. lllingworth y J. Kittler: The Adaptive Hough Transform en el

año 1987, en la revista IEEE Transactions ¡n Pattem Analysis

Machinery Intelligence A/° 9(5).

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 100: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 89 -

- Transformada de Hough por importancia de muestreo [26], desarrollada

por Daniel Walsh y Adrián Raftery (Ver Anexo I)

- Transformada restringida de Hough para detección de curvas [17] de

Clark Olson (Ver Anexo I)

Todos estos métodos tienen en común, en conjunto con otros que se

pueden hallar en la bibliografía, que buscan el mejoramiento del análisis de

la Transformada de Hough, pero orientado a la detección de bordes y

reconocimiento de patrones, mas no están destinados para el

procesamiento a bajo nivel de la imagen. Originalmente ése era el espíritu

de la Transformada de Hough.

3.4 APLICACIONES FUNDAMENTALES DE LATRANSFORMADA DE HOUGH

Paul Hough era un físico que estaba estudiando el desenvolvimiento de las

partículas subatómicas en una cámara de burbujas. Para realizar el

estudio, utilizó cámaras de video, pero el resultado eran imágenes

confusas, sea por la alta velocidad de las partículas como por el ruido

térmico.

De esta pequeña introducción se puede suponer la motivación de la

Transformada de Hough: reconocimiento de formas. Y ese ha sido el

campo de acción de los trabajos hasta hoy presentados en la transformada

de Hough. Todos ellos se enfocan a la solución de un problema que tenga

que ver con el reconocimiento de una característica en particular de las

imágenes previamente digitalizadas por un instrumento.

En la actualidad, la transformada de Hough es aplicada en el campo del

reconocimiento de objetos, sean objetos microscópicos y subatómicos, en

el campo agrícola y de automatización de procesos que tengan que ver con

el reconocimiento de ciertos patrones, reconocimiento de texto,

reconocimiento de patrones y formas en imágenes satelitales,

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 101: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 3: TRANSFORMADA DE HOUGH - 90 -

reconocimiento de formas humanas y características propias del ser

humano con aplicaciones a la seguridad, etc.

El campo de trabajo de la Transformada de Hough continúa en expansión.

Este Capítulo ha buscado dar una idea de los principios en los cuales gira

la Transformada de Hough y del estado en el cual se encuentra su estudio

y las aplicaciones a las cuales se orientan. El siguiente horizonte de la

Transformada es la optimización de sus tiempos de cómputo y

requerimientos de utilización de la memoria del computador. Se está

trabajando en la utilización de la técnica de procesadores paralelos para

reducir los tiempos de cómputo y los requerimientos de memoria.

Estos son los problemas fundamentales de la Transformada de Hough:

tiempo y memoria. La solución de estos problemas hará de la transformada

una herramienta más veloz y confiable para su uso en los campos en los

cuales por el momento se halla inmersa. Sin embargo, y a pesar de estos

inconvenientes, sigue siendo la herramienta más usada en el campo del

reconocimiento de patrones, segmentación, análisis de la escritura

manuscrita, y características físicas propias de un objeto, etc.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 102: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4

DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y

ANÁLISIS DE RESULTADOS

4.1 INTRODUCCIÓN

La Transformada de Hough es un tema que requiere de un análisis

matemático previo para su implementación en cualquier herramienta

computacional. El análisis hecho en el Capítulo anterior, sin ser extenso ni

completo, trata de enfocar los fundamentos matemáticos de la

Transformada Directa de Hough y de cómo deberían considerarse las

variables para la construcción de un algoritmo de cálculo de la misma, para

usarla como base a un trabajo posterior de procesamiento de imagen.

A lo largo de estas líneas se presentará un esquema de diseño de un

algoritmo que permita calcular la Transformada de Hough de una figura

partiendo de la suposición de que la imagen a trabajar puede o no ser

monocromática.

El procedimiento aquí desarrollado puede convertirse en una base para un

trabajo a futuro de procesamiento de una imagen. Sin embargo, cualquiera

de los trabajos que se pudieren desarrollar a partir de éste deberán

orientarse en el espíritu básico de la Transformada: "Este invento debe ser

rápidamente adaptable en áreas como el análisis de escritura a mano,

detección de radar y lectura de mapas..." [31].

F. WtADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 103: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACION DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -92-

4.2 IMPLEMENTACION DEL ALGORITMO PARA EL CALCULO

DE LA TRANSFORMADA DE HOUGH

4.2.1 HERRAMIENTAS DE PROGRAMACIÓN

De un tiempo a esta parte, los programas computacionales y los lenguajes

de programación se han ido especializando más y más. A más de los

lenguajes tradicionales como el COBOL, BASIC, FORTRAN, C, PASCAL

han aparecido mejoras a ellos y, además, nuevos programas, tales como el

Visual Basic, Visual C++, Borland C++, Java, HTML (Hypertext Mark

Language), XML (extended Mark Language), que han ampliado el campo

de acción de los programadores. Esto ha contribuido a que la programación

ya no sólo se enfoque a la solución de una aplicación específica sino de

varios problemas a la vez.

La evolución de los lenguajes de programación ha permitido el

mejoramiento de los entornos en los cuales estos lenguajes se

desenvuelven. Es así como, al principio, el entorno en el cual se

desarrollaban estos programas era el sistema operativo DOS. Este sistema

operativo no permitía la multitarea, algo que sus competidores (como UNIX,

MAC OS y OS de IBM) si permitían y, además, éstos tenían interfaz

gráfica, en la cual se podía tener un mejor manejo de las aplicaciones y de

los archivos, pues permitían abrir archivos, borrarlos con solo hacer clic en

el mouse y arrastrarlos a un basurero.

Esto, junto a otras razones, llevó a Microsoft al perfeccionamiento del

sistema operativo DOS, que se vio reflejado en el aparecimiento de

Windows, al principio como un manejador del sistema operativo DOS y,

después como un sistema operativo propiamente. Windows trabaja con un

sistema de visualización amigable que se denomina GUI (Graphics User

/níerface, Interfaz Gráfica de Usuario) que se convirtió en la interfaz en

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 104: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 93 -

donde se iban a correr todas las aplicaciones de usuario y hacia donde

comenzaron a apuntar todos los programadores.

Al empezar a popularizarse el sistema de "ventanas", también empezaron a

aparecer los lenguajes de programación con orientación a objetos y los

lenguajes visuales. No solo eso, sino que, además, las aplicaciones

también comenzaron a desarrollarse orientadas al entorno Windows®:

Word, Excel, Word Perfect, Lotus, Qpro, etc.

En este desarrollo también aparecieron aplicaciones que permitían

desarrollar programas con un lenguaje propietario o similar a alguno de los

lenguajes de programación existentes. Estas aplicaciones - lenguajes

permitieron el desarrollo de otro tipo de programas cuyo objetivo

fundamental era permitir al usuario desarrollar sus propias iniciativas

computacionales para resolver un determinado problema. Un ejemplo de

este tipo de programas es Matlab®.

¿POR QUÉ MATLAB®?

Matlab® es un lenguaje que permite desarrollar programas para resolver

problemas matemáticos. Es un lenguaje de alto desempeño para

computación técnica. Es un entorno que permite visualizar, computar y

programar en un ambiente de fácil uso, donde los problemas y sus

soluciones se expresan en una notación matemática familiar.

En principio, Matlab es un lenguaje de programación donde sus principales

características son [36]:

- La programación es más sencilla.

- Cuenta con una amplia biblioteca matemática.

- Posee abundantes herramientas gráficas, incluyendo funciones para

manejar la interfaz gráfica con el usuario.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 105: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 94 _

- Capacidad de vincularse con los lenguajes de programación

tradicionales.

- Transportabilidad de los programas Matlab.

En consecuencia, Matlab se presenta como una buena alternativa para la

solución de estos problemas matemáticos y de cualquier otro tipo de

problemas que involucren desarrollos numéricos avanzados y/o simples.

Como método para el procesamiento de imágenes, la versión completa de

Matlab presenta una herramienta en la cual se incluyen algunas

transformadas y "armas" necesarias para desarrollar el tratamiento de

imágenes, específicamente. En el Anexo se lista el conjunto de comandos

de la Image Processing Toolbox de Matlab. Adicionalmente hay otros

comandos del propio Matlab básico que no se listan aquí y que se utilizan

en el procesamiento de imágenes.

Las herramientas que el Matlab® tiene para procesamiento de imágenes

son numerosas y cubren la mayoría de los aspectos requeridos para

tratamiento de fotografías, dibujos, cuadros y hasta video. Esa es una de

las razones por las cuales este programa se ha convertido en uno de los

más utilizados para el desarrollo de algoritmos y procedimientos para

resolver problemas de ingeniería a todo nivel.

Adicionalmente, se tiene posibilidades de crear programas "stand- alone1"

en los cuales no es necesaria la existencia de todo el paquete, sino de

algunas librerías para que pueda correr una aplicación generada en este

programa. Además, el Matlab® puede correr con compiladores de lenguaje

C, o C++2; esto le ofrece la ventaja de interactuar con estos lenguajes de

programación para llamar librerías propias de uno y otro sistema. Al cerrar

esta investigación, el Matlab® había ya alcanzado la versión 6.5 R 13, la

cual tiene compatibilidad con la versión 6.1 en la que se desarrolló todo

este trabajo.

1 "'Stand- alone" se define a los programas que pueden correr por si solos.1 El Matlab® 6.5 soporta la versión Visual C++. NET de Microsoft.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 106: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLE ME NT ACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -95-

4.2.2 PASOS PREVIOS DEL DISEÑO DEL ALGORITMO PARA EL CALCULO

DE LA TRANSFORMADA DE HOUGH

Una vez que se han definido en el Capítulo 3 algunos parámetros

necesarios para el desarrollo de la Transformada de Hough, se debe

aplicar estos conocimientos a la consecución del objetivo planteado a lo

largo de este Proyecto: la obtención de un algoritmo (o varios) que, en este

caso, se implementará en el Matlab, para el procesamiento de imágenes a

nivel intermedio con la ayuda de la Transformada de Hough.

En este punto hay que enfocar los pasos que se deberían seguir para

obtener el producto final, que en este caso serían dos: el algoritmo y su

implementación. Dicho de esta manera, los puntos que se deben apuntar

para la resolución del problema planteado pasan por:

1. La aplicación que tendrán los resultados provenientes de la solución

final encontrada.

2. Tipo de imagen de entrada: monocromática o multicolor.

3. Resolución de la imagen a trabajar.

4. Resolución de la solución final.

5. Tiempo de cálculo utilizado para la resolución del problema final.

6. Memoria utilizada para la solución final.

4.2.2.1 La importancia de la aplicación de la imagen a transformar.

Uno de los puntos fundamentales de cualquier procesamiento de señales

es cuál va a ser la aplicación final de la señal producto del tratamiento

empleado para esa señal.

Tómese como ejemplo una de las imágenes provenientes del satélite

provenientes de las ya célebres emisiones de ceniza del Reventador

(Noviembre, 2002. Figura 4.1). Los técnicos tomaron como referencia esas

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 107: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -96-

imágenes para alertar a las autoridades sobre la dirección de la ceniza, sin

embargo otro grupo de técnicos tomaron esas mismas imágenes para

intentar estimar el grado de la explosión e, incluso, medir la composición de

la ceniza. A pesar de ser la misma imagen, la interpretación es distinta.

(c)Figura 4.1: Imágenes del satélite GOES - 8 al día siguiente de la erupción del volcán Reventador, (a)

Imagen infrarroja (b) Imagen normal. Obsérvese, aunque no muy fácilmente, la nube deceniza sobre Quito en (a). (Imágenes cortesía de la NOAA) (c) El mismo evento geológicotomado por un satélite de la NASA.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 108: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -97-

Otra muestra es el de las imágenes provenientes de las tomografías

axiales computarizadas. Para un médico tendrá su aplicación la cual no

será muy diferente a la de otro; por ejemplo: la interpretación que dé a la

imagen un médico radiólogo puede ser diferente a la de un médico

cirujano, aunque ésta sea algo parecida.

Se pueden encontrar varios estudios para los resultados obtenidos de una

misma imagen, pero éstos dependerán de la rama del conocimiento que

tome las deducciones de ellas. Es por ello que el grado de procesamiento

será distinto según sea el investigador a cargo del estudio de las imágenes.

Obviamente, y al tratarse de un estudio básico de la Transformada, es

prudente definir un área de estudio muy general y no enfocar en una

aplicación específica. Esto conlleva a suponer que el grado del

procesamiento no será muy alto sino más bien básico.

4.2.2.2 Tipo de gráfico de entrada: monocromático o a color.

El primer paso que se debe tomar, luego de la selección de la imagen es

ver si ésta es monocromática o a colores. Hoy por hoy, pensar en

aplicaciones cuya interpretación esté sujeta al análisis de los niveles de

color de la misma no es muy distante de la realidad. Es más, las fotografías

en color a veces son más apetecidas, sobre todo si ellas dan información

acerca de un comportamiento especial de un determinado fenómeno que

es objeto de estudio. Por ejemplo, puede resultar interesante el analizar el

infrarrojo de una zona que ha sido considerada reserva natural, para

constatar si ella ha sufrido destrozos en su ecosistema.

A pesar de elio, son las imágenes en blanco y negro las que, en muchas

ocasiones, son objeto de análisis pues ellas, en su conjunto, permiten

disminuir las variables y la complejidad del procesamiento. Los resultados

que se obtienen de un determinado tipo de imagen se complementan con

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 109: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEN!ENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -98

los extraídos de un conjunto adicional de muestras. En otras palabras, los

científicos toman como referencia una imagen para sobre ella comparar las

observaciones que se realicen de las otras imágenes.

Para llevar a cabo esta investigación, no se desechará la posibilidad de que

el usuario final de este proyecto quiera estudiar los efectos provenientes

del análisis de una imagen a color, para ello, se buscará darle la opción de

convertir previamente la imagen a monocromática.

Se debe resaltar el hecho de que la imagen debe ser convertida al inicio en

monocromática, porque el estudio de este proyecto se enfocó hacia el

análisis de las imágenes en escala de grises. De allí que, dentro del

procedimiento, se debe discriminar automáticamente si el dibujo o la

fotografía son monocromáticas o a color, en cuyo caso, no se puede pasar

a la siguiente etapa de procesamiento mientras el cuadro no esté en

monocromático. La Figura 4.2 muestra un diagrama de flujo del

procedimiento hasta este punto del análisis.

4.2.2.3 Binarízación de la imagen. Selección del método de binarización.

El siguiente paso para trabajar con la imagen, es conseguir un "mapa de

contorno de la imagen". Este "mapa de contornos de la imagen" no es más

que obtener la imagen en formato de 1 y O (imagen binaria), para de esta

manera adquirir las discontinuidades y "mirar" los posibles bordes de la

imagen. Para efectuar esto se aplica un filtro digital, de algunos que

existen, para obtener la imagen como ceros y unos.

Dentro de la literatura existente en procesamiento de imágenes, se pueden

observar que existen algunos métodos para efectuar esta operación, sin

embargo, dentro de Matlab, como caso particular, existe una función que

se llama edget cuyo fin es hallar los bordes de la imagen.

Convenientemente aplicada, se puede convertir en una herramienta que,

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 110: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -99-

combinada con otros procedimientos, ayude a los investigadores a resolver

problemas más complicados de procesamiento de imágenes.

-NO-

CONVERSIÓN AMONOCROMÁTICO

PRESENTACIÓN DELPROGRAMA

X¿SAUR DEL \/

NO!

T

SELECCIÓN DELA IMAGEN

¿IMAGEN..MONOCROMÁTICA?,

iX )

PROCESAMIENTO DELA IMAGEN

Figura 4.2: Monocromatización de la imagen: Se preguntará al usuario si desea usar elalgoritmo o, previamente, el proceso de monocromatización de la imagen por élseleccionada.

Entre los métodos existentes para realizar el procedimiento de binarización

de la imagen, se pueden destacar: Sobel, Prewitt, Roberts, el laplaciano,

cruce por cero y Canny. No es objetivo de este trabajo analizar en

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 111: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 1QO -

profundidad cada uno de estos métodos, pero como información general se

mencionará el fundamento de cada uno de ellos.

- Método de Sobel. Utiliza la aproximación de Sobel de la derivada. Su

resultado se obtiene al encontrar máximos de la gradiente de una

imagen I.

- Método de Prewitt Utiliza la aproximación de Prewitt de la derivada. Los

resultados se obtienen de manera similar al anterior.

- Método de Roberts. Utiliza la aproximación de Roberts de la derivada.

Similar a los anteriores.

- Método del Laplaciano. Busca cruces por cero después de pasar una

imagen I por un filtro laplaciano del gaussiano.

- Método de cruces por cero. Busca cruces por cero en una imagen

filtrada con un filtro definido por el usuario.

- Método de Canny. Busca máximos locales del gradiente de una imagen

I. El gradiente se obtiene con la ayuda de la derivada de un filtro

gaussiano. Este método utiliza dos valores como umbrales para

detectar bordes fuertes y débiles, e incluye los bordes débiles siempre y

cuando éstos se enlacen a bordes fuertes. Adicionalmente, éste es un

procedimiento que no se deja engañar por el ruido y más indicado para

detectar bordes débiles que son verdaderos.

La pregunta que debe estar flotando en el aire es, ¿cuál método es el más

utilizado para realizar este paso del procesamiento de imágenes? La

respuesta está en algunos trabajos prácticos que se hallan en Internet,

aunque, entre ellos, no existe un método que prime más que otro. Sin

embargo, se puede mencionar que los filtros Canny, Sobel y Prewitt [49,

55] tienen algo de preferencia sobre otros. A pesar de ello, el método de la

gradiente es otra técnica que puede ser utilizada para tal fin [6, 54]. En este

trabajo se utilizará el filtro de Canny. La Figura 4.3 presenta un diagrama

de flujo de cómo iría el algoritmo en este punto del diseño del mismo.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 112: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -101-

Figura 4.3: Binarízación de la imagen: Una vez que el usuario ha seleccionado si deseausar el algoritmo o el proceso de monocromatización de la imagen por élseleccionada, el programa deberá binarizar la imagen.

4.2.3 ALGORITMO PARA EL CÁLCULO DE LA TRANSFORMADA DE

HOUGH.

En el Capítulo anterior, se presentaron algunos de los algoritmos existentes

para la aplicación de la Transformada de Hough3. Estos procedimientos

deberán buscar el máximo de detección de puntos en el espacio

parámetro, con el mínimo de tiempo empleado, y la menor cantidad de

espacio en las unidades de almacenamiento.

Sin embargo, casi todos los mecanismos que se presentan en la

bibliografía establecen un cierto grado de complejidad en los

procedimientos; no solo ello, sino que adicionalmente, los órdenes de

complejidad son potencias del tamaño de la imagen, o, al menos,

logaritmos de éstos [17, 18, 19, 24].

1 Ver Capítulo 3, Sección 3.3.

F. WLADIM1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 113: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLE ME NT ACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 102 -

Súmese a ello, que el espíritu de la Transformada de Hough, como se

desarrolló al principio de la investigación sobre el tema, era detectar líneas

[24, 31, 41] y, en el mejor de los casos, detectar formas cónicas

(circunferencias, elipses, etc.) [17, 18, 41]. Con el pasar de los años y la

mejora de la tecnología de captura de imágenes, los requerimientos han

cambiado de perspectiva. Si bien todavía se quiere detectar líneas, o

curvas, además se quiere que estas formas descubiertas sean parte de

una imagen más compleja. En otras palabras, los investigadores utilizarán

este método para, con un patrón predefinido, encontrar uno o algunos

objetos similares a ese patrón, o simplemente, dibujar los contornos de la

imagen.

El principio del análisis de la Transformada de Hough es la creación de un

acumulador para registrar los "votos" que obtienen unos puntos dentro de

la imagen que cumplen una característica definida por el método de

transformación que se vaya a usar. En definitiva, como se expresó en el

Capítulo 3, la Transformada de Hough, en cualquiera de sus versiones

paramétricas, requerirá de un acumulador donde se registre la existencia o

no de puntos en determinadas regiones de la imagen4.

Lo que a veces puede resultar difícil establecer es qué parte de la imagen

se va a detectar: líneas, curvas, formas generales, contornos. Este es un

problema que puede traer muchas complicaciones, por cuanto se podría

pensar que toca desarrollar un mecanismo para detectar cada forma en

una misma imagen, o solo una de ellas, luego otra y a continuación la

siguiente. Algo del inconveniente se ha resuelto, pues se han desarrollado

métodos para procesar cualquier forma que exista en una imagen, sin tener

que pasar un procedimiento para cada forma existente en el gráfico. A lo

largo de este Capítulo se desarrollará algoritmos, o se presentarán

procedimientos para cada uno de los casos establecidos; es decir, se

4 Ver Capitulo 3, Sección 3.3.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 114: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS

mostrarán maneras para trabajar la Transformada con líneas rectas, curvas

cónicas y formas generales.

4.2.3.1 Algoritmo para el cálculo de la Transformada considerando solo líneas

rectas.

Los primeros trabajos sobre el tema giraron precisamente sobre la línea

recta y su parametrización [41] y algunas de las aplicaciones y trabajos

sobre detección de bordes y/o segmentación actual se las hace tomando

en consideración perfiles lineales [2, 49, 56, 57].

Al ser éste, en principio, el desarrollo "más sencillo" para la aplicación de la

Transformada de Hough, obviamente debe ser el primer caso estudiado.

Con el procedimiento seguido hasta aquí, el conjunto de bordes ya ha sido

obtenido, por medio del proceso de binarización de la imagen. Con la

información proveniente del proceso anterior, se debería obtener los sitios

donde la matriz de bordes tenga valores de 15. A partir de este resultado y

el cálculo de los puntos "centrales" de la imagen, se puede establecer ya

los parámetros de las líneas rectas, en el espacio transformado, e ir viendo

cuales tienen los mismos valores de parámetro, para de esta manera ir

aumentando el acumulador para cada punto parámetro. Sin embargo, el

hallar los puntos centrales está ligado al tamaño de la imagen a ser

estudiada y, dependiendo de la manera que se vaya a implementar, se

deberá establecer si es conveniente o no que la imagen tenga la misma

dimensión de ancho como de largo6. En principio, no se considerará este

detalle, con lo cual el algoritmo de procesamiento se construirá sobre la

premisa de que la imagen que se ingresó al procedimiento es de cualquier

tamaño y, por la secuencia de pasos del Acápite 4.2.2, ya ha sido

debidamente tratada.

5 La existencia de 1 en la matriz de bordes implica la existencia de un píxel en la misma. El cero por el contrario implica que no existeun pixel en ella.

6 Algunos trabajos prácticos, encontrados a lo largo de esta investigación, establecen que las dimensiones de la imagen sean cuadradascomo condición indispensable para continuar con el procedimiento (Nota del Autor).

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 115: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 104 -

Con estas consideraciones previas, se debe establecer la parametrización

de la línea recta que será aplicada. En el Capítulo 3, se vio que existen dos

métodos para la interpretación de la línea recta en la Transformada de

Hough; pendiente - intercepto y forma normal. Por tener menos

complicaciones, las cuales ya se discutieron en el Capítulo 3, se usará la

forma normal de la Transformada.

A continuación se presenta un algoritmo para el cálculo de la Transformada

Estándar de Hough en líneas rectas el cual aparece en la bibliografía

anexa a este trabajo [50, 51].

Algoritmo 4.1: Transformada de Hough para detección de líneas rectas [50, 51]

Procedimiento hough_est¡IniciolniciaIizarA(6, p) = OPara i = 1 hasta np haga

InicioPara k = 1 hasta m haga

InicioEvaluar p, por medio de p¡ = x¡ eos 9k + yi sen 0k

pn = cuantizar(p¡, An p)

Fin ParaFin ParaDetectar e! máximo en A(0, p)Fin

Este es un buen algoritmo de referencia para el cálculo de la Transformada

de Hough y la detección de líneas rectas, sin embargo, este no es el único

algoritmo para líneas rectas que existe en la práctica. Un diagrama de flujo,

equivalente a este algoritmo se tiene en la Figura 4.4

Sea cual sea el algoritmo que se piense utilizar para resolver el problema

de la Transformada de Hough, el procedimiento que se escoja debe

considerar un parámetro muy importante en el análisis: el acumulador. Este

acumulador se va actualizando con la cantidad de votos que va a tener una

combinación específica de los parámetros de la línea recta que se haya

escogido.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 116: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -105-

Evaluar p¡ por medio d« p, s *( coa Ok * y¡ sen D

Delectar n*x¡ nos «n A(B.p)

Figura 4.4: Detección de lineas usando la Transformada Estándar de Hough: La funciónCuantizarQ permite la cuantización de p¡ a p que es, en general, un paso previo necesarioen cualquier procedimiento que involucre un procesamiento digital.

Se debe hacer hincapié en que la introducción de una función de

cuantización va a añadir errores en el procesamiento de la imagen. Goto y

Aso en [8] presentan un interesante análisis sobre los errores que se

introducen en el cálculo de la Transformada de Hough y de su método de

minimización el cual no solo considera la posibilidad de parametrizar por

los dos métodos descritos en este trabajo, sino que, adicionalmente,

menciona otro método de parametrización denominado y - co7 que se suma

a los otros procedimientos ya mostrados.

7 WADA, T; SEKI, M., MATSUYAMA, T: HIGH PRECISIÓN y - to HOUGH TRANSFORM ALGQRÍTHM TO DETECTARBiTRARY DIGITAL LINES. Trans. IEICE (D - II), J77, N°3, pp. 529 - 539. March 1994. (in Japanese). (Referencia tomada de[8])

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 117: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 106 -

Una vez que se ha fijado el proceso, o al menos un algoritmo básico, para

la Transformada de Hough para detección de líneas rectas, es

indispensable pensar en que parámetros deben contener los valores de los

votos para poder ser considerados como útiles en el resultado final del

procesamiento. Adicionalmente, se debe pensar en el mecanismo para

utilizar la información que se obtiene del proceso de Transformada de

Hough con el objeto de utilizarla en procesamientos posteriores.

Obviamente, a este par de detalles, debe agregarse el estudio de los

errores en la Transformada. Se definen dos tipos de errores producto del

procesamiento: el de transformación y el de cuantización [7,8, 51].

Al ser el procesamiento de imágenes un tema donde los resultados que se

obtengan pueden ser muy conflictivos, los análisis para minimizar y corregir

los errores son muy importantes. Algunos trabajos sobre el tema, enfocan

el procedimiento de diseño de la Transformada y de sus parámetros para

minimizar el efecto de los errores en los resultados finales del

procedimiento [7, 8, 18, 47, 50, 51, 56].

En [8], Goto y Aso establecen algunas condiciones que el intervalo de

muestreo debe cumplir para que el resultado de la transformación sea

óptimo y no se vea afectado por los procedimientos previos a la obtención

del conjunto de votos que responden a la solución de la misma.

Las expresiones matemáticas obtenidas para seleccionar los parámetros

de muestreo para minimizar los efectos de los ruidos de transformación y

cuantización se presentan en las siguientes expresiones [8]:

a. Expresión para el máximo error de cuantización permitido:

(4-1)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 118: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 107

b. Expresión para el límite superior del intervalo de muestreo:

e cmax(G)-cmin(e) 2N

Donde:

= -xm¡n sen 6 + ymax eos e

(4-2)

Cmin = -Xmax S6H 6 + ym¡n COS 9

Xmin, ymax, Ymín, se refieren a los valores máximos y mínimos de las

coordenadas x e y respectivamente; u/4 < 6 < 37i/4; el valor de N está

relacionado con el tamaño de la imagen8.

(4_3)

* 'c(9) 2N

El desarrollo, que Goto y Aso muestran en [8], presenta dos tipos de

fórmulas que, en principio, llegan a lo mismo. El desarrollo de la Ecuación

(4 - 2) se basa en la limitación de clase 1 y la Ecuación (4 - 3) utiliza la

limitación de clase 29 . Adicionalmente, se debe considerar que la imagen

está centrada en el origen; si ésto es así, el máximo valor de |x¡| es NAs,

donde As es el intervalo entre píxeles de la imagen.

Uno de los puntos que preocupa a todos los investigadores en lo que

respecta a la Transformada es el tiempo que demora en encontrar la

respuesta final del procedimiento. Como se mencionó en anteriormente, los

parámetros más complicados de afrontar en este método son el tiempo de

cálculo (o su complejidad) y el almacenamiento de la respuesta final. Toft

en [24] también hace un estudio de su procedimiento y de los tiempos de

8 Hay que resaltar que el trabajo del Dr. Goto y Dr. Aso se basa en la suposición de que la imagen a estudiar es cuadrada (Nota delautor).9 Ver Goto y Aso en [8], El artículo completo se encuentra en el Anexo I.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 119: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEN!ENTACION DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -108-

cálculo y obtiene algunos resultados que se muestran a continuación

después de aplicar algún método de optimización planteado en su trabajo.

CASO

1. Sin optimización

2. Mapeo de vectores

3. Evitar chequeo de límite y uso de mapeo de vector

4. Evitar chequeo de límite y uso de mapeo de matriz

TIEMPO CONSUMIDO <ms)

PARA 5 PIXELES

8

10

8

7

PARA 10201

PIXELES

1884

742

478

454

TABLA 4.1: Tiempo empleado para distintos tipos de optimización [24]

4.2.3.2 Algoritmo considerando solo curvas.

Una de las siguientes aplicaciones de la Transformada de Hough es su

aplicación para reconocer cónicas, principalmente círculos y elipses por sus

particulares características de la ecuación general, las cuales fueron

analizadas en el Capítulo 310.

En este Acápite, se presentará un algoritmo que considere el efecto de la

Transformada de Hough sobre una imagen con curvas, sólo curvas, y de

entre ellas sólo círculos o elipses.

Al igual que en el caso anterior, el acumulador para este caso también

deberá ser inicializado y, los parámetros a ser estudiados serán: las

coordenadas del centro de la elipse o circunferencia y el radio de la misma.

Aquí se puede intuir una primera limitación, el hecho de que la elipse no

tiene un solo radio sino dos semiejes los cuales son distintos, por

definición. De hecho, se podría "construir" una elipse con ayuda de

circunferencias.

1 Ver Capítulo 3, Sección 3.2.1.6

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 120: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -109-

Figura 4.5: Construcción de elipses usando circunferencias. Geométricamente, y por construcción,es posible encontrar al menos una elipse con ayuda de circunferencias.

Partiendo de estas dos premisas, el algoritmo de circunferencias para la

Transformada de Hough quedaría de la siguiente manera:

Algoritmo 4.2: Transformada de Hough para detección de curvas

Procedimiento hough_circulo;InicioInicializar acumuladoresVotar para detectar el centro del círculoVotar para detectar el radio del círculoSi el radio y centro propuesto no se ajusta a la imagen

Definir otro segmento y centroFin SiFin

La Figura 4.6, muestra el diagrama de flujo del algoritmo anterior.

Sin embargo, y como se puede apreciar en la literatura que acompaña a

este trabajo, las investigaciones sobre detección de curvas se han

convertido en el reto más difícil de vencer en el estudio de la Transformada

de Hough. El tener una elipse o una curva distinta a una circunferencia es

un problema que requiere de un sistema de, al menos, cinco ecuaciones

con cinco incógnitas [17], lo que desemboca en un asunto de mayor

complejidad de cálculo de las variables requeridas para el estudio de

imágenes por este método. A pesar de ello, Kanatani y Ohta [61] presentan

una solución en donde se considera detectar circunferencias por medio de

aumentar, o crecer, elipses.

Una de las consecuencias de este problema, es el cambio de enfoque en el

estudio de la Transformada. Dicho de otra manera, la pregunta que se

necesita contestar es ¿qué tan prudente o útil es tener un método para

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 121: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -110-

resolver la Transformada de Hough para rectas y otro para circunferencias?

Y la respuesta que se hacen los investigadores es "no mucho que se diga".

Por ello la necesidad de contar con un proceso que no sólo sirva para uno

de los dos casos anteriores sino que permita tratar cualquier tipo de figura

dentro de una imagen.

Figura 4.6: Detección de curvas utilizando la Transformada de Hough

El siguiente Acápite se enfocará en este problema de establecer un

procedimiento que permita hallar la Transformada de Hough de una figura

en particular y que éste también se aplique al procesamiento de líneas

rectas y curvas.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 122: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -111-

4.2.3.3 Algoritmo generalizado.

En la evolución de la técnica de Hough, se inició casi de la misma manera

como se ha llevado este trabajo de investigación: primero líneas rectas,

luego curvas y, por último, cualquier tipo de imagen con cualquier forma

dentro de ella. De hecho, en la bibliografía se presenta una variedad de

técnicas para realizar el tratamiento de las imágenes utilizando dos

procedimientos principalmente, la Transformada de Hough generalizada y

la Transformada de Hough aleatoria. Dentro de la lista de textos consultada

que consta, y la que no consta, se hace énfasis a que el Procesamiento de

Imágenes, usando Hough, de fotografías o representaciones pictóricas más

complejas que líneas rectas y/o curvas es usando estas técnicas o

variantes de alguna de ellas.

Uno de los trabajos sobre el tema es la Transformada Generalizada

Aleatoria de Hough (RGHT, por sus siglas en inglés) [54]. Esta técnica

"combina la Transformada generalizada con la aleatoria" y, según sus

autores, mejora la velocidad, almacenamiento, la precisión por medio de la

comparación de la imagen a procesar con un patrón predefinido [54]11.

Como se menciona en [54], se deben considerar dos algoritmos para

trabajar este método: uno que obtenga los datos provenientes del patrón de

imagen y otro que utilice ese patrón obtenido para aplicarlo sobre la imagen

a estudiar. Estos algoritmos se listan a continuación:

Algoritmo 4.3 Generación de la tabla de comparación proveniente de la imagen patrón [54]

Procedimiento TablaR = generar_tabla (im_patron)InicioAsigno gh <- convolución (im_patron, Mh)Asigno gv <- convolución (im_patron, Mv)Asigno centro <- centro de la caja de borde mínima del patrónPara (x,y) E in\_patron

Inicio

11 El articulo que sirve de base para este Acápite se halla en el anexo I.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 123: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -112-

fghfx.y)Asigno 9 <- artg v '

gv(x,y)

lnsertarJista(TablaR(0), centro - (x,y))Fin ParaFin

Algoritmo 4.4 Transformada Generalizada Aleatoria de Hough [54]

Procedimiento Resultado = RGHT(imagen, TablaR, iteraciones, resolución, umbral)InicioAsigno gh <r convolución (imagen, Mh)Asigno gv <- convolución (imagen, Mv)Asigno Resultado 4- §Para i 4- 1 hasta iteraciones haga

InicioGenerar P^x, y) y P2(x, y) aleatoriamenteCalculare!, 82 de P-, y P2

Buscar A^x, y) y A2(x, y) en la TablaR para fy y 62

Calcular O(x,y) y S(x,y)

Si l solución e Resultado y

Ox,Oy,Sx,Sy -Solución < Resolución entonces

Combinar lOx,Oy,Sx,Sy con solución

Caso contrario

Resultado <- Resultados (Ox,Oy,Sx,Sy

Fin SiFin ParaRes_fin <- <|>Para solución e Resultado

Si el valor más alto de solución > umbralRes_fin <- Res_fin u solución

Fin SiFin ParaFin

Los diagramas de flujo equivalentes se muestran en las Figuras 4.7 y 4.8,

respectivamente

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 124: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -113-

INICIO

J<-lm_patron

gh <- convolución (J.Mh)gv <- convolución (J.Mv)

centro <- centro(J)

(x,y)eJ

e «- arlgflh(x.y)flv(x,y)

lnsertar_lista(TablaR(e), centro - (x,y))

Figura 4.7 Generación de la Tabla de comparación proveniente de una imagen patrón

En este algoritmo (4.4), tres parámetros deben ser considerados

adecuadamente:

- Iteraciones: El número de iteraciones, es decir el tamaño de muestreo,

controla el número de los pares de muestras que se toman. Es de

suponer que a mayor tamaño del conjunto, mayor es el esfuerzo

computacional requerido. A pesar de ello, los resultados son imprecisos

si este conjunto no es lo suficientemente grande porque los puntos

exteriores contribuirán relativamente en mayor proporción. La

sugerencia que [54] da es que el número de iteraciones debe ser

directamente proporcional a las dimensiones de x e y; y, este valor

puede determinarse dinámicamente.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 125: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEN!ENTACION DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -114-

Resolución: Determina cuándo dos soluciones se hallan próximas una

de otra. Si dos soluciones se asemejan, (|S1 - 82! < Resolución), ellas

se combinan para formar una sola. Una resolución baja desemboca en

pocas soluciones fusionables y muchas soluciones triviales. Valores

altos ocasionan muchas soluciones que se pueden unir, lo cual conduce

a tener un alto índice de aciertos con la más baja resolución posible.

i INICIO i

Imagen,tablaR,

iteraciones.res. umb

J «- Imagenflh 4- convohición (J,Mti)gv t- convoluciín (J.Mv)

Resultado <- *

Figura 4.8 Transformada Generalizada Aleatoria de Hough

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 126: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -115-

- Umbral (Threshold): Controla el proceso de búsqueda de picos. Un bajo

valor de umbral causará el aparecimiento de muchas soluciones

triviales; mientras que los picos se pueden perder si los valores

escogidos son muy altos. Se recomienda escoger un valor umbral que

esté en función del máximo de aciertos.

A pesar de todo lo que se pueda expresar acerca de este algoritmo para el

cálculo de la Transformada de Hough, no es el único que existe en el

procesamiento de imágenes por este método. De hecho, y como se puede

observar en la bibliografía, es uno de los tantos que se hallan y no solo

ello, sino que cada uno de esos procedimientos manifiestan ser mejores

que los otros. Una de las formas de evaluar si un algoritmo es superior que

otro, es medir sus tiempos de cálculo y sus necesidades de

almacenamiento. Sin embargo, todos ellos dependen del tamaño de la

imagen y del número de muestras que se tomen de la imagen. En [54] se

puede observar un análisis comparativo de algunos métodos utilizados

para la Transformada de Hough.

La Figura 4.8 muestra el diagrama de flujo de la Transformada

Generalizada de Hough por el método descrito en este Acápite. Debe

tomarse en cuenta la importancia del procedimiento anterior del cálculo de

la Transformada para una imagen patrón. Este es un algoritmo que va más

allá de simplemente establecer una recta o una curva, sino que tomará en

cuenta el patrón y lo comparará con la imagen a procesar.

4.2.3.4 Tiempos de cómputo, complejidad de cálculo y tamaño del archivo de

grabación.

Como se ha mencionado en anteriores Acápites, una de las

preocupaciones de los investigadores sobre este tema es la cantidad de

recursos que la Transformada de Hough utiliza para realizar el

procesamiento de las imágenes en estudio. Todos los trabajos citados en

la bibliografía, y los que no constan, hacen mención de este problema y

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 127: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -116-

hacen un análisis adicional sobre el mismo. Unos pequeños comentarios

se hicieron anteriormente, pero ahora se incluirá un mayor análisis.

El mayor problema de la Transformada de Hough es la cantidad de

cálculos que se deben hacer. Olson [17, 18, 19] establece algunas

relaciones que permiten determinar los parámetros necesarios para, de

alguna manera, estimar la complejidad computacional de la solución que

propone. Así mismo, Toft [24], Perantonis y otros [20], Fung y otros [54],

tienen sus conclusiones y sus análisis dedicados a complementar y valorar

los métodos que en sus trabajos desarrollan para la aplicación de la

Transformada de Hough en el procesamiento de imágenes.

Una de las principales conclusiones a las que llegan todos ellos es que la

complejidad de una operación de procesamiento de imágenes está ligada a

la cantidad de píxeies de borde de la fotografía. De hecho, todos los

autores citados, hacen mención de que la complejidad computacional O

tiene relación con los parámetros de la imagen a ser estudiada, por

ejemplo, Toft [24] establece que la complejidad computacional de la

Transformada depende de los parámetros utilizados para el procesamiento,

esto es el tamaño de la imagen y la resolución de la Transformada. Fung y

otros [54], como se mencionó en el Acápite anterior, establecen algunas

consideraciones para el estudio de la Transformada Generalizada Aleatoria

de Hough, y una de ellas dice "la complejidad de tiempo para la

Transformada de Hough clásica no está disponible debido a que es

incapaz de detectar objetos arbitrarios de varias escalas y orientaciones...".

La Tabla 4.4 presenta la comparación entre algunos métodos para realizar

el procesamiento de imágenes con la Transformada de Hough, según Fung

y otros.

Atiquzzamann [58] propone una comparación de los tiempos requeridos

para la acumulación de votos entre el método que desarrolla con otros

propuestos. En este análisis establece que su algoritmo es más eficiente

que el método estándar y el adaptivo.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 128: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -117-

En cuanto al almacenamiento del resultado, el trabajo de Fung y otros [54]

presenta una sencilla ecuación para ef cálculo de la cantidad de espacio

requerido y recalca el hecho de que cae dentro del "tamaño de la

estructura de acumulación" [54].

ALGORITMO

Transformada de Hough Clásica

Transformada de Hough GeneralizadaTransformada de Hough AleatoriaTransformada Generalizada y Aleatoriade Hough

COMPLEJIDAD

TIEMPO

N/A

0(x,-yf#e-#x3-#ys)0(#muestras • f(n))

0(#muestras • c • #0)

ESPACIO

n

J^parametrOj¡=1

x t -y t#muestras • tamaño de celda

Tamaño de la celda dividida

Xt, yt: tamaño de la imagen

#xs, #ys: Número de iteraciones dadas por las escalas en x e y

#muestras: Número de muestras tomadas.

f(n) Función dependiente del número de parámetros del objeto. Para detectar unalínea, f(n) =n3, en cualquier otro caso, f(n) es muy grandePara resolver el sistema de ecuaciones (4 - 7)12

Denota el número de pasos de iteración necesarios para detectar instanciasrotadas de un objeto patrón.

TABLA 4.4: Complejidad de tiempo y espacio para algunos algoritmos [54]

c:#0:

A lo largo de este Capítulo se han presentado algunas alternativas para resolver

el problema del procesamiento de imágenes por medio de la Transformada de

Hough. En el numeral siguiente, se hará un análisis de los resultados que se

obtengan por la aplicación de un algoritmo a una imagen en particular. Nótese

que lo único que se ha intentado hacer es detectar los bordes de la imagen, ya

que ese era el objetivo de esta investigación. El espectro de la aplicación de la

Transformada de Hough, como se lo vio al final del Capítulo 3, es realmente

amplio y lo que se ha mostrado en este Capítulo es solamente la "punta del

iceberg" de su estudio.

12 La referencia a las ecuaciones 4-7 proviene del análisis presentado por Fung., Lee, King en [54]

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 129: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -118-

4.3 ANÁLISIS DE RESULTADOS

4.3.1 REQUERIMIENTOS DEL SISTEMA

Este proceso se lo implemento en el paquete computacional Matlab®

versión 6.1 y 6.5 que contenía la Image Processing Toolbox versión 3.1,

librería incluida en la versión completa del paquete antes mencionado.

Este programa fue probado en dos computadores de características

distintas, las cuales están tabuladas en el siguiente cuadro:

CARACTERÍSTICA

Procesador (Velocidad)

Memoria RAM (MB)Velocidad del Bus (MHz)

Sistema Operativo

COMPUTADOR 1

Pentium IV (1.6GH2)

256400

Microsoft WindowsXPProfessional

COMPUTADOR 2

Portátil Pentium IV (2.6GHz)512266

Microsoft Windows XPProfessional

Tabla 4.5: Características de los computadores usados en laimplementación del Algoritmo

Como se puede observar las características de los equipos utilizados para

el desarrollo del programa que resulta de esta investigación son muy

diferentes, por lo cual, al menos en tiempo de cómputo, se esperaría tener

tiempos diferentes entre ellos. En cuanto a la capacidad de

almacenamiento y resultados fundamentales, éstos no deberían variar,

pues no dependen de las características de los equipos de computación.

Los resultados obtenidos en el procedimiento de detección de bordes de

una imagen, así como su eficiencia, se los resume en los siguientes

Acápites de este trabajo.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 130: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLE MENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -119-

4.3.2 RESULTADO PARA LINEAS RECTAS PURAS.

En la primera etapa del algoritmo se presenta un procedimiento que utiliza

un mecanismo para el cálculo sólo de líneas rectas. Se probó con algunas

imágenes que tenian sólo líneas rectas en distintas posiciones y sólo

curvas con el fin de evaluar las bondades del mismo.

Los primeros resultados que se muestran corresponden a la imagen

"prueba.bmp", que se muestra en la Figura (4.9) como imagen normal (a) y

como imagen binarizada (b)

(a) (b)

Figura 4.9: Imagen para probar el algoritmo solo de líneas (a) imagen original; (b) imagenbinarizada.

El primer algoritmo utilizado es uno desarrollado a base de la función

radon13 propia del Matlab, con el cual se obtuvo las siguientes gráficas

(Figura 4.10)

Es interesante realizar el análisis de los resultados que se muestran en la

Figura 4.10 a partir de la imagen de la Figura 4.9. Se debe notar que, a

medida que se aumenta el valor del pico de voto mayor, el número de

líneas que podrían ajustarse a la imagen disminuye e incluso algunas se

pierden. En el sentido contrario, a medida que se disminuye el voto la

cantidad de líneas que aparecen es alta, de tal manera que pueden surgir

13 Un estudio más pormenorizado de la Transformada Radon y de su relación con la Transformada de Hough puede encontrarse en [24].

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 131: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E 1MPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 120 -

rectas que no corresponden a las existentes en la imagen original y el error

es alto, en ese aspecto.

(a)

(b) (c)

Figura 4.10: (a) Imagen obtenida en el espacio parámetro. Nótese la difuminación de las curvasobtenidas y los puntos en donde los picos son más altos (tendencia a blanco) y dondehay ausencia de picos (negro), (b) Imagen obtenida con los valores en el acumulador delos picos mayores a 60. (c) Imagen obtenida con picos mayores a 50. Nótese lacantidad de líneas falsas que se eliminan al aumentar el valor de los picos detectados,así como las lineas que dejan de ser detectadas.

Comportamiento de la Transformada de Hough frente al ruido.

Una de las virtudes de la Transformada es su inmunidad al ruido, si se

toma en consideración la imagen de la Figura 4.9 (a) y a ella se le afecta

con ruido, los resultados que se obtienen son los que se muestran en la

Figura 4.11. Los ejemplos que se muestran están afectados por ruido

gaussiano, ruido de Poisson14 y ruido "sal y pimenta".

14 Ruido de Poisson: Se define como ruido de Poisson, a aquel ruido que tiene una interpretación según la Distribución de Probabilidadde Poisson.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 132: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -121-

En cualquiera de los ejemplos mostrados, se puede mirar que la variación

en la detección de líneas es muy pequeña. En donde se mira un efecto

más fuerte es en las Figuras 4.11 (e) y (f) donde la binarización de la

imagen arroja algunas formas que en la imagen original no se encuentran.

A pesar de ello, las rectas obtenidas no varían mucho de las halladas en

los anteriores casos.

(a)

(e) (f)

Figura 4.11: Imagen "prueba.bmp" alterada con ruido para probar el algoritmo solo de líneas(a) imagen alterada con ruido gaussiano; (b) imagen resultante: (c) alterada conRuido de Poisson y (d) su respectivo resultado; (e) y (f) con ruido sal y pimienta ysu resultado. Para todos los casos se usó 40 votos.

Esta es una muestra en pequeño de la robustez de la Transformada de

Hough en ambientes ruidosos. Una de las condiciones que se ha venido

sosteniendo en este trabajo es que la Transformada de Hough es inmune

al ruido y, en este grupo de ejemplos se lo ha demostrado.

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 133: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -122-

Al evaluar el procedimiento desarrollado para una imagen con solo curvas

(Fig. 4.12), los resultados del algoritmo se muestran en la Figura 4.13.

(a) (b)

Figura 4.12: imagen para probar el algoritmo solo de líneas para una circunferencia (a) imagenoriginal; (b) imagen bina rizad a.

El problema con la Transformada de Hough para solo líneas en imágenes

que tienen curvas es que un arco puede ser aproximado por una infinidad

de líneas rectas tangentes al mismo. En la Figura 4.13 se aprecia la

cantidad de rectas con una misma ecuación paramétrica que se pueden

ajustar a las circunferencias mostradas en la Figura 4.12, por tal razón se

consigue una imagen tan difusa y es difícil saber que es lo que se aprecia

en la composición final.

(a) (b)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 134: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -123-

(c) (d)

Figura 4.13: (a) Imagen obtenida en el espacio parámetro. La cantidad de sinusoides ha crecidofuertemente, (b) Imagen obtenida con los valores en el acumulador de los picos mayores a50. (c) Imagen obtenida con picos mayores a 45. (d) Con valores superiores a 40.

Las imágenes más complejas, aquellas que tienen la combinación de

líneas y curvas dentro de ella, también deben ser estudiadas dentro del

ámbito de la transformada para líneas rectas. En este caso se muestra la

Figura 4.14, donde se halla una imagen compleja. La Figura 4.15 muestra

los resultados del procesamiento de la imagen por medio del algoritmo de

detección de líneas rectas.

(a) (b)

Figura 4.14: Imagen para probar el algoritmo solo de lineas (a) imagen original; (b) imagenbinarizada.

En el conjunto de las Figuras 4.15, se puede establecer que, a medida que

disminuye la cantidad de votos, la cantidad de líneas aumenta y no se

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 135: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLE MENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -124-

debería sorprender si los resultados que se obtengan sean realmente

ininteligibles en una primera instancia. Esto se debe a que, al ser la imagen

base muy compleja, con muchos detalles, la Transformada intentará

calcular las líneas que se aproximen a estos detalles, resultando,

obviamente, en muchas líneas que harán perder el sentido al proceso.

(c) (d)Figura 4.15: Resultados de aplicar el algoritmo de solo líneas en una imagen genérica, (a)

Espacio transformado, (b) Líneas detectadas con votos mayores a 120. (c) Líneasdetectadas con votos mayores a 100. (d) Líneas detectadas con votos mayores a65.

Un resultado que no se muestra todavía es el tiempo de cálculo de la

Transformada con una imagen en particular y considerando el número de

votos que se deben tomar en cuenta para suponer que las características

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 136: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -125-

de la imagen han sido reproducidas. La Tabla 4.6 muestra los resultados

de este cómputo.

IMAGEN

Prueba.bmp (40 votos)Bolita.jpg (25 votos)Airplane.bmp (60 votos)

TIEMPO (SEGUNDOS)

COMPUTADOR 1

0.7971.1253.61

COMPUTADOR 2

0.6510.731.623

Tabla 4.6: Tiempos de cómputo para el cálculo de laTransformada de Hough. Algoritmo solo líneas

La complejidad de la imagen estudiada dará una primera estimación de qué

tan altos son los tiempos de procesamiento. Nótese que de los tres

ejemplos, el más complejo es el del avión (Figura 4.15 (a)) y el tiempo de

procesamiento, por la cantidad de líneas que tiene la imagen, es mayor que

el de "prueba.bmp" que sólo contiene unas pocas líneas.

La imagen solo de curvas (bolita.jpg) tiene una complejidad media y por

ello los tiempos de procesamiento son relativamente bajos. Un punto

adicional es que a medida que esta complejidad aumente el tiempo

aumentará.

Otro aspecto que vale la pena analizar es que no importa mucho la

cantidad de votos a considerar como límite de análisis, pues este

dependerá de la imagen en particular. Lo que si se puede manifestar es

que a medida que se disminuya el límite inferior, el tiempo de

procesamiento aumentará. Esto quiere decir que el límite de votos y el

tiempo de procesamiento se comportan de manera inversa.

Nótese, adicionalmente, que los tiempos de respuesta en procesamiento

disminuyen al realizar las mismas operaciones en dos computadores de

distintas características. Si se analiza bien y se compara la Tabla 4.5 y 4.6,

se puede observar que los tiempos de procesamiento son, en el caso de la

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 137: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMP U EME NT ACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -126-

imagen 4.12 y 4.13, casi el doble, mientras que para la Figura 4.9 son casi

similares.

4.3.3 RESULTADOS PARA LÍNEAS CURVAS PURAS.

En líneas anteriores se utilizó un procedimiento estrictamente orientado a

líneas rectas para resolver una imagen que tenía circunferencias. En este

Acápite se plantea la solución de una imagen por medio de una secuencia

de programación que se dirige estrictamente a líneas curvas y,

principalmente, circunferencias.

En esta Sección se va a presentar las soluciones para las mismas gráficas

que se propusieron en el literal anterior.

En el caso de las líneas rectas exclusivamente, hay que tomar en

consideración una definición: "la recta es una circunferencia de radio

infinito"15. Por ello es algo complicado representar una recta como un

conjunto de circunferencias consecutivas, pero, geométricamente

hablando, sería posible si estas circunferencias fueran tangentes a cada

una de las rectas.

Este primer análisis sirve como fundamento para encontrar la respuesta

que la Transformada de Hough con algoritmo de circunferencias arroja para

una imagen compuesta solo de líneas, lo que se puede observar en la

Figura 4.16.

Una primera conclusión de analizar el resultado obtenido en las Figuras

4.16(c) y 4.16 (d) es que un menor radio de circunferencia permite tener

una mejor aproximación de las rectas dibujadas.

15 La frase es una definición que escuche varias veces en clase de Geometría en el Colegio y en la Politécnica (Nota del Autor).

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 138: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS - 127 -

(c) (d)

Figura 4.16: Imagen para probar el algoritmo solo de circunferencias (a) imagen original; (b)imagen amarizada. Los resultados de la detección de curvas en líneas rectas (c)radios entre 100 y 300; (d) radios entre 50 y 100

En cuanto al análisis de los tiempos de procesamiento de la imagen por

medio de este procedimiento, se lo muestra al final de este Acápite, una

vez que se analice el comportamiento del algoritmo de curvas en otras

imágenes.

Para el caso de una imagen exclusivamente formada de curvas, los

resultados se muestran en la Figura 4.17.

De los resultados que se obtienen de las Figuras 4.17 (c) y (d) se puede

inferir que, en este caso un mayor tamaño de los diámetros pueden

construir de mejor manera las curvas encontradas en la imagen. Nótese

que los radios que se buscan no están en un rango sino en dos tamaños

definidos. Adicionalmente, este algoritmo trata de simular a una elipse por

medio de la combinación de circunferencias, algo bastante lógico [61].

F. WLADIMIRO BASANTES M, PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 139: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -128-

Q-0

(c) (d)

Figura 4.17: Imagen para probar el algoritmo solo de curvas (a) imagen original; (b) imagenbinarizada. Resultados (c) radios de 5 y 25 píxeles; (d) radios de 27 y 55 píxeles

Dentro de este esquema se analizará el resultado provocado por la

Transformada de Hough en una imagen compleja. Los resultados de

aplicar este algoritmo sobre una imagen combinada se muestran en la

Figura 4.18

Obsérvese que en la Figura 4.18 (c) la cantidad de circunferencias que

tratan de seguir los contornos de los elementos de la imagen no es muy

alta, pero al aumentar la cantidad del radio (Figura 4.18 (d)), el número de

circunferencias aumenta. El primer problema que se presenta en este tipo

de gráficos, como se verá líneas más adelante, es que los tiempos de

procesamiento aumentan considerablemente, pues la cantidad de detalles

que se trata de seguir son mayores que en una imagen solo rectas o solo

curvas.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 140: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -129-

(a)

(c) (d)

Figura 4.18: Imagen para probar el algoritmo solo de líneas (a) imagen original; (b) imagenbinarizada. Resultados (c) radios de 5 y 100; (d) 100 y 300.

Los tiempos de procesamiento para este segmento se ven tabulados en la

Tabla 4.7. Nótese que cuando se aplica en una imagen solo de curvas, los

tiempos de procesamiento son los más bajos. A medida que la complejidad

de la imagen crece, los tiempos aumentan fuertemente.

Un punto adicional es que a medida que aumentan los tamaños de los

radios que se utilizan para detectar las curvas, los tiempos aumentan, pues

hay mayor cantidad de cálculos y comparaciones de votos que se deben

realizar para encontrar los contornos.

Uno de los puntos interesantes que se puede notar de esta Tabla de

resultados es que a pesar de que el computador 2 es algo más rápido que

el computador 1, los tiempos de procesamiento son algo mayores para el

caso de la imagen bolita.jpg.

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 141: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 4: DISEÑO E IMPLEMENTACIÓN DEL ALGORITMO Y ANÁLISIS DE RESULTADOS -130-

COMPUTADOR 1

COMPUTADOR 2

PRUEBAJPG

50-100

78.687

77.882

100-300

119.062

85.492

BOLITA.JPG

5-25

21.094

22.042

27.5 - 50

41.907

45.014

AIRPLANE.BMP

5-100

214.718

166.469

100-300

599.75

447.944

Tabla 4.7: Tiempos de cómputo para procesamiento de imágenes con laTransformada de Hough. Algoritmo solo curvas

En el Capítulo 3 y a lo largo de este Capítulo, se manifestó que la

Transformada de Hough fue originalmente orientada hacia aplicaciones

simples, tales como encontrar el rastro lineal que dejaba una partícula

subatómica en una cámara de burbuja. Al menos así fue su origen.

El grado de complejidad de las imágenes ha aumentado. Esto ha

demandado que la Transformada evolucione y pase de ser un mero

algoritmo para detectar líneas rectas, hoy se convierta en una herramienta

para el procesamiento y detección muy versátil que es utilizada en algunas

aplicaciones prácticas tales como robótica, imagenología, detección

geográfica, entre otras.

La investigación que ha conducido a este trabajo no se arriesga a dar una

solución de la Transformada de Hough para imágenes generalizadas,

debido a la gran cantidad de aplicaciones prácticas que la Transformada

puede afrontar. Sin embargo, en el Acápite anterior se presentó las bases

de un algoritmo que aumenta la potencialidad de la Transformada de

Hough. La implementación de este algoritmo puede ser considerada como

una parte de otras investigaciones que busque profundizar en esta técnica

matemática bastante útil en la actualidad.

Muchos de los trabajos que se incluyen en la bibliografía sugieren

procedimientos desarrollados para alguna aplicación en específico.

Algunos de ellos están a libre disposición en Internet y otros con el pago de

cuotas o suscribiéndose a alguna sociedad.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 142: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5

CONCLUSIONES Y RECOMENDACIONES

5-1 EL FUTURO DE LA TRANSFORMADA DE HOUGH

Cuando Paul V. C. Hough patentó el "Método y los Medios para

reconocer patrones complejos", la investigación científica estaba

evolucionando muy rápidamente. Las imágenes comenzaron a ser

decisivas para la investigación, no solo científica sino también militar,

pues en esos días la "Guerra Fría" estaba en su punto más alto, y más

delicado, y su manipulación, mejoramiento y perfeccionamiento eran uno

de los requerimientos inmediatos.

Algunos meses después de la patente, se desató la "Crisis de los

Misiles" en donde las fotografías tomadas por aviones espías sobre

Cuba, mostró a Estados Unidos la construcción de bases de misiles

balísticos de corto alcance1. Las fotografías tomadas por las cámaras

fotográficas de los aparatos U-2 "permitían leer sin ningún problema las

líneas de un periódico fotografiado a 10000 m"2, lo cual contribuyó a

presionar a la Unión Soviética a la solución pronta de una crisis que

puso al mundo al borde de una guerra nuclear.

En la actualidad, a dos años de los peores ataques terroristas que han

sufrido los Estados Unidos, la seguridad es uno de los temas que más

se ha enfocado. Algunas de las soluciones planteadas para incrementar

la seguridad en los vuelos y en cualquier actividad es la comparación de

las imágenes obtenidas de un dispositivo con un patrón definido. Esto

trae como consecuencia que los ojos de los investigadores vuelvan a los

1 ZENTNER, Christian: LAS GUERRAS DE LA POSGUERRA II. Enciclopedia GRANDES GUERRAS DE NUESTROTIEMPO, Tomo 10. Ed. Bruguera. Barcelona. 1976.

2 ZENTNER, Christian: Obra cit

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 143: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -132-

métodos que permiten ei reconocimiento de patrones, segmentación de

imágenes y detección de bordes.

Entre estos dos acontecimientos históricos, el mejoramiento de las

imágenes obtenidas a nivel de las imágenes, sean fotografías tomadas

de aviones, de satélites o de cualquier otro dispositivo que tenga dicha

capacidad ha sido realmente prodigioso. Las imágenes provenientes de

satélite pueden tener un error de tan solo metros y pueden ser tan

nítidas como las tomadas por cualquier persona ubicada a pocos metros

de ella.

No solo hay que ver la evolución de las imágenes tomadas por aviones,

satélites, también el mejoramiento de los aparatos de Tomografía Axial

Computarizada, que ya no solo presentan imágenes bidimensionales del

cuerpo humano, sino que son capaces de presentar imágenes

tridimensionales con alta resolución que son muy útiles para la

investigación médica y diagnóstico de enfermedades.

No hace mucho, la investigación espacial tuvo un pequeño espaldarazo

con el lanzamiento y puesta en funcionamiento del Telescopio Espacial

Hubble, con el que se espera obtener imágenes del espacio que

permitan investigar y adentrarse en los misterios del Universo. La

aplicación de herramientas para discriminar objetos tomados por el

telescopio es muy importante en este tipo de estudios.

Hough desarrolló su trabajo pensando en que el mismo se iba a utilizar

para el trabajo con partículas subatómicas [31]; sin embargo, sugirió que

también podría ser utilizado para el reconocimiento de patrones más

complejos en imágenes. Esta es una de las aplicaciones más comunes

de esta patente y esto se puede ver en la mayoría de trabajos que se

presentan en la bibliografía. Es por ello el nuevo interés en la

investigación y aplicaciones de la Transformada de Hough.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 144: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -133-

Actualmente, la Transformada de Hough es utilizada para el análisis

geocientífico, para el movimiento de robots, para los estudios de

imágenes médicas, etc. El campo de aplicación de la transformada se ha

ampliado a medida que las necesidades de investigación de las

imágenes obtenidas se han especializado fuertemente. No es lo mismo,

como se mencionó en el capítulo 4, la utilidad de una imagen satelital de

un bosque para un ambientalista como para un geógrafo, aunque los dos

sacarán conclusiones parecidas.

En fin, el estudio de la Transformada de Hough permitirá disponer de

una herramienta más para el análisis de las imágenes a nivel intermedio,

como puede ser detección de bordes, extracción de fronteras,

segmentación, etc.

5.2 CONCLUSIONES

Lo primero que se debe destacar es la marcada relación que existe entre

la informática y el procesamiento de señales. El avance de las técnicas

de procesamiento de imágenes ha dependido de gran manera del

avance y mejoramiento de las técnicas informáticas y del hardware de

las computadoras. A mayores velocidades de procesadores, las técnicas

mejoran sus tiempos de respuesta. A mayor crecimiento de las

necesidades de procesamiento, las complejidades de los algoritmos de

solución también crecen, pero siempre dependerá de la mayor o menor

comprensión que sobre el problema tenga el desabollador del sistema.

Se debe establecer que cualquier sistema de procesamiento de señales

dependerá de las necesidades del usuario final del procedimiento o de

cual es la visión del programador sobre para qué va a servir su trabajo.

Es por ello que siempre, cuando se plantean investigaciones sobre

procesamiento, es deseable que se tenga en claro dónde y quién va a

utilizar el resultado de este trabajo, porque de ello dependerá el grado de

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 145: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -134-

complejidad del algoritmo resultante y, además, que tan interactiva debe

ser la solución informática del mismo.

Los desarrollos de algoritmos de solución de un problema de

procesamiento de imágenes en particular generalmente concluyen con el

desarrollo de un software en el que se aplique ese procedimiento. La

implementación informática de un proceso desarrollado para resolver

alguna necesidad de un usuario es útil para encontrar si éste es lo

suficientemente rápido y confiable para cubrir sus necesidades en este

campo.

La Transformada de Hough fue desarrollada en principio para aplicarse

sobre líneas rectas, ya que el espíritu del trabajo inicial así lo enunciaba.

El aplicar la parametrización de la recta en forma normal permitió que el

horizonte de investigación se abra hacia otras formas geométricas,

llegando a la Transformada Generalizada de Hough. No solo ello, sino

que, al utilizar técnicas estadísticas para estudiar los puntos que

contiene una imagen y con ellos obtener los resultados que se podrían

lograr si se aplican a todos los puntos de la misma imagen, ha permitido

una reducción de los tiempos de procesamiento y la complejidad

computacional. Adicionalmente, la Transformada de Hough utiliza

también otras técnicas que no contradicen el espíritu original de la

misma sino que la fortalecen y hacen de ella una técnica que está siendo

estudiada con mayor profundidad, tal es el caso de la utilización de la

técnica del gradiente que se utiliza conjuntamente con la RGHT.

Las técnicas de Hough pueden aplicarse a cualquier imagen. Sin

embargo, hay que tener un especial cuidado con el tipo de imagen en la

que se quiere utilizar. Lo mejor que se puede hacer es utilizar siempre la

transformada generalizada en una imagen. Eso no quita que, tomando

en consideración si la imagen es sólo de líneas o curvas, se utilice el

algoritmo solo de líneas o sólo de curvas según el caso.

F. WLADIMtRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 146: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -135-

Los métodos para el procesamiento de imágenes, más específicamente,

detección de líneas y bordes con la transformada de Hough han ido

mejorando y evolucionando de manera acelerada. Una de las principales

consecuencias de esta evolución es la rápida disminución de tiempos de

cómputo de los resultados del procesamiento. En algunos casos, esto

está ligado a la velocidad de los nuevos procesadores de las

computadores y a que si las máquinas, que se utilizan para resolver

estos problemas, tienen un solo procesador o trabajan con procesadores

paralelos. Nuevos trabajos sobre la Transformada de Hough plantean la

utilización de procesadores paralelos para mejorar los tiempos de

cómputo del procedimiento.

Una de las razones del actual "boom" de las técnicas de procesamiento

de imágenes es el mejoramiento de los sistemas informáticos. Debe

quedar en claro que los mismos problemas que se pueden resolver en

computadores Pentium I, se van a resolver en los modernos

computadores Pentium IV, lo que va a variar son los tiempos de cálculo

y, en algunos casos, la resolución de las respuestas. En algunos

problemas, no importa mucho tener un potente computador para

resolverlo, sino que el algoritmo que se haya desarrollado para

solucionar dicho ejercicio sea óptimo y eficiente.

Los algoritmos para el cálculo de la transformada de Hough van

creciendo en complejidad a medida que los detalles de la imagen a

investigar vayan aumentando en cantidad. Un algoritmo solo de líneas

tendrá menos pasos que un algoritmo que no sólo detecte rectas, sino

también curvas y formas generales de la imagen.

La nueva tendencia, que se ha visto en los trabajos consultados para el

desarrollo de este Proyecto, apunta a comparar una imagen dada con un

patrón determinado para extraer sus características. Estas técnicas

nuevas se pueden utilizar para aplicaciones relacionadas con seguridad

e investigación de fotografías e imágenes satelitales. Con seguridad,

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 147: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -136-

pues se puede utilizar para identificar patrones físicos de un objeto como

la geometría del mismo, o de una persona. Con la investigación de

fotografías o imágenes satelitales, ya que se lograría identificar formas

predefinidas de un objeto que se necesita estudiar en esa imagen.

En principio, puede resultar raro el hecho de que algunos resultados no

se hayan comportado como se esperaba, pues cuando se pensaba que

los tiempos de cálculo disminuirían en el doble, tan sólo bajaron o

aumentaron en un pequeño porcentaje. Esto resultó realmente

inesperado. Algunos intentos posteriores, arrojaron los mismos

resultados. Es difícil, en primera instancia justificar este problema. Sin

embargo, hay procesos internos de las computadoras que pudieron

afectar el desempeño del software. El mismo procedimiento del

programa daba la sensación de que se había colgado la aplicación, lo

cual ocasionó algunos sustos al autor.

5.3 RECOMENDACIONES

A lo largo de este trabajo de investigación, se han presentado algunos

aspectos que caben ser tomados en cuenta para el futuro de la carrera,

pues, se debe considerar que Ingeniería en Electrónica y

Telecomunicaciones es una rama que, al estar ligada a la evolución de

nuevas tecnologías, está en constante desarrollo y cambio.

No es difícil, después de este desarrollo teórico y la aplicación en la

práctica, inferir la importancia de la correlación que debe existir entre la

informática y el procesamiento de señales de cualquier tipo:

unidimensionales, bidimensionales o tridimensionales. Aunque nuestro

campo de estudio, en el aspecto del procesamiento de señales a ser

trasladadas en un canal de comunicaciones guiado o no guiado,

analógico o digital, se resume en tomar la información ya procesada y

encontrar el mejor camino para enviarla a un destino, no se debe

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 148: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -137-

desechar el procesamiento anterior de esa información y los métodos

usuales para tratarle y extraerle la información necesaria.

A lo largo de la investigación tendiente al desarrollo de este proyecto de

titulación, se ha sentido la necesidad de tener algunos conocimientos

adicionales, que en pregrado no se tuvo, por algunos motivos que no es

objetivo de este trabajo analizarlo pero que se pueden resumir en los

siguientes puntos:

- Informática y procesamiento de señales.

- Procesamiento de imágenes.

- Laboratorios relacionados al tema.

- Las perspectivas de esta investigación.

5.3.1 PROCESAMIENTO DE IMÁGENES

El procesamiento de imágenes es uno de los temas de más amplio

desarrollo en la actualidad, sea por la necesidad de tener imágenes de

un fenómeno sin tener que estar una persona presente en el lugar donde

el hecho se está produciendo, o porque se requiera para interpretar

algún resultado proveniente de la misma. Una muestra de ello es que, en

la mayoría de los casos actuales, los sensores de imágenes no siempre

se hallan en el lugar donde sucede un acontecimiento, a veces están en

los satélites y si los sensores se hallaren en el lugar del hecho, las

personas que los manejan, en ocasiones, se hallan a metros o

kilómetros de distancia.

Es por ello que los sistemas de captura de la imagen se están

perfeccionando más y más. De las cámaras analógicas que se tenían en

los primeros años, con "zoom" bajos, se pueden disponer en la

actualidad de cámaras digitales con posibilidades de hacer

acercamientos muy altos. Para visualizar esta diferencia, tómese como

referencia lo mencionado en líneas anteriores en el caso de los aviones

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 149: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES -138-

espías U - 2 norteamericanos y las actuales imágenes obtenidas por

fotografía satelital. En ambos casos la resolución es altísima, pero la

altitud es distinta.

Obviamente, y como se debería suponer, este avance tecnológico no

solo afecta a la captura de la imagen, sino a la evolución de los sistemas

de procesamiento a nivel intermedio. Gran cantidad de aplicaciones de

sistemas de imagen han aparecido en los últimos años, ligadas a un

mejoramiento del hardware de procesamiento y manejo de las imágenes

obtenidas. Ni que decir de los formatos de almacenamiento y

compresión de imágenes; estos han permitido que los espacios de

almacenamiento de las imágenes procesados disminuyan notablemente.

La pregunta que surgiría es, ¿qué importa a los ingenieros en electrónica

y telecomunicaciones el mejoramiento de los sistemas de procesamiento

de imágenes, en general? La respuesta está ligada a la necesidad de los

ingenieros en electrónica y telecomunicaciones de diseñar sistemas de

transmisión de datos de manera eficiente y a garantizar que cualquier

tipo de anomalía no afecte y/o altere la señal enviada desde el origen

hasta el destino. Un mejor conocimiento de los sistemas de

procesamiento de imágenes, y de los métodos que se utilizan para

tratarla, permitiría tener en claro el efecto que en ellas producen las

anomalías del canal de comunicaciones.

Es por ello que se considera útil impartir esta teoría a los estudiantes de

pregrado, sea ligada a la materia de Procesamiento Digital de Señales, a

la materia de Teoría de la Información y Codificación, como materia

optativa o como un seminario, con el fin de que los estudiantes se

familiaricen con las técnicas de manejo y procesamiento de imágenes.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 150: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES - 139 -

5.3.2 INFORMÁTICA Y PROCESAMIENTO DE SEÑALES

A lo largo de la ejecución de este trabajo, se encontró, en mucho de la

investigación por Internet, la correlación existente entre la informática y

el procesamiento de cualquier tipo de señales, lo cual es algo que se

entiende y se supone perfectamente.

En los últimos 20 años, la evolución de la informática, la electrónica y las

telecomunicaciones ha sido conjunto ya que la microelectrónica, primero

y luego la nanoelectrónica, recientemente, ha permitido que los sistemas

informáticos, principalmente las computadoras personales, se hayan

vuelto más accesibles al común de las personas, por la reducción de

costos, la reducción del espacio que requieren estas máquinas y por la

facilidad de portarlas a los lugares de trabajo. Esto ha hecho que la

computadora se convierta en la herramienta del día a día para una gran

cantidad de habitantes del planeta.

En el aspecto del procesamiento de señales, de cualquier tipo, la

computadora ha permitido que, a través de los distintos lenguajes de

programación, se desarrollen aplicaciones orientadas a resolver

cualquier tipo de problema referente a este tópico, en cualquiera de las

plataformas operativas existentes: Windows, MacOS, Unix, Linux, etc.

Más aún, el entorno gráfico de estos sistemas operativos ha permitido

que las utilidades desarrolladas sean más amigables y llamativas para el

potencial usuario de tal sistema.

En nuestra carrera, se nota un ligero divorcio entre las materias de

procesamiento de señales y la informática. Una de las razones puede

radicar en el hecho de que, a pesar de que los costos de una

computadora son más bajos que hace unos dos o tres años atrás, la

mayoría de estudiantes no puede fácilmente adquirir una computadora,

sea por limitaciones económicas, fundamentalmente, o cualquier otra

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Course Material for Introducto/y Engineering Course*. United Enuinccring Foundation Conference 11-16 August2002 Davos,Switzerland

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 151: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES - 141 -

5.3.3 LABORATORIOS AFINES CON PROCESAMIENTO DE SEÑALES.

Al tener el procesamiento de señales un alto contenido informático, una

fuerte base teórica y aplicación práctica, es indudable que lo que se diga

en la teoría hay que experimentarlo.

Dentro de la carrera de Telecomunicaciones hay algunas materias que

están ligadas al procesamiento de señales, tales como Análisis de

Señales y Sistemas, Teoría de Información y Codificación,

Procesamiento Digital de Señales y, en alguna medida, Sistemas

Analógico - Digitales.

En todas estas materias, se imparte una gran cantidad de conocimientos

que, a la mayoría de los estudiantes, les resultan muy abstractos, pues

se centran en la solución de algoritmos vía papel y lápiz. En el estudio

de McCIellan4 se menciona también esta problemática y las mejoras que

se tuvo en el aprendizaje y el interés de los alumnos cuando se introdujo

la computadora para el desarrollo de problemas de procesamiento de

señales en clases o en casa.

La reorientación de la carga de estas materias, con el propósito de incluir

una parte práctica, sería una interesante estrategia que permitirá el

mejoramiento del aprendizaje en estas asignaturas y que se incremente

el interés en ellas.

Parte de esta solución se puede considerar el repotenciamiento de los

grupos de investigación o la creación de nuevos grupos que tengan

relación a estas áreas y que cuenten con la participación de estudiantes

interesados en estos temas. Para conseguir la intervención de los

alumnos se debería pensar en un plan de incentivos académicos y/o

económicos con el objeto de premiar el interés de los mismos.

4 McCLELLAN, James: Obra cit.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 152: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES - 142 -

En la actualidad, las investigaciones en procesamiento de señales de

cualquier índole abren un interesante horizonte que puede ser explotado

por nuestros profesionales. Este futuro es producto, como casi todos los

avances tecnológicos humanos, de un sueño visionario de una persona.

De que una persona haya sentido la necesidad de cubrir un

requerimiento personal o global, lo que le induce a proponer a otras

personas esta ilusión para llevarla adelante. Algunos le apoyarán, otros

le darán la espalda y, tal vez, se desanimará, pero alguien, o él mismo,

seguirá con la idea y la hará realidad. Mucho de lo que se tiene hoy en

día es producto del sueño de alguien y del tesón de otros. Hay que hacer

que nuestros profesionales sean soñadores para que siga habiendo

investigación.

Los profesionales de la Escuela Politécnica Nacional deben ser artífices

del desarrollo y no cómplices del subdesarrollo; deben estar listos para

aplicar las tecnologías nuevas que importamos y a exportar nuevas

tecnologías que ellos desarrollen. Deben opinar cuando el resto quiera

callarlos y deben saber rebatir, con ideas y proyectos, a quienes quieran

menospreciar sus capacidades y habilidades. Deben saber escuchar y

aprender, deberán ser sabios para cambiar si han cometido errores...

La responsabilidad de todos los actores que están involucrados en la

formación de profesionales en las ramas de Electrónica y

Telecomunicaciones y que sigan desarrollando los temas relacionados

con Procesamiento de Imágenes está en el mejoramiento de su

educación y autoeducación en las áreas ligadas a estas asignaturas:

Informática, Procesamiento de Señales, etc., y al adiestramiento de ellos

en paquetes computacionales tanto de desarrollo como de aplicación.

Este es un reto en donde toJos deben involucrarse y propender al

mejoramiento de quienes trabajen en el proceso enseñanza -

aprendizaje con la realimentación necesaria en este tipo de asuntos.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IM/ :FNES USANDO LA TRANSFORMADA DE HOUQH

Page 153: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

CAPITULO 5: CONCLUSIONES Y RECOMENDACIONES - 143 -

5,3.4 La perspectiva de esta investigación

Este trabajo no está completo debido a que las investigaciones sobre la

transformada de Hough avanzan constantemente. Principalmente, el

horizonte de la investigación gira en torno a mejorar los tiempos de

computación y de encontrar nuevas aplicaciones de este método en el

campo de la Robótica, Imagenología, detección de bordes y patrones,

segmentación de las imágenes, entre otras varias. Debe tomarse en

consideración el impulso que todas las técnicas de reconocimiento de

patrones han sufrido en los ultimes años, principalmente por el incesante

deseo de automatizar los procesos productivos y el enorme impulso de

la informática en todos los aspectos cotidianos del ser humano.

Esta investigación no quiere convertirse en la última palabra sobre este

tema, ya que, como se ha visto en el desarrollo de la misma, no es un

tópico que se haya quedado estancado durante años, sino que ha

estado avanzando con el aporte de nuevas técnicas y desarrollos que

tratan de orientarse hacia e! mejoramiento de este procedimiento y que

se ven reflejadas en la gran cantidad de trabajos teóricos que se

encuentran en Internet. Este proyecto buscó adentrarse más en este

contexto, pero a medida de avanzar en ! búsqueda de información para

su sustentación, se halló la diversidad de aplicaciones hacia las cuales la

Transformada está orientada.

Para finalizar, la puerta que conduce a ¡as distintas aplicaciones de la

Transformada de Hough queda abier41 y este trabajo tan sólo se

convierte en la llave a uno de los trinas, como se ha mencionado

reiteradamente a lo largo de esta investigación, que más desarrollo tiene

durante los últimos años. La orientación que estas investigaciones tiene

va desde una simple detección de lineas i3<:ta la detección de imágenes

más complejas provenientes de satéüíc ; o de cualquier otro dispositivo

de captura de imágenes.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL Dr IM r.NCS USANDO LA TRANSFORMADA DE HOUGH

Page 154: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

BIBLIOGRAFÍA

[I] AGUADO, A. S; NIXON, M. S.: A NEWHOUGH TRANSFORM MAPPING FOR ELLIPSEDETECTION.

[2] ANDRADE, Hugo: OBTENCIÓN DEL MAPA VIAL ESQUEMÁTICO DE UNA ZONAGEOGRÁFICA A PARTIR DE UNA IMAGEN AEROFOTOGRAMETRICA. Tesis previa ala obtención del título de Ingeniero en Electrónica y Telecomunicaciones. EscuelaPolitécnica Nacional. Quito. 1998.

[3] ASHRAGHI, Farzin: PROCESAMIENTO DIGITAL DE IMÁGENES MONOCROMÁTICASMEDIANTE EL USO DE LA TRANSFORMADA RÁPIDA DE WALSH. Tesis previa a laobtención del título de Ingeniero en Electrónica y Telecomunicaciones. Escuela PolitécnicaNacional. Quito. 2000.

[4] COUCH, León W.: SISTEMAS DE COMUNICACIÓN DIGITAL Y ANALÓGICOS. EditorialPrentice Hall Hispanoamericana S. A. 5ta. Edición. México. 1997.

[5] FITTON, N. C.; COX, S. J. D.: OPTIMISING APPLICATION OF THE HOUGHTRANSFORM FOR AUTOMATIC FEATURE EXTRACTION FROM GEOSCIENTIFICIMAGES. Australian Geodynamics Cooperative Research Centre. Accepted for publicationin Computers and Geosciences 18-01 - 1998.

[6] GONZÁLEZ, Rafael; WOODS, Richard: TRATAMIENTO DIGITAL DE IMÁGENES.Editorial Addison - Wesley / Díaz de los Santos. EUA. 1996.

[7] GOTO, Hideaki; ASO, Hirotomo: DESIGNING EFFICIENT HOUGH TRANSFORM BYNOISE - LEVEL SHAPING. IEICE Transactions on Information and Systems. Vol. E83 -D. No. 2. February 2000. Japan. 2000. Pag. 242-250.

[8] GOTO, Hideaki; ASO, Hirotomo: THE EFFICIENT SAMPLING INTERVAL OF THESCANNING PARAMETER IN THE HOUGH TRANSFORM. Systems and Computers inJapan. Vol. 29. No. 11. Japan. 1998. Pag. 9-19.

[9] JAIN, Añil K.: FUNDAMENTALS OF DIGITAL IMAGE PROCESSING. Editorial Prentice -Hall International Inc. USA. 1989

[10] JAIN, Añil K: ADVANCES IN MATHEMATICAL MODELS FOR IMAGE PROCESSING.Proceedings of the IEEE. Vol. 69 No. 5. May 1981. Pag. 502 - 528.

[II] LE, D. X.; THOMA, G.: DOCUMENT SKEW ANGLE DETECTION ALGORITHM. Proc.1993 SPIE Symposium on Aerospace and Remote Sensing - Visual InformationProcessing II. Orlando, FL. April 14-16, 1993. Vol. 1961. Pag. 251 -262.

[12] Ll, Hsiang-Ling; CHAKRABARTI, Chaitali: HARDWARE DESIGN OF A 2-D MOTIONESTIMATION SYSTEM BASED ON THE HOUGH TRANSFORM. Department of ElectricalEngineering. Telecommunications Research Center. Arizona State University.

[13] MARTINS MENDES, Joyce; PEIXOTO, Nathalia; RAMÍREZ FERNÁNDEZ, Francisco:ALGORITHMS FOR PATTERN RECOGNITION IN IMAGES OF CELL CULTURES.Universidade Sao Paulo. Brasil.

[14] WIOREIRA HADAD, Renato: IDENTIFICADO DE PADRÓES EM IMAGENS DESATÉLITES - FORMAS CIRCULARES. Ponencia presentada en la III Semana dePosgraduados. Artículo tomado dewww.dcc.ufmg.br/pos/html/spg99/anais/hadad/hadad.htm. 1999.

Page 155: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

BIBLIOGRAFIA - 145 -

[15] MOREIRA HADAD, Renato: IDENTIFICADO DE PADRÓES EM IMAGENS DESATÉLITES - FORMAS CIRCULARES (VULCÁNICAS, ASTROBLEMAS ETECTÓNICAS). Ponencia presentada en la II Semana de Posgraduados. Artículo tomadode www.dcc.ufmg.br/pos/html/spg98/anais/hadad/hadad.htm. 1998.

[16] MORSE, Bryan S.: LECTURE 15: SEGMENTATION (EDGE BASED, HOUGHTRANSFORM). Brigham Young University. USA. 2000.

[17] OLSON, Clark F.: CONSTRAINED HOUGH TRANSFORMS FOR CURVES DETECTION.Computer Vision and Image Understanding. Vol. 73. No. 3. March 1999. Pag. 329 - 345.

[18] OLSON, Clark F.: DECOMPOSITION OF HOUGH TRANSFORM: CURVE DETECTIONWITH EFFICIENT ERROR PROPAGATION. Proceeding of the European Conference onComputer Vision. Pag. 263-272. 1996.

[19] OLSON, Clark F.: IMPROVING THE GENERALIZED HOUGH TRANSFORM THROUGHIMPERFECT GROUPING. Image and Vision Computing 16.1998. Pag. 627 - 634.

[20] PERANTONIS, Stavros; GATOS, Basilios; PAPAMARKOS, Nikos: BLOCKDECOMPOSITION AND SEGMENTATION FOR FAST HOUGH TRANSFORMEVALUATION. Pattern Recognition 32. 1999. Pag. 811 - 824.

[21] PRICE, Sarah: FUNDAMENTALS: MODELS OF IMAGE FORMATION. Artículo tomadodel Internet: www.icbl.hw.ac/marble/vision/low/fundamentals/models.htm. Actualizado el 4de Julio de 1996.

[22] RESTREPO, Luis: UNA INTRODUCCIÓN A LA VISIÓN DE MÁQUINA. Artículo tomadodewww.luisguillermo.com/visiona.htm

[23] SMITH, Steven: THE SCIENTIST AND ENGINEER'S GUIDE TO DIGITAL SIGNALPROCESSING. Editorial California Technical Publishing. Second Edition. San Diego,California, USA. 1999.

[24] TOFT, Peter: THE RADON TRANSFORM: THEORY AND IMPLEMENTATION, Ph. DThesis. Department of Mathematic Modeling, Section of DSP; Technical University ofDenmark. Denmark. 1996.

[25] VAZ, C.; LOPES, J.; DUARTE, F.; CARVALHO, P.: IMAGE PROCESSING INPARALLEL VIRTUAL MACHINES. SOME EXPERIMENTS AND CONCLUSIONS.Departamento de Engenharia Informática. Faculdade de Ciencias e Tecnología daUniversidade da Coimbra. Portugal.

[26] WALSH, Daniel; RAFTERY, Adrián E.: ACCURATE AND EFFICIENT CURVEDETECTION IN IMAGES: THE IMPORTANCE SAMPLING HOUGH TRANSFORM.Technical Report No. 388. Department of Statistics. University of Washington. February2001.

[27] WU, Dennis; SHOREY, Jamie; HOWARD, Ted: HOUGH TRANSFORM. Digital SignalProcessing: Waffle Page. www.owlnet.rice.edu/~elec431/projects97/waffle.

[28] ZHANG, Zhengyou: CLUSTERING OR HOUGH TRANSFORM. Tutorial. www-sop.inria.fr/robotvis/personnel/zzhang/Publis/Tutorial-Estim/node22.html.

[29] ZEMANSKY, Mark; SEARS, Francis; YOUNG, Hugh: FÍSICA UNIVERSITARIA. EditorialFondo Educativo Interamericano S. A. Sexta Edición. México. 1986

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 156: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

BIBLIOGRAFÍA - 146-

[30] BERTOCCI, Guido; SCHOENHERR, Brian; MESSERSCHMITT, David: AN APPROACHTO THE IMPLEMENTATION OF A DISCRETE COSINE TRANSFORM. IEEETransactions on Communications. Volume Com. 30 No. 4, April 1982. Pag. 635-641.

[31] HOUGH, Paul V. C.: METHODS AND MEANS FOR RECOGNIZING COMPLEXPATTERNS. United States Patent Office. Pat 3 069 654. December 18, 1962.

[32] THOMAS, George: CALCULO INFINITESIMAL Y GEOMETRÍA ANALÍTICA. EditorialAguilar. Quinta Edición. Madrid. 1971.

[33] LEHMANN, Charles: GEOMETRÍA ANALÍTICA. Editorial Limusa. Undécima reimpresión.México. 1986.

[34] SCHWARZ, Doug: GUI PROGRAMMING IN MATLAB 5. Artículo tomado del Internet:www.servtech.com/public/schwarz/guiprog.html.

[35] ETTER, Delores: SOLUCIÓN DE PROBLEMAS DE INGENIERÍA CON MATLAB.Editorial Prentice Hall Hispanoamericana S. A. Segunda Edición. México, 1998.

[36] NAKAMURA, Shoichiro: ANÁLISIS NUMÉRICO Y VISUALIZACION GRÁFICA CONMATLAB. Editorial Prentice Hall Hispanoamericana. México, 1997.

[37] THE MATHWORKS INC.: BUILDINGS GUI WITH MATLAB. MatLab Online Manuals.

[38] THE MATHWORKS INC.: USING MATLAB. MatLab Online Manuals.

[39] THE MATHWORKS INC.: MATLAB FUNCTIONS REFERENCE VOLUME 1:LANGUAGE. MatLab Online Manuals.

[40] THE MATHWORKS INC.: MATLAB FUNCTIONS REFERENCE VOLUME 2: GRAPHICS.MatLab Online Manuals.

[41] DUDA, Richard; HART, Peter: USE OF THE HOUGH TRANSFORMARON TO DETECTLINES AND CURVES IN PICTURES. Communications of the ACM. January 1972. Volume15. N°1. Pag. 11 -15.

[42] YUEN, Shiu Yin; MA, Ch¡ Ho: AN INVESTIGARON OF THE NATURE OFPARAMETERIZATION FOR THE HOUGH TRANSFORM. IEEE Proceedings of ICPR.1996. Pag. 537-541

[43] YUEN, Shiu Yin; MA, Chi Ho: AN INVESTIGARON OF THE NATURE OFPARAMETERIZATION FOR THE HOUGH TRANSFORM. Pattern Recognition. 1997. Vol.30. No. 6. Pag. 1009 - 1040. (Versión completa del articulo anterior).

[44] BEHREN, Thorsten; ROHR, Karl; STIEH, H. Siegfried: USING AN EXTENDED HOUGHTRANSFORM COMBINED WITH A KALMAN FILTER TO SEGMENT TUBULARSTRUCTURES IN 3D MEDICAL IMAGES. VMV 2001. Stuttgart, Germany. November 21 -23,2001. Pag. 492-498.

[45] AGUADO, Alberto; MONTIEL, Eugenia; NIXON, Mark: ON THE INTÍMATERELATIONSHIP BETWEEN THE PRINCIPLE OF DUALITY AND THE HOUGHTRANSFORM. Proceedings of the Royal Society. Vol. 456. London, 2000. Pag. 503 - 526.

[46] ROSENFELD, Azriel; DAVIS, Larry: IMAGE SEGMENTARON AND IMAGE MODELS.Proceedings of the IEEE. Vol. 67. No. 5. May 1979. Pag. 764-772.

[47] COHÉN, ; TOUSSAINT, : ON THE DETECRON OF STRUCTURES IN NO/SEPICTURES. Proceedings of the IEEE. Vol. 67. No. 5. May 1979. Pag. 764 - 772.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 157: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

BIBLIOGRAFÍA - 147

[48] MATAS, ; CÁLAMEOS, ; KITTLER, : PROGRESSIVE PROBABILISTIC HOUGHTRANSFORM. Proceedings of the IEEE. Vol. 67. No. 5. May 1979. Pag. 764 - 772.

[49] VELIGRADIS, Myron: YEAR 2 IMAGE PROCESSING PROJECT, Departamento deCiencias de la Computación. Universidad de Liverpool. Inglaterra. Website:http://www.csc.liv.ac.uk/*u8mv/index.html. (Página descontinuada)

[50] LAM, Wilson; LAM, Lam; YUEN, Kelvin; LEUNG, Dennis: AN ANALYSIS ONQUANTIZING THE HOUGH SPACE. Pattem Recognition Letters 15. November 1994.Pag. 1127-1135.

[51] LAM, Wilson; LAM, Lam; YUEN, Kelvin; LEUNG, Dennis: AN ERROR ANALYSIS ONQUANTIZING THE HOUGH SPACE. Proceedings of the ICPS'93. Octubre 1993. Pag. 946-949.

[52] SOLAIMAN, R; BURDSALL, B; ROUX, Ch.: HOUGH TRANSFORMAN UNCERTAINTYHANDLING. APPLICATION TO CIRCULAR OBJECT DETECTION IN ULTRASOUNDMEDICAL IMAGES. Dept. Image et Traitement de l'lnformation.

[53] SALOMÓN, Brian: HOUGH TRANSFORM ASSIGNMENT.http://www.cs.unc.edu/~salomon/class_projects/COMP%20254/Assignment3/Assignment3.htm

[54] FUNG, Ping - Fu; LEE, Wing - Sze; KING, Irwin: RANDOMIZED GENERALIZEDHOUGH TRANSFORM FOR 2-D GRAYSCALE OBJECT DETECTION. Department ofComputer Science and Engineering. The Chínese University of Hong Kong. Shatin, NewTerritories, Hong Kong. Conference of ICPR. 1996.

[55] KWATRA, Vivek: DETECTING COINS USING HOUGH TRANSFORM.http://www,cc.gatech.edu/-kwatra/computer_vision/coins/coins.html.

[56] PAVEL, Sandy; AKL, Selim: EFFICIENT ALGORITHMS FOR THE HOUGHTRANSFORM ON ARRAYS WITH RECONFIGURABLE OPTICAL BUSES. Departmentof Computing & Information Science. Queen's University. Supported byTelecommunications Research Institute of Ontario and the Natural Sciences andEngineering Research Council of Canadá.

[57] SHIU YIN K YUEN; TZE SHAN L LAM & NANG KWOK D LEUNG: CONNECTIVEHOUGH TRANSFORM. Image and Vision Computing. Volume 11 N° 5. June 1993. Pag.295-301.

[58] ATIQUZZAMAN, M.: MULTIRESOLUTION HOUGH TRANSFORM - AN EFFICIENTMETHOD OF DETECTING PATTERNS IN IMAGES. IEEE Transactions on PatternAnalysis and Machine Intelligence. Volume 14 N° 11. Pag. 1090-1095.

[59] GUIL, N.; ZAPATA E. L.: LOWER ORDER CIRCLE AND ELLIPSE HOUGHTRANSFORM. Journal of Pattern Recognition. Volume 30. N° 10. Pag. 1729- 1744.

[60] HANSEN, Klaus; DAMGAARD ANDERSEN, Jens.: UNDERSTANDING THE HOUGHTRANSFORM: HOUGH CELL SUPPORT AND ITS UTILISATION. DIKU. Department ofComputer Science. University of Copenhagen.

[61] KANATANI, Kenichi; OHTA, Naoya: AUTOMATIC DETECTION OF CIRCULAROBJECTS BY ELLIPSE GROWING. Artículo presentado para la International Journal ofImage and Graphics. Recibido el 27 de mayo de 2002, aceptado para publicación 4 deNoviembre de 2002.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 158: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Dec. 18, 1962 Pf v. a HOUQH 3,069,654METHQO AHD Iffi&HS TOR RBCOGNXZING COÉPLEX PACTEfWS

2 StM»t»-Sb*ftt 1Fil«d Uaroh 25, 1960

Page 159: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Dec, 18, 1962UETKOD

Filad Maroh 25. 1960

p. v. c. HOUGH 3,069,654AKD «EANS FOR RECOGNIZIHG COUPLEX PATTTERNS

2 Sheets-Sheet 2

Ví&yi•vi0

^

NM

\LM

•u£

?S

\>í1•35

§

i\•— _

* '•«<

v

5

ar

§w

**l

!íi*->:

^

^|

v*

U8 1**\

1 ^w

I 3^

«^ e^ a!3í H*$• 5• i

üt-^

«in

^ff

^

^ S

•jK^*-

•le

^2

k*

1í^CH.

Sj

1.

1

^ sXü|]55

ü<0

*SI74

\

» }, /^8i $i \\\IV

fu<\0

§

^J¿¡

!4

^

E^úíi"V

•í*\

!i^!

t;

^tíH_—

— i-

tt*ti^j

>^

s.

q

/"i

!'

iii

— '-<

>í \ tx \s

\

*3-i»V0 ^1

•S1-SiM

1 k\ . M»1 i ,

í 'tí - ^1 i ^k 0 A. ^^ TÍCT^ T

Si ^^ 4^ 11 S ^ - 4 &« J! «

50 ¡í» a3^ £

Í8 8 5ur"^ *» ^ ^5P 3" 1

• M Ur1

r\ \^ r

^ ^í¡ í* fK *3 Mi"— J

^ s ».*5 *F^^ §T ^S 5t

s ^ ' ^\ » í

-??"á^ /.* -a »x /í- s§ (\*\\b *? tt

^ K ^ í S***¿

\11^Si í v . 2 j^f^^^^"» S II* I hVt RH\W*X)

u•4*i

^— r<

íáüísí

-*-fifc^

*4 i*

•3's^'S,b

P

S^*?*> >*• S

W^

1

. »

|L -2

\i *\S' í1 ^l ?LJ^i- )

-Xíá Vn«l ^~|— r

SsU^ ?!s^S •*»h i?5 - l ír^ 1?

*JN V

1?

%

^

INVENTORc; .¿fouy

^ZZ^2~^+¿í.

&Í£-j*f~jv

1&S.§'!«^

''?"» vN

^&

í

&

1^4í

(*f

1§í1í*l

1

ff»S

Page 160: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

United States Patent Office 3,069,654Patented Dec. 18, 1962

1

3,069,654METHOD AND MEANS FOR RECOGNEING

COMPLEX PATTEKNSPaul V. C. Hoogh, Aun Arbor, Mica., assignor to tbe

United States of America as represeníed by the UnitedStates Alónate Energy CommLsston

Rled Mar. 25,1960, Ser. No, 17,7156CIainu. (CL 340—146.3)

lilis ínvention relates to the recognition of complexpattems and more specincally to a melhod and means formachine recognition of complex Unes in photographs orother pictoríal representationa.

This invention Is particularly adaptable to the study ofpubatomic partí de tracks passing through a viewlng field.As the objects to be studíed in modera physics becomesmaUer, ti», problem of observing these objects becomesíncreasingly more complex. One of the more useful de-vices in observing chargcd particles is the bubble chamberwhereia the charged partióles créate tracks along their pathof travel composed of small bubbles appraxiniatciy 0.01inch apart, depending upon the specific ionization of theinitiatíng-.particle. These tracks form complex patterasand are readily. photographed with the use of a dark bacfc-firound Wíth this device, multitudinous photographsare produced with each photograph requiring scveral hoursstudy. by a trained obscrver to recognize the complex pat-tems of the tracks. It ú therefore readily apparent, thatas the photographs mcrease in number, the time consumidby a trained observer to study them becomes excesaiveand, unless large numbers of tiained observers are used,the reduction of data falls far behind the production rate,

It is one object of this invention to provide a method andmeans for the recognition. of complex parteras in a pie-ture.

It U another object of this invenüon to provide an inv-proved method and meaos for recognizing particle tracksin pictüres obtained from a bubble chamber.

In general, the objects of this invention are accom-plished by dividing the viewcd representation into suffi-ciently small sectors or framelets that the complex patterais divided into substantially straight line segmenta. Eachof the segments is detected and transformed into slope andintercept data which may be stored and iater analyzed forthe presence of desired patterna.

, A more complete understanding of the invention wfllbest be obtained from consideration of the accompanyingdrawings in whích:

FÍO. 1 is an ülustration of a plañe transform repre-sentation of straight line segments;

FIO. 1 is a blocfc díggram of an apparaüís accordlng to««Chinga of the proaent invention; and

FIG. 3-ií a detailed block diagram ülustratmg the clec-'tronic plañe transform cnxuits of the appáratus in theembodiment of the presént invention, shown in FIG. 2.

\ geómetra constructioa by hand is shown in FIGUREI which depicts three straight line segments 1*2.104 and146 in a trámelo! 108 and their correspondlng sketchedplano transforma 102A, 104A, and 106A in picure 109.The geom«try of construction for the plana transformsis accomplished according to the following rules.

(1) For a given point on a line segment in framelet108, a Une is drawn in the transforméd plañe in píctnro100.

(2) For a point on the lino at the top of thó frameletIOS, tho line in the tranafonned plañe is inclined 45*to the right; a point on the line segment at the horizontalmidline of the framelet 10Í gives a vertical Une in theplañe transform; a point on the line segment at the bottomof the framelet 108 gives a Une in the transforméd plañeinclined at 45° to the left. In general, the Hne in thetransforme^ pl&he has án angle relative to the verticalwhose tangent is proportíonal to the vertical displacement

of the point 011 the line segment from the horizontal mid-line 109 of the framelet 108.

(3) Each line in the transforméd plañe is made to have:an intercept with the horizontal midline 101 of ¿e píc-

0 ture 100 equal to the horizontal coordínate of its respec-tive point on me line segment in framelet 1OT.

Thus, for a given reference point 110 on une segment102 a line llftA is drawn in the plañe transform 102A.The reference point 110 is approximately midway betweeb

10 the top and the horizontal midline 109 of framelet 108and henee the line 110A is inclined to the right at anangle to the vertical whose tangent is approximately V4.The intersection of the line 110A with the horizontal mid-line 101 of picture 100 ís at a distance from the left

IB edse of the picture 100 equal to the horizontal coordínateof the point 110 on Une segment 102.

It is an exact theorem that, if a series of points in aframelet lie on a straight line, the corresponding linea inthe plañe transform intersect in a point which we shall

20 desígnate as a knot 112. It is therefore readily apparentthat the rectangular coordínales of the fcnota 112 in picture100 have the following properties: '

(1) The horizontal coordinales of the knots 112 equalthe horizontal coordínales in the framelet 108 at which

25 the straight line segments 102, 104 and 1*6 intercept thehorizontal midlihé 109 of the framelet 108. "

(2) The vertical coordínate of the knots 112, relative"to the horizontal midline 101 of picture 100, is propor*tional to the tangent of the angle of the straight Une seg-

50 ments 102, 104 and 106 relative to the vertical. Thus,.tho coordínales of the knots 112 in the plañe transforms;102A, 104A and 106A give the sJopes and intercepta of,the straight Une segments 102, 104 and 106 in framelet108. : ;

35 Although the foregoing description pertained to a hand'constniction of a plañe transform, it is to be understood:ihat it may be performed by adequaie dectronic appáratusor the li!;e. . .

In FIG. 2, the picture containing the complex patternV40 such as from a photograph of a bubble chamber, Is sub-,

dívided into several Kundred rectangular áreas or framtf-Icta. The height of each framelet is chosen small enoughso- that the portions of the pattern within each framelet.is essentially a straight line and large enough so that the'

45 line segments can be reliably distínguished from the ran-dom bubble background. The widlh of the framelet Is.dependen! upon the accuracy nceded in. tbe measurementof the lateral posición of the segment* in the framelet „: A televisión camera 210, such as of the image orthicoa

50 typer scans the framelet 212 containing one or mora:

straight line segments composed of bubbles. As the ícan*.ning beam of the televisión camera 210 passes over>bubble ín the line segment, the televisión camera 210 pro-dieces an ourput pulse. For each ourput pulse from tho

65 televisión camera 210, electrón» plañe transform circuito214 cause a line to be drawn in a plañe transform on &dirplay of an osciDoscope 216 according to the geometrícrules described for FIG. 1. Thus a plañe transform Of.Ihe Une segment of framelet 212 is created. The coordi-

60 nates of the knot in the plañe transform on the dlaplay ofoscilloscope 216 gives the slope and intercept of the Jiñasegment in framelet 212 as previously shown in FIG'. 1.,

A second televinon camera 218, such as of the imagoorthícon type, scans the plañe tranaform display of os-

&G cüloscope 216 and detects the knot with its iclative co-ordínate data. The output of the second televisión cam-era Z18 containing the coordínate data of the knot Isféd to magnetic tape recordar 220 and stored thereon.The magnetic tape is then fed into a computer 221, such

70 as of the IBM704 type, where the coordínate data of e*chline segment is evaluatcd to recognize the original complexpattern in the picture.

Page 161: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

3,069,654

When a standard image orthicon televisión camera scansa bubble chamber sccne, the bubbles appear in the seanline as narrow regions where the video ontnut voltage Umuch less than the background voltage on each side. Thebackground. video signa! also shows considerable variation, 5and so a means must be provided for recognúíng bubblesüi a varying background, and for discríminating againatvaríous unwanted.markings in the scene/ A video pulsemust satisfy two basic 'entena to be admitted as corre-sponding to a bubble. These are: (a) A narrowness 20criterion. The bubbles making up a track have a narrowand reUtively constant width. Therefore, only videopulses of this width (within a certain tole ranee) are ad-mitted. Wider opaque regions in the scene are ignore d.(¿) A contrajt threshold. The difference in light in- 15tensity between the darle track and the lighter backgroundon each side must be greater than a certain mínimumvalué. This threshold Is a. parameter of the systcm wbichis eajüy adjusted. It is set to give the most relia ble trackdetection and highest background rejection for any particu- 20lar groups of pictures.

Reference is now made to FIO- 3 for a detaüed explana-íion of the circuits 214 wherein the pulses from the tele-visión camera 210 representing bubbles in the line seg-ment úvthe viewed «cene are converted.into the more jyjuseable plañe transí oren partera. For the purposes ofclarity, only one detected bubble on the Une segment ofthe framclet 212 will be treated although the treatment ofall other detected bubbles is the sanie.

The video signa! from the first televisión camera 210: JQis nresented undelayed to a first input of a difference am-plifier 222 and also delayed 0.4 microsecond to a second:input of the diíference amplifier 222. The difference inamplitude between the two outputs of the difference am-plifier 222 represent the difference in light level at two 35points, along the sean line of the first televisión camera.210 separated by nalf the width of a bubble in the linesegment of framelet 212. The output from the differenceampUfier 222 corresponding to the 0.4 microsecond inpntIs fed through a 0.1 microsecond delay line to a first, in- 40put of a Garwm ooincidencé circuit 224. The other out-put of the difference amplifier is delayed approximatery.5 microsecond to the other input of the Garwin circuitso- that the two signáis arrive at the coincídencc circuitsüirnltaneonsly. Any opacity greater than twice the width. 45of the bubble in the Une segment of framelet 212 fails totrigger the Garwin circuit 224 and is therefore ignored..The output pulse ampUtude of the Garwin coincidenciacircuit 224 will depend upon the difference in light inten-sity between the bubble in the line segment and the gen- 50eral background. Smaller output pulsea from the Gar-win coincidence circuit 224 will be present due to varia-tiona m intensity of the genera] background. These areeliminated by feeding the output of the Garwm coinci-dence circuit 224 to a 0.5 microsecond monostable multi-vibrator 226 where the bias of the trigger is set so thatonly pulses from the bubbles In the line segment of frame-let 212 have fuflScient ampUtude to trigger the multivi-brator 226. Thua, a single pulse output is obtained fromthe multivibrator 226 when the scanning betún of the firsttelevisión camera 21t passes over the bubble in the Unesegment of framelet 212. . _ .

The ontpnt pulse of the multivibrator 226 triggers a 2 'microsecond monostable multivibrator 228. One outputfrom the monostable multivibrator 228 drivea an un-blanking amptifier 230 in wbich the pulse is delayed 0.3oúcrosecond, cUpped to a length of 1.4 microsecond, am-pUfied, and applied to the cathode of the cathode ray tubein the oscUloscope 216. This pulse thus turas on the 70

beam of the cathode ray tube of the oscUloscope 216 fora.period of time, approxímately 1.5 microsecond, suffi-cient to draw the line transforra corresponding to thebubble scanned. The second outpnt from the monostablemultivibrator 228 driyes a. clipper 232 whicn provides a. 75

6*8

°°

0.3 microsecond pulse output at the leading edge of theoutput pulse of the monostable multivibrator 228.

The ouíput from the clipper 232 is fed to a set pulseamplifier 234 where ít is amplified and provides a 0.3microsecond pulse of fixed voltage, IS volts, wbich is ap-plied to the fixed Une generator 236. A 2 microsecondoutput pulse is also derived from the clipper 232 wbich isidéntica!, to the 2 microsecond output pulse of the mono-stable jcnultívibrator 228. This 2 microsecond output pulsefrom the clipper 232 is fed to a reset ampUfier 238 whereit is amplified and inverted. Both the inverted. 2 micro-second pulse from the reset ampUfier and tbe 15 volt out-put pulse from the set pulse ampUfier are fed simul-taneously to the flxed Une generator 236. The 15-voltoutput pulse applied to the fixed line generator 136 ¡3caused to decay therein at a predetermined linear rate ofdecay to —15 volts. The 2 microsecond inverted pulsefrom the reset ampUfier 238 gatee the decay of the 15volt pulse from the *e£ pulse amplifier 234 and causes itto be cíamped at —15 volts. The resultíng-2 micrósec-ond linear decay waveform output from the flxed Unegenerator 236 is amplified by me amplifier 139. and thenapplied to the vertical deflection platea of the oscilloscope216.

The 0.3 microsecond palie from clipper 232 ií also fedto a set pulse modulator-amplífier 240 where itis Jnódú»lated. The modulation ia provided by a vertical sawtoothgcnerator 242 wbich ia svncbronized with. the vertical"deflection of televisión camera 210. The modulation iusuch that when the vertical deflection of televisión cam-'era 210 ia at the top of the televisión field; the amplitudeof the 0.3 microsecond pulse is 50 volts and the amplitudeof the pulse drops linearly to 10 volts when:.the vertical^deflection of me televisión camera 210 Is at the bóttom ofthe televisión field. The 0.3 microsecond set pulse fromthe set pulse modulator-amplifier 240 fe fed tb a variableUne generator 244. There, the variable amplitude oí theset pulse is set to 25 volts for the timo when> the1 vertical''deflection of the televisión camera 210 is at the top of ttiételevisión field and 5 volts when the vertical deflection isat the bóttom of the televisión field, intermedíate pointtfdecaying Knearly thereto. The variable Uno generator •244 causes the set pulse from the set pulse modulator-amplifiér 240 to decay therein at a predetcrxoined rate ofdecay and linear waveform to —25 volts, for the verticaldefiectibn being at the top of the televisión field to —5"volts, for toe vertical deflection being át the bóttom of the;televisión field* The 2 microsecond inverted pulse fromthe reset ampUfier 238 is applied to the .Variable Une gen-erator 244 simuJtaneously with the 03 microsecond setpulse from the set pulse modolator-ampliñer 240 andgatea the set pulae causing it to be cíamped át tbe afore-raentioned négative voltages. The resulting 2 microsec-ond variable-ampütüde línear-decay output pul» fromthe variable Une generator 244 is fed to an input of add-ing circuit 246.

The 2 microsecond linear decay pulse from tbe fixedUne generator 236 U inverted by an mverting circuí f 248and fed to an input of adding circuit 246. Ap output istafeen from the horizontal deflection circuit of televisión,camera 210, amplífied by the horizontal deflaction ampli-fier 250 and applied to an input of adding circuit 246.The adding circnit 246 acta on the three mputa In the,following manner. .If triggered when the vertical defloc-tion of the televisión camera 210 ia at the top of the tele-visión Reíd, the 2 microsecond output pulse of the variableline generator 244 starts at 25 volts. The 2 microsecond.inverted pulse of the Une generator 23$ always starts at—15 volts. The adding circuit 246 sums these two pulsesinto a Linear decaying sweep tnát starts at 10 volts and de-cays to —10 volti. If the 2 microsecond pulse of the vari-able line generator 244 is triggered at the bóttom of thetelevisión field of televisión camera 210» the result U arising linear sweep starting at — 10'voltif and rislng to,10.volts, If the.2 microsecond pulse of the variable lifle

Page 162: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

gcnerator 244 is triggéréd in the center of the televisiónficld of televisión camera 210, the 2 microsecond pulseof the variable Une genera te r 244 starts at 15 volts, can-celling the —15 volt 2 microsecond inverted pulse frotathe fixed line generator 236, and resulte in a zero output.The output from the horizontal deflection amplifier 250 isadded to the combined variable amplitude linear sweepof the variable line generator 244 and the fized line gen-erator 236, amplified by an amplifíer 252, and then ap-plied to the horizontal deflcction piafes of oscilloscopc216.

Thus, a line is drawn in the plañe transform for a bub-ble in the line segment of framelet 212. The linear sweepoutput of tbe ftjced linear generator 236 applied to thevertical deflection platea of oscilloscope 216 acts in com-bination with the linear sweep of variable amplitude pro-duced by adding the 2 microsecond inverted linear decaypulse from the fixed line generator 236 and the 2 micro-second variable amplitudes linear decay output pulsefrom the variable line generator 244 to produce a line inthe plañe transform having an angie to the vertical whosetangent is proportional to the vertical displacemcnt of thedetected bubble tracic in tbe Une segment of framelet 112.If the detected bubble is at the top of framelet 212, thehorizontal deflection applied to the horizontal deñectíonpiales of oscilloscope 216 is initially large, positive, anddecays linearly therefrom. If the detected bubble occursat the center of framelet 212, the horizontal deflectionis zero and if below the center of the framelet 212, thehorizontal deflection is initially largo and negativo inpolarity from which it decays linearly. The output fromthe horizontal defiectíon amplifier 250 canses the spot onthe diaplay of oscilloscope 216 to follow tbe horizontalgcanning beam of tbe televisión camera 210. When tbehorizontal scanning beam crosses the detected "bubble, theoscilloscope spot is at tbe horizontal posiüon of tbe de-tected bubble and the video pulse at this instant causesthe line transform to be drawn as heretofore described.Tne time reqnired for tne drawing of the one Une in thetransform is 1.5 microsecond. The delayed unblanküjgpnbe of the unblanking pulse delay amplifier 230 gatesthe oscilloscope for this period of time. The set and re-set of the Une generators 236 and 244 is not seen in thetransform.

The cutiré process described above is repeated eachtune the scanning beam of televisión camera 210 crosseaa bubble in the Une segment of framelet 212 and resultsin a plañe transform being created on the oscilloscopedisplay 216 as depicled in FIO. 1.

Thongh the above descriptíon {Ilústrales the presenta-tion of only one framelet at a time to the televisióncamera, as many as four framelets can be presented atone time. Each framelet is caused to cover the full widthand one-fourth the height of the televisión field; the re-moimnp treatment of the framelets remaining the sameas for a single framelet It ¡a also necessary to sean eachpictnre twice at right angles to correctly recognize thecomplex patteras contained therein.

The present ¡nvention should be readfly adaptable forapplication in such áreas as handwritíng analysis, radardisplaya and map reading.

Persona skflled in the art wiD, of ceñirse, readüy adaptthe general teachings of the invention to embodimentsother man the specific embodiments ülastrated. Acoord-ingly the scope of the protection afforded the inventionshould not be limited to the particular embodiment shownin the drawinga and described atove, but shafl be de-termined only in accordance with the appended claima.

What is claímed is:1. A method of analyzing a complex pattern in a pic-

ture comprising dividmg said picture into framelets, saidframelets sized so that that any segment of said complexpattern therewithin is essentially a straight line, trans*forming each of said segment* into a plañe transform,

and reading the coordínate position data of each. planotransfonn. j.

2. Ine method of analyzing a complex pattern ín *picture comprising dividmg said picture into framelels,

6 said framelets sized so that any segment of said complexpattern therewithin is essentiaily a straight Une, tranacrib-ing points along each of said segment* luto sepárateUnes, pictorially displaying said transcribed linea to fonn

- a plane transfonn for each of said segments, the coordi-10' ríate position of said plañe transform in íaid display be-

ing representative of the positrón of said segment in saidframelet, and summing'the coordínate position data.

3. A method of analyzing a complex pattern in apicture comprising divídiag said picture into framelets,

15 said framelets sized so that any segment of said complexpattern therewithin is essentially a straight line, transcrib-ing points along each of said segmento into sepárate linea,pictorially displaying said transcribed Unes to fonn aplane tranaform for each of said segmente, each line in

20 said plane transfonn being positiúned latératty so thata point on said Une midway between the top and thebottom of said pictorial display occurs at a distance fromthe left edge of said pictorial display equal to a distanceof said point in said segment from tbe left edge of said

*** framelet. said line in said plañe transfonn being inclinedin said pictorial display at an angle to the vertical whosetangent is proportional to the vertical displacement ofsaid point in saíd segment from the center of said frame-let, and deterinining the coordínate position of the point

80 of intersection of said Unes in said pictorial display foreach segment

4. A method of analyzing a complex pattern in a pic-ture comprising dividing said picture into framelets, said

_. framelets sized so that any segment of said complex pat-tern therewithin is essentially a straight line; transcribingpoints along each of said segments into sepárate Unes,pictorially displaying said transcribed Unes to fonn aplañe transform for each of said segments, each Une in

40 said plane transform being positioned laterally so thata point on said Une midway between the top and thebottom of said pictorial display occurs at a distance fromthe left edge of said pictorial display equal to the distanceof said point m said segment from the left edge of said

¿_ framelet, each said Une in said plane transform beinginclined Ín said pictorial display at an angle to the verticalwhose tangent is proportional to the vertical displacementof said point in said segment from the center of saidframelet; scanning said pictorial display of said plañe

50 transfonn of each of said segmenta and determinlngthe coordínate position of tbe intersection point of saidlínes in said pictorial display of said plane transfonn*tbe lateral position of said intersection point in said pic-torial display of said plane transfonn being equal to the

55 lateral position at which a point in said segment on saidframelet is equidistan! from the top and bottom of saidframekt, the vertical position of said intersection pointin said pictorial display of said plañe transform denotingthe tangent of the angle of said segment in said framelet;

00 recording the coordínate data of said intersection point Insaid plane transform of each of said segmenta and aum-ming said recorded data.

5. A device for electronically tr&nrforming a straightline in a pictorial representation Into coordínate data com-

ee prUing means for scanning «aid representation and pro-ducing an electrical pulse for each point scanned on saidUne, means for transforming each of said pulses into asepárate line and for displaying each of said transf ormedlines, cach of «aid transformed Unes being geometrically

70 positioned ín said display with relation to the geometrícposition of its respective point in said representation, saidtransformed lines intersecting at a point in said displaywhose coordínate position is descriptivo of the geometrfcposition of said straight line In said representation.

T5 6. A device for electrically transforming a straight Une

Page 163: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

0,060,654.

in a pictorial representatipn into coordínate data.' com-prising meana for acanning saíd representatíon and pro-ducing an eléctrica] polae for each point scanned on saidlinejV'cathode ray tube having vertical and horizontaldeflection piales, means for deriving a first linear decarysigna!' having iniíial constant. amplitude írom each of.said" eléctrica! pulses and' applyintf said firat. sigñal to said

gering the cathode of «aid cathode ray. tube to cause .saidfirst and second ágnal* of each of said eléctrica! pulses,to draw a Une on said cathode ray tobe havíng a tlopeand an intercept with the horizontal midline of saídcathode ray tube proportíonal to the coordinóte positioaof said scanned point in said pictorial repretenUÜoñ, said'linea having an intercept point whose coordínates- on saidcathode.ray tube are proportional to the alope and the^intercept with the horizontal midline of said pictorial'

Vertical deflectíon platea of said cathpde ray. tufee, meansfor detivihg a second linear decay pulse having'.initial'variable amplitude from each of said eíectrical pulses. JO representaron of saíd straight Ime..and applyíng said second signa! to said horizontal de- .flection platas of said cathode ray tube, meánVfor trig- No references cited.

Page 164: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Graphics andImagc Processing

W. NcwmanEditor

Use of the HoughTransformation ToDetect Lines andCurves in PicturesRichard O. Duda and Peter E. HartStanford Research Instituto,Menlo Park, California

Hougfc ha* proposed a* iateresting andconputationally efficient procedve for detectíogtn pictures. This papcr points oot that the use ofaagle-radittfi rather than slope-intercept parameterssi mp tifies the coraputatíon further. It also shows howthe method can be used for more general curre flttíng,and gires alternativa taterpretations that expUín thesource of its efflctency.

Key Words and Phrases: plcture procesa ng, patternrecognitioM, Une detection, curve detection, calinearpoints, point-tine transformation, Hough transformation

CR Categories; 3.63

Copyright © 1972, Association for Computing Machinery, Inc.General permisuon to republish, bul oot for proflt, ull or part

of this material is granted, provided that rcference is made to thispublicaron, to its date of fesuc, and to tbe fact that repriotíngpriviteges were granted by pennissíotl of the Association for Computinf Machinery.

This work wu supportcd by the Advanced Research ProjectsAfency and the National Aeronáutica and Space AdministratioauDder Contract ÑAS 12-2221.

1. Introductíon

A rccumng pro ble m ia computar ptcture processingis the detection of straight Unes in digitized images, Inthe simplest case, the picture contains a number of dis-crete, black figure points lying on a whíte background,The problera is to dctect the presence of groups of co-linear or almost colinear figure points. U U clear thatthe problem can be solved to any desired degree of ac-curacy by testing the Unes formcd by al I pairs of points.Howcvcr, the computation required for n points is ap-proximatcíy proportiooal to /í1, and may be prohibitivofor large it.

Roscnfcld [1] has described an ingcnious method dueto Hough [2) for replacing the original problem of find-ing coünear points by a mathematicaUy oquívalent prob-lem of finding concurrent lines. This method involvcstransforming each of the figure points into a straightUne in zparameter space. The parameter Space U deflnedby the parametríc representation used to describe Unesin the picture plañe. Hough chose to use the famfliarslope-intercept parameters, and thus bis parameterspace was the two-dimensional slope-interccpt plañe.Unfortunately, both the slope and the intercept are un-bounded, which complícales the application of the tech-níque. In this note we sugge&t an alternative parameteri-zation that eliminatcs this problem. We also give two al-ternative interpretations of Hough's method, one ofwhich reveáis plainly the source of its efficiency. Fmally,we show how the method can be extended to fiad moregeneral ciasses of curves in pictures.

2. Fundamentáis

The set of all straight Unes in the picture plañe con-stitutcs a two-pararactcr famüy. If we fix a parametcriza-

Commiuticatioiisoftbe ACM

Jam»ryl972VdiHnelSNnmbcr I

Page 165: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

tion for thc famflty, thco an arbitrary straight Hoe can bereprescnted by a single point in thc paramctcr spacc. Porreafton* that become obvióos, we prefer thc so-callednormal parameterízaíion. As illustrated io Figure 1, taisparametertzation specifies a straight Une by the anglc 0of its normal and hs algébrate distanoe f» frora che origin.The eqiution of a Une corresponding to this geometry is

x coy 9 -f y sin í •«• p.

If we restrict 9 to the intcrval {O, f], then the normalparameters for a Une are unique. With this restriction,every Une in thc x-y place corrcsponds to a unique pointin thc tf-p plañe.

Supposc DOW, that we have somc $ct ((xi, y¡), ...,(*« , y*)\f n figure points and wc want to find a set ofstraight lines that fit them. We transform the points(x,-, y{) into the sinusoidal curves in the #-/> plañe de-fined by

p =• Xí eos 6 + y¿ sin í. (O

It is easy to show that the curves corresponding to co-linear figure points have a common point of intersec-ción. This point in the 0-/> plañe, say (ft>, #,), defines theUne passing through thc colinear points. Thus the prob-lem of detecting colinear points can be converted to thcproblcra of finding concurrcnt curves.

A dual propcrty of thc point-to-curve transforma-tion can also be cstabUshed. Supposc we have a setI (0i, PI), - -., (í* i ftt}\f points in thc tf-p plañe, alllying on the curve

p *« XD eos 0 4- >'o sin 0.

Then ft is easy to show that all these points correspondto lines in the x-y plañe passing through the point (xo,ys). We can summarize these interesting properties ofthe point-to-curve transformatíoo as foUows:

Property 1. A point in the picture plañe correspondato a sinusoidal curve in the parameter plañe.

Property 2. A point in the parameter plañe corrc-sponds to a straight Une in thc picture plañe.

Property 3. Points lying on thc same straight Une inthe picture plañe correspond to curves through a com-mon point in the parameter plañe.

Property 4. Points lying on the same curve in theparameter plañe correspond to lines through the samepoint in the picture plañe.

In Section 3 we apply these results to the probtem ofdetecting colinear points in the picture plañe and showhow significant computatíonal economies can be reaüzedin certain aituations.

3. AppUcatíoos aad Atternatíre Interprctatíons

Suppose we map all of thc points in the picture plañeinto their corresponding curves in the parameter plañe.In general, these n curves will intersect in n(n — l)/2points corresponding to the lines between all paira of

Fi». |.Tbenonnalpuaoodtnfor*Uae.

Fig. 2. Projection ofcotinear point» onto a line.

UoftfaoACM

J»nuaryVolumelSNun&erl

Page 166: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

figure points. Exactly colinew subsets of figure pointscaá be found, at least in principie, by finding coincidentpoints of ¡mersection in the parameter plañe. Unfor-tunateíy, this approach ís essemiaUy exhaustive, and thecoraputation requircd grows quadraticaUy with the num-ber of picture points.

When it is not necessary to determine the Unes ex-actly, the computation a I burden can be reduced con-sidcrably. Following Hough's basic proposal, we specifythe acccptable error in 9 and p and quantize the &~pplañe into a quadruled gríd. This quantization can beconfined to the región O < 6 < T, -R < p < R,where R is the size of the retina, since points outsidethis rectangle correspond to Unes in the picture plañethat do not cross the retina. The quantized región Ístreated as a tw o-dimensión al array of accumulators.For each point (x,, j\-) in the picture plañe, the cor-responding curve given by (1) is entered in the arrayby incremcnting the count io each cell along the curve.Thus, a givea cell in the two-dimensional accumulatoreventuaUy records the total number of curves passingthrough it. After all figure points have been treated, thearray is inspected to find cclls having high counts. Ifthe count in a given cell (8if p¿) is kt thcn preciscly kfigure points lie (to wnhin quantization error) along theKne whose normal parametcrs are (0,, pj).

An alternative interpretation of the point-curve trans-formación can be obiamed by recognizing that the pcomputed by (1) locates the projection of the point(xít y¿) onto a line through the origin with slopeangle ff. Thus, if a number of figure points lie cióse tosome Une /, their projections onto the Une normal to/ are nearly coincidem (see Figure 2). A given columnin the 8-p accumulator array is just a histograrn forthesc pTOJcctions, so a high count in a given cell clearlycorresponds to a nearly colinear subset of figure points.A variation of this approach was used by Griffith [3Jto find long lincs in a picture.

Let us investígate how the computation required bythe accumulator implementation varíes with the numberof figure points. To be more specific about the quantiza-tion, suppose that we restrict our attention to di valúesof $ uniformly spaced in the interval [O, *•)• Supposefurther that the p axis in the interval (— Rt R] is quantizedinto dt cells. For each figure point (xt, yt)t we use (1)to compute the di different valúes of p corresponding tothe </i possible valúes of the independen! variable 8.Since there are n figure points, we need to carry outthis computation ndi times. When these computationsare complete, the ¿Adt cclls of the two-dimensionalaccumulator are inspected to find high counts. Thus thecomputation required grows lincarly with the numberof figure points. Clearly, when n is large coraparcd to¿i, this approach is preferable to an exhaustive pro-cedure that requires considering the lines bctween alln (n — 1 }/2 pairs of figure points.

Another alternative interpretatíoo exposes the sourceof this efficiency. Consider again Propeny 4 in Section

2: Points íying on che same curve ¿a the í-p pUne cor-respond to lincs through the same point in the pictureplane. When the curve corresponding to figure point(xf, yt) is "added" to the accumulator, we are realtycomputing and recording the parameters of the dt Unesin the picture plane passing through (*,, >»,), andbecause 9 is quantized, these are "all the lines in theplane" passing through (x»-, y¡). Should a given param-eter pair ever recur as a result of computing the d\s through 5 o me other figure point, the recurrence

will be reflected in an incrcased count io the appro-priatc accumulator cell, Roughly speaking, then, foreach figure point the quantized transform mcthod con*siders only the set of all di lincs through that point,whereas more exhaustive methods consider all (n — I )lines between the given point and all other figurepoints.

4. Example

The following exarnple iUustrates some of the featuresof the transform approacb. Figure 3 (a) shows a televi-sión monitor view of a box, and Figure 3(b) shows adigitized versión of that view. A simple differcncingoperation locates sígnificam intensíty changes and pro-duces the binary picture shown in Figure 3(c). This120 X 120 picture contains many nearly colinear figurepoidts that can be fit well by a few straight lines.

SampÜng 9 at d\ 9 twenty-degree increments in8 and, quantizing p into d? « 86 two-ciernent cells, weobtain the two-dimensional accurnulator array shownin Table I. If the array entry at (00, PO) is Jto, then *<jfigure points h'e on parallel lines for which 8 = Í0, and plies between po and po -f 2. When many points arenearly colinear, che entry for Che line that fus them bcstis large. The largest entry in Table I occurs at (0°, —5)and correspondí to the middle vertical cdgc of the box,The nine circled cntries correspond to locaüy máximumvalúes that exceed the arbítrary threshold of 35. Thecorresponding nine groups of nearly colincar figurepoints are shown in Figure 3(d). In this example, ithappens that every group corresponds to some phys-ically raeaningful line in the picture. However, twosignificam lines oo the top of the box were not found—onc, because it containcd very few poims, and the other,because it feü between the lines at fl » 806 and 8 - 100°.The 20° angular quantization interval was choscn tokeep the accumulator array small. Clearly, we werefortúnate to have found as many lines as we did, and asmalier quantization interval would have to be used inpracticc.

A few remarks concerning some limitations of thetransform approach are in order. First, the results aresensitive to the quantization of both 8 and p. Finerquantization gives bettcr resolution, but increases thecomputation time and expotes the probtem of clustcringentríes corresponding to nearly colinear points. Secoad,

CorormiQicaooo*ofibeAGM

l«mmry 1972VoUunolSNumber 1

Page 167: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

be technique finds coGncar points without regará toxnttiguity. Thua the position of a bení-fit fine can beiistoctcd by the prcscncc of unreiated figure points ininother part of the picturc. A relatcd problem is thatof raeaninglcss groups of colinear points being detected.Ea our examplc, a false line would be detected if thethreshold were reduced from 35 to 24, the valué neededto detect the top left-hand edge of the box.

The transform approach does successfuüy find groupsDf colinear or neariy colinear figure points. If the mini-num size of a significant group is known, all such groups;an be detected. If additíonal properties such as con-üguity are known, they can be used to reject meaning-Less results. In general, the transform approach shouldbe viewed primarily as a computationally efficient wayof accomplishing a conceptually simple stcp in sccneana ly sis.

5. Extensión» and C o nc fusiona

The transform method can be generalized and spe*cialized in several ways. We note immediatety that anyparametrization of the family of straight Unes can beused. As we nave men ti onecí, Hough used the slope-intercept parameterization. However, this parameteriza-tion has the disadvantage of being sensitive to the choiceof coordínate axes in the picture plañe. If several figurepoints lie on a nearly vertical Une, for example, both theslope and the intercept may be arbitrarily Urge. Thusthe cntíre two-dimensional parameter plañe must beconstdercd. As Roscnfcld [1] has pointcd out, onc coulddo the cntirc problem twicc, interchanging the x- and>--axes, but this would introduce additional complica-tiüns. The normal parametrízation avoids these dis-advantages, fundamentally for the same reasons thatmalee it useful in integral geometry: It atlows us toplace an invariant measure on the set of all straightUnes.

An important special use of the transform method isto detect the occurrence of figure points lying on astraight Une and possessing some specified property.For examplc, suppose we want to find whether a sig-nificant number of figure points lie on a line through thepoint (&, jfc) in the picture plañe. As we have seenfrom Property 4, the normal coordínales of any suchline must lie on (or, in practice at least near) the curvep — Xo eos 6 + y* sin 9, Henee, the transform processcan be carríed out in the usual way, but attention can berestricted to the región of the 9-p plañe near this curve.If we find a «11 with count k near this curve, then we areassured that k figure points lie on a line passing (nearly)through the point (XQ, jfc). Similarly, suppose we areinterested only in Unes having a given direction, say0i. Again, we carry out the process in the usual way,but restríct our attention to a subset of the 6-p plañe inthe vicinity of & = 9t -

U is clear that the general transform approach can be

3 An ühmrwivc exmmpfc.

(e) Gmdk*i

14 ComnumintToo»oftbcACM

January 1972VotumetSNumber 1

Page 168: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

TatJe I. Accumulaior Array for Firurc 3 fe)

X_*

SS83ti797773737169«76363615957355351494745434139373333312927252321191715131197531

— . 0'\

4964384498

12

35137787999

10 .121010111310

20*

2

13569647

U1720171416111*161812171412139

I I108

U1314

40*

2

131

41421212122172221181212U12121213IS131622151317

«0*

2

14

34442433

13131717212323303220231616U11141412118

11

80'

2

5

U10

5102010

38

©2320201917a7677

©8

©23187

100*

11214-11219

124

232

123229t

108

142027©1179

1010109««78

120'

1468644421

135

1111111311121811107S

U137a

11151416161616147

11119

140*

22434632332238

10H9

1013106

107

11999í9976

116

121413132112141»10

160'

223354449

1215121488

108aa7

10¿9

109687

IQ77

106

132221141512

\*

-83-83-81-79-77-73-73-71-69-67-65-63-61-39-57-55-53-31-49-47-45-43-41-39-37-33-33-31-29-27-25-23-21-19-17-15-13-11-9-7-3-3-1

— V 0'

\

760

16©32107B67786597567«76

101079

©2610

20*

22

1

101313181617127

1079

129

101210U1313171313131413131413

40'

1

2

6121111I t1114149

U17IS191210

K<*91í

109

108

12151418

601

13

2

1

©221110118ItS8998897

16151715777969

SO1

2

18151514161314

1217101288676

109789888788

IOO*

12I4

1613161817148979

11991

111011111317172321l-l128

120'

11I

121

©127

U1210U161818221916Í7161011987

109

U

140'

I9

211719201823221818199

12109

1414UU1213121112

160'

24fi6356£

1223242326131319149

U10139

12151512151815

extended to curves other than siraight fines. For ex-ample, supposc we want a methotí to detect circularcon figura ti ons of figure points. We can choose a para-metric representaron for the family of all áreles (withina retina) and tramform each figure point in the obviousway. If, as a parametríc representación, we describe acirck in the picture plañe by

(x - <>)' + (y - b)* - c',

then an arbitrary figure point Cx., yt) mil be trans-formed into a surface in the a-b-c para meter spacc de-fincdby

(je.- - -t- (yi -

In this ex ampie, then, each figure point will be trans-formed into a ríght circular cone in a three-dimensionalparameter space. ]f the cones corresponding to manyfigure points intersect at a single point, say the point(¿la , b* , cc), then aU the figure points lie on the circledefined by those three paramelers. As in the precedingcase of straight lines, no saving is effected if the entireprocess is pcrformcd analytically. Howevcr, the processcan be implementcd efficiemry by using a three-dimen-

15

sional array of accumulators representíng the three-dimensional parameter space.

In principie, then, the transform method extends toarbitrary curves. Wc necd only pick a converüent parara-cterization for the family of curves of interest and thenprocccd in the obvious way. A parameterization havingbounded parameters is obviously preferable, althoughthis is not essentíal. It is much more important to havea small nurnber of parameters since the accumulatorimplementation requires quantizatíon of the entire pa-rameter space and the coraputation growa exponentíallywith the number of parameters.

Receíved November 1970, revised AprÜ 1971

R«femees

1. Rosenfdd, A. Picture Processing by Computer. Academic Press,New Yorie, 1969.2. Hough, P.V.C. Method and meaos for rccognicng complexpatterns. US. Patón 3,069,654, D«c. 18,1962.3. Gnffith, A.K. Computer recognítion of prismaiic solida. Ph.D.Th., Dep. of Math., MIT, June 1970.

CommuníCAtioosoftbeACM

January 1972VolüinelSNumber 1

Page 169: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Randomized Generalized Hough Transform for 2-D GrayscaleObject Detection *

Ping-Fu Fung, Wing-Sze Lee and Irwin Kingf

Department of Computer Science and EngineeringThe Chínese University of Hong Kong

Shatin, New Terrítories, Hong KongE-mail: {pffung, wslee, king}@cs.cuhk.edu.hk

Abstract

This paper proposes a n&v algorithmfor 2-D object de-tccrion callea Randomized Generalized Hough Transform(RGHT). I: combines the Generalized Hough Transform(GHT) with the Randomized Hougk Transform (KHT). Ouralgorithm can detect arbitrar? objects of various scalesand orientaíions in graylevel imanes. We also demónstrateRGHT's advantage ofhighspced, low storage requirement,highaccuracy and arbitrary resoiuüon tnrough comparisonwith óther rclated algoriíhms.

1. Introduction

One of the key issues in imagc processing is to extrae*interested objects from an image. Hough Transform (HT)[2] is a classical algorithm for extracting Unes from a bi-nary ímage. Another irnproved algorithm is the GeneralizedHough Transfonn (GHT) [ 1J which can delect arfaitrary ob-jccc in a grayscale image. With titile modificatioos, th*algorithm can detect objects of various scaJcs and orienta-tions ai the expense of more coraputatioa time. A fasteralgorithm called Randomized Hough TVansfonn (RHT) [4]detects various analytical geometric shapes in binary im-ages by usiog probabilistic method. Since random samplingis used, the algorithm works qxúte fást with low storagerequirement

Here, wo present a new algonthm for object detection. Ucombines the advantages of both GHT and RHT, heneeit is oamed Randomized Generalized Hough Transform(RGHT). Xt works on grayscale images and detects arbi-trary grayscale object with various scalcs and orientations,lifce OHX Moreovcr, it is based on probabilistic method asin RHT, so it has reduced time and space complexities, highaccuracy and arbitrary rcsolaáon.

"This work U suppofted in part by RGC E«nnariccd Grant #221500620and fedostry Graní «2427 01300 of Hong Kong.

TThe coobctñig authot

2. Background

2.1. The Hough Transform

The HT is based on transformaron of image points' co-ordinales into a 2-D Une r^rameter space. HTissIowdue toa large number of lines need to be plotted in the paiameterspace. Moreover, it can only work on binary images. Nev-erthctcss, a slight modification can be made for detectinganalytíca] shapes other ihan une, for example, circle, el-lipse, etc. at the expense of greatex storage complexity (dueto larger parametcr space) and heavier computation (morecomplex equations are involved).

22. The Generalized Hough Ttaosform

Tbs GHT detects arbitrary object, not Hmited to analyti-cal geometric ones, in a grayscale image. It uses the gradi-cnt information to genérate a lookup tabk, called R-table forshape detection. Original GHT is only sen si ti ve to a specificaizc andorientatíonoían object. AlthoughperformingGHTiteratively with augmented R-table is a rcmcdy, the resultingcomputaüon effort increases drastically with bad accuracyand resoluíion.1 We analyse time and space complexities ofGHT in a later section.

23. The Randomized Hough TVansform

The RHT is based on probabilistic method. Sincc sam-pling ís xised, a small subset of points is examined thus thecomputation time and storage are reduced. It guaranteesinfinite and continuous parametor space. However, cur-rent versions of RHT only work on binary images so thata preparan on step of thresholding or tUtering has to be ap-plied to grayscale iroages beforehand, Also, it only detectsanalytical geometric shapes rather than arbitrary ones.

1 Seatfog ti» offsets, in tfae R-table for detoctíng scoled objeets, shiftiugUbtc eotíM for dotecbne rotated objccti

1015-4651/96 $5.00 © 1996 IEEEProceedings ofICPR '96

511

Page 170: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

relation can be set up:

- (te, O, 1,0)4- Sy • (O, A», O, I)

The abovc linear combinatíon reíales PÍ(X¿, #), A¡(«¿, y,),0(z, 3/) and S(T, y) in our 4-D parameter space. For com-putauonal puipose, we rewrite it in vector notation:

(Oar.Oy) = (PxitPyi) + (5a, Sy) • {d*,-,A|«)

In tbe Urget imag«, pick any two points PI(ZI,!/]) andPz(^2, ife), as shown in Flg. 4, we have ihe folio wingequa-tions:

(2)

(3)

(4)

(5)

(6)

(7)

(3x, Oy) = (Pxlt

Equaiing Eq. 2 and Eq. 3, we gct

Ox = Pxi + Sx-Áxi =

R cañan ging terms and obtain:

Sx =

Sy =

Eulmued Anchor PDÍK O (x, y)

Figure 4. Eatimatíng O(xty) and S(xry)

After evaluaüng Eq. 6 and Eq. 7, we ftnd 5(x, y)^ Tben»subsütute the result imo Eq. 4 and Eq. 5, we get O(x, y).Fraally, we obtain the estiinated anchor point 0(x, y) andthe estimaled scale 5(x,y) of the témplate object in theimage.

By pickiag randomly two^sainple^points frora the targetimage^ we obtain a point (Ox, Op, Si, Sy] in the param-éter spnce. After a number af iteratíons and accumulate

the result, peaks in the accumulation indícate tbe I oca ti on0(x, y) and scale $(x, y) of the témplate object in the targetimage. Undergoing a peak sccking proccss. we can find outthe parametere of the detected objecis.

To detect rptated objects, we need to modify the R-tableand then re-apply the algorithm on the target image. Tliemodificaüon is simple: shift the entríes in the R-table, Inthis way, we detect rotaíed objects at tl>e expense of spend-ing more computation time, Iteraüng for different angles,témplate object with different orientatíons can be detecied.

3.2. Procedure and analysls

Témplate; out: R-Algorithm I Generate-R-Table(in:Table)

c- Témplate image dtpendint. target image iitdspendeni1 HorizooLal-gradient *— Convalve(Template, Horizontaí-mask)2 Vertical-gradiem <- ConvolvefTemplate.'Vertical-masy)3 Anchor 4- Center of Min-bounding-boxCTemplate)4 for (r, y) e Témplate<5

> R-table tí an array of UnJud-itaUst-inacrt(R-T6ble[ffl, Anchor—

end

AJgoriÜim 2 RGHT(in: Iraage, R-Table, Iteration, Resolu-tion, Threshold; out Result-seí)

t* Témplale unage indipm&nt, torgeí image dfpeadetu\t í- Convolve(ínjage, Horizontaí-raaifc)2 Vertical-gradient í- Convolve(Image, Vcrtical-mask)3 Solutíon-set i- $ * Th* accuaatíwon stt4 for Í 4- 1 to Iteration5 Genérate Pt(x\, y\) and ft(x2,yi) randomly6 Calcúlala fl| and íj of P¡ and PÍ P- By Eq. I7 Lookup Ai(n, yi) and Ajfra, ya) from R-T^blchy Slt 028 Calcúlale O(x, y) ana S(x, y) e- By Eq. 4 10 Eq. 79 if 3 Sol 6 Solution-«t10 s.t- \(Ox, Qy, Sx-, Sy) - Sol| < Resolutíon thcn

\2

13141516

1718

Merge (Ox, Oy, Sx, Sy) with Solt» Tote averagt and incnase hit rate afSol

el»Sohmon-seí +- Sotution-set U (Oí, 6y, SJT, Sy)p ¡usen the new soíuáon mut the aci-umtiaíwn set

endRciuh-sct 4- <I>for Sol € Soluüon-sct.

If hit rate of Sol > Threshold tben»< Extrae* ntttttfrom aecunuilatían «f

Renüt-sd <- Resutt-s« u Solend

In the two al goritnins usted above, there are thiee impor-tant parameters can be tuned:

Iteration The number of iteratíons (i.e. the saxnpling size)controls the number of sample pairs takcn. If it is set too

513

Page 171: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

3.TheRGHT

3.1. Basic idea

The RGHT combines both GHT and.RHT, thus it sharesthe advantages of the two algorithms. Before showing howthe algorithm works, the notations employed in the foílow-ing context are Usted:

Pxi, Pyí x, tf-coordinatesof pt -Pi£xi, j<)0(x,y)tÓ(x, y] actual and est. anchor pointsS(x, y},S(x, y) actual and est. scaling factorsA¡(£f,&i) offset o£ Pj(xi,yi] fromO(x, y]A/i(x,y),Av(z,2/) hori. and vert local gradient&i gradient angle at P,-(r,-: y,-)

Given a témplate image, in which the interested grayscaleobject resides, we apply a gradient operator to ihe image toproduce a R-table, just as in GHT. The gradient opera-tor makes use of two filtering masks: the horizontal maskand the vertical mask, as shown in Fíg. I. By performingconvolütion on the témplale image with these two rnasksindependently, we obtain two gradient difference maps. Asillustrated in Flg. 2, local gradient at each point in the tém-plale image is given by:

Anchor point

9 =. arctan CD

In the témplate image. we choose an anchor point O (x, y} as

- 1 - 2 - 3 -2 -10 0 0 0 01 2 3 2 1

-1 O i- 2 0 2- 3 0 3- 2 0 2-1 O 1

Graben t S

Figure 3. Building R-table

error is minimized. From any point Pi(r.; , y¡) in the image.there is an offset to the anchor point:

Cotnbining the local gradíent and offset, we fonn the R-tablc. The R-table indicares the offset to the anchor pointfrom omer image points with varióos local gradienis. Fíg. 3ilíustrates how the table is created and Table 1 shows thestructure of the R-table. Note that the R-table is actually aone-to-many mapping and einpty entries are aHowed.

Figure 1. Horizontal and Vertical masks

Gradient in Degree

012

358359

List of Offset Pairs |Á.i(xi¡y¡)lA2(x'2,yz)Aafo.W)Nil:

Am(Xm, JTm), - . An^^n)

Nil

Figure 2. Applying gradient operator

a reference origin point. In order to reduce calcuiation error,it nad better to pjck the cen ter of the mínimum bounding boxof the témplate object as anchor. Such choice reduces therange of the offset valúes in the R-table, thus the reladve

Table 1. An example of the R-table

After generating tfae R-table> we proceed to the objectdctectioa process.2 Given a urget image, our task is to lócatethe interested object and tell the scale of the detected object.In other words, we are trying to find out (Ox, Oy, Sx,Sy)in our 4-D parameter space xfM x ypot x x,COÍB x y9cais.Given any point PÍ(XÍ . y¡] in the target image, we calcúlatethe local gradient 0,- by Eq. 1. Using 0¡ to índex Lnto theR-table gjves us the offset A¿(z¡, y,-). Iben the foHowing

3 Prepare and save the R-table foc each témplate íntage once is eaough,e.g. oae R-table fot circle (ellipse included due to sttetched scafing), onefbrpentagon.etc.

51(2

Page 172: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

largc, more computation effort is required. Howovcr, re-sult is inaccuraíe if it is nol large enough because out-lierwill contribute relatively higher proportion. Gcnerally, itdepends on the size of the image: numbcrof iterations oc£jt« x yfise. Hs valué may be dynamically determined.Whcnevcr a soratioo with relatively high hit ratc is encoun-texcd, the proccss can be stopped. [3] gives more. informa-tion on stopping criteria of RHT and the anajysis is applica-ble to all sorts of RHT based algorithms.

Resolution It determines when two solutions are consid-ered as cióse. If two solutions are resemble (}S\ 5*2! <Resolution), they are merged to fonn a single solution.Small resolution resuHs in no merging at all and a largenumber of trivial solutions will be reported. Large valúescause many solutions lo be merged together; thus, they willget high hit rate with relatively lower resolutíon.

Threshold It controls the peak seeking process. Lowthresbold will cause a lot of trivial solutions to be foundwhile peaks may be missed with high threshold valué. Wemay define the threshold in terms of the máximum bit rate,for example, \f the valué.

In order to mate the algorithm work more efficiently,we suggest some special data structures. The R-tafale maybe stored as an array of Hnked-list. Por the 4-D parameterspace, (Gz>Gy,Sz, 5y}> the slorage required is in the or-der of O(xaite • ytize • #z,e«i« - Ajeáis)- However, due toappli catión of random sampling, the result ¡s sparse enoughthat hashing technique helps to reduce the storage. To faciH-tate highspeedsearching of resemble solutions and mergingthem, the 4-D parameter space is reduced into a 4-D bashtable. Each bucket of the hash table is implemented by aList. This dala structure is very space savmg and efficientfor storing the result withoutloss of accuracy or resolution.

3 3. Characteristics and advantages

Worfcs on Grayscale Images Wlthout thresholding or fil-tering, RGHT works on the original image with great«rdetaUs,

Detects Arbitrary Object RGHT detecta e ven free handcírawn shapes and gray filled objects.

Sc*l«d/StntElicd Tnfrtfinr^ ük « Siugl* RonRGHT does no* need to do iteration out rathec detects allscaled instances at one time.

High Spe*d by Random Sampling By random sampling,RGHT does ñor need to sean the whole image.

High Accuracy by EqoationSolving Object location andscale are detected by equation solving and parameters arenot limited to integral discreto valúes.

Arbitrary ResoLation The solution mer^ing process al-lows adjustment of the resolution of object detection.

3.4. Comparison between RGHT and other HoughTransforms

Algorithm HT GHT RHT RGHT |

Image typeBinaryGrayscale

VX

VV

VX

VV

'EargetLineGíreleParametricArbitrary

Spted

Storage

Accuracy

Resolution

Vy

V(slow)X

slow

high

médium

low

X

VVV

slow

high

médium

iow

VV

Vtslow)X

fast

Iow

High

any

X

VVV

fast

Iow

highany

The table above summaries the comparison between RGHTand other HT algorithms. Following are the time and spacecomplexities of the mcntioned algorithms.

AJgoriimn ¡ Time Complexity ( Space Complexity |

HTGHT

RHTRGHT

N/A^fci'^r'O(#sample-/(n])O(#sample-c-#0)

nTi=i parameten%sixe. ' Vaise

#sarnple • cell sizehash table size

Time complexiry of el as si cal HT is not available becauseHT is unable to detect arbitrary object of various scales andorientations. In RHT, f(n) is a function which dependson ihe number of parameters n of the analytical object Fordetectmg Une, Gaussian Elimination sol ves the linear systemwith f(n) = n3. For detecting other analytícal object, /(n)will be larger. In RGHT, the constant term c is for solvingthe 4 equations (Eq. 4 to Eq. 7) and #9 denotes the numberof iteración steps for detecting various rotated instances ofthe témplate object. If we only need to detect scaled objectswithout rútation, no iteration is required.

The main storage concern falte into tbe size of the accu-mulation structure. RGHT uses a 4-D hash table and thestorage used is 10* • p + s - c, wbere 104 = 10,000 is thenunibcr of cntries in the hash table, p is the size of a pointerfor a list, 9 and c are the number of samples and cell size re-specti vely. Since it is a table of üsts, so each entry is simply

514

Page 173: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

a pointer. The cell size c in RGHTis a constant. 5, since eachcell only contains the tupie: (Hit rate, Ox, Oyt Sx, Sy)

3.5. Dlscnssion and iroprovement

Image reducüon is a tecbnique for speeding up the al-gorithm. By shrinking the original image, less samples areneeded to acquire certain accuracy. After locating the ap-prcximateposition and scale of the targets, we can work onsuch área in more detall in the original image.

la addiüoo, with the help of line extraction algorithms,such as Canny operator, we can remove soroe noise andunwanted disturbancc in the target image. After prc-processing, we can nave more accurate result. It is illustratedin our cxperiments.

4. Computer Experimenta

Hcre are some experíments of using RGHT to detectvarious objects. All the experimenta were conducted on aSUD SPARCsíation 20 with SunOS Solaris 5.4 and the timewcre measured in CPU time.

Fíg. 5 shows the result of delecting ellipses using theRGHT. The témplate image is a circle and the 3 targecs aresuccessfully marked with a cross al the estimated anchorpoint. The detection process costs 11 seconds with 200itcraüons and the result is summarized in the lable below.

(a) Templóte otyect(136x211)

(b) Original real woridimage(209x180)

CcJ Extracted edgesfrora(b)by Canny Op-erator

(d)ResuttofRGHT

Rgure 6. Result of detecting object in real im-age

5. Conclusión

Ox

37.593.091.7

Oy81.239.5140.5

SiOJ0.20-4

5y JHit

0.30.50.2

3012S

w (b)(140x170)

Figure 5. Result of dotacting elllpse

Oa; Óy \ | 5y | Hit

133.9 j 0.3 | 0.3 j if

A human head is shown in flg. 6. Hcre we use anotherarbitntry object as the témplate object The table abovcsutnmarizes the result Note that the centcr of the ear ismarked by a cross. The dapsed time is 10 seconds with 300iterations.

This paper proposes a new algorithm for object detection.The algorithm can work on grayscalc Lmagcs and detectarbitrary object witfa various scaies and orientations. RG3ÍTis actuaíly a combination of GHT and RHT and it shares theadvantages of the two algorithms. Since random samplingis used, there is a grcat save in tune and space, Otheradvantages are hígh accuracy and arbitrary resoíution.

References

[U D. H. Ballard. Gcncraliiing the Hough Transform co detectariñtruy thapes. Pattem Recognition, 13(2):U1-122,1981.

[2] Hough and P. V.C Medióos and Meaos for Rccofinizing Com-plex Pattems. U.S. Patent 3,069,654,1962.

[3] L, Xu and E. Oja.Randomíied Hough Transform (RHT); Ba-sic Mecfaanisms. Algodthmg, and Computadonal Complexi-ties. JmaSeUnJerstanding,57(T):\ll-l54,3 1993.

[4] L.Xn,E.O^,aJXiP.Kultancn,Anewcurvcdetectionmetbod:Randondud Hocgh Ttunsform (RHT). Pawtm RecogníríonLctters, 11:331-338,5 1990.

515

Page 174: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Efficient technique for circle detection usinghypothesis filtering and Hough transform

W.C.Y.LamS.YYuen

fndexing í&mis: Heugh (ransforms, ímage processing, Circle detection, Pararneier hypvthesis

Abstract: A tast circle detection method using avariant of Hough-like technique is reported. Theproposed techoique is simple in implernentation,efficicnt in computation and robust to noise. Ingeneral, to evalúate circle parameters for allpossible point triplets in an edge image containingn points, nC3 enumerations of the points have tobe examined, However, if spccifíc rclations of thccircle points are sought, the required nuinber ofenumerations can be reduced, The authorspropose one such seríeme of detection with pointtriplets possessing right angle property and therequired enumerations can be reduced to nC2

Moreover, a novel processing strategy known ashypothesis fíltering is introduced. The strategyincludes two hypothesis constraints tcrmed asconsistency checking with gradient angles andneighbouring points vaiidation. Experimentalresults are demonstrated to reveal theperformance of the method on detecting circles inboth synthetic and real images. Since theproposed method adopts a right angle criterionfor hypothesis, circles occluded or broken bymore than one half may not be detected. Testresults show that the limitation of the proposedmethod appears to be acceptable. Whencompared with estabÜshed Hough transformtechniques, thc main strengths of the proposeddetection method are its attractively lowcomputational and memory complexities andgood accuracy of detection.

1 Introduction

In everyday experience, many objects that we perceiveare ni circular form. The detection of their presence inan image rclíably and efficiently is therefore an essen-tial task in image analysis. One frequently adoptedtechnique is the standard Hough transform (SHT)method [2], which is robust to noise and can withstandcertain degree of occlusion and boundary defects.Moreover, thc technique can also be extended to dctect

© IBE, 1996IEE Proceeftings onüoe no. 19960794Paper fust reodved 26th January and in revised form 29th July 1996The authois are with thc Department of Electronic Engjneering, CityUnívereity of Hong Koag, 83, Tat Chec Avcnue, ICowloon Tong, HongKoag

arbitrary shapes [3, 4] Unfortunately, the major short-comings of the technique which inhibir its applicationto higher-order analytic shape detection are its massivestorage requirement and high cost of computation.

To tackle these problema, many improvements havebeen suggestcd [5, 6], Kimmc et al. [3] and Ballard [4]used gradient information to reduce computation cost.Davies [7] used a two-pass algorithm to lócate a circlecentre in 1wo 1-D arrays. Yuen et al. [8] compared fourmodified HT methods for circle detection with theSHT. These were the Gerig Hough transform (GHT)[9], the Gerig Hough transform with gradient (GHTG)[8], the two-stage Hough transform (21 HT) [10, 11] andthe modified fast Hough transform (MFHT) [8, 12].These methods employ one edge point for each accu-mulation in their Hough space (HS). Their strengthsand shortcornings are also discussed in the same refer-ences.

Variants of the Hough technique using more thanone edge point for evidence accumulation have alsobeen adopted recently. Among these reportedmulüpoint traüüfonn approaches, Leavers [1, 13]detected circles by a dynamic generaJised Hough írans-form (DGHT) method which is probabilistic in nature.First, it picks a seed point which must be part of a con-nected curve. Then, a región of interest correspondingto the seed point is hypothesised. Subsets of edgepoints sampled within the región, together with theseed point, are used for parameter estimation and accu-mulations in the projection subspaces formed by 1-Darrays. Since the entena of selectiug the seed points arequite simple and the selection of the región of interestrequires prior Information of the range of dimensionsof the shapes under detection, the efííciency of themethod may easily be affected by an invaHd hypothesisof the seed point or región of interest. Yip et al [14]suggestcd the use of parallcl tangcnts and accumulatioaof the four vértices (referred to by the authors as theend points of the circle diameters parallel to the co-ordínate axes) in a 2-D accumulator array. Subsc-quentíy, peaks formed by the four vértices are detectedto recover the circle parameters. However, as reportedby the authors, difíículties may occur when detectingcircies with more than one quarter missing or beingoccluded by more than one quarter. Lam et al. [15J pre-sented a Hough prediction/correction (HPQ methodwhich can detect nearly half the occluded circies with-out using gradient information. In the method, circleparameters are evaluated with two of the points enu-merated combinatorially from the image and the thirdpoint searched along a path perpendicu/ar to the íínejoining the point doublet. The number of enumerations

292 IEE Proc.-Vls. JmaK.e Signa! Pracess., Yol. I4i. No. J, October 1996

Page 175: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

quired by the method is nC¿N> where A'' is the dimen-ín of a square image. A major merit of this category

multipoint transform techniques is a signifícantduction of memory storage. However, due to thembinatorial eamncraüon of points required, theimputational complexity of these methods Ls usuallygher than the conventionai single point approach.herefore, to find a way to reduce the number of enu-erations is a main concern for íhese methods.This paper presents an approach for circle detection.be proposed scheme also belongs to the multipointanstbrm category. TheoreticaUy, to evalúate cíteleirameters for point triplcts in an edge image contain-g n points, „€$ enumerations of the edge points have

be examined- However, if specific relations of therelé points are sought, the required number of enu-erations can be reduced enormously. The idea of the•oposed technique comes from a property of a circleiat any íbice points lymg on it and with two of these3Ínts being the diameter, the third point forms a rightigle triangle with the remainiag two points. Usingich a criterion to form specific sets of a feature pointiplet, the number of enumerations can be reduced to72 only. The performance of the proposed technique isromising ín that ít is both fast and memory saving asiinpared with conventionai Hough transform meth-ds.

3b

1g. 1 Co-ordtnafex of P3. and P]b deíermintd /rom> edge point) searchcd «dg* poiat location

, and P¡

Proposed scheme for circís detection and itsTtplementatíon details

^onsider any two end points Pí(xlf y{) and P2(x2í ^2)if a diameter Z)( of a circle as shown in Fig. l. We can?cate simply another two points P^xí9 y-¿) and /^¿(xj,i) which fonn a second diameter D2 of the same circleuch that PJ, P^} P2 and P¿b constitute the four cor-en of a rectangle circumscribed by the circle. In suchconfiguration, the sides of the rectaoglc are parallel

o the co-ordinate axes. Since both the angles /.f*i/*3irP2

nd ¿P-iPjbPi are right angles, the exístence of either»ints P$a or ^3^ in the image, together with P{ and P2

orming a feature point triplet, can be used to ¿ypothe-ise the same circle. Tncrefore, without losing general-ty, we use P3 to refer to P^ or P%, when the third>oint need not be distinguished explicitly.

With the feature point triplet formed, we can deter-nine the paramctcrs (a , b^ r^} of a hypothetical cir-;le by the following simple equalions:

i. . . . i, , (1)

ind

(2)

Since the hypothesis of a circle depends on its diameterfonned by P\d P2, cúreles which are occluded orbroken by more than half may not be determined. Thisconstitutes a limitation of using the lechnique. How-ever, the ümitatioo is less severe than Yip's method [14]where the imperfect boundary cannot be more than aquarter. The DGHT method [l] does not have this lim-itation for circle detection. However, as tested by theauthor for good quaiity image data where the degree ofconnectivity for edge boundaries are high, minimumdata requirements are of the order of a half circle. Aquarter are is insufñcient and leads to ambiguity in theresults. In this regard, the limitation of the proposedtechnique appears to be acceptable.

Another issue to be considerad here is that the HTtechnique used in [l, 14] obviously requires a largcnumber of feature point triplets for vaBd accumula-tions in the HS. This is not easily accomplished herewhen few point triplets satisfy the right angíe criterion.To get rid of this requirement, a hypothesis-verifícatioaparadigm is introduced in our detection scheme. Theparadigm employed here is essentially based on a singleoccurreiice of a point triplet satisfying the right anglecriterion for hypothesis, Basically, the hypothetical cir-cle can be mitiated by two points P\d P2 which isadequate to determine the circle parameters. However,the additional point P$ located can provide greater evi-dence ío screen out unlikely hypotheses. Therefore, thelocation of P3 can be considered as a simple but usefulstrategy for preliminary hypothesis ñltering. Moreover»since the right angle condition for any point triplet isnot a unique property of a circle, invalid hypothesescan still be generated when the image contains noncir-cular objects. To elimínate these invalid hypotheses, weimpose two more hypothesis constrainLs. These con-straints will be elaborated further in the following sub-section,

With the addilional constraints introduced, the pro-posed detection scheme can be performed in the follow-ing manner:

For any point triplet in an image satisfying therequired right angle criterion and hypothesis con-straints, we hypothesise a circle passing through them.The corrcsponding circle parameters (a^ b^, r^) areevaluated with eqns. 1 and 2, Subsequentíy, edge pointsthat exist within a región of interest (i.e. an associatedrectangular témplate to be described in Section 2.2)corresponding to the hypothetical circle are located.Their distances from the hypothetical circle centre areevaluated and accumulated in a 1-D accunrulator array(i.e. the radius array). A circle is regarded as existingwhen a prominent peak is detected in the array. Oncethe circle is detected, its parameters are recorded in aparamcter Ust. As rcvealed from the cxperiments inSection 3, we shall see that the detected parameters aresufficiently accurate for general requirements. How-ever, the parameter valúes can be further improvedwhen better subpixel accuracy is desired. This can bedone by an optional procedure for refincmcnt as elabo-rated in Section 2.4. Subsequently, edge points corre-sponding to the detected circle are removed from theimage. The scenario is repeated until all of the enumer-ations are completed.

Based on the above scheme of detection, a completedetection algorithm is presented as shown in Section7.1.

*EB Proc.-Vu. Imagt Slgnaí Prvcess., Val. 143, Na, S, October 293

Page 176: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

2.1 Filteríng with hypothesis constraintsThe hypothesis constraints adopted in thc detectionscheme are mainly composed of two categories. Thefírst category tests the compatíbility of gradient anglesin a point triplet before a hypothetical circle is verified.The gradient angles used are obtained from a 3 x 3Sobel edge detector, In the second category of con-strainís, the neighbouring points of the point triplet areverified. The reason is that if thc hypothesis is valid, itis equally Hkely that the proximal points of the tripletshould also satisfy the same set of circle parameters.The following explains the details of the constraintsemployed:

2.1.1 Consistency checking with gradientangles: The consistency checking with gradient anglesof a point triplet is divided into two cases:Case 1: For points P\d P^ thcir respective gradientangles 0j and $3 diíTer by JT, i.e. \<pi — fo] — JT.Case 2: For the gradient angle fo of point P^ ils, con-sistency can be tested vía the corapañson of r>/.} withbhp, i.e. bp3 - bty. The parameter bp. is the the verticalcoordínate of the circle centre determined using P3(x3,>>3) and ahp and thcy are related by the folíowing equa-tion:

. ,. \ ' i / O\« —- to/ip — -í-~¿) ton<p^ i* y^ v^/

This equation can be obtained simply by differentiaüngthe circle equation

_2 — (-r ~~ ni. \ in — hi. \ — Vx "/ip/ T^ \y un-p! \.J

with respcct to x.

Fíg.2 Validation of neighbouring points wíihin a 3 x 5 window(i) search locauon(ii) pUel lix^itioii

2.7.2 Neighbouring points valídatíon: Considcra 5 x 5 window corresponding to PI as shown inFig. 2. Edge points are located from the shadcd regiónwithin the window. An edge point Q that exists ia theregión is considered as a feature point of the hypothet-ical circle when the following two entena are satisfied:(a) The separation of Q from the hypothetical circlecentre rQ is approximately the same as r^ i.e. TQ ~ rhp.(b) The gradient angle of Q is consistent. The consist-ency is verified by using a procedure similar to case 2ofvSection 2.1.1.The same test is also performed for /*2 and P3. The val-idation of neighbouring points is satisfíed when foreach point P¡ in the triplet, the following condition ismet:

Tfti'~ > r-, where i = 1,..., 3MÍ

(5)

Tn the above equation, M¡ is the number of neighbour-ing edge points that exíst in the shaded región of P¿ m¡

is the number of these edge points satisfying criteria (a)and (¿>); and r is a threshold valué set experimentally as0.5.

Fig.3 Rectangular témplate endosing the hypotheti&tl circle CHyifi) rectangular témplate(ii) circular témplale(iii) hypotheticd circle

2.2 Des/gn of recfangu/ar temp/ateTo verify the existence of the hypothetical circle, a rec-tangular témplate can be designed and edge pointswithin the témplate región are located for evidenceaccumulation using a l-D array. An example of thetémplate designed wilh the parameters of a hypotheti-cal circle Cüyp is shown in Fig. 3. The témplate is corn-posed of fwo rectangular boundaries Kecii and Rect0

which are defíned by

Redi '(r«)r

V2-),

(ri)r

andVa

(^t/max)-,

(6)

+ ax j^Ap + (?"¿)maa;)} (7)

The parameters (rt}min and (rr)wflx are the bounds of thehypothetical circle radius rhp. An analysis of thesebounds due to discretisation errors in the sensingdevice is shown in Section 7.2. We assume that theimages containing the circular features are taken withsufficient care of Hghting and that the camera used iswell caiibrated such that the effect of perspective pro-jection and optical anomalies can be conected. If theprojection distortion is dominant, an ellipse detectorwill be more appropriate for detection. These assump-tions are usually valid and achievable in indoor envi-ronments or industrial applications.

For each point P(x> y) located in the témplate, a ver-ifícation radius rv is evaluated using

- ahp)2 4- (y - b^ (8)

and the valué is accumuiated in a smaü l-D radiusarray. A prominent peak formed in the array can implythe existence of a nypothetical circle.

2.3 Using an interíeaved scanning heuristicThe processing of pixei points in an image is dependenton the scanning sequence applied to the image, andconventionally pixel points are scanned from leñ toright and top to bottom. In the proposed detectionscheine, once a circle is detected, edge points belongingto the circle can be removed from the image and they•wül not be used in subscquent hypotheses and verifica-tions. Therefore, the earlier the shape can be detected,

IEE froc.-Yis bnage Slgnat Process.. Yol. Í43, ÍVo. 5, Octoó«r 1996

Page 177: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

e fewer the remaining points will be used for hypoth-is and verificación. Since points scanned from succes-/e columns (or rows) are usually neighbouring points,cy usually correspotid to similar local información ofe same shape which are of little use to aid the earlier¡tection of other shapes. To facilítate the detection,e can reorder the scanning sequence in an interleavedtanner. For example, with an image of N columns, ife let the scanning direction be column by column, themventional scanning sequence wili be (c,: i = 1, ...,}, where c, represents the ¿th column of the image.rtth the heuristic of interleaved scanning applied, thesw scanning sequence will become {c¿t Í-VKH> t^^-i),., c*.rt-0_i) ' J - li ••• ' s-l}9 where s is an interleavedictor and K ~ N DIV s. The symbol DIV denotes aniteger división operation and scanning is not per->nned when KS + O' - 1) > N.

'.4 Refinement of the circle parameíers/hea a hypothetical circle is verified as cxisting, itsarameteríi (aAp, bhpr rAp) are considered as the detectedarameters. However, when desired, their accuracy cane further improved by an optional refinement process.'he process is composed of three SHT modules which;fine the circle parameters independently, For exam-i\e, if the paiameter rhf is to be rcíincd, the samplinglarameters, which are the centre parameters a and bised in one of the SHT modules, can be set with small

c dRg.4 Exp&irnent 1. Synthctic drawing of áreles

sampling ranges and across the detected valúes ah andbty respectively. The same technique is apphed toreíine a^ and b^ in another rwo SHT modules. Again,in each SHT module, only edge points in the témplateregión are used for accmnulation ín the 1-D arrays, Tocope with a noise corrupted circle where the boundariesmay not be exactly circular, the size of the témplate

a b

c dFÍQ.6 Experiment 3. Synthetic drawing ofoccktded circles

c dFÍQ.7 Experiment 4. Discriminarían of circular and rectangular objecis

c aFlg.5 Experiment 2. Synthetic drawing ofconcentric circtes

c dFU).8 Experiment 5. Detection of chess pieces in chtner environment

IEE Proc.-Vis. Image Signa! froctsí., Yol, 143, No. 5, Oaober 1996 295

Page 178: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

región can be tolerated further hy severa! pixels accord-ing to eqns. 17 and 18 derived in Section 7.2. Toachieve better subpixel accuracy of the refíned parame-ters, the co-ordinates of the edge points and the resolu-tion of the sampling paramctcrs in the SHT modulescan be oversampled to reduce thcir discretisationerrors.

Table 1: Execution time for experiments 1-5

Experiment

1

2

3

4

5

n (pixels)

1248

1755

1614

1162

4843

Tf{a)

0.9

1.0

1.2

1.8

1.9

T^ís)

1.4

1.6

2.Q

2.2

22.8

T¿at (sí

5.1

7.5

6.7

4.9

26.6

n = number of edge points ¡n thinned edge imageTt - execution time for Sobel edga detectíon and thinníng7"o* - executlon time of the proposed methodTÓ»I = execution time of the proposed method with refínement

3 Experimental resulta

The algorithm presented in Sectíon 7.1 has been imple-mented in C language on an IBM-PC compatible DX-2/66MHz computer, A total of fwe images (Figs. 4-8).each with size 256 x 256 pixels, have been tested. In theexperiments, the size of each 1-D array used for accu-mulation was 15, the angular tolerance for consistencychecking was 7°, the interleaved scanning factor was setexperimentally as 5, and the existence ratio for localpeak delection was 0.54. The results for the tíve experi-nients are also shown ia the corresponding subfíguresin Figs. 4-8. The execution times of the experimentswere tabulated in Table 1. As shown in the last twocolunias of Table 1, the íírst four experimenU werecompleted within 3s when no refínement is performed.But for the fifth experiment where the edge pointsprocessed are about three times the other edge images.the time taken was reasonably longer and is about 23s.With the detected parameters refined, the additionaltime rcquircd is fairly constant for all the experimentsand is within 6s. Moreover, as revealed from the ílrstfour experimente, the yield of bcttcr subpixei accuracywas achieved at a higher cosí of processing efforts. Fortríese cases where the refinement is performed sequen-tially and constitutes the main proportion of the overallcomputatioo.» it appears that bensfíts have to beweíghed against accuracy and additional effort paid

Tabte 2: Number of enumerations and hypothesís countsrequired

Exparimerrt n (pixels) nC¡

1

2

3

4

5

124a1755

1614

1162

4843

778128

1539135

1301631

674541

11724903

A/E*,*.59661

4507

102655

51147

7803724

/%^

211

50

320

146

38477

NQna

7

13

33

33

654

/%*

7

19

32

21

207

f Afe*

e5

6

5

6

n * number of edge pointa in thinned edge image..Cj => theoretícal number of enumerations requiredW&wrn * actual number of enumerations requiredNftgt*ng = counta passlng the rlght angle cond'rtionMenú = counts passing the consistency checking using gradient

anglesNKg0d= counts passing the neighbouring points vaüdationNOM- number of detected circles

for. Another possible alternative that can he consideredfor irnplementation is to perform the refinement in aparallel manner.

To investígate the effectiveness of the hypothesis con-strainls employed, hypothesis counts passing theimposed constraints were recordad in Table 2. Sincethe feature points of the detected circles were removed,the actual number of enumerations required NEnum isless than HC2. As revealed from N£gtAtlF NGfad andNf/gM, most of the invalid hypotheses are effectivelyscreened out by the constrainís imposed. Moreover ascompared lo NEm^tt NNgb(¡ (Le. Ihe number of point tri-pleto actually verifíed) constitutes a very small fractiononly. Therefore, the main core of processing, i.e. theverifícation and refínement process which require theheaviest computation effort, is limited to a smallamount of confident hypotheses only.

The fírst three experiments shown in Figs. 4-6 revea!the performance of the proposed algorithm to lócatesyníhetic circles with different sizes and positions and itscapability to handle concentric and occluded circles. Tnthe ílrst experiment, six circles were synthesised asshown in Fig. 4a and its edge detected image is shownin Fig. 4¿. The circles deLected by the algorithm aresuperimposed on the edge image and reconstructed asshown in Fig. 4c. In the sarne Figure, the crosses drawnon each reconstructed circle denote the correspondingtriplet of edge points that initiates the hypothesis.Moreover, the rcctanglcs cmbracing the detected circlesare their associated témplales for verificatiou. In practi-ca! impíementation, each rectangular témplate is com-posed of two pairs of equal área regions. The search ofpoints in the same pair of regions is performed simulta-neously by simple transiation of the región co-ordinates,Fig. 4¿ shows the refined resuíts superimposed on theoriginal intensity image. The detected and refined circleparameters obtained in this experiment were recorded inTable 3 and compared wilh the actual parameters ofthe synthetic circles. As seen from the third column ofthe Table, the errors of the detected parameters withoutreñnernent are within 1 pixel. When relinement was per-formed» an appreciable improvement on the overalldetection accuracy can be observed as shown in thefourth column. The cases for the sccond and thirdexperiments are depicted in Figs. 5 and 6, respectively.For the third experiment, it should be noted that differ-ent parts of the circles are purposefully occhided andtwo of the circles are occluded by more than a quarterby another circle located at the lower right córner.E)espite these missing portions, all of the circles are stilldetectable and the reconstructed circles approximate themissing portious qxúte welL

Tabie 3: Absoluto error» for detected and refined circteparameters in experiment 1

ítems

1

2

3456

Actual parametersU, b, r)

138.2,46.7,25-S)

(60.6,180.9,50.2)

(112.3,40.0,33.5)(120.4,121.6,30.91

(190.3,80.5,43.7)(170.1,180.5,38.3)

Errors withoutraflnomant(\ó&\. \ób\, |¿rj)

(0.2.0.3,0.0)

(Q. 1,0 .6,0.0)

(0.3,0.5,0.2)

(0.6,0.1,0.1)

(0.2,0.5,0.2)

(0.1,0.5,0.1)

Errors withrefínement

(0.1,0.1,0.0)

(0.2,0.1,0.0)

(0.2,0.5,0.6)

(0.1,0.2,0.1)

(0.2,0.3,0.0)

(0.2,0.3.0.1)The co-ordinates are ¡n Cartesian form and the origin is at thebottom left corners of the images

296 ÍES Prac.-V'x. ímage Signal Proceu.. Vol 14Í, JVo. 5. Oztabcr 1996

Page 179: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Che last two experimcnts were performed on realínsity images as shown in Figs. 7 and 8. In theirth experirnent, a match box with right-angíed cor-s was placed together with three coina and a circular1 of adhesive tape. No false detection due to theht-angled corners was obscrved. Another point thatworth rnentioning here is that the edge boundaries ofs coins shown in Fig. 76 are not exactry circular. Theomalies arising from thesc boundaries did not affcctsir detection as circles. A similar performance oftection was observad in the fifth experiment. Thisle the te&t úrvage contains several Chínese chess;ces which are in a cluttered environment arisen from: shadows of chess pieces and patterns of the chess-

-JUU

200

100

01

: so 10r (for verificación)

g.9 Accumulation scores for oim of the detected circles inperiment 1: veri/ication radias

AUUU

3000

§ 2000u

1000

o J55 60

16

board, Fig. 8c and d show the corresponding detectedand refined results. The complicated patterns ot" char-acters preaent in the image do not make the resultsdeteriórate too much. Since less than half of the chesspieces are \ocated at both the left and right top corners,they are undetectable. The outer boundaries of otherchess pieces are imperfect and severely distortcd andthey cannot be detected as circles either. From this lastexperimení, the strength (i.e. the computational eífi-ciency, accuracy of detection and robustness to clutternoise) and the weakness (i.e. the amount of the circie tobe detected should be more than half) of the methoüare simultaneously observed.

150

100'

50

20 30 50 50

r (for verificQtíon)

Fig. 13 Áccumuiaiion scores for one of the detected chess pieces inexperiment 5: verification radias

13UU

1000

500

o mD

r-

-

Ih72 73 7¿. 75 7

ifl.10 Arcumulatinn ,<if:orfS for one. of tfa detected fircles incperimeni 1: parameter a

*«wv

3000

g 2000u

1000

0

1i

175 180L

te

Fig. 14 Accumularían ícores for one of the detected chess pieces inexperimení 5: parameter a

1500

1000

500

208 209 210 211 212

Ig.ll Acaenulatum scores for one of the detecied circles inxperimeni J: porameier b

¿,000

^ 3000

u 2000

1000

o

Fig. 15 AccurmilalioTí scores for one of the detected cftea» pieces in.experimení 5: parameter b

50 56

Iu

¿UUU

1500

1000

500

0:

r

Jn

k0 32 3A 3

Fig. 12 Accwttuíatíon scores for one of the detected circles inexperiment ¡: parameter r

Fífl. 16 Áccumuíation «wes for one of the delected chess pieces inexperimení 5: parumeter r

IEE Proc.-yis. Image SlgMal Process., Vot. ¡43, fío. 5. Oclober ¡996 297

Page 180: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

In Figs. 9-12 and Figs. 13-16, two scts of detectedcírcle parameters, one obtained from experiment 1 andanother from experiment 5, were plotted, respectívely.In each set of Figures» the first Figure is the accumula-tion score of the venfication radius rv as described inSectiou 2.2. The remaining thrce Figures in each setcorrespoüd to the tefíned para-metenj obuined from thethree SHT modules described in Section 2.4. As men-tioned previously, to reduce the discretisation errors forrefinement, the co-ordinates of the edge points in thetémplate región and the resolution of the samplingparamcters in the SHT modules were oversamplcd.This resulta in higher accumulation scores obtained. forthe tefined circte paiameters as compared to the scorefor the verification radius rv. Therefore, in the two setsof Figures, the vertical scales are different. From thesesubpíots, distinguishable peaks are observed..

count

500

400

300

200-

100-

-100

Fig. 17 Projected acacmulütiQn scores obtained by SHT method

-100

200

100200

n iwO o

. 18 Accumulation scores obtamed by GHTG method

300

Finaüy, using the image of the fifth experiment, acojnparison of ihe proposed method with the SHT andthe GHTG methods were made. The aceumulationscores of the SHT and GHTG methods, together withtheir contour plots, are shown in Figs, 17 and 18. Sincethe complete HS of the SHT method is three-dimen-sional, the visuaüsation of peak formation is diffícult.Altcrnatively, Fig- 11 shows the accumulation scoresprojected to a 2-D subspace of centre parameters.Moreover, gradient information has been used for fil-tering invalid accumulations. However, to "be fair for

the comparison of the execution time, the unmodifiedSHT algorithm was used. The execution time andmemory storage required by the three methods werecompared as shown in Tabíe 4. Their limitations arealso shown. in the last column of the same Table. Itshould also be noted that the execution time for theSHT and the GHTG methods denote their processingin accumulations only and their times for peak detec-tion were not accountcd.

Table 4: A comparison of SHT, GHTG and our proposedmethod

Methods Execution time (s) Memory iwords) Limitations

SHT 3388

GHTG 1218

Proposed 26.6rnoihod

2563= 16.7x10" n¡l

256a - 65.6X103 yes1""

15*", 15x3=45(i¡1

{'O Case when no refinement or sequential refinement ¡sperformed

(ii> Case when paralleJ refinement is performed(iii) Concentric circles csnnot be detected(iv) Circles occluded or broken by more than half may not be

detectad

4 Conclusión*

In this paper, a fast method for circle detection is pre-sented. The proposed detection scheme adopts ahj'pothesis and verifícation paradigm and the relationemployed for hypothesis is a right angle criteñon whichexists in subsets of point triplets of a circle. A similartechnique proposed by Lam et al. [15] requirea nC2Nenumerations. However, in the proposed method, therequired number of enumerations is only nC2. Theoreti-cally, only one good occurrence of the condition for acircle is sufíicient to initiate a correct hypothesis. How-ever, as the right angle criterion for a point triplet isnot a unique distinguishing property of a circle, ahypothesis filtering strategy is introduced. The strategyincludes two novel constraints which can tllter theinvalid hypotheses eflfectiveíy. Experiments were carriedout which include both synthetic and real images toin ves lígate the performance of the detection scheme interms of accuracy of detection, processing speed,robustness to clutter noise and partiaJ occlusion. It isfound that the method performed quite well in att theabove aspects.

As compared with the conventional HT methods, themain strengths of the proposed method are its attrac-tivcly low computational and memory complexities»and good accuracy of detectíoa. Howcver, theímproved performance in these many aspeéis is at theexpense of not being abíe to detect circles which areoccluded or broken by more than half. Moreover, anovel contribution of our proposed detection schemethat difíers from the work of Leavers [1] and Lam et ai.[15] is the introduction of a hypothesis filtering strategyin the adopted detection paradigm. The mechanismlimita the heaviest computation effort, i.e. the verifíca-tion and refinement (optional) processes, to a smaHamount of conñdent hypotheses only. Invalid hypothe-ses that inhibit the processing are effectively screenedout in our method as revealed from the performedexperiments.

298 IEE Proc.-Vis. ímaxe Sfcnai Process.. Voi 143. No. 3, October 1996

Page 181: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Acknowledgm«nts

ic authors wouíd likc to thank the anonymous/icwers for thcir valuable commeuts and suggestions.

References

LEAVERS, V.F.; 'The dYnarxúc geocralizo:l Hough transform: Itsretationship to the probabiHstic Hough txansform and an appUca-lion to the concurrent dctection of círcfes and ellipses', CYG1P:Image Umierst., 1992. 56, (3), pp. 381-398DUDA, R.O., and HART, P.E.; 'Use of the Hough transform todctect lines and curves in picturcs', Commua, ACM, 1972, 15, pp.U- 15KIMME, C, BALLARD, D., and SKJLANSKY, J.: 'Finding cir-cles by an array of accurmilators', Commun. ACM, 1975, 18, (2).pp. 120-122BALLARD, D-H.: 'Genenüwmg the Hough transform to dctectarbitrary shapes', Paltern Recognit.. 1981, 13, pp. 111-122ILLINGWORTH, J-, and KITTLER, J.: 'A survey of the Houghtransform*, Compui. Vis. Graph. ímage Procesa, 1988,44, pp. 87-116LEAVERS, V.F.: 'Survey: Which Hough transform? ', CVGÍP:Image Uníkrsf., 1993, 5», pp. 250-264DAV1ES, E.R.: 4A high gpecd algorithm for circular object loca-Üoft', Pattern Aecognit. Leu., 1987, 6, (3), pp. 323-333YUEN,H.K., ILLINGWORTH, J., and ÍOTTLER, J.: 'Cora-paraüvc study of Hough transform methods for circle detection1,Image Vis. Compuí., 1990, 8, (1), PP- 71-77GERIG, G,, and KLEIN, F.; Tast conloar identificatioathrough efficieDt Hough transform and simphTied interpreíationstrateg/. Proceedings of the 8th intemational conference ou Pu¡~íern recognitio«, 1986, pp. 498-500

0 ILLINGWORTH, J., and füTTLER, J.: ^The adaptivc Houghtransform', IEEE Trans., 1987, PAMI-9 , (5), pp. 690-697

1 ÜAVIES, E.R.: 'A modified Hough scheme for general circlelocation', Pattern Recognit. Leíl., 1988, 7, (1), pp. 37-44

2 U, H.f LAVTN, M.A., and LEMASTER, R.J.: 'Fast Houghtransform: A híerarchical approach', CVGIP: Image UruJerst.,1986,36, pp. 139-16]

3 LEAVERS, V.F., B-TZVL D.. and SANDLER, M.B.: 'ActiveintcllJgcnt visioD uaing the dynamic generalizad Hough. trans-forra'. Proceeduigs of British Machine visión conference, 1990, pp.49-54

4 Y1K, K.K.K., TAM. P.K.S., and LEUNG, D.N.K.: 'Modifica-lion of ílough transform for nicles and cllipsca dctccúoa using a2-diraensíonal ura>'. Pattern Recognií,. 1992, 25, (9), pp. 1007-1022

15 LAM, L.T.S., LAM, W.C.Y., and LEUNG, D.N.K..: 'A Hough-lüte prediction/correction appfoach for circle detection1. Proceed-ings of the 8th Scandinavian conference on Image analysis, 1993,pp. i 51-1 58

7 Appendix

7. 1 Proposed algorithm for circle detectionInput:Interleave scanned sequence of edge points {P¡(Jc¡, y¡) : '= 1, ..., n) obtained from an N x N edge image.Output:List of circle parameters Lmí{(a, b, r)h : h = 1,where m is the uumber of detegteU areles.Alponthm:for any edge point P\h gradient angle fa {

for any edge point P2 l^ gxadient angle //Coosíslency chcclcing wíth cuc 1 in Scction 2.1.1

m},

the pre*eoce of the third poiol.if (P3 exista) {

Evalúate the circle parameters using^3-//Consisteocy checldng with case 1 in S-ction 2.1.1

and

//Neigbbouriag pomts validatioa ¡o Section 2.1.2if (neighbouring points validation for Plt P2

and P3 is satisfied) {Determine a rectangular témplate corre-sponding to the hypothetical circle.

VTs. Image Slgnal Pmetos.. VoL 141, No. 5. Ocíoher 1996

Atxumulate r, in the rectangular témplatewith an initialised 1-D radius array.Detect local peaks m the 1-D radiua array.if (local pcaks cxists and abovc a thrcshoíd) {

t/.\& optionaJ procedure as describid in Section 2A

Refine the detected parameters with threeSHTT modules.Store the circle parameters as (a, /?, r)h inLguf

Remove the circle points in the image.

Fig. 19 ¿4/tatysis of the uncertaíníies for circle porameters(í) pirtel point(ii) pixel point containíog hypoihctkal ciicl* centreíiii) truc circic centre location

7.2 Analysis of ths unc&rtainties for thehypothetical circle parametersWithout loss of generality, consider a circle locatcd asshown in Fig. 19, where P$ is at the lower left córnerof a circumscribed rectangte. In the following where noambiguity occars, we assume parameters with subscriptí refer to the predigitised or truc valúes. With this nota-tion, the co-ordinates of the digitised point Pt(Xp >•/)can be expressed m terms of its predigitised co-ordi-nates Pn(Xfi, >"fi) &&& P>xe^ uncertainties Óx¡ and Óyt as

Xi - Zti + i, Vi - Vti + £jK for t = 1, . . . , 3 (9)By applying cqn. 1, the uncertainties of the centre (cz^,

is determined to be

at = -{(a6a =

and

06 = - bt = {(yi 4- ítt) - +

(12)

(13)

After eqns. 10 and 11 are simplified, we have1 _ l

2Now letSxi — 5x2 — <*> eos and áj/i — dy^ — <*> sin 1When T¿I is eUminated from the two equations, the fol-lowing relations can be obtained:

u;2 = (¿IL — ¿^2) + (¿S/i ~ ^3/2) (14)Moreover, from Fig. 19, we haveXl — x-2 — 2rhp coa O and 3/1 — y<¿ = 2T^P sitié? (15)Substituting eqns. 9, 13 and 15 into eqn. 2, the predig-itised radius r¡ can be re-expressed a&

299

Page 182: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

r] = -

= j

+ fon - fcs)2}

foi + 6x2)2 + (yi - ya - áyi +

Since r¿p, w, T/Í and 0 are independent, we can obtain(r,)^ and (/•,)«« by varying tí and maximising o), i.e.

(17)

(18)

(rtU,=i

and vrhen & — ir 4- V'

(rt)m« = '

Therefore, the deviatioa of (O,, from (rt)nin, i.e.(¿O/naje» can evaluated as

(¿r)ma* = (rt)m«x - (r()mín = wm« (19)Ja the worst case, let \6x¿ = |óx2| = (5^1 = |Sy2| = 1/2,we have

wmwí = v^ (20)With eqns. 12 and 19, the máximum imcertainties ofthe circle parameters can be determinad as follows:

(21)

and(6r)max = V2 (22)

Moreover, using eqns. 17 and 18, the valúes of (r,)m¡n

and (rí)max can be determined.

3UO /££ Prot.-Vií. Image Signal Procos,. Vol ¡43, No. 5, October 1996

Page 183: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

242IEICE TRANS. INF. le SYST, VOL.Efl3-D, NO.2 FEBRUARY 2000

PAPER

Designing Efficient Hough Transform by Noise-LevelShaping

Hideaki GOTO* and Hirotomo ASOn, Members

SUMMARY A larga number of techniques have been pro-posed for acceleration of the Hough Transform, because the trans-formation ia computatíonally very expensive in general. It isknown that the sampling interval in parameter space is stronglyrelated to the computation coat. The precisión of the tranaforma-tion and the processing speed are ¡n a trade-off relationship. Nofair camparison of the procesalng speed between varioua methodswas performed in al) prevíous works, because no criterion hadbeen given for the sampling interval of parameter, and becausethe precisión of parameter was not equal between methods. Atthe beginning of our research, we derive the relationship betweenthe sampling interval and the precisión of parameter. Then wederive a framework for comparing computation cost under equalcondition for precisión of pararoeter, regarding the total numberof sampling pointa of a parameter aa the computation cost. Wedefine the transformaron error in the Hough Transform, and theerror is regarded as transformation noise. In this paper we alaopropose a design method called "Noise-level Shaping," by whichwe can set the transformador! noise to an atbitrarily tevel. Thelevel of the noiae is varied according to the valué of a parameter.Noise-level Shaping makes it possible for us to find the efficientpárameterization and to find the efficient sampling interval in aspecific application of the Hough Transform.key words: Hough. TYansform, sampling interval, transforma-tion noise, Noise-level Shaping

1. Introduction

In the standard algorithm of the Hough Transform, avoting curve is drawn in a parameter space for everyfeature point in an image región. Even though someacceletated transformationa auch as based on a prob-abilistic algorithm had been proposed, the standardalgorithm has often been preferred and used, becauseit provides a very simple correspondence of the votingcounta to the number of pixels on a figure. However,the standard algorithm is coraputationaUy very expen-sive, Acceleration techniques for getieration of votingcurves are required in most applications. The discus-sion in this paper is limited to the transformation basedon the standard algorithm,

Let us take up the Hough Transform for line de-tection such as p-0-type transformation [1], Some meth-ods were proposed for the acceleration of voting curve

Manuscript received February 5, 1999.Manuscript revised June 28, 1999.

'The author is with the Education Center for Informa-tion Processing, Tohoku University, Sendai-shi, 980-8576Japan.

tfThe author is with the Gradúate School of Engineering,Tohoku University, Sendai-shi, 980-8578 Japan.

generation; for example, the approximation of cosinecurves by polygonal lines[2¡, and the straíghtening ofvoting curves [3]. These two methods aimed at reducingthe computation cost of voting curve generation claim-ing that a straight line is far faster to genérate than acosine curve.

In the standard irnplementation of the HoughTransform, we first define a transformation functionwhich gives the valué of one of the parameters. Then,for every feature point (such as edge points) on the fig-ure, all the other parameters for the figure are scannedwith some discrete numbers, and the only one param-eter is caículated using the transformation function. Ifthe voting curve is a straight line, the voting curve(line) can be generated only incrementing a parame-ter without substituting any valúes for every parame-ter in transformation function. On the other hand, thegeneration of cosine curve has been thought to be com-putationaíly very expensive, because it requires multi-plicatiohs and calculations of trigonometric functions.However, if we use Look-Up-Tables for the trigonomet-ric functions, the cosine curve generation requires onlymultiplications and additions. Moreover, a methodwhich requires only additions and incrementa was pro-posed^]. Multiplications are omitted in this method.Therefore, there is no strong reason that the votingmethod which use cosine curves are much disadvanta-geous in processing speed.

The precisión of an estimated parameter dependaon the sampling interval of the scanning parameter. Alarger sampling interval makes the precisión worse. Theprocessing time of the voting curve generation is pro-portional to the number of sampling points on the vot-ing curve. Assuming to use the same transformationfunction, and if the rangea of parametera are same, theprocessing time of voting curve generation is inverselyproportional to the sampling interval. Therefore, weshould discuas the precisión of parameters as well ascomparing the shape of a voting curve when we com-pare the speed of voting curve generation among vari-ous transformation. Only the difficulty of voting curvegeneration has been regarded as important, and the dis-cussion of the precisión of parameters has been left in-complete in the previous works. In our work, a methodfor designing efficient Hough Transform is derived, pay-ing attention to the relationship between the precisiónof parameters and the processing speed.

Page 184: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

GOTO and ASO: EFFICIENT HOUGH TRANSFORM BY NOISE-LEVEL SHAPING243

Main purposc of our research is to derive a theo-retical and general method for designing the most effi-cicnt Hough Transform. However, we have sonie sub-goals as well. Our first subgoai is to design a frame-work for the comparison of processing speed amongHough Transforms with difFerent transformation func-tions or párameterizationa. In our previous work [5] weobtaincd the result that there exists an upper boundof the sampling interval for the scanning parameter onthe assumption that we need the most precise param-eters from the given discrete image. If we use the up-per bound as the sampling interval for each of varioustransformation functions, wc can compare the process-ing speed of Hough Transforms on an eqiial condition.The second subgoai is that we theoretically compare theperformance of Hough Transforms with various param-eterization presented before and make the relationshipclcar among those parametcrizations.

This paper first introduces a generalizad represen-tation of the Hough Transform for line detectiou inSect.2 and we reveal the relationship between the pre-cisión and the Kampling interval of a parameter. InSect. 3, we proposc a design method called "Noise-levelShaping" by which the level of transformation noise inthe Hough Transform can be modified arbitrarily. Wealso demónstrate that. the most emcient Hough Trans-forms can be designed by the method. Finaiíy, the re-sult of comparison of processing speed arnong HoughTYansforms with various parameter i zations is shown.

2. Errors and Sampling Intervals in HoughTransform

2.1 Errors in Hough Transform

A straight line in a 2-dimensional Euclidean space isrepreseuted by the linear equation

F(x,y ; u,v) =0 (1)

using coordinates x = (x,y) and parameters (tt,u). Asolution of (1) with respect to v is reprcscnted by

v = Fv(x,y ; u) (2)

using a continuous function Fv which givcs a uniqueparameter v for a set of x,y and u. We cali Fv trans-formation function.

A discrete line is obtained by mapping the Unedenoted by (2) onto a set of pixels in a discrete imageregión. Let a discrete image región be represented bya set of pixels which are placed on the lattice points ofa square grid with sampling interval As. Assume eachof the two orthogonal axis of the square grid is parallelto the ar-axis or to the j/-axis. We also assume that theshape of the discrete image región is square and thatthe length of a side of the image región is 2NAs. Letus put the origin of coordínate system at the centcr of

u uoFig. 1 nVansformation error in the Hough Transform.

the square image región.We define a quantization of a line as follows, whcre

the angle between the line and the x-axis is in the range[—7r/4,7r/4). In the discrete image región, a continu-ous sampling point x¿ = ( x , , y i ) is defined as the in-tcrsectíon of the continuous line and the straight linex = t • A.s (wherc t is an integer) which is parallelto y-axis. The suffix. i denotes the serial number ofthe sampling point. Using the follawing equations, letus define the quantized point (¿t.yi) for (x¿,j/i) as thepixel which Ls a component of the discrete line.

x = y = (3)

[ J is the floor operator, thus \_z\s the máximuminteger that is less than or equal to z. Quantizationerrors of the discrete image are denoted by Sxi = x* —#11 $yi — y* ~ yi- Obviously, we have &r¡ = O and\Syi\ As/2 by the dennition.

In the Hough Transform, the coordinates of thediscrete sampling points (xt,y¿) and all valúes of pa-rameter u are put into (2), and tlien the valué of pa-rameter v is calculated, The parameter u is the scan-ning parameter which define the angle of the line. Somesampling points ük in the range of u are substituted for

after another. Let u¿¿ be the calculated vahíe ofv, For a sampling point )i we nave

(4)

Though Vik will be quantized in the implementation ofthe Hough Transform, wc use continuous parametershere in the error analysis. In tilia paper, the preci-sión of the estimated parameter is not measured by thequantized parameter, but measured by the continuousparameter v^.

Let Au be the sampling interval of u, and let(UQ,VO) be the real parameters of a line. As shown inFig. 1, the votes are observed in gray interval on eachline parallel to v-axis. The peak of vote counts in theparameter space stands at u — ük, where (ü* — WQ| <Aw/2 is satisfied. Let Su — ük — í/o be the quantizationerror of TÍ at the peak. The error of parameter v is given

Page 185: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

244IEICE TRANS. INF. A: SYST., VOL.R83-D, NO.2 FE3RUARY 2000

óvi = Vik -

; «o) . (5)

If we apply the Taylor expansión around x — xt andu = un in the first terrn on the right side of the aboveequatAon. and if wc assume that the terms of seconddcgree and above in 5u and <5y¿ are small enough, theerror of v is given by

dy 5_£. u_u

(6)

Thc first tcrm on thc right side of this equation repre-sents the error produced by quantization of the image,We cali tliis error "quantization error." and write it a-sEQ(XÍ\ The second term reprcscnts the errorthat springs from quantization of the scanning parani-eter in the Hough TVansform. We cali it "transforma-tion error," and write it as ET^^UQ-^U). Note thatthe transformation error is indcpcndcnt of thc quanti-zation error of the image. Even for a continuous imagesuch that 5yi — O, the trausformation error is still in-cluded in w,jt and it causes the spread of votes along theline u = Uk.

If wc considcr all thc sampling points along the dis-crete Une, the errors <5w¿ are distributed around v = VQin the parameter space. The quantization errors are dis-tributed according to the change of i. In thc same way,thc transformation errors are distributed. Regardingthe distributions as probability distñbutions, we can re-gard the errors as the noises which come from the prol>-ability distributions. We use NQ and NT to representtríese noises and cali them "quantization noise" and"transformation noise" respectively. A real distributionof votes at u = ¿fc (the quantized valué of i¿o) is ex-pected to follow the distribution of VT — v¡\- NQ 4- NT,where VT is a random variable.

Wc can determine thc máximum valué of the quan-tization errors. A "máximum quantization error,1'which is denoted by qv or íví'^o), is defined as themáximum absolute valué of the quantization crrors

luoí <5í/í)- From (6) and \$yi\ As/2, we have

qv = maxdFv

dy (7)

where X2 denotes the set of all points in the squareimage región. Note that \NQ\ gv is always satiafietl.

2.2 Distribntiou of Votes and Discrimination Condi-tion of Parameter

The distribution of the quantization noise NQ follows

Q*D

Fig. 2 Distribution of quantization noise and transformationnoise.

that of the quantization error Óy, bccause the transfor-mation function Fv is a linear function of y. It is knownthat Óy follows a discrete distribution for the saniplingof images with square grid if the tangent of the anglehetween x-axis and a straight line is a rational numbcr.It is also known that Óy follows a continuous, uniformdistribution for a infinitely long line if the tangent isan irrational number. We can regard the distributionof the quantization noise NQ as a continuous and uni-form distribution Q in the range [-Qv,qv] as shown inFig. 2 [5).

In general, dFv/du in the transformation errorET(XÍ', "o; f>u) is the linear function of the coordinar.es xand y. Thcrcforc, thc valúes of dFv/du for every point(x,y) on a certain line are distributed uniformly fromthe mínimum to the máximum valué. We have veri-fied by some experimenta that the real transfonnationcrrors ET(^Í\^\^U] = (dFv/du) • 5u have a uniformdistribution [5].

We introduce some notations at this point.

Cmin(u0) =OF

(8)

(9)

Let e+ and £v denote the máximum and the mín-imum valué of the transformation error respectively.Wc obtain ^J = max[5u • cmax(uo))(5u - ^(uo)} ande~ = minfíu • Cfnax(uo)i^u • Cmin^o)}- Thc transfor-mation noise NT is distributed in the range between e~and E¿~ such as D shown in Fig. 2. We define fíj andv0/f as follows.

1(10)

(12)

We introduce a random variable NT,3ym which followsa uniform distribution in the range [—fíj, J2j). We haveNT ~ NT.sym+^o//; ^nd henee, the ohservational valué

Page 186: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

GOTO and ASO: EFF1C1ENT HOUGH TRANSFORM BY NOISE-LEVEL SHAPING245

(counts)

Rv>qv

Fig. 3 Rclation between peak distance and the width of trans-formation error.

VT is given by VT = i'o + v0// 4- NQ -I NT.¿ym. We caliR® "width of transformation error." v0ff denotes theoffset of the error distribution.

Since óu is an unknown valué, and since the máx-imum valué of R® is iniportant in the following discus-sion, we use \Su = Au/2 which naaximize fí°. Themáximum valúe is given by

Rv = Rv(uü) =Au

- Cm¿7t(í¿ü)} - (13)

ñv can be regarded as the level of transformation noise.The distribution of VT is known to have a shape of a

trapezoid if the modcl of the figure is a straight line [5].The upper base length of the trapezoid is 2\qv - Rv\,and the center of the upper base is VQ + v0}j (Fig. 2),

Let us discuss the separation of two parallel andcióse lines defined by parameters (UQ^VI) and (UD,^)-Their lengths along x-axis* are the same. The distri-butions of votes ín the parameter spacc for these linesfollow the two diatributions:

T = vi + ?/„// + NQ 4-T = V? 4- Voff + NQ +

(14)

(15)

The shapes of these distribution are the same, whileonly the positions of their centers differ. The followingproposition holds [5] for the separation of peaks whichcome from the two parallel lines.

[Proposition 1]: Let Gv = GV(UQ) = max(20w(uo)f2,^(1*0)). Two upper bases of the peaks are separatcd,and two parameters v\ v0ff and v-¿ + v0/f can beobtained (Fig. 3), if

Gv (16)

is satisfied.Gv in the above proposition denotes the marginal

difference of two parameters for v by means of whichvi and v-2 are distinguished in the parameter space. Wecali Gv Marginal Gap. Gv can be regarded as one of theparameters which represcnts the precisión of the HoughTransform.

Image space Parameter space

Fig. 4 Rclation between peak distance and imagc resolution.

A continuous Une (figure) moves according to thechange in parameter v. Let dr denotes the differencein the positions of the figures (meastired along y-axis^)when the parameter v is varied by dv (Fig. 4). Assuni-ing that both dr and dv are vcry small, the equationdv 2¿ \dFv/dy\ dr is dcrived from the transformationfunction Fv. Two continuous lines <:annot be distin-guished in a discrete iinage if they are placed in a gapsmaller than or equal to the sarnpling interval A.s ofimage. Therefore, two discrete lines which are distin-guiahable in a discrete image should be apart more thanAs, and the difference of parameters is greater than

_dy (17)

i.e. vi — v<¿\ (i,, should be satisfied. Using (7) andthe above equation, we also have 2qv > d,,. Followingproposition holds.

[Proposition 2] For any pair of two liues which aredistinguishablc in a discrete image and have a commonparameter UD, the máximum quantization error qv andthe level of transformation noise R^ must satisfy thefollowing condition if the lines should be distinguishablcin parameter space (Fig. 3),

Resolution Preservation Condition:

(Proof) If qv < /?«, we have d^ < 2qv <mñx.(2qVl2Rv) = Gv- Henee there are parameters

(18)

and v^ such that Gdefinid by v\d vBut the parameters

> \v\ u2| > d«. These linesare distmguishable in an image.

^ and v^ is not distinguishable inparameter space by Proposition 1. D

The inequality (18) represents the condition forpreserving the image resolution in the parameter spacc.

2.3 Optimum Sampling Interval for Parameter u

Equation (13) shows that the width of transformationerror depends on the sampling interval Aw of the scan-ning parameter. In the aspect of the proceasiiig speed,

is in the case that the angle between the lines andis in Üte range [— 7r/4,ir/4).

Page 187: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

246IEICE TRANS. INF. k SYST., VOL.E83-D, NO.2 FEBRUARY 2000

a larger valué is desirable for Au. Wc discuss the mut-able selection of the sainpling interval Au hcrc.

Let us introduce Mínimum Acceptablc MarginSv(u) which denotes the minimiim tlifference of param-eters to be distinguishcd in parameter tspace. The fol-lowing proposition holds when wc givc Sv(u) as a designparameter.

[Proposition 3] If botli SV(UQ) > 2qv(uo) and

— mín Au

25v(u0)(19)

are satisfied for two discreto lincs defined by (?¿o.wi)and (un,v2), two parameters v\. and u2 which satisfyVi — v-2\ £,(WQ) can be obtained as v\ v0ff and

1*2 + v0ff respcctwcly.(Proof) From (13) and (19), we obtain the followinginequality-

By thi.s inequality and the condition, wc have Sw(«u) >Gv = max(2qVÍ2Ru). Thus. the above proposition isproved by Proposition 1. a

The right side of (19) denotes the upper bound ofthe sampling interval Au. As the upper bound is pro-portional to the Mínimum Acceptablc Margin $V(UQ),we should prcfer a larger valué for SV(UQ) in ordcr toreduce the computation cost. Following propositionholds.

[Proposition 4] If the Hough Transform should sat-isfy the Resolution Preservatiou Condition given by(18) in Proposition 2, the following upper bound ex-ista.

Upper Bound of the Sampling Interval:

Au = (20)

(Proof) By Proposition 3, if SV(UQ) > 2gv(uo), there«xiats RV(UQ) such that S^UQ) > 2.RTJ(uo) > 2qv(uQ).The Resolution Preservation Condition (18) is not al-ways satisfied. If both SV(UQ) < 2qv(uo) and (19) aresatisfied, wc have 2qv(uo) > SV(UQ) > 2Rv(uQ), TheResolution Preservation Condition is satisfied in thiscara. Therefore, (20) derived from (19) represents theupper bound of the sampling interval. Q

Thus, 5^(7^0) = 2£/v(i¿o) is the suitable selectionwhen we should minimize the computation cost of theHough Transform satisfying the Resolution Preserva-tion Condition, When we use a constant sampling in-terval for the scanning parameter in the Hough Trans-form, the upper bound of the sampling interval is givenby

(21)

where P denotes the set of all possible valúes for param-eter u. In other words, P denotes the range of definitionof u. The Hmitation of sampling interval given by (21)is the Class-1 Hmitation which was introduced in ourprevíous paper [5].

Fiually in this section, wc introduce a frameworkfor designiíig the Hough Transforms that have desiredprecisión of parameters. Let us discuss the case thatan input image is quantized too fine. Suppose we havean virtual discreto image whose sampling interval isA.s'. The sampling interval As' is assigned a valué thatwc think it small enough for an application of HoughTransform. Obviously, As' > As, where As denotesthe sampling interval of the input image, We introducea design parameter rj(u) defined as rj(u) ~ As/As' here,and we cali the parameter Rdativc Resolution. By (7),the máximum quantization error QV(UQ} is proportionalto the sampling interval of image. Therefore,

£j(iio) = 2y1,(uo)/?/(^o) (22)

is the auitable selection of the Minirmim AcceptableMargin for the virtual discrete image.

Using the above design parameter, wc can obtainthe Hough Transform that has desired precisión of pa-rameters. without converting the original irnage to thereduced image whose sampling interval is As'. TheResolution Preservation Condition (Proposition 2) forthe virtual discrete image is satisfied in this case. Morc-over, if we use As' which is a function of the scanningparameter u, the precisión of parameters in the HoughTransform can be varied according to the angle of aUne. Note that the Resolution Preservation Conditionfor the original image is satisfied only under the condi-tion rj(u) = 1.

3. Noise-Level Shaping for Hough Transform

3A Noise-Level Shaping and Reduction of Computa/-tion Cost

According to the discussions in Sccts. 2.2 and 2.3, theMarginal Gap Gv = mñx(2qvt2Rv) representa the pre-cisión of the Hough Transform, and the width of trans-formation error RV is proportional to the sampling in-terval Au of the scanning parameter -u. These proper-ties make it possible for us to design the Hough Trans-form that has a desired precisión by setting an appro-priate valué to the sampling interval Au. We can alsovary the precisión according to the valué of the scan-ning parameter u arbitrarily by means of changing At¿according to u (See Fig. 5). The shape of the functionR1f(u) can be modified into an arbitrary shape by irreg-ular sampling of the scanning parameter. We cali sucha proccdure "Noiae-level Shaping."

Page 188: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

GOTO and ASO: EFFICIENT HOUGH TRANSFORM BY NOISE-LEVEL SHAPING247

Noise-level Shaping

OO u/4

I 1 1 ! I 1 1 I I I I 1 1 ! I 1 1 I I 1 1 1 1 Regular samplingi ! ! • i í ! i ' i ! i ! i Irregular sampling

Fíg. 5 Quanüzatíon noise and transformation noise in p — &parameterízatíon.

Some other metliods based on the irregular sam-pling havc been proposed [3], [4]. However, we cannotdesign any Hough Transform that has a given precisiónin those methods, because the relationship bctwccn thcsampling interval of the scanning parameter and theprecisión of the other parameter is left out of eonsid-eratíon. The most distinguishing point of Noisc-lcvclShaping from those methods is that the relationship istaken into account.

Wc can also design one of the most, efficient HoughTransform using the Noise-level Shaping technique.This is one of the remarkable advantagc of Noisc-lcvclShaping. The upper bound of the sampling interval Auis derived in the previous section by the analysis of therelationship between the width of transformation errorRU and the máximum quantization error qv- In gen-eral, RV and qv are the functions of u, If we use theupper bound A?/1) as the nonstant sampling intervalAu, and if the shape of the function R^,(u) differs fromthat of 4«(tt), there are some rangcs of thc paramctcru where RV(U) < Qv(u) is satisfied. The parameter uis quantized too fine in such a range of the parameter,because the sampling interval AÍÍ is less than the up-per bound Au given by (20). Note that the precisión ofthe Hough Transform is the same as that in the case ofRV(U) = Qu(u)} even if Rv(u) < qv(u) is satisfied, sincethe Marginal Gap is given by Gv(u) — 2qv(u).

The number of sampling points on a voting curvecan be reduced by increasing thc sampling interval Au.The processing time of voting curve generation will alsobe reduced, because the computation cost is almost pro-portional to the mimber of the sampling points in gen-eral. We can obtain the most efficient Hough TYans-form by shaping thc curve of the function Rv(u) intothe same shape as the function qv(u), because the widthof transformation error Rv(u) is increased and conse-quently Au is increased by the shaping. In other words,WR can obtain the most efficicnt Hough Transform byletting RV(U) — gv(u). The shaping of Rv(u) is per-formed by means of changing the sampling interval Auaccording to the valué of u.

cote)

Fig. 6 A longest Une in the hnage región.

3.2 Hough Transform with p~6 Parameterization

This subscction describes thc details of the Noise-level Shaping for well known Hough Transform withf>~0 pararneterization proponed by Duda and Hart[l].The transformation function for p~9 paramctcrizationis given by

p = x eos 9 H y sin 9 (23)

Let 9 denote the scanning parameter corrcsponding tou, and Ict p denote thc parameter corresponding to v.The range of O is [-7T/4,3;r/4) for the detection of ar-bitrarily oriented lines. The range [7r/4,37r/4) of O cor-responds to the range [-77/4,^/4) of the angle betweenz-axis and a line, because & denotes thc anglc betweenx-axis and the normal of the line.

By (7) and (23), the máximum quantization errorof parameter p is represented by

(24)

For general valúes of 6,is represented by q^Q) =

if 7T/4 < 9 < 3?r/4.(-7r/4.37r/4), the error(As/2) • max(|oostf|, |sintí|). Note that the error ha.sminimimi values at O = ±?r/4 as shown in Fig. 5.

Next, let us show thc width of transformation er-ror RP(Q). Suppose we have a longest line Crossing bothof the left and the ríght side of the image región, be-cause cmax(0)~ cm¿n(£) in (13) is maximized and, conse-quently, RP(Q) is maximized for such a Une, We obtain

f'-max(0) = niax (-xs

= A^As(sin Q-\t 0 eos 0) + p cot OTVAs

(sin2 9 + eos2 Q)+p cot OsmO

^«.L. + / )— -r ~ + P COt & (25)

(See Fig. 6) from (8) if 7r/4 < 0 < 37T/4. In the sameway, we obtain

Page 189: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

248IEICE TRANS. INF. &c SYST.. VOL.E83-D, NO.2 FEBRUARY 2000

= T—~ + pcottfsm&

from (9). Using (13), (25) and (26), we obtaiii

= — • {cjnax(0) - cmín(0)}

(26)

s'mO(27)

For general valúes of #, [-7r/4.37r/4), the width oftransformation error is given by

(28)2max(| cos#|,

Note that Rfl(Q) has máximum valúes at Q = i-7r/4(Fifí. 5).

From (20), (24), (25) and (26), the upper bound ofthe sampling interval is given by the following equatiouas a function of (9.

A0 =

As - siiv2 6 sin2(29)

When we use a constant sampling interval A^T wemust use the inininiuin valué of the right side of theabove equation.

sm i~N

_L2^

(30)

Note that the width of transformation error RP(Q)and the máximum quantization error qp(0) satisficeRP(Q] < dbjr/4. This result in the in-crease of sampling points.

In order to retain the relationship Rp(&) — qf)(&)for any 9, wc must use the variable sampling intervaldefined by (29). The Noise-level Shaping is completedif we use this variable sampling interval.

In general, a regular sampling is easier to handlethan an irregular sampling, For the p-6 parameteriza^tions wc can find an alternativo paramctcr whosc sam-pling interval is constant. Let r = f(9) denote the newscanning parameter, and let Ar denote its samplinginterval. Obvionsly, we have

(31)deIn order to let Ar be a constant here, the gradient ofthe function /(#) ühould be inversely proportional toA^ represented by (29). Such a function f(Q) can bedcrived as follows.

d 8 sin2 O

f(0) = r.¡ cot^ + c2 s d jCarcons t . (32)

Wc obtain f(0) = -cot6, if wc choosc the constants

Ci,C2 so that the range of 6, [7r/4,37r/4), correspondato the range of /(#), [-1,1).

The equation of straight line, (23), can be trans-formed into

7 = x cot O 4- y- -X • f ( 9 ) +

(33)

(34)

íf we introduce a new paramctcr 7 — p/ sin O as a substi-tuto for p, The equation of straight line, (34), becomesequivalent to the equation in a-b parameterization, i.e.

y = ax + b (35)

if we substitute 6 = 7 and a = r for (34). Thus the samercprcscntation as a-b parameterization is obtained byapplying the Noise-level Shaping to the Hough Trans-forin with p-0 parameterization. Therefore, the HoughTransform with a-b parameterization is cxpected to bemore cfficicnt than the transformation with p-0 param-eterization without Noise-level Shaping. We verify inthe next section that the number of thesampling pointsfor scanning parameter a is actually less than that forP-

3.3 Comparing the Numbers of Sampling Points ofScanning Parameters

To begin with, let us show the sampling interval for a-bparameteiization so that we can compare the numbersof sampling points in the Hough TVansforms with p-Qand a-6 parameterization. Let a and í> correspond tou and v respectively at the discussion in Sect. 2. Thetransformation function is given by F^(x, y\) = y — axfrom (35). The range of the parameter a is [—1,1)(See (32)). By (7) and (13), the máximum quantizationerror g¡, and the width of transformation error Rb aregiven by

46 =As

2Aa-¡"

AaT"

(36)

(37)

where Aa denotes the sampling interval of the param-eter a, The upper bound of the sampling interval isAa — 1/N. Since the range of the sampling interval is[-1,1), the number of the sampling points, Na, is givenby

Aa= 27V (38)

On the other hand, the constant sampling intervalfor p-0 parameterization is given by (30). Since therange of the sampling interval AS is ¡Tr/4, 37T/4), the

Page 190: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

GOTO and ASO: EFFICIENT HOUG1T TRANSFORM BY NO1SE-T.EVEL SHAPINC249

1 The sampling intervalfi for various parameterizations.

Máximum sampling interval (A.u)Number of sampling pointa for u (JV^)

Nu/Na (a. - h for referencc)

p-0

1/2N\*N]

~ 1.57

7-0

1/2Wí^^l 1-1.57

Parameterization7-uJ

Aw = 1 (a = 1/N)2N

1

i

a ~ 6 [ a' - d\JN \ 2AT

1*: The range bf 'a' differs from that of a — b.

numbcr of tKe sampling points, Ar$, is given by

(39)

The ratio of the two sampling intervais is N$/Na ~ 1.57and this means the computation cost oí p-9 parameter-ization is greater than that of a-b parameterization by57%.

3,4 Relationship between a-b Parameterization andOther Parametcrizations

Wada et al. pointed out that there is the bias of the votecounts along p-axis in the Hough Transform with p-9parameterization ¡3). They inlroduccd two alternativetransforinations, 7-0 Hough Transform and 7-0; HoughTransform. In those transfomnations, the accumulatorbins are «.rranged appropriately in the parameter spaceso that cvery lines which are prime each other in the dis-crete imagc región should be separatcd. The samplinginterval of the parameter p is adjusled to the apparentsampling interval of the image by varying the samplinginterval p according to the valué of B or uj. In the imple-mentations of those transformations, they did not usethe parameter p whose sampling interval is variable,but they used an alternative parameter 7 whosc sam-pling interval is constant. The transformation functionfor the 7-0 Hough Transform is given by

7= —max(|cos0|,. (40)

The above equation becomcs the same formula as (33)if wc sct the raiige of B to be [ir/4, 3*7 4). In -y-B HoughTransform, (21) provides us with A0 = 1/27V for theupper bound of the sampling interval of the scanningparameter. This upper bound is the same valué as thatof the p-B parameterization givcn by (30). Only thesampling interval of the parameter p scems to nave beenoptimizad in the 7-8 Hough Transform.

7-0; Hough TVansform was derived by straightcningthe voting curve in 7-$ Hough Transformation varyingthe sampling interval of 9 according to the valué of 9.The transformation function for 7-0; Hough Transformis given by

7 = -u/a; + y ,1 3

where o/ = CKUJ ~ 2, — < u < — .Q ¿y

(41)

The parameter a is a constant which determine the an-gular resolution of straight lines, and the parameter wis an integer. The range of the parameter u/ is [—1» 1).where the sampling interval of u}' is constant. There-fore, T in (34) and u>' are the idéntica! paramcters. (34)and (41) are the identical equations, 7-0; Hough Trans-form seems to be the same as the transformation whichis obtaincd through optimization of the sampling inter-val of the scanning parameter in p-Q parameterizationby apply'mg the Noise-level Shaping to the transforma-tion.

Wada et al. pointed out the importance of the anal-ysis of the distribution of votes around pcaks in parain-eter space. They derived 7-0; Hough Transform from7-6 Hough Transform considering t,hat a voting curveand a feature point in image space should have a sim-ple relationship in order to design a precise transforma-tion [3]. They also claimed that the straightcning of thevoting curves has an advantage of speeding up of thevoting. According to the discussion in this paper, -y-tjHough Transform is one of the most emcient transfor-mation theoretically as well as in the practical aspee tmentioned above.

By the way, the angular resolution of straight linesis arbitrary and the parameter a is an arbitrary positiveinteger in 7-0; Hough Transform. Various valúes canbe used as the sampling interval, Au/, of the scanningparameter o/, where a = Au/. However, as described inSect. 2.3, an upper bound of the sampling interval existswhen the Resolution Preservatíon Condition should besatisfied. The upper bound is given by AUJ' = l/N,which is the same as that in a-b parameterization. Inthe same way, the iiumber of the sampling points isgiven by N»< = 2N.

Moreover, 7-cü Hough Transform with a special pa-rameter o = I/TV is known to be identical with theHough TVansform with a-d parameterization which wasproposcd by Svalbe [3], [G]. Thus, the transformationwith a-d parameterization is one of the most emcientone theoretically as well.

The upper bounds of the sampling intervals andthe numbers of the sampling points in various parame-terizations are Usted in Table 1. The anfíle between astraight Une and x-axis is assumed to be in the range[-•7r/4,7r/4). The numbers of the sampling points inthe table must be doublcd when we consider straightUnes of arbitrary orientation.

Page 191: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

'¿50IEICE TKA.NM. INF. & SYST.. VOL.E83- I), NO/¿ PEBRUARY 2<KK)

4. Conclusión

TKis paper has dosoribed the relationsliip hetweeu theprodsion of parnrtietcrs and the efficient sampling inter-val of thfi scannuig paramctcr for the general formula ofthe Hough Transform for straight Une detección. Theformula is nevcr limited to p-0 paraineterizatioii. Theriwe have shown that the level of the transformat.ion noisein the Hough Transform can be dmiiged arbitrarily byvarying the sampling iulerval of the Huaiuiiiig paratno-ter according to the valué of the parameter. \Ve haveproposed a design mothod callee! "Noise-lcvel Shaping,"which was desigiied to shape f.he level oí tbc transfor-mation Tioise.

If we assurne that Ihe Hough Transform shouldhave enough precisión as the natural quant.izatiori errorof a Hiscrete image, tho well kriown Hough Transformwirh a-b parameterization is derived by applying theNoise-level Sbaping t,o the Hough Transform with p-típararntíterization. Wc have verified that tho a-h param-elerization i.s one of the most. eñicient representa!; ion ofthe Hough Transform for stniight Une detection. Tlincomputation cost. for the conven ti orí al p-ti parameteri-zation ÍH grealer than that of the a-h parameterizatiouby 57%.

7-w Hough lYaiiaform proptise<l by Wadaet al. andthe Hough Transforní with a-d parameterization pro-pt)se<l by Svalve are idéntica! with the Hough Traiiüformwith a-h parameterization. and they are the most effi-eient transíoriiiations HS well. Therefore. such a parain-eterizaUon Is more suitable than p-$ paraineterizatioTí,for a¡)plieatioiiK whirh are free from regular sampling ofangíc 0.

In the exaxii[)le of the Noise-level Shaping iri thispaper, we pmforretl ?j(u) — 1 for t.he Relativc Rcso-lution of image. Wheii an image iy quantiztxl by toosmall sampling intcrval, or wheu we want to vary theprecisión of parameters accorriing lo the angle of aline, wc can use any Relativc Rfisolution which satis-fies r/(u) < 1, and we will be ab!c to obtain the effi-cient Hough Transform without having any resolution-rcduced image. Koshitnir/n et al. proposed a frameworkcalled "Extended Hough Transform (EHT)[4].n Usingthe framework, we can desigrí various Hough Trans-forrns wbich have the required sensitivity of Une detec-tion. by chuosing tlic fineness of resolution for the an-gular parameter and the fineness of resolution for thepositional parameter arbitrarily. If we use Noisc-levelShaping with the frarnework of EHT, we <:an design var-ious types of Extended Hough Transform which guar-antee the precisión of parametera as well as the finenes»of resolution. Further inveatigations into the optimizartiou of parameterizations are nccdcrí for various ftgurcsbeskles straight linna.

Referen ees

[1] U.O- Duda and P.K. Hart, "Use uf the Hough tmnsformft-lion to Hptftrt linew and curves in pirtures," Commun. ACM,vol.15, no.l, pp.11-15, 1972.

['2] '!'. Kushiniizu íuid M. Ni imada, "On a fast Hough Tranaformmethod P1,HT hased on pú'co-wisc linear Hnngh fnnrtinn."1E1CE Trans., vnU72-D-II, mi.l, pp.5G-05, Jan. 1989.

[3] T. Wada, T. Fujii, and T. Matsuyama, "T-CJ HoughTransform Linearizing voting curves in an imbiaüud p-Q pa-rameter üpuce," IE1CK 'iVans., vol.,I75-D-II, rio.l, pp.21-3U,Jan. 1992.

[4] T- Koshimizn and M. Nuinatla. llOn t.he extensivo rct:on-strurtinn of Hough Transform," Proc. Third Int. Cunf. unComputer Vision, pp.740 74?t, 1990.

[5] H. Goto and H. Aso, "On the cfKcient sampling interval ofthe parmneter in Hough Transfomi," I K I C K 'IVana., vol.JSl-Ü-ll, no.'l, pp.6í)7-70fí, April 199H.

[6] 1.1). Svalhc. "Natural reprpsentations for straigtit lines uruithe Hough transform on discreto urruys." IKKK 'IVans. Pat-

U-rn Anal. & Mach. IntolL, val.U, nn.9, pp.941-950, Scpt.1989.

Hideaki Goto received the B.Sc. de-gTi:<! in physirs in 1990, the M.Sc. dtígret-

in physirs ÍTI 1992 and the Ph-D. degree ininforrnatíon enginctiring in 1995 from To-

hoku Uuivcrsity in .lapan. He was an Aa-sistunt Profesor at Faculty üf Enginw'r-

ingt Tohoku University iu 199G, and hasbeen H» Assiatant rrolessor at the íxi-

ucation Cent or for Information Proccsa-ing, Tohoku Umvfírííit.y since 1996. His re-scarcli interests include image recognition,

aad dornment image analysis and recognition. He is a member üfthe; ínformution Processing Society of Japan and IEBE Cuinpulcr

Society.

Hirotumo Aso r«.-civccl his B.E.,M.E., ;wid Ph.J). dcf^rcca from Tohnk»Uuiv^rsity, ñendai, Japan tn 1968, 1970

and 1974, respective!y. He was willi the

Department of Information Engineering,Tohoku UiiiverKit.y in 1973. He joinedtht: Faeiilty of Enginecring, Nagoya XJni-

versity from 1979 to 198(í. He is nuw aProfessoT of Tohüku llniversity. He en-gaged in risearch in the fields of learn-irig aiid adaptive autómata, rpllnlar au-

. thftory of coticurrent i>rograms a:id parallel proccssing,of systolic algorithms, devclopmtMit of iiiaractt?r n:eogiú-

tion systcm, and speech recognition. He has rect:ived the YoungEnginoer Award of 1E1CEJ in 1978 and the Achievement Awarü

of IEICK.I in 1992. Dr. Aso is a rnembcr of IEEE, ACM, EATCS,the Information Processing Society of .Tapan, Japáñese Society

for Artificial Intelligenoe, Japáñese Cognitive Sriencc Society and

LA,

Page 192: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Systems and Computers in Japan, Vol. 29, No. 11,Transíala! from Denstó Joho Tsushin Gakkai Ronbuhshi, Vol J81 -D-Q, No. 4, Apfil 1998. pp. 697-705

The Efficient Sampling Interval of the Scanning Parameter inthe Hough Ttansform

Hideaki Goto

Educación Center for Information Processing, Tohoku University, Sendaí, Japan 980-8576

Hirotomo Aso

Gradúate School of Engineering, Tohoku University, Sendai, Japan 980-8578

SUMMARY

It is well known that in the Hough transform, thesampling interval of the scanning parameler influences thevote distribución around the peak in parameter space. De-creas ing the sampling interval to improve the precisión ofparameters ulereases the computación cost, and this oftenbecomes a major problem in applications ustng Houghtransform. A standard that guáranteos the practica! preci-sión of parameters is required for the sampling interval.

In chis paper, wc first define two types of noise: thetran&formation noise, causea by the Hough transform, andthe quantization noise, caused by the quantízatíon of theimage. We investígate their distribución. A condición isderived that the transformación noise must satisfy under theassumption that sufficient image resolución must be re-tained, and wc introduce a method for dcriving the upperbound of the sampling interval. €> 1998 ScripCa Technica,Syst Comp Jpn, 29(11): 9-19,1998

K«y words: Hough transform; saropling interval;transformación noise; quantization noise.

1. Introduction

In general, in an irnplementation of the standardHough transform on a compuCer, we first define a transfor-mación function that gives the valué of one of the parame-ters, and then all of the other parameters for the figure areobtained by scanning all of the other parameters with dis-crete numbers for every feature point (such as edge points)on the figure. Each number in the defined domain of theparameter should be substítuted for every parameter to bescanned, which wehenceforth cali the scanning parameters.Smaller sampüng intervals are desirable for the scanningparameters so as to reduce the parameter errors. However,decreasing the sampling intervals results in an mercase inmemory usage and compuCation cost In order to obtain auseñil and efficient implementation of the Hough trans-form, we required a standard for each of the samplingintervals that is appropriate for the required or expectedprecisión of the parameter.

In the Hough transform, votes are accumulated intocelis arranged in the parameter space, and the strength ofthe parameter—that is, the likelihood of the parameter—ismeasurcd by the number of votes al the cell correspondingto the local máximum of the votes. It is known that in theHough transform, the votes are often distributed in cellsaround a local máximum, even for an ideal inpuC, such as aline defined by continuous parameters. This property is

CCC0882-1666/98/110009-11© 1998 ScripCa Technica

Page 193: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

¡trongly related to the parameterization (the choice of theDararaetcrs), the parameter sampling intervals, and the ar-rangement of cells in the parameter space.

Svalbe analyzed the distribution of the angle and thedensity of straight Unes, each of which connects any twopoints on a grid in a discrete image space. He íntroducedthe Hough transfonn with a-d pararaeterization, in whichthe ñneness of the angle betwecn straight lines ís fíxed [I].Wáda and colleagues proposed the y-ct> Hough transform,in which the accumulalor cells are specially arranged so Chatany pair of prime straight lines in a discrete image spacecan be separated [2]. However, only those straight lines thetangents of whose angles are rational numbers were consid-ered in the a-d parameterization, and the distribution of theparameter y was not taken into account in the y-to Houghtransform when the angle O oí a. straight line differed fromihat of the sampling point 0¿. Morimoto and coworkersanalyzed the quantization errors in the Hough transform bythe p-B parameterization, which had been presented byDuda and Hart [31, and designed a 2D variable filter forprecise Hough transforms that accoun ted for the error of theangular parameter O [4]. No bounds on the parameters werederíved theoretically in their work; however, they suggestedthat there is a standard of the sampling interval of O througherror analysis. Van Veen and coworkers anatyzed the p-6parameterization, estimated the width of the distribution ofthe parameter p for a straight line in a discrete image, andderíved a condition that the sampling interval of 6 shouldsatisfy [5]-

Errors are added to the coordínales and to the parame-ters by quantization of the image and by the Hough trans-form, In this paper» we analyze these errors by treating themas noise. We derive an upper bound on a scanning parame-ter. This fbrraulation gives us the general condition, freefrom p-6 parameterization.

In section 2 of this paper, we propose a method fordcriving the upper bounds on the sampling intervals ofparameters for general figures having 2-dimensional pa-rameters. In section 3, we give upper bounds on the Houghtransforms for straight line detection by two well-knownparameterizations (a-b and p-ff) as examples.

2. Errors in the Hough Transform and inthe Sampling Intervals

2.1. Deflnltíon of the discrete image regiónand the Hough transform

An image Ís treated as a set of pixels in a limitedregión on a computer. In this paper, the limited región isdefined to be a square of a certaín size in 2-dimensionalEuclidean space, and we cali the región the "continuous

image región." We assume that each edge of the squareregión is paraüel to the *-axis or to the v-axis. The pixelinterval is As (measured in units of length). Thus, thecoordínales (x, y) of each point on a continuous figure in acontinuous image región are quantized and the point isnepresented by a pixel whose center is at the discrete posi-tion (x, y) given by the following equations:

x ~ (i)

L _/is the floor operator, thus Lz7 denotes the máximuminteger that is less than or equal to z. As denotes thesampling interval for image quantization, and we caliSx = x - x and <5y = y - y the quantization errors. Obviously,\5x\ As/2 and \8y\ As/2 are always satisfied.

Assume that the length of each edge of the squarecontinuous image región is given by 2WAí, where N is apositive integer. Here, the number of pixels along each ofthe edges is (2N + 1). A discrete image región is defined asthe set of all sampling points whose coordínales are quan -tizcd and that are in a continuous image región.

In this paper, we discuss continuous figures, definedby continuous functions with various parameters. We calithe quantized versión of a continuous figure the discretefigure. Let í2 be a subset of 2-dimensional Euclidean spacethat we cali the parameter space. We use («, v) to representan element of í2. A continuous figure with parameters («,v) is defined as a set of points (x, y) satisfying

F(x,y;u,u) =0 (2)

using F(xt y; ut v), which is a continuous function of fourvariables. In this paper, we use only continuous functionsthat satisfy the following condition.

Condition: When a set of x, y, u Ís given, only onevalué of v is defined by Eq. (2).

Let v = Fv(x, y,«) denote the parameter v that satisfies theabove condition, then we cali Fv tbe transformation func-tion. We also use the vector representations ?= (i, v) and~p- (u, v) to write the coordínales and the parameters,respectively.

Defínitíon 1 When the transformation function Fw

is a linear function of x and y, the discrete Une (or simplythe line) having parameters (u^ VQ) is the discrete figuredefined by the following notation:

(3)

where Jt2 is the range of defmition, denoting the range ofthe placement of straight lines in a subset of the continuousimage región.

10

Page 194: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

The following transformation functions are oftenu sed to define discrete lines:

(4)a — 6 panuneterization

I 6 = Fb(x,yta)-y-ax

p — parameterization." p = F0 (x, y; 0) ~ x eos O + ?/ sin 9

(5)

Detecting the discrete lines in a given discrete image regiónis the, same as obtaining the parameters (u^ v0) for the litie.Consider the continuo u s sampling points on a continuousfigure. If the angle between the x-axís and the tangentialline in a local región of the continuous figure is in the range[-TI /4, rc/4), let the continuous sampling points be definedas the intersection of the figure and the straight linex = t • AJ (t is an integer) that is parallel to the y-axis.Otherwise, let the continuous sampling points be defined asthe intersection of the figure and the straight Une y = t • As(t is an integer) that is parallel to the .x-axis. Let (*/, y¡)represen! the i-th continuous sampling point, and let(x¡, pf) denote its quantized valué. Note that one of thequantization errors (<$x¡ = 5,- - x¡ which is parallel to theje-axis or ¿y, = >V - ,yí which is parallel to the .y-axis) isalways zero for one discrete sampling point. "Hiat is, bothof the errors cannot be non-zero at the same time.

A figure is reprcsented only by the set of discretesampling points ((xh y,) l¿ = 1,2,..., nJ; the parametersfor the figure are unknown. The standard procedure forfigure detection by the Hough transform is summarized asfollows. Let u denote the scanning parameter, let uk denotethe A-th sampling point of «, and let Au denote the samplinginterval of u. In the same way, vm denotes the m-th samplingpoint of v, and Av denotes the sampling interval of v. First,we puf an accumulator ceü(kt m), which holds the votes, oneach of the sampling points (uh v^ in the parameter space.For every point (xh pj) on the discrete figure and for every

/VCÍí, yt\O is calculated. The quantized valué ofgiven by vm(= Lv^/Av 4- \/2j - Av). By varying i and fc,

votes are accumulated at the corresponding ceü(k, m}. FÍ-nally, & local máximum of tbe votes (shown as the peak Ain Fig. 1) is foimd among me cclls. The estimated parame-

ters for the figure are given by the corresponding coordí-nales (u*, vj in the parameter space.

2.2. Analyzlng the errors in the Houghtransform

The votes are distributed around the point of the trucparameters (MQ, v0) in a butterfly shape as shown by themesh in Fig. 1* in the Hough transform. The estirnatedvalúes of the parameters, which correspond to the coordí-nales of the local máxima, are expected to be the quantizedvalúes of the truc parameter («o, v0). Leí Su = u* - "o andóv = vffl - v0 denote the errors of the parameters.

Since u is the scanning parameter in the two parame-ters, we will be able to find the valué of u whose error iswilhin the quantization error

Au2 (6)

if we use a precise peak detectíon method. In the followingdíscussion, we assumc that the estunated valué of u is givenby uh satisfying Eq. (6).

kJvl, the absolute error of the parameter v, cannot bemade smaller simply by decreasing the sampling intervalAv. The coordínales ( ,y¡) that are substituted for thetransformation function include an error of at most ±As/2,which comes from image quantization. The parameter uk

also includes an error of al most ±Áu/2. In general, vrt isaífected by these errors through the transformation func-tion. Let 5vk - vtt - V0 be the difference (of the error) be-tween v¡¿ and the true parameter VQ. In order to makeI5vl = lvm - 1 smaller in the Hough transform, láv/l, theabsolute valué of the error of non-quantized valué vü inparameter space, musí be made smaller. We mainly discussthís non-quantized error in this paper.

For the case that óxt = O, the error Sv¡ is given by

(7)^Vi ; tío)

Rg. L Transformation error in the Hough transform.

If we apply the Taylor expansión around x = (xh y¡) and setu = UQ in the first term on the ríght side of the above cquationweobtain

*Here, we havc selected the scanning parameter so that the anglc betweenthe voting curve and the axis of the scanning parameter gets smaller ínvoting curve genentíon. If we switch the scanning parameter, we maydivide eacb range of definiüon of the parametcr at the voting curvegeneration; the dúcussion in this paper is applicablc to that case as wcll.

11

Page 195: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

dFv

(8)

The first term on therightsideof thisequaíionreprcscnts theerror produced by quantization of the image. We cali this errorthe quantization error and write it as EQ (x¿ UQ; Sy¿. Thesecond term represents the error that springs frotn quantizationof the scanning parameter in the Hough transfbrnx We cali itthe transformation error and write it as Ej- (x¿ UQ, Su). Wecali the sum of the fírst and the second term the approxi-mated total error and write it as ¿vf. Moreover, we cali Óv¡the total error. If we assume that the terms of second degreeand ábove in óu and Óy¡ are small enough, the error of v isgjvenby

Equations (8) and (9) denote the errors for only a singlesampling point (x^y,-). If wc consider all the samplingpoinls aJong the Une or if we consider moving a point alongthe line the approximated total errors Sv^ are distríbutedaround v = v0 in the parameter space. Each of the quantiza-tion errors and the transformation errors also has a sort ofais tribu tion, according to the change in i. Considering thedistribuüons as probability distributions, we can regard theerrors as noise that comes from the probability distribu-tions. We use NQ and NT to represent these kinds of noiseand cali them quantization noise and transformation noise,respectivcly. A real distribution of votes at u = ük (thequantized valué of u¿) is expected to have the same distri-bution as a random variable Vy, where

VT = VQ -f NQ + NT (10)

When we design a system that requires the Hough trans-form, we often try to make the máximum valué of errorssmaller or to make the average valué of errors smaller. Hete,we give a defínition for the máximum absolute valúes ofthe quantization errors and thosc for the transformationerrors when (r¿, y/) takes various valúes. A máximum quan-tization error, which is denoted by qv or gv(u^t is dcfincdto be the máximum absolute valué of the quantization errorsEg(*¿ «o'. £>/)• Fron* Eq- (g) a™1 fyfr * ^ w« obtainNote that \NQ\ qv is always satlsñecL

As—2 (H)

The máximum transformation error, which is denotedby ev or s¿u& Su), is defined to be the máximum absolute

valué of the transformation errors ET (?/; MQ; <5i¿). From Eq.(8), we obtain

- \6u\)

where

du

Note that \Nj\ EV is always satisñed.

23. Dtstribution of votes and discriminatíonconditkm of parameter

BFv/c)y in the quantization error f^?,; UQ; ¿y() is aconstant because Fv is a linear function of y (See Eq. (8)).Therefore, the distribution of the quantization noise NQ

follows that of the quantization error ¿jy. It is known that6y f oUows a discrete distribution for the sampling of imageswith a squaregrid if the tangent of the angle between jc-axisand a straight line is a rational number. It is also known thatSy follows a continuous, uniform distribution for an infí-nitely long line if the tangent is an irrational number. Wecan treat the distribution of the quantization error ¿y as acontinuous and uniform distribution in the range [-$„ q^[4]. Therefore, the probability distribution of the quantiza-tion noise NQ is represented by the probability distributionfunction Oír, UQ) defined by the following equation.

otherwise (13)

where z denotes a valué determincd by NQ.In general, dFy/du in the transformation error

ET (*t\ is a function of the coordínales x and y. IfFv is a linear function of x, thcn dFv/du is also representedby a linear function of x. Thus the valúes of 5F/3u for everypoint (x, y) on a certain line are distributed from the míni-mum to the máximum valué. We assume that the transfor-mation errors ET (J¿; WQ; Su) - (3F,/dK) - Óu also have auniform distribution. The vaíidity of this assumption can beconfirmed by experiment (see Fig. 3). Let ej and e? denotethe máximum and the mínimum valúes of the transforma-tion error, respectively. The noise NT is distributed in therange between s¿ and ej. We introduce

c")

6u) = - (15)

12

Page 196: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

and a randora variable AV-i>wt me probability distri-bution ftinction D(z; MO» <5W) defined by the foUowing equa-tion:

O otherwise (16)

Here, t denotes a valué given by ty^. We haveNT = Nj-.tyn 4 Voff and, henee, the observed valué VT is givenby

~ «o 4 u o r 4- NQ 4- NT-*V (17)

Q*D

Fig. 2. Distribution of quantization noise andtransfonnation noise.

Ws cali tile ¿?v the width of transformation error, v^ denotesthe offset of the error distribution. We introduce somenotation al chis point.

= max

= min

=St ,U=liQ(18)

(19)

We obtain equations £+ = max{(5uand e~ = nan[Óu • C^UQ), <5u • C and then

and

Cml,i(tio)}

(20)

(21)

are satisfied. From Eq. (12), we also have

c(u<>) = maxdcmM^)). |coün(t*o)l} (22)

and

= \voff\)

The distribution of VT is represented by the distribution ofthe sum of the two noises NQ, NT. If the model of the figureis a straight Une, the following propositíon holds.

Propositíon 1 In the Hough transform, the shape ofthe distribution of VT is a trapezoid. The length of the upperbase of the trapezoid is given by 2\qv - Rv\> and the positionof the center of the upper base is given by v0 4 v^ In thespecial case of gv = RVÍ the shape of the distribution be-comes a triangle, and the position of the top of the triangle

It is known that in the Hough transform with p-Qparameterization, the real distribution of the votes gives atrapezoid shape [6]. We examined the Hough transformwith a-b parameterization for straight Une detectors. Weused many discrete Unes synthesized by a computen, andexamined the shapes of the transfonnation errors, the quan-tization errors, and the total errors for the parameter b.Figure 3 shows the results. The une segment that gives mesedistributions is one that passes through the center of theimage. The length of the segment along the jc-axis is 254(the number of sampling points), and the inclination is a$ =74.5/127. TTie samph'ng interval of the parameter a is Aa =1/127, and the width of each class is 1/20. The result showsthat each of the distributions gives a rectangular shape, andthe distribution of votes gives a trapezoid shape for a realdiscrete Une.

Next, we derive conditions for the discriminaron ofthe two parameters v = vj and v = v^ with the parameter ufíxed to ü = i/o L0* us introduce two paraJíel and cióse Unes

5 10 15

(a) Ttansfonnatton (b) QuantizationEiror Error

O 5 10 15 O 5 10 15

(c) Composite Error

Flg. 3. An example of the real distribution of íhe errorof parameter b. (OQ = 74.5/127. ak = 74/127)

13

Page 197: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

defined by parameters (MQ, v\) and (u& vz). Their lengthsalong the *-axis* are the same. From Eq. (17), the distribu-tions of votes in the parameter space for these Unes followthe two distributions:

VT = vi + voff +NQ (24)

(25)

The shapes of these distributions are the same; only theposiüons of their centers differ. The real distribuüon ofvotes is given by the sum of the two distributions, and thefollowing propositíon holds.

Proposítioo 2 When we have two Unes with theparameters (1*0, V|) and (MQ, 1*2), the shape of the distribuüonof the votes is represented by the sum of the two trapezoide,and we have the following properties, where we defineGv = max(2?v, 2RV).

(1) The two trapezoids can be separated and twoparameters Vj + v^ and v2 + v<í^caa be obtained ifIvj - v2\ Gr

(2) The two trapezoids cannot be separated iflvi - Vjl £ GV, and then we can obtain only one parameter(vi + Vz)/2 + v,,

Proof The votes corresponding to v¡ have trape-zoid shape, as shown in Fíg. 2, if Rv S qv is satisfied. If wehave another set of votes whosecenter is just 2^vaway fromthe center of the previous trapezoid, the sum of the heightsin the overlapped región is the same as the height atv = vj + v^f, and all the votes form a large trapezoid. (SeeFig. 4.) The two parameters vj + v^ and v-¿ + v^cannotbediscnminated in this case. If the distance between the twotrapezoids of votes is greater than 2flv, that is, iflv| - v2f > 2qv is satisfied, we can find a depression in theoverlapping región, and v\ v^ and Vj + v^ can be dis-cnminated. (See Fíg. 4.) For the case Kv > q^ we obtain thesame coadition Ivi - v2l > 2RV as above by interchangingRv and qr D

Cv in the above proposition denotes the marginaldifference between two parameters for v by means of whichVi and v2 are distinguished in the parameter space. We caliGv the marginal gap.

A continuóos Une (figure) moves according to thechange in parameter v. Let dr denote the difference in theposition of the figure (measured along v-axis*) whcn theparameter v is varied by dv (Fig. 5). Assuming that both df

and dv are very small, the equatíon

(26)

(counU)

Fig. 4. Relation between peak distance and the width oftransformation error.

which is derived from the transformation function Fy, issatisfied Two continuóos Unes cannot be distinguished ina discretc image if they are placed with a gap smaller thanthe sampling interval Ar. Therefore, two discreto Unes thatare distinguishable should be separated by at least Ar, andthe difference of parameters is at least

•As =(27)

dv ^ Ov musí be satisfied if the difference is to be detectedby the Hough transform. Therefore, the foUowing proposi-tion holds.

Propositíon 3 When two Unes with the same pa-rameter Uo are distinguishable in a discrete image, thefoUowing inequality must be satisfied if the Unes are to bedistinguishable in parameter space.

(28)

Proof A Une that is separated from another Une byAi has parameter v with a difference dv ~1qv from that of

*ThÍB U m tbe ca« ihal the angle between the Itncs and jt-axis is in therange [-ff/4, ff/4).

Image space Parameter space

Fig. 5. Relation between peak distance and imageresolution.

14

Page 198: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

the other Une in the parameter space. If qv < R^ we getdv=2qv< 2RV = max(2^, 2RV) = Gv. According to Propo-sition 2, the dífference 4, cannot be detected in this casebecause d, is smalier than the marginal gap, D

We cali the inequality in Eq. (28) the condition ofimage resolution preservation.

2.4. Sampling íntervals

Equation (12) shows that the transformation errordepends on the sampung interval AM. In respect of process-ing speed, the larger valué is desirable for Aw. However,larger valúes of Aw will result in greatcr errors during theprocess. We discuss the selection of a suitable samplinginterval Au here.

Introduce the mínimum acceptable margin S^u) todenote me mínimum valué of the difference of parametersto be distinguished in parameter space. The followingproposition holds when we use S¿u) as a design parameter.

Proposition 4 If both S^WQ) S 2¿?v(uo) andAw 5 E7«p(Sy(uo)' "o) are satisfied for two discrete linesdefíned by (UQ, v¡) and (UQ, Vj), two parameters, v, and v2,that satisfy - v2l > Sv(«o) can be detected as V] + voff andv2 + vaff* respectively, where

25.(29)

Proof By the definition of Rv and Eq. (20), weobtain tbe following tnequalities.

- Cm|D(tlo)}\ÓU\y Sv(wo) £ Gv = max(2^ 2tfv) is also den ved.

Thus, the above proposition is proved with Proposition 2nAccording to Proposition I, the parameter VQ + voffis

obtained ínstead of the truc parameter v0 in the Houghtransform. In other words, the error v^ is added to theparameter. In determining the limits of sampling intervals,initially we try to keep the absolute error Iv^f below or equalto an upper bound given by the máximum acceptable errorHV If wv is given as tbe design parameter, the followingproposition holds.

Propositíon 5 Iv^Sw, is satisfied ifUQ), where

Proof The result can be obtained using\5u\ Au/2, which is shown as Eq. (6), and using voff,definedbyEq.(21). Q

Next, we try to keep the absolute valué of the trans-formation error below or equal to the upper bound given bythe máximum acceptable error wr The following proposi-tion holds.

Proposition 6 \N¿£wv is satisfied ifUM(*V> «o).

(31)

The total error satisfies \NQ+NT\ qv + wr

Proof We obtain \Nj\ wv from Eqs. (6) and (12)using the conditioa in the proposition. a

The following two propositions hold for Umi]n UoS>and C/^ shown in Propositions 4,5, and 6, respectively.

Proposition 7(a) U^w» 1*0) £ U^w^ «o).(b) USép(S^ no) S U^w» «o) if Sv S 2Wv.(c) ty K, «p>, t/«p (SVt «o)» and Ü^Jy»^ «o) are

al! monotone íncreasing to wv and Sv.Proposition 8 AM S C/^Wv, MO) and Aw ^ C/J<p

(5v,uo) are satísfied if both A«S Í/^M/^HO) and SVZ2wv are satisfied.

Thus, lv<£t is below or equal to wv if the absolute valuéof the transformation error is set below or equal to themáximum acceptable error HV Moreover, we should set themínimum acceptable margin 5V to a valué greater thanmax(2wv 2^v) "^ **<* ^ «re to be distinguishable inthe parameter space when the difference of the parameter vis greater than S^

We DOW discuss selection of the máximum acceptableerror wv and the mínimum acceptable margin 5r Accordingto Proposition 4, Sv — 2^v(uo) is desirable for parameter «oso that the condition of image resolution preservation issatisfied Consídering that all the Unes with various parame-ters are to be detected in a discrete image, and consideringthat the parameter u takcs various valúes among the unes,we have the following upper bound of the sampling intervalfrom Proposition 4:

(32)

AH Au(1) should be satisfied for the sampung interval A».We cali this condition Class-1 limitation.

According to Qass-1 limitation, RV(UQ,ÓU} <qr(u0)is satisfied for arbitrary UQ, and henee the condition of imageresolution preservation is also satisfied However, there is

15

Page 199: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

no limitation for the offset v^ of the error distribution. Thisis because there is no definite relationship between^off(wv) M*d t/«p(5v) in general cases. Here, the folkywingproposition holds.

Propositíon 9 If Aw satisfies the condition of ímageresolution preservation, and if the condition c^u^) £ O^ C«U(«Q) is satisfied for arbitrary UQ, then we have therelatíonship lv^ á ?v(«o)-

Proof By the conditions in Proposition 9, we obtain

tíon is proved using Eqs. (6) and (21), and the Class-1limitación. a

To select the máximum acceptable error w^ weshould consider 5V = 2q^u¿t which gives the condition ofimage resolution preservation, and we should use the con-dición in Proposition 8. The relationship ¿^"o) **V isderived from the condition £v¿2wr Therefore,H'u = V(«Q) 's &£ bcst f°r me máximum acceptable error, sothat the sampling interval Au becomes as small as possible.Similarly to Class- 1 limitation, an upper bound of samplinginterval derived from the condition ín Proposition 8 is givenby

= min Un (33)

considering that all the Unes should be detected.Au £ Aw12* is a condition to be satisfied, which is called theClass-2 limitation. If we use the sampling interval thatsatisfies this limitation, the condition of image resolutionpreservation is satisfied (Proposition 4 and 7), andIv^ £ 4/Uo) is also satisfied for arbitrary UQ (Propositions5 and 7).

Class-1 and Class-2 limitations are derived naturallyfrom the sampling interval based on the assumption that weobtain sufficient resolution of the image. In particular, theClass-2 limitation includcs not only the requirement forimage resolution but also the requirement to determine themáximum transfbrmation error. Therefore, me Class-2limitation gives more severe conditions man the Class- 1limitation. Class-1 limitation is sufficient only to detect allthe unes. If we need the precise parameter for each line, weshould use the Class-2 limitation.

Fínally, we discuss the best sampling interval Av forthe parameter v. We use the mínimum acceptable marginSv as the design parameter. It is given as a limit for theseparan' on of v in a parameter space so that the two pararne-ters (Vi and v¿) wifl be separated if their difíerence is greaterthan Sy. On the other hand, Av á Sv is required for thesuitable selectíon of 5V and the sampling interval because adifference that is less than or equal to Av cannot be detectedin a parameter space quantized by Av. We found in cheprevious discussion that Sv = 2^(uo) for every MQ is the bestselection to satisfy the condition of image resolution pres-

general case that the parameter u of a line in the image isunknown.

3. Some Examples of the Limitation of theSampling Interval

3.1. Hough transform with a-bpáramete rizatíon

We first describe the example of the limitation ofsampling interval in the Hough transform with a-b para-meterization. Let a and b correspond to u and v, respec-ávely, in the discussion in section 2. The transformationfünctíon is given by F&(JC, y; a) = y - ax as Eq. (4). We use[-1, 1) as the range of the parameter a. We haveqb(a) = Ar/2, c^afa) = max^-*), and c^a) = min ,<-*,)for the line segment defined by the parameter a. Therefore,we obtain c^^a) - c^á) = lx and c(a) = ma^Lc^, wherelx denotes the difference between the Jt-coordinates of thetwo ends of the íine segment. The valué corresponds to thelength of the line segment raeasured along ¿-axis.

Let Aa denotes the sampling parameter of a. Class-1limitation and Class-2 limitation are given as the following:

Class-1: 2As

I,, in the above inequality is a design parameter that weprovide whcn we construct a system using the Houghtransform. We must use the length of the longest linesegment in the image región for ¡x instead of the length ofthe segment detected. This is because the condition ofimage resolution preservation would no longer be satisfiedif the image contains an unexpected line segment whoselength is greater than lx or if the sum of the lengths of someline segments on the same line is greater than /,. If the imageregión ts square, we have the condition Aa £ \/N as thesampling interval, using I, = 2A/As, which is the same as thelength of an edge of the región:

Class-2:AJÍ

max(|z£|) max(|i¿|)

ervation. Therefore, Av £ min,,. is required in the

If the image región is a square centered at the origin, themáximum valué of IxJ is N&s. Substituting the valué for meabove inequality, we have Aa £ 1/M This means that therange of the parameter a, defined by [-1, 1), raust bepartítioned into 2N equal parts. This limitation agrees withthe Oass-1 limitation. However, if the origin of the coordí-nate system is not on the center of the image, we must usethe smaller sampling mterval Aa under the Class-2 limita-tion. Even in this case, we have the same sampling interval

16

Page 200: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

A¿i as in the previous case under the Oass-1 limilation.However, the precisión of the parameter is not alwaysguaranteed because the Class-1 limitaüon does not dependon the coordinates directly. Therefore, when it is requiredfor a system to obtain precise parameters, we should firsttransíate the coordínate system so that its origin comes tothe center of the image región and then apply the Houghtransform to the transíated image. Rnally, we transíate thecoordínate system inversély back to the original positionafter finding the parameters of the lines. As a result, theupper bound of the sampling interval under the Class-1limitaüon equais that under the Class-2 limilation, and theprecisión of the parameters is guaranteed.

Ws have no approximation in the a-b parameteriza-tion. Therefore, it is obvious that <5v,- = ¿vf1 is satisfied. Thetransformaüon error ís in the rangc ±Aj/2, and the totalerror is in the range ±Ás,

On the other hand, in the Hough transform by a-dpararneterization introduced by Svalbe [1], the transforma-tion function Ís written as

2ox TV-I2 (34)

where a is an integer and the angle between a Une and thejc-axis is in the range [-jc/4, re/4], W in the above functionis defíned for an image región with tfxff pixels. If we useN* which is used in this paper, we have N* = 2N+lt and dcan be represented as

(36)

From Eqs. (18) and (19), if n/4$e<n/2, we havecosfl and cmi¿8) = -jwsintf

, where xnfccí y^ x^, and y, denote the máxi-mum and the mínimum valúes of the coordínales x, y ofdiscrete samplíng points on the same Une. In the same way,we can calcúlate c^JíO) and (0) for n/2 $0< ln/4. Asa result, we have c^B) - cmht(G) = l^inO + ly\cosO\rn/4£6<3n/4 (general case). Here, ^x^-x^ and^ = y*tax ~~ ímúr MoreovcT, if the Icngtfi of a Une segment ís/, we have lx = ¿sin0 and ly - /cos0, and then, c^Q) -Cmin(fy = l is obtained. We can obtain c(0) =

Thís equaüonshows that c(ff) depends on the position of the origin of thecoordínate system.

2qp(Q) has the mínimum valué 2As/^]2 atO- jr/4.On the other hand, if the image región is square, the length/ of the Une has the máximum valué 2V2tf Ai al the samevalué of 0. Henee, by the Class-1 limilalion, the upperbound of the sampling interval is

A0(n = min 12N (37)

If the image región is square and if the origin of thecoordínate system is on the center of the región, the sameupper bound is obtained as the following by Class-2 limi-tation:

ax~Ñ (35)

e above equaüon is in the range [-], 1], which ispartitíoned into 2N equal pazts. Therefore, the upper boundof the sampling interval Aa derived using the Class-2 limi-taüon is the same valué as the sampling interval in a-dparameterization.

3.2. Hoagh transform witb p-6parameterization

We now obtain a suitable sampling interval in theHough transform with p~Q parameterization. The transfor-mation function is given by Ffl(x, y,&}~ xcosB +ysín^ asEq. (5). Let O and p corrcspond to u and v, respectively, inthe discussions in sections 2.2 to 2.4. The angle betweenthe r-axis and a une is in the range [-K/4, n/4) in tbosesections. 6 denotes the angle between the x-axis and thenormal to a line. Therefore, & is defined in the range of

c(&) (38)

The máximum quantiration error q? is given by

Wc omit the dctails of the calculation for want of space.ThuB, if the origin of the coordínate system is not on thecenter of the image región, the coordínate system should betranslated as desoibed in section 3.1.

Ib find the sampling interval by using the Class-2limitaüon, if we omit the effect of the approximation in Eq.(9), the transformation error of v is in the range ±qv\,the approximated total error ¿vf is in the range ±2^ How-ever, there is a possibility that the total error will exceed therange ±2^ due to the effect of approximation in Eq. (9).We examined the effect of approximation by a numérica!simuiation in which the real errors in the Hough transformwere evaluated. We used 10,000 Une segments whose pa-rameters (po, OQ) were uniformly distributed random realnumbers. The origin of the coordínate system was placedon the center of the image región. As a result, from a verysmall Lmage (# = 7) to a largeimage (Af= 511), we foundno Une segmení whose total error exceeded ±2?^ It hasbeen confirraed in the p-6 parameterization that the total

17

Page 201: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

error can be held within the range ±2qp under the upperbound conditíon given by Eq. (38) for the sampling interval.

Van Veen and others denved the boundary betweenthe oversampling and subsampling of the quantization ofparameter space [5]. The boundary is given by

Ap ~ I • sin (T) (39)

where / denotes the length of the longest line segments andAp denotes the sampling interval of the parameter p. If bpis given, the above equation gives the condition that A#must satisfy. The equation is thought to be a kind of Class-1limitation, because the length of the line segment is used asa parameter. Assuming that A0 is very smaU, A0 can becalctilated by substituting A/> into Á0 = lApIl. Using theupper bound on Ap given at the end of section 2.4, weobtain Ap aminas 0*3,74 2^(0) = A$/V2~. The lengthof the longest line segment in the square image región isgiven by / = 2V2Jv*Aj. From that, we obtain A0 = 1 /2N.This sampling interval is the same as that derived in thispaper.

The equation given by Van Vcen represents the con-dition for the optímum sampling interval A¿? under theassumpüon that the parameter p is quantized. In contrast,we have here derived the upper bounds for Ap and A0 onlyfrom the condition of image rcsolution preservatíon. Thismeans that these upper bounds are denved from moreessentíal conditions to guarantee precisión of parameters.

4. Conclusions

In this paper, we revea! that there is an upper boundon the sampling interval of the scanning parameter in theHough transform by an analysis of general Unes that have2-dimensional parameters. We also derive a method fordctermining the upper bound. The upper bound of thesampling interval is given by Eqs. (32) or (33).

We have derived the upper bounds of the samplingintervals for the two parameterizations (a-b and p-6) thatare often used for Une detection, considering the quantiza-

tion errors produced by quantization of the image. Thesampling interval for the a-b parameterization agrees withÜiat proposed by Svalbe. The condition for the samplinginterval in the p-Q parameterization also agrees with thecondition derived by Van Veen and others. We have made itclear that these prcviously proposed conditions also guar-antee the precisión of the Hough transform.

We analyzed the errors in the real Hough transformby numérica! simulation. The result showed that the máxi-mum absolute valué of the total error is precisely limited tothe given upper bound by the condition given by Eq. (38).

One of our future objectives is to ñnd a generalformulation for the conditions on the sampling intervals forfigures defined by three- or higher-dimensional parameters.

REFERENCES

1. I.D. Svalbe. Natural representations for straight linesand the Hough transform on discrete arrays. IEEETrans. P.A.M.I., PAMI-11, No. 9, pp. 941-950(1989).

2. T. Wada, M. Seki, and T. Matsuyama. High precisióny-ctí Hough transform algorithm to detect arbitrarydigital lines. Trans. I.E.I.C.E. (D-H), J77, No. 3, pp,529-539 (March 1994). (in Japancse)

3. R.O. Duda and RE. Hart Use of the Hough transfor-mation to detect lines and curves in pictures. Com-mun. ACM, 15, No. 1, pp. 11-15 (1972).

4. M. Morimoto, T. Shakunaga, S. Akamatsu, and Y.Suenaga. A high-resolution Hough transform usingvariable filter. Trans. I.E.I.C.E, (D-fl), J75, No. 9, pp.1548-1556 (SepL 1992). (in Japanese)

5. TM. Van Veen and F.CA. Groen. Discretizatíon er-rors in the Hough transform. Pattem Recognición, 14,pp. 137-145(1981).

6. M.MorimotoandY.Suenaga.Ahigh-resolutionvari-ablc Hough transform using LoG variable fílten Vari-able filter desígn based on the frequency analysis ofthe Hough space. Trans. I.E.LC.E. (D-II), J77, No.11, pp. 2160-2170 (Nov. 1994). (in Japanese)

18

Page 202: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

AUTHORS (from left to right)

Hideaki Goto received his B.S. degree in physics in 1990, his M.S. degree in physics in 1992, and his Ph-D, degree ininfbrmation engineering in 1995 from Tohoku University in Japan. He became an assistant professor on the Faculty ofEngineering, Tohoku University, in 1995 and has been an assistant professor al the Education Center for Information Processing,Tohoku University, since 1996. His research interests include ¡mage recognition and document image anaiysis and recognition.He is a member of the Information Processing Society of Japan.

Hirotomo Aso received his B.£.,M.E.,andPh.D.degrees from Tohoku University, Sendai, Japan in 1968,1970 and 1974,respectively. He joined the Department of Information Engineering, Tohoku University, in 1973. He was on the Faculty ofEngineering, Nagoya University, frora J979 to 1986. He is now a professor at Tbhofcu University. He has engaged in researchin the ñelds of leanúng and adaptive autómata, cellular autómata, theory of concurren! programs and parallel processing, theoryof systolic algorithms, development of character recognition systetn, and speech recognition. Hereceived the Young EngineerAward of LEJLC.EJ. in 1978 and thc Achievement Award of I.E.I.C.E.J. in 1992. Dr. Aso is a member of IEEE, ACM, EATCS,the Information Processing Society of Japan, the Japanese Society for Artificial Intclligcnce, thc Japanese Cognitive ScienceSociety, and LA.

19

Page 203: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Proc. of the European Confereuce on Computer Vision, pages 263-272, 1996.

Decomposition of the Hough Transform: CurveDetection with Efflcient Error Propagation

Clark F. Olson

Department of Computer Science, Cornell University, Ithaca, NY 14853, USA

Abstract. This paper describes techniques to perform fast and accuratecurve detection using a variant of the Hough transform. We show thatthe Hough transform can be decomposed into small subproblems thatexamine only a subset of the parameter space. Each subproblem consideraonly those curves that pass through some small subset of the data potnts.This property allows the efficient implemeritation of the Hough transformwith respect to both time and space, and allows the careful propagationof the effects of localization error in the delection procesa. The use ofrandomization. yields an Ofn) worst-case compulational complexity fortlüs method, where n is the number of data points, if we are only requiredto find curves that are sign.ifi.cant with respect to the complexity of thedata. In addition, this method requires little memory and can be easilyparallelized.

1 Introduction

The Ilough transform is a method to detect parameterized models (e.g. curvesand surfaces) in data by mapping data features into manifolds in the parameterspace [3, 5]. The models are detected by locating peaks in the parameter space(which is typically performed usiag multi-dimensional histograming). In thispaper, we consider metíiods to improve curve detection by decomposing theÍTough transform into many small subproblems. We use randomization to limitthe number of subproblems that we must examine and we carefully propágatethe effects of localization eiror in the subproblems that we do examine. Whilewe concéntrate on curve detection, similar Hough transform techniques can beapplied to surface detection and a number of other problems.

We willuse amodified versión of the formal definition of the Hough transformgiven by Princen et al. [6]. Let X = ( z , y) be a point in ttte image space, Q =(uji, ...,0;^) be a point in an ,/V-dimensional parameter space, and f(X,íí) = Obe the function that parameterizes the set of curves. We willcall the set of datapoints £ = {Xi,...,Xn}'

Standard Hough transform imple me ntations discretize the parameter spaceand maintain a counter for each cell. The counters record the number of datapoints that map to a manifold that intersects each of the cells, In the errorlesscase, each data point maps to an ;V ~ 1 dimensional manifold in the parameterspace. Princen et ai denote a cell in parameter space centered at í? by C/j. Theydefine:

Page 204: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

> if íyl : KX>A) = 0} n Cfl ?¿ 0, otherwise

Thus,p(A", í?) is 1 ifany curve in the parameter space cell, Cn, passes throughthe point, A", in the image. If we assume that there is no localization error, theIlough transform can then be written:

//(.<?) is now the number of data points that any curve in Cn passes through.In an ideal system, the discretization of ihe parameter space would not be im-portant. Instead, we should consider the error in the localization of the iniagepoints. Let's assume that the true location of each data poiut lies within abouuded región, NX, of the determined location, A'. We can redefine p(X,Q] asfollows;

PÍA' í?) =J O, otherwise

Now, p(A",í?) is 1 if the curve represented by í? passes through NX- Withthis definition we can still use (1) to describe the Llough transform. This yields,for each curve, the number of data points that the curve passes through upto the localization error. Since discretization of the parameter space will not beimportantfor the techniques that we present here, we will use the new definition.

2 Mapping Point Sets into the Parameter Space

A technique that has been recently introduced [1, 2, 4, 7] maps point sets ratherthat single points into the parameter space. Rather than considering each pointseparately, this method considers point sets of some cardinality, k. For eachsuch set, the curves that pass through each point in the set (or their errorboundaries) are determined and the parameter space is incremented accordingly.The benefit of this technique is that each mapping is to a smaller subset of theparameter space. If the curve has N parameters, then, in the errorless case, Nnon-degenerate data points map to a finite set of points in the parameter space.For the curves we examine here, this will be a single point. We thus need toincrement only one bin in the parameter space for each set, rather than thebins covering an N — I dimensional manifoldfor each point. Of course, we don'tneed to use sets of size N, we could use any siae, fc > 0. If fe < N, each non-degenerate set maps to an N — k dimensional manifold in the parameter space.The disadvantage to methods that map point sets into the parameter space isthat there are (£) sets of image pixels with cardinality k to be considered.

An examination of how the technique of mapping point sets into the param-eter space is related to the standard Ilough transform is informative. Let's labelthe Oough transform technique that maps sets of k points into the parameter

Page 205: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

space l!k(Q). An image curve (a point in the parameter space) now gets a voteonly if it passes within the error boundary of each point in the set, so we have:

where (jji) is the set of all fc-subsets of the data points, €.Consider this function at an arbitrary point in the parameter space. For sonie

set of data points, {X3l , ..., Xgk}, the product, p(XSl , Q] • ... • p(X9k , Í2), will be1 if and only if each of the p(A', J?) terms is 1 and otherwise it will be 0. íf thereare x points such that p(X, í?) is 1 fthese are the points that lie on Ü up to thelocalization error), then there are (¿) sets with cardinality k that contribute 1to the sum. /Yfc(i?) will thus be (£). Since the standard Ilough transform willyield //(í?) = x in this case, we can express Hk(Q] simply in terms of //(í?):

If the standard TIough transform uses threshold t > k to find peaks and themethod of mapping point sets into the parameter space uses threshold (¿), thescmethods will find the same set of peaks according to the above analysis. Theiraccuracy is thus the sanie.

3 Decomposition into Subproblems

Let us now introduce a new technique, where we map only those point setsinto the parameter space that share some set of j distinguished points, 1> ={Xdí,...,Xd}}. We will still vary k — j data points, Q = {Xgi,...,Xgk_í}y inthese sets. The point sets we are mapping into parameter space are thus 1) \jQ.This yields:

Consider this function at an arbitrary point in the parameter space. Sincewe aren't varying the distinguished points, { X ¿ l , . . . J X d J } í the curve must passthrough the error boundary of each of these to yield a non-zero response. If xpoints lie on a curve and we use a set of j of distinguished points on the curve,then x — j of these points remain in £\D. We thus have:

(^ O, otherwise

We should thus use a threshold of (¿~^) in this case if the standard Iloughtransform used a threshold of i. We would then find those curves that are foundby the standard Ilough transform that pass through the distinguished points

Page 206: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

up to the localization error. We can formúlate algorithms to recognize arbitrarycurves by considering several subproblems, each of which examines a particularset of distinguished points, as above. A deterministic algorithm using these ideaswouid consider each possible set of distinguished points. This would guaranteethat we would examine a correct set of distinguished points for each curve. Ifwe are willing to allow a small probability of failure, we can use randomizationto considerably reduce the number of sets of distinguished points that we mustexamine (see Section 5).

To gain the máximum decomposition of the problem, we want j, the numberof distinguished points, to be as large as possible, but note that if we choosej > k, we will havc //^^(í?) = O or 1 for all Ü. Our response will be 1 if J?goes through the j points and otherwise O, but it yields no other information.We thus want to nave j < k. In addition, we want h < N or else we will examinesets that are larger than necessary. The optimal choice is thus j = k — I ~ N — 1.

Note that considering sets of N data points that vary in only one point (i.e.when j = it - 1 = N - 1) constrains the transform to lie on a I-dimensionalmanifoid (a curve) in the parameter space. This can easily be seen since we haveN variables (the curve parameters) and the N—l distinguished points yield N — lequations in them. Let's cali this curve the Ilough. curve. When localizationerror is considered, the transform will no longer be constrained to He on theIlough curve, but the transform points will remain cióse to this curve. This yieldstwo useful properties. First, since the Ilough curve is essentially I-dimensional,it is much easier to search than the full parameter space. Second, it is nowmuch easier to propágate localization error carefully. This will be accomplishedby determining tight bounds on the range that a set of points can map to inparameter space.

4 Error Propagation

Let's now examine how to propágate the localization error in the curve detectionprocess. We will first consider how error would be propagated in the ideal case.Each set of points maps to a subset of the parameter space under given errorconditions. This subset consists of the curves that pass through the set of pointsup to the error entena. Cali this subset of the parameter space the error cloudof the set of points. Ideally, we would determine how many error clouds intersectat each point of the parameter space. This would tell us, for any curve, howmany of the points the curve passes through up to the localizaron error. We donot do this since it is not practical, but for the subproblems we now examine,we can efficiently compute a good approximation.

Since the Ilough curve is one-dimensional in the noiseless case, we can pa~rameterize it in a single variable, t. Consider the projection of the error cloudsonto the í-axis (see below for examples). The number of such projected errorclouds that intersect at some point in this projection yields a bound on thenumber of error clouds that intersect on a corresponding hypersurface in the fullspace. Furthermore, since the error clouds do not vary far from the Ilough curve,

Page 207: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Fig. 1. For any two points. we can determine bounds on the range of 6 by consideringlines tha,t pass through the boundaries of their possible localization error.

this yields a good approximation to th.e máximum number of intersecting errorclouds, which is the Information we want.

Once we have projected each of the sets that we consider in some subproblemonto the í-axis, we can find the peaks along the Ilough curve in one of twoways. We could simply discretize t and perform voting by incrementing the binscoosistent with each range in í that an error cloud projects to. This discretizationcan be done finely since it is only in one dimensión. Alternatively, we could sortthe minimaland maximalí points of each error cloud and use asweep algorithm.This method would examine the extremal points in sorted order and keep acounter that is incremented each time we hit a minimal point and decrementedeach time we hit an máxima! point. If the counter reaches a large enough valué,then a line has been found which passes through (or cióse to) many points.

The followingsubsections describe how we can parameterize the Ilough curveiu í for the cases of lines and circles, and how we can project the error cloud forthe point sets onto the f-axis for each case.

4.1 Lines

If we use the p-0 parameterization for lines (i.e. xcosO + ysia.0 -=. p), we cansimply parameterize the Elough curve by O, since p is a function of 0. To projectthe error cloud for a pair of points onto the 0-axis, we simply determine theminimal and máxima! O that a pair of points can yield. If we use square errorboundaries, we need only consider the corners of the squares in determiningthese minimal and máxima! O valúes. See Fig. 1.

4.2 Circics

We can parameterize the space of circles by the coordinates of the center of thecircle and the radius, so there are three parameters: (xc,yc,r). For this case,the optimal decomposition will use j — N — 1 = 2 distinguished points. We canparameterize the Hough curve by the distance of the center of the circle from themidpoint of the two distinguished points (which we will take to be positive whenthe center is to the right of the segment connecting the distinguished points, andnegative otherwise).

Page 208: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Fig. 2. We can determine bounds on the position of the center of a circle passingthrough 3 points (up to localization error) by examining the range of possible perpen-dicular bisectors for the segments between the points.

To project the error cloud onto the ¿-axis, we now waut to determine errorbounds on this distance given three points and their localization error bound-aries. Recall that the center of the circle passing through three points is the pointwhere the perpendicular bisectors of the segments between the points meet. Wecan thus determine bounds on the location of the center of the circle by examin-ing the set of points in which two of the perpendicular bisectors of the segmentscan meet (see Fig. 2). The mínimum and máximum distance from the center ofthe circle to the midpoint of the distinguished points can easily be determinedby examining the extremal points of this set.

5 Computational Complexity

This section determines the computational complexity of the techniques de-scribed in this paper. Let's first determine how many of the sets of distinguishedpoints we must examine to maintain a low rate of failure. We'll assume thatwe only need to find curves that comprise some fraction, f , of the total numberof data points. The probability that a single set of j random points lie on aparticular such curve is then at least:

since we must have (ej*) sets of distinguished points that He on the curve amongthe (£) possible sets of distinguished points. K we take. i such triáis, the proba-bility that all of them will fail for a particular curve is no more than:

For each curve, we thus have a probability no larger than p that we will failto examine a set of distinguished points that is a subset of the curve in / triáis.

Page 209: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Since conservativo peak finding techniques are used, we can assume that any trialexamining a correct set of distinguished points will lead to the identificaron ofthe curve.

We can now choose an arbitrarily small probability of failure, 6, and deter-mine the number of triáis necessary to guarantee this accuracy:

(i-eJV <6Solving for í yields:

t> lnó l n*Por each trial. we now have to find the peaks on the Ilough curve. Recall

that we use j = N - 1 in our method to facilitate the propagation of error. If weuse voting, the time is dependent on how finely the Ilough curve is discretized.íf there are a bins, we need to increment O(a) bins per trial per point, yieldingO(na) time per trial. The total time requirement is thus O( nffi3 ) or simplyO(n) when measured by the size of the input (a, St e, and N are constants).

If we use the sweep algorithm, we must sort the O(n) maximal and minimalpoints of the error clouds, requiring G(nlogn) time per trial. Processing thesorted points requires O(n) time. We thus require Q("'°y_l°ff¿) total time orO(n logn) when measured by the size of the input.

6 Results

These techniques have been applied to real images to test their efficacy. Figure 3shows au image that was used to test the line detection techniques. The edgeswere determined to sub-pixel accuracy. For tests on this image, square errorboundaries were used such that the true location of each point was assumed tobe within 0.25 pixels of the measured location in both x and y. When a largethreshold was used (e = 0.01), all of the long Unes were found in the image,but short or curving lines were not found. When a lower threshold was used(c — 0.004), even short lines were found in the image.

Figure 4 shows an image that was used to test the circle detection techniques.This image is an engineering drawing that has been scanned. For this reason,it was not possible to determine the location of pixels to sub-pixel accuracy. Inaddition, the presence of small and dashed circles and the clutter in the imagemake this a difficult test case. While all of the large circles were found withe = 0.04, the small and dashed circles did not comprise a large enough fractionoí the image to be found. With e — .008, the implementation finds severa! ofcircles, some of which are not perceptually obvious. Note that in each of theinsalient circles, the pixels found overlay most of the perimeter of a circle andthus if we want to find small and/or broken circles it is difficult to rule out thesecircles without using additional information. In addition, the implementation hasdifficulty finding both of the dashed circles with the same center since they areso cióse together and are imperfect circles. The dashed circles shown in Fig. 4(c)consist of the top half of one of the circles and the bottom half of the other.

Page 210: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Fig. 3. A test image forline detection. (a) The original image. (b) The edges detected.(c) The unes found with e = .01. (d) The Unes found with € = ,004.

7 Ellipses and Other High-Order Curves

When applying these techniques to curves with severa! degrees of freedom, wemust take special care, since the number of triáis that are required can becomelarge. Let's consider the detection of ellipses, which have five parameters. If theimage is sparse or we can segment the image, then we should have no prob-lems. For example, if we only need to detect ellipses that comprise 50% of theimage pixels (or sonie subset after segmentaron), then the number of triáis re-quired to achieve 99% accuracy is 74. On the other hand, if we wish to detectellipses that comprise at least 10% of the image pixels using these techniques ina straightforward manner, then this would require 46,052 triáis to achieve 99%accuracy.

When we wish to detect high-order curves in complex images there are ad-ditional techniques that we can use in order to perform curve detection quickly.One simple technique is to use more information at each curve pixel. For exam-ple, we can use the orientation of the curve at each pixel (as determined ftomthe gradient, the curve normal, or the tangent). When we do this, we requirefewer curve points to determine the position of the curve. We can determine the

Page 211: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

LI2S

(b)

Fíg. 4. A test image for circle deteclion. (a) The original engineering drawing. (b) Thecircles found with e = 0.04. (c) Perceptually salient óreles found with e = 0.008. (d)Insalient areles found with c = 0.008.

position of aa ellipse using three points with orientations rather than uve uuori-ented poiats. We would thus use two, rather than four, distinguished points, andwe would require many fewer triáis to ensure that there is a low probabülty ofnot selecting a correct set of distinguished points. Of course, we do not need torestrict this technique to high-order curves. We can use two oriented points todetermine the position of a circle, rather than the three unoriented points usedin the previous sections.

An altérnate technique that can detect high-order curves quickly is to use atwo-step technique, where we first determine a subset of the curve parametersand then determine the remaining parameters. For examine, Yuen ei al. [8]describe a method for detecting ellipse centers. They note that the center of anellipse must lie on the Une connecting the intersection of the tangents of twopoiuts on the ellipse with the midpoint of the segment between the two points.A point of intersection between several such lines yields a likely ellipse center.We can use decomposition techniques similar to those already described in thispaper when this method is used to detect ellipse centers. Once the center of theellipse has been detected, there are three remaining ellipse parameters. These canbe detected using a three parameter Ilough transforní similar to the detection

Page 212: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

of áreles.

8 Summary

We have considered efficient techniques to perform the Ilough transform withcareful propagation of localization error. To this end, we have modified a formaldefimtion of the Etoiígh transform to allow localization error to be analyzedappropriately. We then considered a new method where the Ilough transformis decomposed into severa! subproblems, each of which examines a subset ofthe parameter space, by considering only those point sets that include somcset of distinguished points. These subproblems allow us, first, to propágate thelocalization error efficiently and accurately in the parameter space, and second,to use randomization techniques to reduce the complexity while maintaining alow probability of missing an important curve. The overall complexity of theresulting algorithrn is O(n), where n is the number of data points in the image-Finally, we have given resulta of this system detecting, straight Unes and cueles incluttered and noisy real images and discussed the application of these techniquesto curves with se ver al parameters.

References

1. J. R. Bergen and H. Shvaytser. A probabiüstic algorithrn for computing Houghtransforma. Journal of Algorithms, 12:639-656, 1991.

2. A. Califano, R. M. Bolle, and R. W. Taylor. Generalizad neighborhoods: A newapproach to complex parameter feature extraction. In Proceedings of the IEEEConference on Computer Vision and Pattern Recognition, pages 192-199, 1989.

3. J. lllingworth and J. Kittler. A survey of the Hough transform. Computer Vision,Graphics, and Image Processing, 44:87-116, 1988.

4. V. F. Leavers. The dynamic generalized Hough transform: Its relationship to theprobaVüistic Hough transierais and an apphcation to the concurrent detection ofcircles and ellipses. CVGIP: Image Understanding, 56(3):381-398, November 1992.

5. V. F. Leavers. Which Hough transform? CVGIP: Image (/mfcríían<fmff,58(2):250-264, September 1993.

6. J. Princen, J. lllingworth, and J. Kittler. A formal deünition of the Hough trans-form: Properties and relationships. Journal of Mathematicai Imaging and Vision,1:153-168, 1992.

7. 1, Xu, E. Oja, and P. Kultanen. A new curve detection method: Randomized Houghtransform (RHT). Pattern Recognition Letters, 11:331-338, May 1990.

8. H. K. Yuen, J. lllingworth, and J. Kittler. Detecting partially occluded eUipsesusing the Hough transform. Image and Vision Computing, 7(l):31-37, 1989,

This article was processed using the UT^ macro package with ECCV'96 style

Page 213: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Accepted for publication in Computer Vision and Image Understanding as of 31 July 1998.

Constrained Hough Transforms for Curve Detection

Clark F. OlsonJet Propulsión Laboratory, California Institute of Technology

Mail Stop 107-102, 4800 Oak Grove Drive, Pasadena, CA, 91109http://robotics.jpl.nasa.gOV/people/olson/h.omepage.html

Abstract

This paper describes techniques to perform fast and accurate curve detection using constrained Houghtransforma, in which localization error can be propagated efficiently into the parameter space, We firstreview a formal definition of Hough transform and modify it to allow the formal treatment localiza-tion error. We then analyze current Hough transform techniques with, respect to this definition. It isshown that the Hough transform can be subdivided into many small subproblema without a decreasein performance, where each. subproblem is conatrained to consider only those curves that pass throughsome subset of the edge pixels up t;o the localization error. This property allows us to accurately andeíficiently propágate localization error into the parameter space such that curves are detected robustlywithout finding false positives. The use of randomization techniques yields an algorithm with a worst-case complexity of O(n), where « is the number of edge pixels in the image, if we are only required to findcurves that are sígnificant with respect to the complexity of the image. Experiments are discussed thatindícate that this method is superior to previous techniques for performing curve detection and resultsare given showing the detection of lines and circles in real images.

1 Introduction

The Hough transform is a method to detect parameterized curves in images by mapping image edge pixelsinto manifolds in the parameter space [13, 9]. The parameters that are consistent with many of the manifoldscorrespond to curves in the image and thus methods that find peaks in the parameter space can be used todetect the image curves. For example, we may parameterize lines by their slope and intercept (y = mx + b).Each edge pixel, (x,y), in the image is mapped into the line b = —im 4- y in the parameter space (m x b),corresponding to all of the lines that pass through (a:,y).

The peaks in the parameter space are typically found using a multi-dimensional histogramming procedure,where each manifold votes for the cells of the histogram that it passes through. The cells of the histogramthat receive many votes are taken to indícate curves in the image. Unfortunately, this technique does nottake into account the localization and discretization errors that are present in the image edge pixels. Whiletechniques have been proposed to deal with these errors, they have not been fully satisfactory in both robustlylocating noisy curves and eliminating false positives from consideration. In addition, many of these Houghtransform techniques have been very expensive, in terms of both computation and memory requirements.

In this paper, we consider techniques to improve the efficiency and accuracy of curve detection using theHough transform. The key úisight that enables the design of an improved algorithm is that the curve detectionproblem can be subdivided into many small subproblems that can be examined independently without areduction in the curve detection performance. This decomposition of the problem allows the localizationerror in the image features to be efficiently propagated into the parameter space, and the additional use ofrandomization yields a robust algorithm for curve detection that requires linear time in the number of imageedge pixels.

We first discuss previous work on the Hough transform for curve detection and review a formal definitionof the Hough transform given by Princen et al. [32]. This definition assumes that a histogramming method

Page 214: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

is used to perform peak detection, and is not dircctly applicable to methods that propágate the localizationerror accurately. We give a modification to this definition that allows the formal treatment of the efFects oflocalization error in the Hough transform.

We then consider a technique where sets of pixels, rather than single pixels, are mapped into the parameterspace. In this technique, the set of curves that, are consistent with small subsets of image edge pixels aredetermined, and the parameter space peaks are accumulated accordingly. Variants of this method can befound in raany papers, for example [2, 5, 9, 20, 23, 48]. Our analysis shows that this technique, by itself, doesnot change the accuracy with which curves that surpass some arbitrary threshold are found, assuming thata perfect peak finding method is used, since peaks due to random accumulation form in the parameter spacewith the same freque-ncy as when individual pixels are used. Furthermore, unless additional hexiristics areuscd, the running time of the method is exponential in the number of curve parameters (as is the standardHough transform1).

We next show that subproblems of the curve detection problem can be considered that are constrainedto examine only those sets of image edge pixels that share some distinguished set of pixels of some fixedsizc j. This method is adapted from recent work on object recognition [7, 28], and also has been used in alimited form for curve detection [20, 24]. Each such subproblem corresponds to examining only the curvesthat pass through the distinguished set of pixels (up to the localization error). If we examine each possibíesubproblem, we suffer no loss in curve detection performance.

Randomization can be used to limit the number of subproblems that need to be examined while main-taiiüng a low probabüity of fallure. Unlike previous uses of randomization in the Hough transform, wherethe image edge pixels are randomly sampled in some manner during the accumulation process, this doesnot reduce the detection performance for any particular subproblem. We still examine all of the edge pixelsin each of the subproblems. The only reduction in performance is that there exists a small probability,which can be set arbitrarily low, that no subproblem will be examined that uses a distinguished set of pixelsbelonging to a curve present in the image. This distinction is important. Many Hough transform methodsthat have incorporated randomization examine a subset of the possibíe features or a subset of the possibíefeature combinations when accumulating scores in the parameter space. This not only causes curves in theimage to be missed, but also causes false positives to be detected, since only an approximation of the Houghtransform is computed. Our technique does not suffer from these problems.

The examination of these subproblems not only allows an effective use of randomization, but it also allowsthe efficient propagation of the localization errors into the parameter space and makes the paraHelizationof these techniques simple. We consider the propagation of localization error in detall for the cases ofstraight Unes and circles and we analyze the expected accumulation of votes due to random combinations ofpixels. These techniques are compared with previous Hough transform methods with respect to detectionperformance, both theoretically and empirically, and the new techniques are shown to be a signincantimprovement over previous methods.

The computational complexity of the algorithm is O(n) (or O(nlogn) depending on the method usedto detect peaks) when randomization is used to limit the number of subproblems that must be examined.Results are given demonstrating the detection of Unes and circles in real images. We then discuss theapplication of these techniques to higher-order curves such as ellipses. Finally, the contributions of this workare summarized. An appendix is included that describes parameterLzations for some interesting curves andgives methods to solve for the parameters of each from the minimal amount of information.

2 Related work

The Hough transfonn was introduced in a U.S. patent in 1962 [13] and was initially used to lócate particletracks in bubble-chamber imagery. It was brought to the attention of the computer visión community by

1The base of the exponentiai is the number of bina per dimensión in the accumulator method for the standard Houghtransfonn method, while it is the number of image edge pixels for the techniques where pixel sets are mapped into the parameterspace.

Page 215: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

image windows.Bergen and Shvaytser [2] give a theoretical analysis of the use of randomization techniques to speed up the

Hough transform, although no implementation is described. They consider both mapping individual pixelsand mapping sets of pixels into the parameter space. Their method achieves a computational complexityindependent of the number of edge pixels in the image, but with two caveats. First, only curves that representsome predetermirxed fraction of the total number of edge pixels are found. Second, the method is allowedto be in error by a fractional parameter all of the time and by greater than this fractionai parameter withsome small frequency. The practicality of this method is questionable, since the constant number of randomsamples that must be examined is often very large. In fact, this number may often be larger than the numberof different samples that are possible.

Kiryati et al. [19] use randomization to improve the running time of the standard Hough transform.They simply subsample the edge pixels in the image and proceed with the standard algorithm. Theiranalysis implies that the computational requirements of the Hough transform can be improved, while theperformance is degraded little.

Califano and Bolle [5] use a múltiple window parameter transform to exploit long distance informationin the extraction of parameterized objects from image data. Lateral inhibition is used in a connectionist-likeframework to improve the accuracy. In addition, a radius of coherence is defined for each pixel to reduce thecomputation time required by the method.

Leavers [20] describes a technique called the dynamic generalized Hough transform. She uses the techniqueof mapping N image pixels into a single point in the parameter space and, furthermore, in each iterationselecta a single image pixel to constrain the transform, which must be present in each of the sets of pixels thatare mapped into the parameter space. We propose a similar technique in this paper, in which the problem isdivided into subproblems where the pixel sets that are mapped into the parameter space must share N — 1image pixels and demónstrate that this is superior to using a single pixel to constrain the transform. Leaversuses a storage eíEcient voting mechanism in a discretized parameter space, where the votes are projected ontoeach of the parameter space axes and severa! one-dimensional accumulators are kept. While this method ofaccumulating votes reduces that amount of memory that is required, it may exacérbate the problem of falsealarms if the votes in the parameter space are not sparse.

Finally, we note that an additional technique that has proven useful in the efficient implementation ofHough transform techniques is a multi-resolution or coarse-to-fine search of the parameter space to findpeaks [1, 3, 16, 22, 29, 31]. For example, Li et al. [22] recursively divide the parameter space in hypercubesin a coarse-to-fine hierarchy. At each level of the hierarchy, only those hypercubes that receive enough votesto surpass some threshold are passed on to the next level for examination.

3 The Hough transform

Except where noted, we will consider each edge pixel to located at the point at the center of the image pixelin which it lies, with an insignificant extent. The discretization error inherent in this formalism is treated incombination with localization error below. We note, though, that this focmalism is not necessary, and thetechniques that are described here apply equally well to arbitrary sets of points.

Princen et al [32] have given a formal definition of the Hough transform that, with some modification,will prove useful in our analysis. Let X = (x,y) be a point in image space, O = (wi, ...,u)yv) be a point inthe parameter space, and f ( X , íí) = O be the function that parameterizes the set of curves. The set of edgepixels in the image, £ = [Xi,.., Xn}, is represented by the sum of the delta functions at the pixel's locations:

*>> (1)

Princen et al. use Cn to denote a cell in the parameter space centered at O. Examining such cells allowsthe consideration of a discretized parameter space. They define:

Page 216: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

O otherwise

So, p(-X\) is 1 if any curve in the parameter space cell, Cn, passes through the point, X, in image space.The Hough transform can be written:

= í p ( X , ü ] I ( X ) d X (3)

or

,n) (4)

is thus the number of image pixels that any curve in <7n passes through. This definition is correct forthe accumulator method that is typically used to implement the Hough transforra. Such methods discretizethe parameter space into cells and maintain a counter for each cell. These counters record the number ofedge pixels that map to a manifold in the parameter space that intersects the cell. However, the performanceof such methods is less than optimal for two reasons. First, this assumes that there is no localization errorin the edge pixels. When localixation error is present, the cell corresponding to the position of the curvemay not receive a vote for various pixels that belong to the curve. Second, a single bin may receive votesfrom múltiple edge pixels that cannot lie on the same Une, even when localization error is considered. Itis implicitly assumed that, the bins are large enough to catch the votes for the curves of interest, yet smallenough not to catch a large number of votes from false positive curves.

In this work, we discuss a method that solves the first problem and greatly reduces the second, througha decomposition of the problem into constrained subproblems and propagation of the íocalization error intothe parameter space in each of the subproblems. We thus prefer a definition that does not incorpórate adiscretization of the parameter space, but that does take into account the propagation of the localizationerror into the parameter space. Let's assume that the true location of each edge pixel lies within somebounded región, NX, of the determined location X. We can redefine p(X, Q) as follows:

1 tfí^ = /^n) = o}n^?É* ,.}o otherwise (o)

Now, p(X^ O) is 1 if the curve represented by O passes through NX- With this definition we can stül useEqs. (3) and (4) to describe the Hough transform and we achieve our goal of accounting for the propagationof error, without úicorporating a discretized parameter space. To be fully general, we could further modifythis defimtion such that p(X, íí) was a coritinuously-valued function as in [30, 33, 43]. However, this requiresus to assume a model for the image noise and localization error, at least implicitly, rather than just an upperbound on the allowable localization error.

In this definition, the Hough transform is continuous in the parameter apace. This gives us freedomin considering methods by which the peaks in the parameter space are found. We are not bound to theaccumulator method. We are also not constrained to use the same localization error boundary, NX , for eachpoint. If we have information as to the relative quality of the localization of the edge points, it can be usedhere.

Note that it is possible to propágate the localization error into the parameter space in the accumulatormethod for impleraenting the Hough transform by determining, for each image edge pixel, precisely whichcells in the quantized parameter space contain the parameters of a curve the passes within the bounded errorregión of the pixel and incrementing the counters accordingly. This method has been proposed by Shapiro[38]. Unfortunately, this process is computationally expensive and addresses only the first of the problemadiscussed above.

Page 217: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

4 Mapping pixel sets into the parameter space

Let us now consider the technique of mapping sets of pixels into the parameter space. Rather than consideringeach pixel separately, this method considers the sets of pixels with some cardinality k. For each such set, thecurves that pass through every pixel in the set (or through the bounded error región of every pixel in the set)are determined and the parameter space scores accumulate accordingly. The primary benefit of using thistechnique is that, each mapping is into a smaHer subset of the parameter space. If /(X, fi) is an N parameterfunction, then, in the errorless case, N non-degenerate edge pixels map to a single point in the parameterspace.2 In this case, the accumulator method needs to increment only a single bin in the parameter space foreach set, rather than the bins covering an N — 1 dimensional manifold for each edge pixel. Such a techniquehas been used in some fonn by severa! researchers [2, 5, 9, 20, 23, 48]. Of course, we need not use sets withcardinality AT, we could use any size k > 0. If k < N, then each non-degenerate pixel set maps into an N - kdimensional manifold in the parameter space. The disadvantage to this technique of mapping sets of pixelsinto the parameter space is that there are (j£) sets of image pixels with cardinality k to be considered, whichgrows very quickly as k increases.

An examination of how this technique is related to the standard Hough transform is informative. Let'sdenote the transform where sets of k pixels are mapped into the parameter space Hk(tt). (The standardHough transform is thus íf1(Q), but we will continué to denote it simply H(£t).) An image curve (i.e. apoint in the parameter space) now receives a vote only if it passes within the error boundary of each pixelin the set, so we have:

H*(íí) = Y. p(X9l, O) -... - p(X3h, O) (6){*« ^Je(f)

wherc (j¿) denotes the set of all fc-subsets of the edge pixels, £.Consider this function at an arbitrary point in the parameter space. For some set of pixels, [X9í,..., Xgtt},

the product,p(Jt5,,n)-...-p(Xsl(,n)) is 1 if and only if each of the p(J£, O) ternas is 1 and otherwise it is 0. Ifthere are x pixels such that p(X, O) is 1 (these are the pixels that lie on Q up to the localization error), thenthere are (J) sets with cardinality k that contribute 1 to the sum. íffc(H) is thus (J). Since the standardHough transform yields íf(Q) = x in this case, we can express Hk(ft) simply in terms of H(O):

(7)

This result indicates that the method of mapping point sets into the parameter space has the sameaccuracy as the standard Hough transform. If the standard Hough transform uses threshold í > k to findpeaks and the method of mapping pixel sets into the parameter space uses a threshold of (£), then theabove analysis implies that they will find exactly the same set of peaks, assuming that a perfect peak findingmethod is used. No correct peaks are nüssed as a result of using this method and no false positives areeliminated.

In addition, curve detection still requires time that is exponential in N. Let a be the number of bins ineach dimensión of the parameter space. The standard Hough transform increments O(avv~l) bins for eachimage edge pixel, for a total requirement of O(naN~'1). The new method increments 0(aN~k) bins for eachof the O(nk) sets, for a total of Q(aI>f~knk}? Furthermore, the accurate propagation of localization error inthe parameter space appears to be no easier with this method. This technique thus has not gained us much,yet. In fact, it is less efficient than the standard Hough transform method when there are many edge pixelspresent in the image.

2This Í6 trae for the curvea considered in this paper (lines, circles and ellipses,) but it ia not necessarily true for arbitraryclasses of curves. In general, ¡f we assume non-degeueracy, then a set of W errorlesa edge pixels maps to a finite set of pointsin the parameter space.

3This assumea that k < AT. If fe > N, we require G(nfe) > O(nN) time, but this ia ínefflciem, since we can achieve O(nN)time by uaing k = N. Por this reaaon, we will not further consider using fe > N.

Page 218: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

A . . -

Figure 1: Line segments A and B amid random noise.

Let's examine what these transforms look like in the parameter space. Figure 1 shows an example imagewith two short Une segments amid some random noise that we use to ülustrate the transforms. Figure 2shows transforms of this image using the p-Q parameterization for lines. The peaks corresponding to the linesegments in Figure 1 are labeled with letters. The first pk>t is the standard Hough transform of the imageand the second plot is the transform where pairs of pixels are mapped into the parameter space. Whüethe peaks are much higher in the second case, our analysis indicates that if there was a false positive peakin the standard Hough transform, it would also be present for this case. These plots were made withoutpropagating the localization error into the parameter space. However, to somewhat ameliorate the effects oferror, the counters were incremented for each cell in a 3 x 3 window around the cells that were intersectedby the appropriate manifold in the parameter space.

5 Decomposition into subproblems

Let us now consider a new technique where only those pixel sets that share some distinguished set of jedge pixels, T> = {X^,...,^}, are mapped into the parameter space. This is similar to previous work byMurakami et al. [24] and Leavers [20], who use a single edge pixel to constrain the curves in the parameterspace. However, we do not restrict ourselves to using a single pixel to constrain the curves. This techniquehas also been used in the context of object recognition to subdivide difficult problems in to small subproblems[7, 28].

In these constraíned transforms, we vary k - j edge pixels, Q = {Xgi,...,Xgk_j}, in the edge pixel sets.The pixel sets we map into the parameter space are thus V U Q. This yields a new transform as follows:

(8)

Consider this function at an arbitrary point in the parameter space. Since we don't vary the distinguishedpixels, {X^ , ... , Xd} }, the curve must pass through the localization error boundary of each of these pixels toyield a non-zero response. If x pixels lie on a curve up to the localization error, and we use a distinguishedset of j of these pixels, then x - j of these pixels remain in S — T>. We thus have:

(9)k-jO otherwise

Page 219: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

(a) (b)

Figure 2: Transforma of the image in Figure 1. The peaks labeled A and B correspond to the line segmentsA and B. (a) Standard Hough transform. (b) Transform mapping pairs of pixels into the parameter space.

A threshold of (jü) is appropriate for j < fc, if we wish to find curves comprising at least £ pixels. Perfectpeak finding methods will find any curve that passes through the localization error boundaries of each of thedistinguished pixels, if it would have been found by the standard Hough transform method with threshold t.

We can formúlate an algorithm to recognize arbitrary curves by considering severa! subproblems, each ofwhich examines a particular distinguished set, as above. A deterministic algorithm using these ideas wouldconsider each possible distinguished set. This would guarantee that we examine a correct distinguished setfor each curve. If we are willing to allow a small probability of failure, we can use randomization to reducethe number of distinguished sets that must be examined. Note that even when randomization is used inthis manner, each of the subproblems retains full accuracy in terms of discrimination between true curvesand false positives, unlike other uses of randomization in the Hough transform. The only drawback is anarbitrarily small possibility of missing a curve due to failing to examine a distinguished set of pixels thatbelongs to the curve. An analysis of the number of random distinguished sets that must be examined tomaintain high accuracy can be found in Section 8.

To gain the máximum decomposition of the problem, we want j to be as large as possible, but note that jcannot be greater than fc, and we saw earlier that we want k < N for efficiency reasons. Furthermore, whenj = fc, there is only a single set of k pixels containing the distinguished set and thus the only Informationthat is gained is which curves go through every pixel in the distinguished set. In other words, when j — kwe have:

k-j oregardless of the valué of íf(íí) and thus little information is gained. The optiraal cardinality for thedistinguished set is thus j = k — 1 = N — 1. This máximum decomposition of the problem allows each of thesubproblems to be processed quickly and the best effiáency is achieved by the overall algorithm with thisdecomposition when randomization is used.

Figure 3 shows three examples of constrained Hough transforms for the image in Figure 1. The first plot

Page 220: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

(a) («O

Figure 3: Constrained Hough transforms of the image in Figure 1. (a) A pixel £rom segment A was used asthe distinguished pixel. (b) A pixel from segmcnt B was used as the distinguished pixel. (c) A noise pixelwas used as the distinguished pixel.

shows a case where a pixel on segment A was used as the distinguished pixel, the second plot shows a casewhere a pixel on segment B was used as the distinguished pixel, and the third plot shows a case where a noisepixel was used as the distinguished pixel. Once again, we have not propagated the localization error intothe parameter space in these examples. The propagation of error will be examined in the following section.Note, though, that peaks are present where appropriate, but that no peak is ptesent when a noise pixel wasused as the distinguished pixel. Notice also that considering sets of edge pixels that vary in only one pixel(i.e. when j — k — I = N — 1) constrains the transform to lie on a 1-dimensional manifold (a curve) in theparameter space. Let's cali this curve the Hough curve. When localization error is considered, the transformis no longer constrained to lie on the Hough curve, but the transform points remain cióse to this curve.

This decomposition of the curve detection problem into subproblems has two very usefxil properties, bothof which derive from the fact that the transform is constrained to lie on the Hough curve in the errorlesscase. First, since the Hough curve can be parameterized in a single variable, it is much easier to search thanthe full parameter space. Second, it is now much easier to propágate localization error into the parameterspace. This is accomplished by determining tight bounds on the range that a set of pixels can map to in theparameter space under certain localization error bounds.

6 Error propagation

We now consider methods to propágate the localization error into the parameter space. Here we takelocalization error to encompass both the error in determining the precise position of the edge pixels in theimage and any discretization error that is incurred in the image space. The conventional method for treatinglocalization error is to use a binning procedure in the parameter space, where each set of pixels maps intoa single bin or a rectilinear volume of cells in the parameter space. As previously uoted, this assurues thatthe bins are large enough to catch the votes from the correct sets of pixels and are small enough not tocatch enough votes to result in false positives. This is very difficult to achieve in practice, since the shape ofthe volume of the parameter space that is consistent with a set of pixels up to the localization error is notrectilinear and the volumes have very different shapes and sizes depending on the locations of the pixels inthe set.

An additional problem with such techniques is that the parameter space bins are not infinitesimal. Thisimplies that each bin in the parameter space maps to some non-infinitesimal área in the image space. Let's

10

Page 221: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Image space

Figure 4: A cell in the parameter space sweeps out approximately an hourglass shape in the image space forthe p~& parameterization of Unes.

consider the case of straight lines in particular. Each bin covers some set of parameters, [pi,p2\ [0i,#2],in the p-9 parameterization of lines. This sweeps out an área in the image space that is shaped somewhatlike an hourglass (see Figure 4). A detailed analysis of this shape can be found in [3]. Note that this shapeexpands as it moves out from its point that is closest to the origin in the coordínate frame. A line passingthrough the wide región of the hourglass contributes several votes to the bin, even though the line itself hasparameters very different from those in the bin. This factor contributes to false positives in Hough transformimplementations that use the accumulator method.

Now, let's examine how localization error should be propagated ideally in the curve detection process.Each set of pixels maps to a subset of the parameter space under given error conditions, This subset consistsof all of the curves that pass through each pixel in the set up to the localization error. Cali this subset ofthe parameter space the error cloud of the set of pixels. Ideally, we would lócate exactly those points inthe parameter space at which some predetermined number of error clouds intersect. This would yield thecurves that pass through some mínimum number of the points up to the localization error. We do not dothis predsely, since it is not practica!. However, for the subproblems that we now examine, we can efHcientlycompute a good approxiraation to this number.

We first parameterize the Hough curve in a single variable, t. Consider the projection of the errorclouds onto the £-axis for each of the pixel sets that are examined in some subproblem (examples of theseprojections for the cases of lines and óreles can be found below). The number of projected error clouds thatintersect at some point on the Hough curve yields a bound on the number of error clouds that intersect on acorresponding hypersurface in the full space. Furthermore, since the error clouds do not stray far from theHough curve, this bound is a good approximation to the actual number of intersecting error clouds, whichis the information we desire.

Since we sum the number of projected error clouds that intersect at points on the Hough curve, thiscorresponds to a kernel function for each error cloud that looks like a top hat. The kernel function takes ona valué of O or 1 at each point depending on the whether the point is contained in the projection of the errorcloud. If desired, we could instead map each error cloud into a smooth, continuous kernel on the Houghcurve using the techniques described by Princen et al [33] and Palmer et al [30], This yields the possibilityof achieving better performance at the cost of additional computation.

Once we have projected each of the pixel sets that are examined in some subproblem onto the í-axis,we can find the peaks along the Hough curve using any of several different techniques. We could simplydiscretize t and perform voting by incrementing the bins consistent with each range in t that an error cloudprojects to. This does not suffer from the problems of previous accumulator methods, since we can discretize

11

Page 222: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 5: We can determine bounds on the range of Q for any two pixels by considering lines that passthrough the boundaries of their possible localization errors.

t finely and increment all of the cells that are consistent with a particular error cloud. Alternatively, wecould sort the minimal and maximal t points for each error cloud and use a sweep algorithm. This methodexamines the extrema! points in sorted order and keeps a counter that is incremented each time we hit aminimal point and decremented each time we hit an maximal point. If the counter reaches a large enoughvalué, then a line has been found which passes through (or cióse to) many edge pixels.

Note that the reason that we can project the error clouds onto a single parameter axis in this methodwithout exacerbating the problem of false positives is that we have already constrained the error clouds to lienearly on a one-dimensional manifold of the parameter space. However, we nrnst take care to parameterizethis manifold correctly, such that the mapping between points on the manifold and points in the parame-terization is one-to-one. The following subsections describe bow we can parameterize the Hough curve in tfor the cases of lines and circles, and how we can project the error cloud for the sets of edge pixels onto theí-axis for each case.

6.1 LinesIf we use the p-0 parameterization for lines (i.e. x eos 6 + y sin O — p), we can parameterize the Hough curveby Q, since p is a function of 9, To project the error cloud for a pair of pixels onto the ¿?-axis, we simplydetermine the minimal and maximal 9 such that there exists a line with that orientation passing throughboth of the pixels up to the localization error. If we use square error boundaries, we need only consider thecorners of the squares in determining these minimal and maximal 9 valúes. See Figure 5.

6.2 CirclesWe can parameterize the space of circles by the coordinates of the center of the tírele and the radius, so thereare three parameters: (orc,j/c,r). For this case, the optimal decomposition uses j = N — 1 — 2 distinguishedpixels. The Hough curve can be parameterized by the distance from the center of the árele to the midpointbetween the two distinguished pixels (we take this distance to be positrve when the center is to the right ofthe segment connecting the distinguished pixels, and negative otherwise).

To project the error cloud onto the ¿-axis, we now need to determine error bounds on this distance giventhree points and their localization error boundaries. Recall that the center of the circle passing through three

12

Page 223: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 6: We can determine bounds on the position of the center of a circle passing through three points(up to the localization error) by examining the range of possible perpendicular bisectors for the segmentsbetween the points.

points is the point where the perpendicular bisectors of the segments between the points meet. We can thusdetermine bounds on the location of the center of the circle by examining the set of points at which two ofthe perpendicular bisectors of the segments can meet (see Figure 6). The minimum and máximum distanceírom the center of the circle to the midpoint of the distinguished pixels can be determinad by examining theextrema! points of this set.

7 Analysis and comparison with previous rnethods

In order to study the rate of false positives that these methods yield, let's examine, in the context of linedetection, the average number of error clouds that are consistent which a particular point on the Houghcurve for a single tria!. Since there are n — 1 such error clouds that are examined and the Hough curve coversTT radians, the average number of error clouds consistent with each point on the Hough curve is:

(n - \)E[9d\)

where E[0¿] is the expected length of the projection of the error cloud onto the Hough curve.We can place an upper bound on 0d( the length of the projection of an error cloud for a particular pair

of points onto the Hough curve as follows. Considex the triangle formed by the midpoint between the pairof pixels and the two corners of one of the points' localization error boundaries that form an acute trianglewith this midpoint (see Figure 7). 0¿ is given by the angle of the triangle formed at the midpoint betweenthe pixels.

13

Page 224: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 7: The range of possible O valúes can be determined using the law of cosines.

If d is the distance between the pair of pixels, then we have / i , /2 > 2

.4 2 - I?47 < d'

&d < arceos ( 1 —

The sLde of the triangle opposite to #d has length V27, where 7 is the length of a side of the lacalizationerror boundary. Let l\d /2 be the other edges of the triangle. The law of cosines yields:

(u)

(12)

(13)

E[0d] is not straightforward to determine, but we can compute it empirically by examining the distributionof d in sample images. For example, for the image in Figure 1, we get E[^¿] = 0.08485, with 7 = 1 pixel, andsince there are 262 edge pixels in the image, we get E[N^} = 6.21. So, the average number of votes that eachpoint on. the Hough curve receives (including the peaks due to the trtie Unes) is just over six. Meanwhile,the peaks for the curves in this case are 34 and 41 votes high. Figure 8 shows constrained transforma of theimage in Figure 1 with error propagation. The distinguished points used are the same as in Figure 3. Notethat the signal-to-noise ratio is higher when the error is propagated into the parameter space.

Let's contrast this with a method that simply divides the Hough curve into bins and, for each pair ofpixels that is considered, casta votes for some set of bins centered at the bin that the pair of pixels wouldmap into if they had no localization error. As opposed to the previous method, this method can make noguarantee that the correct bin is voted for, even if it intersects the error doud of the pair of points, since itdoes not accurately model the localization error. However, the pixels must vote for enough bins that it islíkely that they hit the correct bin. This means that the redundancy, -~, should be at least as large as inthe case above (and probably larger), yet since some predetermined constant size is used, the redundancy isunderestimated for some pixels, and overestimated for others. We thus miss some correct Unes due to theunderestimations and find some false positives due to the overestimations.

For the standard Hough transform and the techniques where set of pixels are mapped into the parameterspace, we have exactly the same problems, but now we have underestimates and overestimates in each of thedimensions of the parameter space and thus the problems may be compounded.

14

Page 225: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

vMA

(a) (b) (c)

Figure 8: Constrained Hough transforms of the image in Figure 1 with error propagation. (a) A pixel fromsegment A was used as the distinguished pixcl. (b) A pixel from segment B was used as the distinguishedpixel. (c) A noise pixel was used as the distinguished pixel.

Wc have perfonned empírica! tests using four methods to detect curves in synthetic images. The methodsthat we compare are:

1. The method described in this paper, where subproblems are examined and the localizatíon error ispropagated into the parameter space. A 900 bin accumulator was used.

2. The method where subproblems are examined, but without propagation of the localization error intothe parameter space. A 900 bin accumulator was used

3. The method where pairs of pixels are mapped into the parameter space without propagation of thelocalization error Lnto the parameter space. A 360x360 accumulator was used.

4. The standard Hough transform method. A 360x360 accumulator was used.

To ameliorate the effects of error in the cases where localization error is not propagated into the parameterspace, votes are cast for all cells that are adjacent (including those sharing only a córner) to the cells thatare hit precisely in the transform.

The synthetic test images were generated by placing a straight line consisting of 64 pixels in a 256 x 256image. In addition, 1000 randomly selected pixels and two distractors were added to the images. Thedistractors consisted of circular ares with a radius of curvature of 100 pixels. An example can be found inFigure 9.

Tests were performed on 1000 such synthetic images. Figure 10 shows the results of these tests. For eachmethod, the probability of detecting the correct Une segment is plotted versus the probability of finding afalse positive for varying levéis of the threshold that is used to determine which Unes are detected. Themethod described in this paper, where the localization error is propagated into the parameter space has byfar the best performance among the methods tested. Somewhat surprising is the poor performance of themethod where subproblems are examined, but that localization error is not propagated into the parameterspace. This performance is due to a combination of the inaccurate propagation of error with the use ofconstraints (the distinguished pixel) that contain error, When a distinguished pixel with very little error ischosen, the performance is acceptable, but when no such distinguished pixel is examined, the performancebecornes poor. This indicates that when constrained subproblems are examined, it is crucial to propágatethe localization error accurately into the parameter space.

15

Page 226: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 9: Example synthetic image that was used in generating ROC curves.

Probabilityof detection

- ConMrwncd transformwilk error propagación

- Cfnutraincd tranafomtwilbout error propaga!ion

t mapping poirs ofpoint» ¡nio paramclcr apacc

Standard Hough traiwfonn

Probability of a false alarm

Figure 10: Receiver operating charactertstic (ROC) curves generated using synthetic data.

16

Page 227: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

8 Computational complexity

This section examines the computational complexity of curve detection using the techniques described above.Let's first determine how many of the distinguished sets must be examined to maintain a low rate of failure.We assume that we only need to find curves that comprise some fraction e of the total number of edge pixelsin the image and thus are significant with respect to the complexity of the image. The probability that asingle set of j random pixels all lie on a particular such curve can be bounded by:

» , » . . <This follows since we must have (^) distinguished sets that lie on the curve among the (J) possible

distinguished sets. If we take t such triáis, the probability that all of them fail for a particular curve isbounded by:

?<(!-&)*** (l-¿)1 (15)

For each curve, we thus have a probability no larger than p that we fail to examine a set of distinguishedpixels that is a subset of the curve in í triáis. Since conservativa peak finding techniques are used, we canassume that any trial examining a correct set of distinguished pixels leads to the identification of the curve.

We now choose an arbitrarily small probability of failure, (5, and determine the number o£ triáis necessaryto guarantee this accuracy:

( l -e J ' )É <S (16)Solving for t yields:

Hog(l-Ó >log<5 (17)

<">The number of triáis necessary is thus dependent on the probability of success desired (but only to a

logarithmic factor), the fraction of image edge pixels that must comprise the curve, and the size of thedistinguished set. Note that while the number of triáis is exponential in the size of the distinguished set,the number of bins we have to increment per trial in the parameter space is inversely exponential in thissize. The number of triáis is not explititly dependent on n, although it is implicitly dependent on n. Thisis because, as the complexity of the image increases, we need to lower e to detect the same curves, althoughthese curves become less significant with respect to the complexity of the image.

Now let's consider the complexity of detecting peaks on the Hough curve for each trial. Recall that weuse j = N — 1 in our method. For the technique of discretizing the Hough curve and voting fot the binsover an appropriate range for each set of pixels that is mapped onto the Hough curve, the complexity isdepeudent upon how finely the Hough curve is discretized. H there are a bins, then we need to increment0(07) bins per trial per edge pixel, and this yields a complexity of 0(na^) per trial. The total complexityis thus O^tN-f1) or simply O(n) when measured by the size of the input (a, 7, 5, e, and N are constants).The storage required by this technique is 0(n + a).

If we instead use the sweep algorithm, we must sort the O(n] mínima! and maximal points of the errorcloud projectkms onto the Hough curve, which requires Ü(nlogn) time per trial. Processing the sortedpoints requires O(n) time. We thus require Q(nl°8jJ'-i8T) total time or O(nlogn) when measured by thesize of the input. The storage required by this technique is O(n).

While the time that is required is exponential in the number of curve parameters, N, the base of theexponential is now e rather than n or a as in previous algorithms. We thus have an accurate algorithm inwhich the time dependence on the number of edge pixels and the accuracy of the algorithm is low.

17

Page 228: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 11: Example image used to test Une detection.

An additional área where randomization may be used if we are willing to sacrifice some performance inthe discrimination of truc curves versus false positivas is by subsarnpling the pixels that are examined ineach subproblem. The analysis of Bergen and Shvaytser [2] implies that we can achieve a complexity thatis independent of the number of image edge pixels if we are willing to allow the method to be in error withslightly increased frequency. We have not fully explored this possibility, since its practicality is questionable(the number of sampled pixels necessary may be larger than the total number of edge pixels in the image).

9 Results

These techniques have been applied to real images to test their efficacy. Figure 11 shows an example image(483x318 pixels) that was used to test the une detection techniques. Figure 12 shows the edges found inthis image. These edges were determined to sub-pixel accuracy using a versión of the Canny edge detector[6].

For tests on this image, square localization error boundaries were used such that the true location of eachedge pixel was assumed to be within 0.25 pixels of the measured location in each direction. For each linethat surpasses the detection threshold in each subproblem, only the parameters at which the peaks occurred•were kept. Furthecmore, for any two lines that were detected in sepárate subproblems that were withinsome minirmim distance of each other, only the line with the higher vote count was kept. Finally, we outputthe connected segmenta of edge pixels along the lines that were detected in the image using a method thatallowed small gaps to be bridged. Figures 13 and 14 show the lines that were detected at two thresholds.When a large threshold was used (e — 0.01), all of the long lines were found in the image, but short orcurving lines were not found. When a lower threshold was used (e = 0.004), even short lines were found inthe image.

Figure 15 shows an image (400x300 pixels) that was used to test circle detection using the methoddescribed in this work. This image is an engineering drawing that has been scanned. For this reason, itwas not possible to determine the location of edge pixels to sub-pixel accuracy. In addition, the presence of

18

Page 229: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 12: Edges detected in the image.

Figure 13: Straight lines detected with e = .01.

19

Page 230: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 14: Straight lines detected with e = .004.

small and dashed circles and the clutter in the image make this a diíRcult test case. For this circle detectionexample, we used the additional constraint that each circle that is output should be represented in the imageby at least some mínimum fraction of its perimeter edge pixels.

Figure 16 shows the circles found with e = .04. While all of the large circles were found, the smalland dashed circles did not comprise a large enough fraction of the image to be found. With e = .008, theimplementation finds a number of circles, some of which are not perceptually obvious. Figure 17 shows thecircles found for this case that are perceptually salient. The implementation had difficulty finding both of thedashed circles with the same center since they were so cióse together. The circles shown consist of the top halfof one of the circles and the bottom half of the other. This may partially be a result of the circles not beingperfectly circular in the image. Figure 18 shows circles that were found that are not perceptually salient.Note that in each case, the pixels found fonn most of the perimeter of a circle. These circles successfullymet the acceptance criterion specófied, so this is not a failure of the algorithm.

10 Ellipses and other high-order curves

When applying these techniques to curves with many degrees of freedom, we must take special care, sincethe numbex of triáis that are required can become large. Let's consider the detection of ellipses, which havefive parameters. If the image is sparse, or we can segment the image, then we should have no problema.For example, if we only need to detect ellipses that comprise 50% of the image edges (or some subset aftersegmentation), then the number of triáis required to achieve 0.99 probability of success is 74. Oa the otherhand, if we wish to detect ellipses that comprise at least 10% of the image edges using these techniques in astraightforward manner, then we require 46,052 triáis to achieve 0.99 probability of success.

When we wish to detect high-order curves in coraplex images, there are additional techniques that wecan use to perform curve detection. quickly. One simple technique is to use additional information at eachedge pixel. For example, we can use the orientation of the curve at each pixel (as determined from thegradient or the curve normal or tangent). When we do this, we require fewer curve points to determine the

20

Page 231: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 15: Engineering drawing used to test circle detection.

Figure 16: Gíreles detected with e = .04.

21

Page 232: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

Figure 17: Perceptually salient cirdes detected with e = .008.

Figure 18: Perceptually insalient cardes that surpassed the threshold with e = .008. The original image isdrawn in lightly to show why these were detected.

22

Page 233: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

position of the curve. We can determine the position of an elh'pse using three oriented points4 rather thanfive unoriented points. We would thus use two, rather than four, distinguished pixels, and we would requiremany fewer triáis to ensure that there is a low probability of failure (461 for the example given above). Ofcourse, we need not restrict this technique to high-order curves. We can use two oriented points to determinethe position of a circle, rather than three unoriented points.

An altérnate technique that can detect high-order curves quickly is to use a two (or more) step technique,where some subset of the curve parameters are determined first, and the remaining parameters are determinedsubsequently. An example of this technique is the method of finding the center of an ellipse that is describedby Tsuji and Matsumoto [45]. They note that the points on an ellipse that have parallel tangent Unes lieon opposite sides of the center of the ellipse, and thus ellipse centers can be detected by finding points thatare midway betwcen many such pairs of points with parallel tangents. Problem decomposition techniquessimilar to those described here can also be used with this method to detect ellipse centers. Once the centerof the ellipse has been detected, three parameters remain to be determined. These can be determined usinga three parameter Hough transform technique, similar to the detection of circles.

11 Summary

This paper has discussed efficient and accurate methods to perform curve detection using a decomposition ofthe Ilough transform that allows locaUzatiou error to be eíficient propagated itito the parameter space. Tothis end, we have modified a formal definition of the Hough transform that allows the localization error tobe analyzed appropriately. Under this definition, it was shown that the mapping of pixel sets (rather thanindividual pixels) into the parameter space did not, by itself, improve the accuracy or efnciency of curvedetection.

We then considered a new method where the Hough transform is decomposed into severa! constrainedsubproblems, eachofwhich examines a subset of the parameter space by considering only those pixel sets thatinclude some distinguished set of pixels. If each possible subproblem is examined, then no loss in performanceresults, but no decrease in complexity is gained. However, the examination of these subproblems allows us,first, to propágate the localization error efficiently and accurately into the parameter space, and second, to userandomization techniques to reduce the complexity of curve detection, while maintaining a low probabilityof failure. The overall complexity of the resulting algorithm is O(n) or O(n log n) (depending on the rnethodused to find peaks in the parameter space), where n is the number of edge pixels in the image. In addition,only O(n) storage is necessary.

Analysis of this method indicates that curves can be detected robustly with a lower rate of false positivesthan previous methods to perform curve detection. An empirical investigation confirmed this result anddemonstrated that even in the presence of random noise and correlated distractors, this technique can detectstraight lines without a high rate of false positives, where previous methods break down. We have givenexamples of these techniques detecting straight Unes and circles in real images.

Further improvements to these techniques and extensions to curves with many degrees of freedom arepossible through the use of additional information. For example, the orientation of each edge pixel can beused as an additional constraint on the location of a curve. This reduces the number of points that arenecessary to solve for the parameters of a curve and thus reduces the dependence of the algorithm on thenumber of curve parameters.

The primary contribution of this work is twofold. First, the technique of subdividing the Hough transforminto many small subproblems has previously only been considered in a very limited fashion. We haveformalized this technique and shown that it allows randomization to be used in manner that introduces asmall probability of failure, since a correct distinguished set of pixels may not be examined for a particularcurve, but that it does not reduce the detection performance, assuming that a correct distinguished set ofpixels is examined. Second, we have described new techniques by which the localization error present in theimage edge features may be propagated into the parameter space allowing curves to be detected robustly.

4In fact, three points with orientations overconstrain the poaition of the ellipse in the errorless case.

23

Page 234: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

The combination of these techniques results in an algorithm that combines both efficiency of operation androbustness of curve detection performance, without the detection of false positives that are not supportedby the image.

Acknowledgements

This research was performed while the author was with Cornell University, Ithaca, NY. A preliminary versiónof this work appeared in the 1996 European Conference on Computer Vision [27].

A Parameterizations

This appendix describes parameterizations for lines, circles, and ellipses that can be used in Hough transforníimplementations.

A.l Lines

One parameterization for lines is the standard slope-intercept representation:

y - mx + & (19)

While this parameterization has the advantage that the points in the image space map to lines in theparameter space, it has the disadvantage that the ranges of m and b are unbounded, since we may navevertical or horizontal lines.

Duda and Hart [9] proposed to use the normal parameterization instead:

x eos O 4- y sin O = p (20)

In this parameterization, O is the orientation of the line and p is the distance of the Une from the origin.While p is theoretically unbounded, for any image we can bound p by the máximum distance of any imagepoint from the origin. This parameterization maps points in the image space to sinusoids in the parameterspace.

Given two points (#1,2/1) and (#2, Jf2) we can solve for & and p as follows:

9 = arctan (21)yz — yi

p = TI eos 0 -f 2/1 sin O (22)

For any distinguished point, (arj,^), the Hough curve is given by Xdcosd + ydSinQ = p. In addition, pis a function of 0, so we can parameterize the Hough curve by Q.

A.2 Circles

The standard parameterization for circles is (a;c,2/c,r), where (xc^yc) is the center of the circle and r is theradius. The circle is given by the solutions to:

Given thiee points, (xi,yi), (z2,2/2)5 and (2:3,3/3), the circle that passes through each of them has pa-rameters:

1/3 - Vi Vi ~ 2/2 1 F *Í + 3/| - x\ 2/1-X3 S2-*i J [ Z3 + 2/32-~i ^ j (

- Wi) ~ (2/2 -

24

Page 235: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

A slightly difTerent parameterization that is useful in the context of Hough curves is (xc,yc,d)t where dis the distance of the center of the circle from the segment connecting the two distinguished points. If wechoose d to be positive when the center of the circle is to the right of the segment and negative when it isto the left,5 we can reparameterize the curve in one variable by d. In this case the Hough curve forms astraight line in the parameter space.

A.3 EllipsesEllipses are typically parameterized by (sc,j/c,a,M). where (xcjyc) is the center of the ellipse, a and bare the lengths of the major and minor axes, and 9 is the orientation of the major axis. Forbes [10] hasdetermined a stable method to solve for the parameters (a description was found by this author in [20]).Given (xÍ7 yi}, i = 1—5 we can determine the coemcients in the following equation and solve for (17, V, R, S,T)using Gaussian elimínation:

We then solve for (xc,yc,a,b,0) in the following equations:

(27)

(28)1 + e2

I -e2(29)

R = 2xc(l -U)- 2ycV (30)

5 - 2yc(l -U)- 2xcV (31)

xcR xcS

References[1] M. Atiquzzaman, Multiresolution Hough transform - An efficient method of detecting patterns in images,

IEEE Transactions on Pattem Analysis and Machine Intelligence 14(11), Nov. 1992, 1090-1095.

[2] J. R. Bergen and H. Shvaytser, A probabilistic algorithm for computing Hough transforms, Journal ofAlgorithms 12, 1991, 63$-656.

[3] T. M. Breuel, Finding Unes under bounder error, Pattern Recognition 29(1), 1996, 167-178.

[4] C. M. Brown, Inherent bias and noise in the Hough transform, IEEE Transactions on Pattern Analysisand Machine Intelligence 5(5), Sept. 1983, 493-505.

[5] A. CaUfano and R. M. Bolle, The múltiple window parameter transform, IEEE Transactions on PatternAnalysis and Machine Intelligence 14(12), Dec. 1992, 1157-1170.

[6] J. Canny, A computational approach to edge detection, IEEE Transactions on Pattern Analysis andMachine Intelligence 8(6), Nov. 1986, 679-697.

5If the segment is horizontal, then left and right of the segment have no meaning. In this casej we take above be positiveand below to be negative.

25

Page 236: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

[7] T. A. Cass, Polynomial-Time Geometric Matching for Object Recognition, PhD thesis, MassachusettsInstituto of Technology, Feb. 1993.

[8] M. Cohén and G. T. Toussaint, On the detection of structures in noisy pictures, Pattern Recognition9, 1977, 95-98.

[9] R. O. Duda and P. E. Hart, Use of the Hough transformation to detect lines and curves in pictures,Communications of the ACM 15, 1972, 11-15.

[10] A. B. Forbes, Fitting an ellipse to data, Report NPL-DITC 95/87, National Physical Laboratory, Dec.1987.

[11] G. Gerig, Linking image-space and accumuíator space: A new approach for object-recognition, inProceedings of the International Conference on Computer Vision, 1987, pp. 112-115.

[12] W. E. L. Grimson and D. P. Huttenlocher, On the sensitivity of the Hough transform for objectrecognition, IEEE Transactions on Pattern Analysis and Machine Intelligence 12(3), Mar. 1990, 255-274.

[13] P. V. C. Hough, Method and means for recognizing complex patterns, U. S. Patent 3069654, 1962.

[14] D. J. Hunt, L. W. Nolte, A. R. Reibman, and W. H. Ruedger, Hough transform and signal detectiontheory performance for images with additive noise, Computer Vision, Graphics, and Image Processing52, 1990, 386-401.

[15] J. IHmgworth, G. Jones, J. Kittler, M. Petrou, and J. Princen3 Robust methods of 2d and 3d imagedescription, in Progress in Image Analysis and Processing II, V. Cantoni, M. Ferretti, S. Levialdi,R. Negrini, and R. Stefanelli, Eds., World Scientific, 1991, pp. 3-26.

[16] J, Illingworth and J. Kittler, The adaptive Hough transform, IEEE Transactions on Pattern Analysisand Machine Intelligence 9(5), Sept. 1987, 690-698.

[17] J. Illingworth and J. Kittler, A survey of the Hough transform, Computer Vision, Graphics, and ImageProcessing 44, 1988, 87-116.

[18] N. Kiryati and A. M. Bruckstein, Antialiasing the Hough transform, CVGIP: Graphical Models andImage Processing 53(3), May 1991, 213-222.

[19] N. Kiryati, Y. Eldar, and A. M. Bruckstein, A probabilistic Hough transform, Pattern Recognition24(4), 1991, 303-316.

[20] V. F. Leavers, The dynamic generalized Hough transform: Its relationship to the probabilistic Houghtransierais and an application to the concurrent detection of circles and ellipses, CVGIP: Image Un-derstanding 56(3), Nov. 1992, 381-398.

[21] V. F. Leavers, Which Hough transform?, CVGIP: Image Vnderstanding 58(2), Sept. 1993, 250-264.

[22] H. Li, M. A. Lavin, and R. J. Le Master, Fast Hough transform: A hierarchical approach, ComputerVision, Graphics, and Image Processing 36, 1986, 139-161.

[23] P. Liang, A new and efficient transform for curve detection, Journal of Robotic Systems 8(6), 1991,841-847.

[24] K. Murakami, H. Koshimizu, and K. Hasegawa, On the new Hough algorithms without two-dimensionalarray for parameter space to detect a set of straight lines, in Proceedings of the IAPR InternationalConference on Pattern Recognition, 1986, pp. 831-833.

26

Page 237: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

[25] W. Niblack and D. Petkovic, On improving the accuracy of the Hough transform, Machine Vision andApplications 3(2), 1990, 87-106.

[26] F. O'Gorman and M. B. Clowes, Finding picture edges through collinearity of feature points, IEEETransactions on Computers 25(4), Apr. 1976, 449-456.

[27] C. F. Olson, Decomposition of the Hough transform: Curve detection with efficient error propagation,in Proceedings of the European Conference on Computer Vision, 1996, vol. 1, pp. 263-272.

[28] C. F. Olson, Efficient pose clustering using a randomized algorithm, International Journal of ComputerVision 23(2), June 1997, 131-147.

[29] P. L. Palmer, J. Kittler, and M. Petrou, Using focus of attention with the Hough transform for accurateline parameter estimationT Pattern Recognition 27(9), 1994, 1127-1134.

[30] P. L. Palmer, M. Petrou, and J. Kittler, A Hough transform algorithm with a 2d hypothesis testingkernel, CVGIP: Image Understanding 58(2), Sept. 1993, 221-234.

[31] J. Princen, J. Dlingworth, and J. Kittler, A hierarchical approach to line extraction based on the Houghtransform, Computer Vision, Graphics, and Image Processing 52(1), Oct. 1990, 57-77.

[32] J. Princen, J. Illingworth, and J. Kittler, A formal definition of the Hough transform: Properties andrelationships, Journal of Mathe-matical Imaging and Vision 1, 1992, 153-168.

[33] J. Princen, J. Ulingworth, and J. Kittler, Hypothesis testing: A framework for analyzing and optimizingHough transform performance, IEEE Transactions on Pattern Ánalysis and Machine Intelligence 16(4),Apr. 1994, 329-341.

[34] T. Risse, Hough transform for line recognition: Complexity of evidence accumulation and clusterdetection, Computer Vision, Graphics, and Image Processing(4Q), 1989, 327-345.

[35] A. Rosenfeld, Picture Processing by Computer, Academic Press, 1969.

[36] S. D. Shapiro, Transformations for the computer detection of curves in noisy pictures, ComputerGraphics, and Image Processing 4, 1975, 328-338.

[37] S. D. Shapiro, Feature space transforma for curve detection, Pattern Recognition 10, 1978, 129-143.

[38] S. D. Shapiro, Generalization of the Hough transform for curve detection in noisy digital images, inProceedings of the International Joint Conference on Pattern Recognition, 1978, pp. 710-714.

[39] S. D. Shapiro, Properties of transforma for the detection of curves in noisy pictures, Computer Graphics,and Image Processing 8, 1978, 219-236.

[40] S. D. Shapiro and A. lannino, Geometría constructions for predicting Hough. transform performance,IEEE Transactions on Pattern Analysis and Machine Intelligence 1(3), July 1979, 310-317.

[41] J. Sklansky, On the Hough technique for curve detection, IEEE Transactions on Computers 27(10),Oct. 1978, 923-926.

[42] M. Sofier and N. Kiryati, Guaranteed convergence of the Hough transform, in Vision Geometry III}

Proc. SPIE 2356, 1994, pp. 90-100.

[43] R. S. Stephens, Probabilistic approach to the Hough transform, Image and Vision Computing 9(1),Feb. 1991, 66-71.

[44] P. R. Thrift and S. M. Dunn, Approximating point-sets image by line segments using a variation of theHough transform, Computer Vision, Graphics, and Image Processing 21, 1983, 383-394.

27

Page 238: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

[45] S. Tsuji and F. Matsumoto, Detection of ellipses by a modified Hough transform and simplified inter-pretation strategy, IEEE Transactions on Computers 27(8), 1978, 777-781.

[46] T. M. van Veen and F. C. A. Groen, Discretization errors in the Hough transform, Pattern Recognition14(1-6), 1981, 137-145.

[47] L. Xu and E. Oja, Randomized Hough transform (RHT): Basic mechanisms, algorithms, and compu-tational complexities, CVGIP: Image Understanding 57(2), Mar. 1993, 131-154.

[48] L. Xu, E. Oja, and P. Kultanen, A new curve detection method: Randomized Hough transform (RHT),Pattern Recognition Letters 11, May 1990, 331-338.

28

Page 239: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B

PRINCIPIOS DE LA TRANSFORMADA RADON

INTRODUCCIÓN

Un punto de importancia en esta fase del análisis es delimitar claramente los

lineamientos que deberá cumplir el algoritmo a implementarse, pues de ello

dependerá si los resultados que se obtengan son o no útiles para el estudio

posterior de los resultados. Adicionalmente, se deberá establecer los campos

de aplicación de los resultados del procesamiento de imágenes derivado de la

Transformada de Hough. Es perfectamente comprensible que de una misma

imagen, los resultados que se arrojen serán interpretados de manera distinta

por los científicos que los vayan a analizar.

Tómese como referencia una imagen proveniente de un satélite geográfico. A

un geógrafo le interesará estudiar el efecto de la deforestación en el perfil

geográfico de la zona, por ejemplo. Pero a un ambientalista le importará, en

cambio, el crecimiento del desierto en esa misma zona producto de la

deforestación. Las imágenes son las mismas pero el análisis resultante es

diferente.

Es por ello la especialización de los sistemas de procesamiento intermedio de

las imágenes, pues la interpretación que se haga de los datos obtenidos será

distinta según la persona encargada de analizarlas y la rama científica a la cual

pertenezca el investigador..

Una vez que se ha establecido toda la base de funcionamiento de la detección

de bordes y discontinuidades, lo que compete estudiar en adelante son los

métodos para aplicar la transformada de Hough en este proceso.

En la literatura consultada [11, 16, 19, 20, 24, 26], se puede encontrar algunos

algoritmos para la aplicación matemática y computacional de la transformada

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 240: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.2 -

de Hough, varios de los cuales se presentaron en el capítulo anterior1. Sin

embargo, la transformada de Hough no puede interactuar muy sola que se

diga, pues necesita que "alguien" convierta los píxeles en unos y ceros para

ella poder entrar a procesar. En los siguientes acápites se realizará la

formulación de la transformada Radon, una transformada que se convierte en

"el caso general de la Transformada de Hough ..." [24], que permitirá realizar

un procedimiento para efectuar el análisis de la transformada de Hough de una

imagen y de cómo eso sirve para dibujar el contorno de la misma.

LA TRANSFORMADA RADON

La Transformada Radon es una operación a la cual se la define como el "caso

más general de la Transformada de Hough" [24], pues, como se verá más

adelante, la forma de definición de la Transformada Radon es bastante similar

a la Transformada Hough, solo que la primera se usa para cualquier tipo de

funciones, continuas o discretas y, Hough tan solo se usa para casos discretos

[24]. Tanto Hough como Radon son transformadas cuya área de influencia gira

en torno al análisis de imágenes binarias y, principalmente, al estudio de las

características perimetrales de las mismas.

La forma general de la Transformada Radon está descrita por la ecuación (B -

1) así:

DO OO

= J Jf(x,y)S(!j0-$1x-!;2y)dxdy

Una forma de interpretar los valores de las variables (^o, £1, ^2) es que ellas

representan el número de grados de libertad de la función que permite hacer la

transformación.

' Ver Capítulo 3, Sección 3.3.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 241: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.3 -

Al igual que la Transformada de Hough, la Transformada Radon tiene dos

formas: la forma directa y la forma normal.

La Transformada Directa Radon continua y discreta

La Transformada Radon de una función f(x, y) continua en un espacio definido

por dos variables g(m, b) se define por medio de la expresión:

OO

g(m,b)= Jf(x,mx + b)dx (B-2)-00

Donde y = mx + b es la ecuación de la línea recta dada la pendiente y el punto

donde corta al eje vertical. En otras palabras, esta forma de la Transformada

Radon es muy similar a la Transformada Directa de Hough.

Una de las formas más comunes de la utilización de la Transformada directa

Radon es la que utiliza la función delta de Dirac2, 8(x), de la siguiente manera:

oo oo

g(m,b)= J Jf(x,y)8(y-mx-b)dxdy (B-3)—00 —co

Si se compara la expresión (B - 1) con la (B - 3) se encontrará que el valor de

las variables (£o, 4i. £2) son, respectivamente (-b, m, -1). La expresión de la

forma general permite establecer que la línea recta tiene tres grados de libertad

! La función delta de Dirac, S(x) se define como:1 x = 0

o x*o

Además que:

f í (x)-1

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 242: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.4

En Toft [24], se hace un análisis bastante al detalle de las propiedades que

cumple la Transformada Radon, tales como linealidad, desplazamiento y

escalamiento.

La versión discreta de esta transformada debe partir de la consideración de

cómo se va a discretizar la función de imagen. El proceso de discretización de

la transformada Radon tiene como referentes las siguientes relaciones:

x = x¡ = xmin+iAx ¡ = 0,1,2,...,1-1

y = y, = ym¡n+j AY j = 0,1,2,..., j -1(B — 4)

m = mk =mmln +k Am k = Ol1,2f...,K-1

b = br=bm i n+rAb r = 0,1,2,...,R-1

Donde xmjn es el límite inferior de la muestra, i es un contador entero hasta I

- 1, y Ax es la distancia de muestreo de x. En principio, las variables tienen la

misma definición que los determinados aquí para cada uno de ellos.

En consecuencia la ecuación B - 2 que define la transformada directa Radon,

tomando las relaciones enunciadas en la ec. B - 4, tomará la forma:

00 1-1g(mk,br) = f (x,mkx + br)dx « Ax> f(xj,mkxi + br) (B - 5)

La función imagen muestreada será de la forma:

f(x¡, y;) = f(U) (B-6)

Y la función resultante de aplicar la Transformada Radon a la función de

imagen será de la forma:

g(k. r) = g(mk, br) (B - 7)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 243: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.5 -

De esta manera, la transformada Radon puede presentarse como una imagen

digital.

Hay otras propiedades de esta transformada3 que se las va a pasar por alto,

pues este estudio versa sobre la Transformada de Hough mas no sobre la

Transformada Radon.

La Transformada Normal Radon continua y discreta

La formulación de la Transformada Radon (Ec. B - 1) da lugar a que se puedan

plantear nuevas formas de definición. Una de esas formas gira en torno a la

ecuación normal de la línea recta, la cual ya se definió en el capítulo anterior4.

La aplicación de la ecuación 3 - 12 en la Transformada Radon, pasará por

igualar los grados de libertad, (£o, £1, ^2), por (p, cos0, sen 6) en la ecuación B

- 1, de donde se obtendrá una expresión como:

co oO

g(p,9)= J Jf(x,y)5(p-xcos9-ysen0)dxdy (B-8)—co —CO

La cual es bastante similar a la obtenida para la Transformada de Hough

Normal que se analizó en el Capítulo 35.

Al igual que para el caso de la transformada directa Radon, se va a analizar el

caso de la transformada discreta Radon. En el caso de la Transformada

Discreta Normal Radon, se parte de una consideración similar a las de la

Transformada Discreta Directa, esto es:

•' En [24] se encuentra una explicación muy clara sobre la Transformada Radon.4 Véase la sección 3.2.1.1.5 Véase la Sección 3.1.2 5

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 244: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.6

= X i= X min+ Í A X ¡ = 0,1,2....,1-1

= yj = ym¡n+jAy j = o,i,2I...,j-i= pk=Pmin+kAP k = 0.1,2 K-I (B"9)

Donde i, j, k, r son subíndices de los contadores, (x, y) es un punto de la

imagen, (p,9) son los valores de la ecuación normal de la línea recta que pasa

por el par (x, y).

Se debe asumir que la imagen a estudiar es cuadrada, por facilidad de análisis,

en consecuencia se tendrá:

Ax = Ay (B-10)

I = J (B-11)

En consecuencia, las muestras que se obtengan caerán dentro del intervalo

definido por las relaciones:

Xm¡n=-Xmax=—¿-AX (B - 12)

in = Xmin = max = ~^X (B - 1 3)

K — 1Pmin = -Pmax = ~ ¿P (B - 14)

Para el muestreo del ángulo 6, se debe considerar que 6m¡n = O y se aplicará la

relación:

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 245: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.7 -

Debido a que n es el valor máximo del ángulo que se define en la ecuación

normal de la línea recta6.

Con estas consideraciones, la expresión de la Transformada Normal Discreta

Radon se circunscribe a fijar como parámetros I, K, R y los intervalos de

muestreo Ax y Ap. Con esta información, una primera aproximación a la

Transformada Discreta sería:

cC

g(pk,9r)= Jf(pkcos9r ~ssen9r,scos0r +pksen6r)ds (B- 16)-oo

Que aproximando a sumas discretas, se obtendrá:

v-i

IV=0

g(pk,0r)^As^f(pkcoser-svsener,pksener+svcoser)

El valor de sv se obtiene del muestreo lineal de la variable s, aplicando un

procedimiento similar al presentado en la ecuación (B - 9). Sin embargo, este

desarrollo tiene muchas implicaciones. La más seria se presenta por el hecho

de que para un valor dado de v, los puntos de la imagen, encontrados por la

ecuación (4 - 38), esto es: (x, y) = (pk eos 6r - s sen 0r, s eos 9r + pk sen 0r), en

principio, no coincidirá con la imagen supuesta originalmente g(xk, yr) = g(k, r),

de aquí que se necesita la interpolación en dos variables. Sin embargo, y a

pesar de lo necesario, este procedimiento se debería evitar pues se incrementa

el ruido de muestreo.

Un análisis más profundo sobre lo que concierne a la Transformada Radon se

lo puede encontraren [27].

{í Véase la sección 3.2.1.1.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 246: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO B: TRANSFORMADA RADON -B.8 -

La Transformada Radon versus la Transformada Hough.

El análisis de la Transformada de Hough y de la Transformada Radon, o una

de sus formas de aplicación, está ligada a la estudio de la ecuación de la línea

recta y a la parametrización de curvas como se vio con anticipación en el

Capítulo III. Sin embargo, y como se puede inferir fácilmente, es necesario

establecer cual de estos métodos permite un mejor procesamiento de las

imágenes y cuales son las ventajas del uno con respecto al otro.

Sobre la Transformada de Hough se han hecho muchos trabajos, algunos de

estos se los incluye en la bibliografía anexa a este trabajo7, al igual sobre la

Transformada Radon. En algunas Universidades, este tema es parte del

currículo académico de las Facultades de Computación y Telecomunicaciones,

y es objeto de investigación en otras muchas, por tal motivo es necesario

realizar un análisis básico de las bondades de la una y otra y de la interrelación

entre las dos.

En el punto más importante de comparación entre la transformada de Hough y

Radon está su similitud con el procesamiento de la imagen y el método que

utilizan. Es difícil establecer cual de las dos genera la otra, pero se puede

afirmar que la Transformada Radon es "el caso más general de la

Transformada Hough" [27]. A pesar de ello, lo más importante es la

coexistencia entre las dos; sin embargo, para hacer un procesamiento con

herramienta computacional, se puede utilizar la Transformada Radon, como

soporte de la de Hough, mas no ocurre la relación inversa.

El análisis más importante a realizar para determinar las bondades de la una y

las dificultades, o complejidades de la otra será el tiempo de cómputo y la

cantidad de operaciones a hacer para encontrar el conjunto de respuestas

necesarias. [27]

7 En el Anexo A, se presentan dos de los más importantes trabajos ligados a la Transformada de Hough. Otros trabajos se listan en labibliografía. (Nota del Autor).

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 247: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C

AYUDAS CITADAS DEL MATLAB

Image Processing Toolbox

Image Processing Toolbox,Versión 3.1 (R12.1) 18-May-200i

Reléase Information.¡mages/Readme - Display Information about curren! and previous versions.

Image display.Colorbargetimageimageimagescimmovieimshowmontagemoviesubimagetruesizewarp

Image file I/O.dicominfodicomreaddicom-dict.txtimfinfo¡mreadimwrite

Image arithmetic.¡mabsdiffimaddimcomplementimdivideimlincombimmultiplyimsubtract

- Display colorbar {MATLAB Toolbox).- Get ¡mage data from axes.- Créate and display image object (MATLAB Toolbox).- Scale data and display as image (MATLAB Toolbox).- Make movie from multiframe image- Display image.- Display múltiple image frames as rectangular montage.- Play recorded movie frames,- Display múltiple images in single figure.- Adjust display size of image.- Display image as texture-mapped surface.

- Read melad ata from a DICOM message.- Read a DICOM image.- Textfile containing DICOM data dictionary.- Return information about image file (MATLAB Toolbox).- Read image file (MATLAB Toolbox}.- Write image file (MATLAB Toolbox)

- Compute absolute difference of two ¡mages.- Add two images, or add constant to image.- Complement image.- Divide two images, or divide image by constant.- Compute linear combination of images.- Muttiply two images, or multiply image by constant.- Subtract two images, or subtract constant from image.

Geometric transformations.checkerboard - Créate checkerboard image.findbounds - Find output bounds for geometric transformaron.fliptform - Flip the input and output roles of a TFORM struct.imcrop - Crop image.imresise - Resize image.imrotate - Rotate image.¡mtransform - Apply geometric transformation to image.makeresampler - Créate resampler struct u re.maketform - Créate geometric transformation structure (TFORM).tformarray - Apply geometric transformaron to N-D array.tformfwd - Apply forward geometric transformation.tforminv - Apply inverse geometric transformation.

Image registration.cpstruct2pairs - Convert CPSTRUCT to valid pairs of control points.cp2tform - Infer geometric transformation from control point pairs.cpcorr - Tune control point locations using cross-correlation.cpselect - Control point selection tool.norrnxcorrS - Normalizad two-dimensión a I cross-correlation.

Pixel valúes and statistics.corr2 - Compute 2-D correlation coefficient.imcontour - Créate contour plot of image data,imhist - Display histogram of image data.impixel - Determine pixel color valúes.improfile - Compute pixel-value cross-sections along line segments.mean2 - Compute mean of jnathx elements.

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 248: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C: AYUDAS CITADAS DEL MATLAB -C.2

pixvalregionpropsstd2

Image analysisedgeqtdecompqtgetblkqtsetblk

Image enhancement.histeqimadjuslimnoisemedfilt2Ordf¡lt2stretchlimwiener2

Linear filtering.convmtx2fspecialimfilter

- Display Information about image pixels.- Measure properlies of image regions- Compute standard deviation of matrix elements.

- Find edges in intensity image.- Perform quadtree decom pos ilion.- Get block valúes in quadtree decom pos ition.- Set block valúes in quadtree decomposition.

- Enhance contrast using histogram equalization.- Adjust image intensity valúes or colormap.- Add noise to an image.- Perform 2-D median filtering.- Perform 2-D order-statistic filtering.- Find limite to contrast stretch an image.- Perform 2-D adaptive noise-removal filtering.

- Compute 2-D convolutíon matrix.- Créate predefined filters.- Filter 2-D and N-D images.

Linear 2-D filter deslgn.freqspace - Determine 2-D írequency response spacing (MATLAB Toolbox),freqz2 - Compute 2-D frequency response.fsamp2 - Design 2-D FIR filter using frequency sampling.ftrans2 - Design 2-D FIR filter using frequency transformation.fwindl - Design 2-D FIR filter using 1-D window method.fwind2 - Design 2-D FIR filter using 2-D window method.

Image debturring.deconvblind - Deblur image using blind deconvolution.deconvlucy - Deblur image using Lucy-Richardson method.deconvreg - Deblur image using regularized filter.deconvwnr - Deblur image using Wiener filter.edgetaper - Taper edges using point-spread function.otf2psf - Optical transfer function to point-spread function.psf2otf - Point-spread function to optical transfer function.

Image transforms.dct2 - 2-D discreto cosine transform.dctmtx - Discrete cosine transform matrix.fft2 - 2-D fast Fourier transform (MATLAB Toolbox).fftn - N-D fast Fourier transform (MATLAB Toolbox).fftshift - Reverse quadrants of output of FFT (MATLAB Toolbox).idct2 - 2-D inverse discrete cosine transform.ifft2 - 2-D inverse fast Fourier transform (MATLAB Toolbox}.ifftn - N-D inverse fast Fourier transform (MATLAB Toolbox).¡radon - Compute inverse Radon transform.phantom - Genérate a head phantom image.radon - Compute Radon transform.

Neighborhood and block processing.bestblk - Choose block size for block processing.blkproc - Implement distinct block processing for image.co!2im - Rearrange matrix columns into blocks.colfilt - Columnwise neighborhood operations.im2col - Rearrange image blocks into columns.nlfilter - Perform general sliding-neighborhood operations.

Morphological operations (intensity and bínary images),conndef - Defauit connectivity.imbothat - Perform bottom-hatfiltering.imclearborder - Suppress light structures connected to image border.imclose - Cióse image.imdilate - Dilate image.imerode - Erode image.imextendedmax - Extended-máxima transformimextendedmin - Extended-minima transform.¡mfill - Fill image regions and holes.imhmax - H-maxima transíorm.imhmin • H-minima transform.imimposemin - Impose minima.inopen - Open image.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 249: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C: AYUDAS CITADAS DEL MATLAB -C.3-

imreconstructimregionalmaximregionalminimtophatwalershed

- Morphological reconstruction.- Regional máxima.- Regional mínima.- Perform tophat filtering.- Watershed transform,

Morphological operations (binary ¡mages)applylut - Perform neighborhood operations using lookup tables.bwarea - Compute área of objects in binary image.bwareaopen - Binary área open (remove small objects).bwdist - Compute distance transform of binary image.bweuler - Compute Euler number of binary image.bwhitmiss - Binary hit-miss operation.bwlabel - Label connected components in 2-D binary image.bwlabeln - Label connected componente in N-D binary image.bwmorph - Perform morphologloal operations on binary image.bwpack - Pack binary image.bwperim - Determine perimeter of objects in binary image.bwselect • Select objects in binary image.bwulterode - Ultímate erosión,bwunpack - Unpack blnary image.makelut - Construct lookup table for use with applylut.

Structuring element (STREL) creation and manipulation.getheight - Getstrel heightgetneighbors - Get offset location and height of strel neighborsgetnhood - Get strel neighborhood.getsequence - Get sequence of decomposed strels.isflat - Return true for fíat strels.reflect - Reflect strel about ¡ts center.strel - Créate morphological Structuring element.transíate - Transíate strel.

Region-based processing.roicolor - Select región of interest, based on color,roifill - Smoothly interpólate wíthin arbitrary región.roifilt2 - Filter a región of interest.roipoly - Select polygonal región of interest.

Colormap manipulation.brighten - Brighten or darken colormap (MATLAB Toolbox).cmpermute - Rearrange colors in colormap.cmunique - Find uníque colormap colors and corresponding image.colormap - Set or get color lookup table (MATLAB Toolbox).imapprox - Approximate indexed image by one with fewer colors.rgbplot - Plot RGB colormap components {MATLAB Toolbox).

Color space conversions.hsv2rgb - Convert HSV valúes to RGB color space (MATLAB Toolbox).ntsc2rgb - Convert NTSC valúes to RGB color space.rgbZhsv - Convert RGB valúes to HSV color space (MATLAB Toolbox).rgb2ntsc - Convert RGB valúes to NTSC color space.rgb2ycbcr - Convert RGB valúes to YCBCR color space.ycbcr2rgb - Convert YCBCR valúes to RGB color space.

Array operations.circshift - Shift array circularly.padarray - Pad array.

Image types and type conversions.dither - Convert image using dithering.gray2ind - Convert intensity image to indexed image.grayslice - Créate indexed image from intensity image by thresholding.graythresh - Compute global image threshold using Otsu's method,im2bw - Convert image to binary image by thresholding.im2double - Convert image array to double precisión.Ím2u¡nt8 - Convert image array to 8-bit unsigned integers.im2uint16 - Convert image array to 16-bit unsigned integers.ind2gray - Convert indexed image to intensity image.irn2mis - Convert image to Java MemorylmageSource.ind2rgb - Convert indexed image to RGB image (MATLAB Toolbox).isbw - Return true for binary image.isgray - Retum true for intensity image.isind - Retum true for indexed image.isrgb - Retum true for RGB image.Iabel2rgb - Convert label matrix to RGB image.

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 250: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C: AYUDAS CITADAS DEL MATLAB -C.4

mat2grayrgb2grayrgb2ind

Toolbox preferences.¡ptgetprefiptsetpref

Demos,dctdemoedgedemofirdemoimadjdemolandsatdemonrfiltdemoqtdemoroidemo

Sude shows,ipssOO!Ípss002¡pss003

Extended-examples.ipexindex¡pexsegmicroipexsegcellipexsegwatershedípexgranulometryipexdeconvwnripexdeconvregipexdeconvlucyipexdeconvblindipextform¡pexshearipexmri¡pexconformalipexnormxcorr2ipexrotateipexreg aerial

- Convert matrix to intensity ¡mage.- Convert RGB image or colormap to grayscale.- Convert RGB image to indexed image.

Get valué of Image Processing Toolbox preference.Set valué of Image Processing Toolbox preference.

- 2-D DCT image compression demo.- Edge detection demo.- 2-D FIR filtering and filter design demo.- Intensity adjustment and histogram equalization demo.- Landsat color composite demo.- Noise reduction filtering demo.- Quadtree decomposition demo.- Region-of-¡nterest processing demo.

- Región labeling of steel grains,- Feature-based logic.- Correction of nonuniform ¡llumination.

- Index of extended examples.- Segmentation to detect microstructures.- Segmentation to detect cells.- Watershed Segmentation.- Granulometry of stars.- Wiener deblurring.- Regularized deblurring.- Lucy-Richardson deblurring.- Blind deblurring.- Image transform gallery.- Image padding and shearing.-3-D MRI slices.- Conformal mapping.- Normalized cross-correlation.- Rotatíon and scale recovery.- Aerial photo registraron.

Ayuda de la función EDGE

EDGE Find edges in intensity image.EDGE takes an intensity image l as its input, and returns a binary image BW of the same size as I, with 1'swhere the function finds edges in I and O's elsewhere.

EDGE supports six different edge-finding methods:

The Sobel method finds edges using the Sobel approximation to the derivative. It returns edges at thosepoints where the gradient of I is máximum.

The Prewitt method finds edges using the Prewitt approximation to the derivative. It returns edges at thosepoints where the gradient of I is máximum.

The Roberts method finds edges using the Roberts approximation to the derivative. It returns edges at thosepoints where the gradient of I is máximum.

The Laplacian of Gaussian method finds edges by looking for zero crossings after filtering I with a Laplacianof Gaussian filter.

The zero-cross method finds edges by looking for zero crossings after filtering I with a filter you specify.

The Canny method finds edges by looking for local máxima of the gradient of I. The gradient is calculatedusing the derivative of a Gaussian filter. The method uses two thresholds, to detect strong and weak edges,and includes the weak edges in the output only if they are connected to strong edges. This method istherefore less likely than the others to be "fooled" by noise, and more likely to detect true weak edges.

F. WLAD1M1RO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 251: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C: AYUDAS CITADAS DEL MATLAB - C.5 -

The parameters you can supply differ depending on the method you specify. If you do not specify a method,EDGE uses the Sobel method.

Sobel Method

BW = EDGE(l,'sobel') specifies the Sobel method.

BW = EDGE(l,'sobeP,THRESH) specifies the sensitivity threshold for the Sobel method. EDGE ignores alledges that are not stronger than THRESH. If you do not specify THRESH, or if THRESH ¡s empty ([]}, EDGEchooses the valué automatically.

BW = EDGE(l,'sobel',THRESH,DIRECTION) specifies directionality for the Sobel method. DIRECTION is astring specifying whether to look for 'horizontal1 or 'vertical' edges, or 'both' (the default).

[BW,thresh] = EDGE(i;sobel',...) returns the threshold valué.

Prewitt Method

BW = EDGE(l,'prewitt') specifies the Prewitt method.

BW = EDGE(i;prew¡tt',THRESH) specifies the sensitivity threshold for the Prewitt method. EDGE ignores alledges that are not stronger than THRESH. If you do not specify THRESH, or if THRESH is empty ([]), EDGEchooses the valué automatically.

BW = EDGE(l,'prewitt',THRESH,DIRECTION) specifies directionality for the Prewitt method. DIRECTION is astring specifying whether to look for 'horizontal' or 'vertical' edges, or 'both' (the default).

[BW.thresh] = EDGE(l,'prewitt',...) returns the threshold valué.

Roberts Method

BW = EDGE(l,'roberts') specifies the Roberts method.

BW = EDGEfl.Yoberts1,THRESH) specifies the sensitivity threshold for the Roberts method. EDGE ignores alledges that are not stronger than THRESH. If you do not specify THRESH, or if THRESH is empty ([]), EDGEchooses the valué automatically.

[BW.thresh] = EDGEfl/roberts',...) returns the threshold valué,

Laplacian of Gaussian Method

BW = EDGE(l.'log') specifies the Laplacian of Gaussian method.

BW = EDGE(l,'log',THRESH) specifies the sensitivity threshold for the Laplacian of Gaussian method. EDGEignores all edges that are not stronger than THRESH. If you do not specify THRESH, or if THRESH is empty([]), EDGE chooses the valué automatically.

BW = EDGE(l,'log',THRESH,SIGMA) specifies the Laplacian of Gaussian method, using SIGMA as thestandard deviation of the LoG filter. The default SIGMA is 2; the size of the filter is N-by-N, whereN=CEIL(SIGMA*3)*2+1.

[BW.thresh] = EDGE(l,'log',...) returns the threshold valué.

Zero-cross Method

BW = EDGE(l,'zerocro5s',THRESH,H) specifies the zero-cross method, using the specified filter H. IfTHRESH is empty ([]), EDGE chooses the sensitivity threshold automatically.

[BW.THRESH] = EDGE(l,'zerocross',...) returns the threshold valué.

Canny Method

BW = EDGE(l,'canny') specifies the Canny method.

BW = EDGE(l,'canny',THRESH) specifies sensitivity thresholds for the Canny method. THRESH is a two-element vector in which the first element is the low threshold, and the second element is the high threshold. Ifyou specify a scalar for THRESH. this valué is used for the high threshold and 0.4*T_HRESH is used fgr_the

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 252: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO C: AYUDAS CITADAS DEL MATLAB - C.6 -

low threshold. If you do not specify THRESH, or if THRESH ¡s empty ([]), EDGE chooses low and high valúesautomatically.

BW = EDGE(i;canny',THRESH,SIGMA) specifies the Canny method, using SIGMA as the standard deviationoí the Gaussian filter. The default SIGMA is 1; the sizeof the filter is chosen automatically, based on SIGMA.

[BW.thresh] = EDGE(I,'canny',...) returns the threshold valúes as a two-element vector.

Class Support

lean beof class uintS, uint16, ordouble. BW isof class uintS.

Remarks

For the 'log' and 'zerocross1 methods, if you specify a threshold of O, the output image has closed contours,because it indudes atl of the zero crossíngs in the input image.

Example

Find the edges of the rice.tif image using the Prewitt and Canny methods:

I = imread ('rice.tif};BW1 = edge(l,'prewitt');BW2 = edge(l,'canny');imshow{BW1)figure, imshow(BW2)

See also FSPECIAL.

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 253: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D

LISTADO DEL PROGRAMA

D.l PÁGINA PRINCIPAL

function varargout = Hough_home(varargin)% HOUGH_HOME Application M-file for Houghjiome.fig% FIG = HOUGHJHOME launch Houghjiome GUI.% HOUGH_HOME(tcallback_namel,...) invoke the named callback.

% Last Modified by GUIDE v2.0 21-Apr-2003 16:46:17

if nargin == O % LAUNCH GUI

fig = openfig(mfilename,'reusel);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 254: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.2

% Genérate a structure of handles to pass to callbacks, and store it.handles = guihandles(fig);guidata(fig, handles);

if nargout > Ovarargout{1} = f¡g¡

end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

try¡f (nargout)

[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyardelse

eval(varargin{:}); % FEVAL switchyardend

catchdisp(lasterr);

end

end

%| ABOUT CALLBACKS:%¡ GUIDE automatically appends subfunction prototypes to this file, and%¡ sets objects' callback properties to cali them through the FEVAL%¡ switchyard above. This comment describes that mechanism.

Each callback subfunction declaration has the following form:<SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)

%| The subfunction ñame is composed using the object's Tag and the%| callback type separated by '_', e.g. 'slide^CalIback',%j 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.%l%| H is the callback object's handle (obtained using GCBO).%l%| EVENTDATA is empty, but reserved for future use.%l%| HANDLES is a structure containing handles of components in GUI using%| tags as fieldnames, e.g. handles. figurel, handles. slider2. This%¡ structure is created at GUI startup using GUIHANDLES and stored in%¡ the figure's application data using GUIDATA. A copy of the structure%¡ is passed to each callback. You can store additional information ¡n%| this structure at GUI startup, and you can change the structure%| during callbacks. Cali guidata(h, handles) after changing your%| copy to replace the stored original so that subsequent callbacks see%¡ the updates. Type "help guihandles" and "help guidata" for more%| information.%l%| VARARGIN contains any extra arguments you have passed to the%j callback. Specify the extra arguments by editing the callback%¡ property in the inspector. By default, GUIDE sets the property to:%| <MFILENAME>('<SUBFUNCTION_NAME>1, gcbo, [], guidata(gcbo))%¡ Add any extra arguments after the last argument, before the final%¡ closing parenthesis.

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 255: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.3 -

function varargout = Continuar1_Callback(h, eventdata, handles, varargin)

delete(handles.figure1)FIG = houghl

o/ __ „/o — — — —

function varargout = Salir1_Callback(h, eventdata, handles, varargin)

pos_size=get(handles.figure1,'Positionl);dlg_pos=[pos_size(1 )+pos_size(3)/5 pos_size(2)+pos_size(4)/5]¡user_response=modaldlg(dlg_pos);switch user_response

case 'NO'return

case 'SI1delete(handles.figurel)

end

function varargout = figure1_CloseRequestFcn(h,eventdata,handles,varargin)Salir1_Callback(h,eventdata, handles)

function answer = modaldlg(varargin)% MODALDLG Application M-file for modaldlg.fig% FIG = MODALDLG launch modaldlg GUI.% MODALDLGCcalIbackjiame1, ...) invoke the named callback.

% Last Modified by GUIDE v2.0 18-Mar-2003 10:28:15error(nargchk(0,4,nargin))if nargin == O | isnumeric(varargin{1}) % LAUNCH GUI

fig = openfigímfilename/reuse1);%set(fig/Color\get(0/defaultcontrolBackgroundColor1));

% Genérate a structure of handles to pass to callbacks, and store it.handles = guihandles(fig);gu¡data(fig, handles);

if nargout > Ovarargout{1} = fig;

end

if nargin == 1pos_size = get(fig,'Position');pos=varargin{1}¡íf length(pos) ~= 2

error('Argumento de entrada debe ser un vector de dos elementos1)endnew_pos = [pos(1) pos(2) pos_size(3) pos__size(4)];set(fig1lPosition'1new_pos1Visiblel,'ont)

enduiwait(fig);¡f ^ishandle(fig)

answer = 'Cancelar1;else

handles = guidata(fig);answer=handles.answer;delete(fig);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 256: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.4

end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

try[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard

catchdisp(lasterr);

end

end

%| ABOUT CALLBACKS:% GUIDE automatically appends subfunction prototypes to this file, and%¡ sets objects1 callback properties to cali them through the FEVAL%¡ switchyard above. This comment describes that mechanism.

%| Each callback subfunction declaration has the following form:%] <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)

%¡ The subfunction ñame is composed using the objects Tag and the%¡ callback type separated by'_', e.g. 'slider2_Callback',%¡ lfigure1_CloseRequestFcn'l 'axis1_ButtondownFcn'.

%j H is the callback object's handle (obtained using GCBO).

%j EVENTDATA is empty, but reserved for future use.

%¡ HANDLES is a structure contaíning handles of components in GUI using%¡ tags as fieldnames, e.g. handles.figurel, handles.slider2. This%¡ structure is created at GUI startup using GUIHANDLES and stored in%¡ the figure's application data using GUIDATA. A copy of the structure%¡ is passed to each callback. You can store additional information in%¡ this structure at GUI startup, and you can change the structure%¡ during callbacks. Cali guidata(h, handles) after changing your%j copy to replace the stored original so that subsequent callbacks see%¡ the updates. Type "help guihandles" and "help guidata" for more% information.

%¡ VARARGIN contains any extra arguments you nave passed to the%¡ callback. Specify the extra arguments by editing the callback%¡ property in the inspector. By default, GUIDE sets the property to:%¡ <MFILENAME>('<SUBFUNCTION_NAME>', gcbo, [], guidata(gcbo))%| Add any extra arguments after the last argument, before the final%j closing parenthesis.

function varargout= Si_Callback(h, eventdata, handles, varargin)

handles.answer='SI';guidata(h,handles)¡uiresume(handles. Cerrar);

function varargout = No_Callback(h, eventdata, handles, varargin)

handles.answer='NO';guidata(h, handles);uiresume(handles.Cerrar);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 257: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA -D.5-

o//o ——————— ——— — — ..——_—..— —_ _

function varargout = Cancelar_Callback(h, eventdata, handles, varargin)

D.2 PAGINA DE SELECCIÓN Y PREPROCESAMIENTO

function varargout = Houghl(varargin)% HOUGH 1 Application M-filefor Houghlfig% FIG = HOUGH1 launch Houghl GUI.% HOUGHICcalIbackjiame1,...) invoke the named callback.

% Last Modified by GUIDE v2.5 07-Oct-2003 09:23:10

¡fnargin<= 1 %LAUNCH GUI

¡f nargin == O % LAUNCH GUIinitial_dir=pwd¡varargin{1}=pwd¡

elseif nargin == 1 & existívararginflj/dir1)in¡tial_dir=varargin{1};

elseerrordlg('Argumento de entrada no valido1,...

'La entrada debe ser un directorio')return

endfig = openfigímfilename/reuse1);

% Genérate a structure of handles to pass to callbacks, and store it.handles = guihandles(fig);guidata(fig, handles);

load Jistbox(varargin{1}, handles)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 258: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.6 -

if nargout > Ovarargout{1} = fig;

end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

tryif (nargout)

[varargout{1:nargout}] = feval(vararg¡n{:})¡ % FEVAL switchyardelse

feva!(varargin{:}); % FEVAL switchyardend

catchdisp(lasterr);

end

end

%| ABOUT CALLBACKS:%j GUIDE automatically appends subfunction prototypes to this file, and%| sets objects1 callback properties to cali them through the FEVAL%¡ switchyard above. This comment describes that mechanism.%l%| Each callback subfunction declaration has the following form:%| <SUBFUNCTION_NAME>(H, EVENTDATA, HANDLES, VARARGIN)%l%| The subfunction ñame is composed using the object's Tag and the%¡ callback type separated by'_', e.g. 'slider2_Callback',%¡ 'figure1_CloseRequestFcn', 'axis1_ButtondownFcn'.%l%| H is the callback object's handle (obtained using GCBO).%l%| EVENTDATA is empty, but reserved for future use.%|%| HANDLES is a structure containing handles of components in GUI using%| tags as fieldnames, e.g. handles.figurel, handles.slider2. This%| structure is created at GUI startup using GUIHANDLES and stored in%| the figure's application data using GUIDATA. A copy of the structure%¡ is passed to each callback. You can store additional information in%¡ this structure at GUI startup, and you can change the structure%¡ during callbacks. Cali guidata(h, handles) after changing your%¡ copy to replace the stored original so that subsequent callbacks see%¡ the updates. Type "help guihandles" and "help guidata" for more%| information.%l%| VARARGIN contains any extra arguments you have passed to the%| callback. Specify the extra arguments by editing the callback%¡ property in the inspector. By default, GUIDE sets the property to:%¡ <MFILENAME>('<SUBFUNCTION_NAME>'( gcbo, [], guidata(gcbo))%¡ Add any extra arguments after the last argument, before the final%j closing parenthesis.

function load_listbox(dir_path,handles)

cd (dir_path)dir_struct=dir(dir_path);[sorted_names1sorted_index]=sortrows({dir_struct.name}');handles.file_names=sorted_names;handles. is_dir=[dir_struct.isdir]¡

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 259: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.7 -

handles.sorted_index=[sorted_index];guidata(handles.Hough1 .handles)set(handles.listbox1,'String',handles.file_names,Valué1,1)set(handles.text1 /String'.pwd)

function varargout = Archivo_1_Callback(h, eventdata, handles, varargin)

function varargout = Nuevo_Callback(h, eventdata, handles, varargin)

nuevo_Callback(h, eventdata, handles)

•j/-/O ™~™~—-—-—- ™— _____

function varargout = listbox1_Callback(h, eventdata, handles, varargin)

if strcmp(get(handles.Hough1 .'SelectionType'j/open')index_selected-get(handles.listbox1, Valué1);file_list=get(handles.listboxi;string')¡filename=file_list{index_selected};if handles.is_dir(handles.sorted_jndex(index_selected))

cd (filename)load_listbox(pwd,handles)

else[path,name,ext,var]=fileparts(filename);switch extcase {'.bmp'/.jpg'/.pcx'/.BMP'/.JPG',1.PCX1}

k=imfinfo(filename);Nmreadífílename.kOJ.Format);axes(handles.imor)%clear ¡morimshow(l)

case {'.gif,'.GIF'}

axes(handles.imor)imshow(filename)

case '.fig1

guide (filename)otherwise

tryopen(filename)

catcherrordlg(lasterr,'Error de tipo de archivo1,'modal')

endend

endend

function varargout = seleccion_Callback(h, eventdata, handles, varargin)

index_selected=get(handles.listbox1, Valué');

F. WLAD1MIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 260: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.8 -

fileJist=get(handles.listbox1plStringl);filename=filejist{index_selected};k=imfinfo(filename);

prueba=k(1).BitDepth;%z=get(k(1),'ColorType')¡f (prueba==24)

set(handles.monocromatico,'VisibleVon');setíhandIes.binim.Visible'/on');axes(handles.imor)axis image

elseif prueba==8[l,map]=imread(filename);set(handles.binim,VisibleYon');axes(handles.binim)Ímshow(l)J=i;save Jset(handles.b¡narizac¡on,'Vis¡bleVon')

elseif prueba<8[l,map]=imread(filename);set(handles.binim,Visible1,'on')¡axes(handles.binim)imshow(l)J=l;save Jset(handles.binarizacion, Visible1,'on')

elseif k(1).Format=='GIF'[l,map]=imread(filename}¡J=ind2gray(l,map);axes(handles.imor);imshow(J);setíhandles.binim/VisibleYon');axes(handles.binim)imshow(J)save J

set(handles.binarizacion, Visible1, 'on')endend

o/ _/o _—_—______— — — -— ______

function varargout = monocromatico_Callback(h1 eventdata, handles, varargin)

index_selected=get(handles.listbox1, Valué');file_list=get(handles.listbox1/Stringl)¡filename=file_list{index_selected};l=imread(filename);axes(handles.binim)J=RGB2GRAY(I);imshow{J)save Jsetíhandles.binarizacion/Visible'.'on');

function varargout = binarizacion_Callback(h, eventdata, handles, varargin)

load J;thresh=[0.1 0.45];[L,L1]=edge(J,'cannyl,thresh);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 261: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.9 -

% m=0.5¡K=edge(L);axes(handles.binim)imshow (~K)save L

% set(handles.Procesamiento, Visible', 'on');set(handles.Algo_fwbrn, Visible1,'on');set{handles.Algo_1,Visible','on');set(handles.Algo_2,Visible1,'on');setíhandles.tiempoVVisibleYon');set(handles.remido/Visible','on');set(handles.nuevo, Visible','on');

function varargout = Salir_Callback(h, eventdata, handles, varargin)pos_size=get(handles.Hough1,'Position1);dlg_pos=[pos_size(1)+pos_size{3)/5 pos_size(2)+pos_size(4)/5];user_response=modaldlg(dlg_pos);switch user_responsecase {'no', 'cancel'}

returncase 'SI1

deleíe(handles.Houghl)FIG = HOUGHJ-IOME

end

function varargout = Algo_2_Callback(h, eventdata, handles, varargin)

set(handles.tc_algo2,VisibteYonl);

o/ _ _______________ ___________ _/o ----------------------- — — — ------------ ™- — _ —

function varargout = Algo_fwbm_Callback(h, eventdata, handles, varargin)

set(handles.tcfwbm, Visible1, 'on');delete(handles.Houghl);fig=houghfwbm;

o/ _________________ _______________/o

function varargout = Algo_1J3allback(h, eventdata, handles, varargin)

set(handles.tc_algo1, Visible', 'on');delete(handles.Houghl);FIG = HOUGHCIRCULO;

% -----------------------------------------------------------------function varargout = reinicio_Callback(h, eventdata, handles, varargin)

set(handles.tcfwbm, Visible', 'off);set(handles.tc_algo1,VisibleYoff);set(handles.tc_algo2, Visible1, 'off);

function varargout = nuevo_Callback(h, eventdata, handles, varargin)

delete(handles.Houghl);FIG=Hough1;

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 262: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA -D.10-

function varargout= Hough1_CloseRequestFcn(h, eventdata, handles, varargin)

Salir_Callback(h, eventdata, handles)

D.3 PÁGINA DE CÁLCULO DEL ALGORITMO SOLO LÍNEAS

function varargout = houghfwbm(varargin)% HOUGHFWBM Application M-fíle for houghfwbm.fig% FIG = HOUGHFWBM launch houghfwbm GUI.% HOUGHFWBM('callback_name', ...) invoke the named callback.

% Last Modified by GUIDE v2.0 10-Aug-2003 16:15:22

if nargin == O % LAUNCH GUI

fig = openfig(mfi!ename,'new');

% Genérate a structure of handles to pass to callbacks, and store ithandlesl = guihandles(fig);guidata(fig, handlesl);

% set{handles1.imagen1, Visible','on')¡% axes(handles1.imagen1)% load K¡% ¡mshow(K);

%uiwait(fig)¡

if nargout > Ovarargout{1} = fig;

end

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 263: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.ll -

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

tryif (nargout)

[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyardelse

feval(varargin{:}); % FEVAL switchyardend

catchdisp(lasterr);

end

end

%|ABOUTCALLBACKS:%¡ GUIDE automatically appends subfunction prototypes to this file, and%¡ sets objects' callback properties to cali them through the FEVAL%j switchyard above. This comment describes that mechanisrn.%l%| Each callback subfunction declaration has the following form:%| <SUBFUNCTIONJMAME>(H, EVENTDATA, HANDLES, VARARGIN)%l%| The subfunction ñame is composed using the object's Tag and the%| callback type separated by '_', e.g. 1slider2_Ca!!backl,%¡ 'figure1_C!oseRequestFcn\%l%| H is the callback object's handle (obtained using GCBO).%|%| EVENTDATA ¡s empty, but reserved for future use.%l%| HANDLES is a structure containing handles of components in GUI using%j tags as fieldnames, e.g. handles.figurel, handles. slider2. This% structure is created at GUI startup using GUIHANDLES and stored in%| the figure's application data using GUIDATA. A copy of the structure%¡ is passed to each callback. You can store additional Information in%| this structure at GUI startup, and you can change the structure%¡ during callbacks. Cali guidata(h, handles) after changing your%| copy to replace the stored original so that subsequent callbacks see% the updates. Type "help guihandles" and "help guidata" for more%| information.%|% VARARGIN contains any extra arguments you nave passed to the%¡ callback. Specify the extra arguments by editing the callback%¡ property in the inspector. By default, GUIDE sets the property.to:%| <MFILENAME>r<SUBFUNCTION_NAME>'p gcbo, [], guidata(gcbo))%| Add any extra arguments after the last argument, before the final%| closing parenthesis.

function varargout = inicio_Callback(h, eventdata, handlesl, varargin)

%load 'K1

axes(handles1 .imagenl )load L;imshow (L);tic;theta=(0:179)';[R,xp]=radon(L,theta)¡cx=size(L,2)/2-1¡

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 264: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D. 12

cy=size(L.1)/2-1;set(handles1.Gráfica/Visible1,'on')axes(handles1 .Gráfica)imagesc(theta,xp, R),colorbar;t1=tocsave t1xlabelf'Angulo (grados)')(ylabel('Distancia del centro de la imagen (pixeles)1

title('\fontsize{14} \bf Espacio transformado1);set(handles1.Continuar, Visible1,'on');setíhandleslvotos.'Visible'/on');set{handles1.Bordes,'VisibleYon');save R;

o/n/O —--——---———™ __________________ _______

function varargout = reinicio_Callback(h, eventdata, handlesl, varargin)

closereqFIG = HOUGH1;

function varargout = sal¡r_Callback(h, eventdata, handlesl, varargin)

closereqFIG = HOUGHJHOME;

o/ ./o - — _ - . _ _

p¿/o ——. - —

function varargout = houghfwbn\_CloseRequestFcn(h, eventdata, handlesl, varargin)

salir_Cailback(h, eventdata, handlesl)

function varargout = Continuar_Callback(h, eventdata, handlesl, varargin)

load Rload t1tic;p=get(handles1 .votos/String1);s=str2num(p);i=find(R>s);[foo,ind]=sort(-R(i));

[y,x]=ind2sub(size(R),k);t=-theta(x)*pi/180;r=xp(y);lineas=[cos(t) sin(t) -r];lineas(:,3)=lineas(:,3)-lineas(:,1)*cx-lineas(:,2)*cy;axes(handles1 .Bordes);imshow(~K);title('\fonts¡ze{12} \bf Imagen gradiente con lineas1);drawjines(lineas);t2=toc;t=t1+t2;I=num2str(t);set(handles1 .textS.'String'J)

function varargout = votos_Callback(h, eventdata, handlesl, varargin)

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 265: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.13 -

% I=get(handles1 .votos.'String');% set(handles1.picos,'Value',l);

function [XX,YY] = drawjines(l_, X, Y, It)

if nargin < 4It = '-';

end¡f nargin < 3

¡f nargin < 2It = '-';

elselt = X;

endV = axis;X = V(1:2); Y = V(3:4);

hold on

end

i = find(abs(L(:,1)) < abs(L(:,2)))¡j - find(abs(L(:,1)} >= abs(L(:,2)))¡

YY1 = -L{i,1)./L(i,2)*X + -L(i,3)./L(i,2)*ones(size(X));XX1 =ones(length(i),1)*X;

XX2 = -L(|,2)./Lü,1)*Y + -L(j,3)./L(j,1)*ones(size(Y));YY2 = ones(length(j),1)*Y;

XX = [XX1'XX2'];YY = [YY1'YY2']¡

[foo,k] = sort([i; j]);plot(XX(:,k),YY(:,k),lt)if nargin < 3hold offend

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 266: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA -D.14

D.4 PAGINA DE CALCULO DEL ALGORITMO SOLO CURVAS

function varargout = houghcirculo(varargin)% HOUGHCIRCULO Application M-file for houghcirculo.fig% FIG = HOUGHCIRCULO íaunch houghcirculo GUI.% HOUGHCIRCULO('callback_name', ...) invoke the named callback.

% Last Modified by GUIDE v2.5 28-Oct-2003 11:27:35

¡f nargin == O % LAUNCH GUI

fig = openfig(mfilename/reuse');

% Genérate a structure of handles to pass to callbacks, and store it.handlesS = guihandles(fig);guidata(fig, handlesS);

if nargout > Ovarargout{1} = fig;

end

elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK

tryif (nargout)

[varargout{1:nargout}] = feval(varargin{:})¡ % FEVAL switchyardelse

feval(varargin{:})¡ % FEVAL switchyardend

catch

enddisp(lasterr);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 267: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.15 -

end

%| ABOUT CALLBACKS:%¡ GUIDE automatically appends subfunction prototypes to this file, and%¡ sets objects1 callback properties to cali them through the FEVAL%¡ switchyard above. This comment describes that mechanism.%1%| Each callback subfunction declaration has the following form:%| <SUBFUNCTION_NAME>(H, EVENTDATA, MANÓLES, VARARGIN)%l%| The subfunction ñame is composed using the object's Tag and the%| callback type separated by '_', e.g. 'slider2_Callback',%| 'figure^CloseRequestFcn1, 'axis1_ButtondownFcn'.%l%| H is the callback object's handle (obtained using GCBO).%|%| EVENTDATA is empty, but reserved for future use.%l%| HANDLES is a structure containing handles of components in GUI using%| tags as fieldnames, e.g. handles.figurel, handles.slider2. This%¡ structure is created at GUI startup using GUIHANDLES and stored in%¡ the figure's application data using GUIDATA. A copy of the structure%j is passed to each callback. You can store additional information in%| this structure at GUI startup, and you can change the structure%j during callbacks. Cali guidata(h, handles) after changing your%¡ copy to replace the síored original so that subsequent callbacks see%¡ the updates. Type "help guihandles" and "help guidata" for more%¡ information.%l

%| VARARGIN contains any extra arguments you have passed to the%| callback. Specify the extra arguments by editing the callback%1 property in the inspector. By default, GUIDE sets the property to:%| <MFILENAME>('<SUBFUNCTION_NAME>TT gcbo, [], guidata(gcbo))%| Add any extra arguments after the last argument, before the final%¡ closing parenthesis.

/O —— _ - . _ _ — _ - —.______

function varargout = inicio_Callback(h, eventdata, handlesS, varargin)

load J;axes(handles3.im_norm);imshow(J);

% — Executes during object creation, after setting all properties.function edit1_CreateFcn(hObject, eventdata, handlesS)% hObject handle to editl (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER,if ispc

set(hObject,'BackgroundColorl,'whitel);else

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 268: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.16 -

setíhObject/BackgroundCotor'.getíO/defaultUicontroIBackgroundColor'));end

function ed¡t1_Callback(hObject, eventdata, handlesS)% hObject handle to editl (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and userdata (see GUIDATA)

% Hints: get(hObject,'String') returns contents of editl as text% str2double(get(hObjectp'String')) returns contents of editl as a double

r=str2double(get(hObject,'String'));save r;

% — Executes during object creation, after setting all properties.function edít2_CreateFcn(hObject, eventdata, handles3)% hObject handle to ed¡t2 (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.% See ISPC and COMPUTER.if ispc

setíhObject/BackgroundColor1, 'white');else

setthObject/BackgroundColor'^etfO.'defaultUicontroIBackgroundColor1));end

function edit2_Callback(hObject, eventdata, handlesS)% hObject handle to edit2 (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'Str¡ng') returns contents of edit2 as text% str2double(get(hObjecVString')) returns contents of edit2 as a double

l=str2double(get(hObject;string'));save I;

% — Executes on button press in continuarS.

function continuar3_Callback(hObject, eventdata, handles3)% hObject handle to continuarS (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and user data (see GUIDATA)

load J;ticimwriteíJ/proc.jpg1);axes(handles3. resultado);[p,m] = coin_detect2Cproc.jpg');%axes(handles3.graf)%imagesc(m)%imshow(m)t5=toc;texto=num2str(t5);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 269: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.17 -

set(handles3.text2,'Stringl,texto)

% — Executes on button press in reiniciar_cir.function re¡niciar_cir_Callback(hObject, eventdata, handlesS)% hObject handle to reiniciar_cir (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and user data (see GUIDATA)

closereqFIG = HOUGH1;

% — Executes on button press in salir_cir.function salir_c¡r_Callback(hObject, eventdata, handlesS)% hObject handle to salir_cir (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and user data (see GUIDATA)

closereqFIG = HOUGH HOME;

% — Executes when user attempts to cióse circuios.function circulos_CloseRequestFcn(hObject, eventdata, handlesS)% hObject handle to circuios (see GCBO)% eventdata reserved - to be defined in a future versión of MATLAB% handles structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure

sali^ci^CalIbackíhObject, eventdata, handlesS)

function [circimg, himg] = coin_detect2(imfile, varargin)

% dist is the distance between cells in the hough space of circle centers% thresh define low and high thresholds for the canny edge detector

dist = 2;thresh = [0.1 0.45];

if (nargin > 2)dist = varargin(1);thresh = varargin(2);

elseif (nargin > 1)if (size(varargin(1), 2) == 1)dist = varargin(1);

elseif (size(varargin(1), 2) == 2)thresh = varargin(1);

endend

coin = imreadOmfile/jpg1);%axes(handles3.resultado);¡magesc(coin)ecoin = edge(coin(:,:,1), 'canny1, thresh);imagesc(ecoin)%radii of the coins to be detectedh=27.5;f=50;load r;load I;

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 270: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.18

if (r~=0&l~=0)rf(r>=l)

rbv = [r, I];elseif(r<l)

rbv = [I, r]¡end

elseif (r==0&l~=0)rbv = [h, l]¡

elseif (r~=0&l==0)rbv = [r, f]¡

elseif (r==0&l==0)rbv = [h, f]¡

end%x,y coordinates of centers to considerxbv = 1:dist:size(ecoin, 2);ybv = 1;dist:size(eco¡n, 1);

%himg has the hough transform imagehimg = hough_circle2(ecoin, xbv, ybv, rbv);

%final image with circles markedcircimg = mark_c¡rcles2(coin, himg, rbv);

imshow(circimg);

function [himg] = hough_circle2(edgeimage, xbinvec, ybinvec, rbinvec)

% computes the hough transform

% xbins, ybins and rbins are the number of bins in hough spacexbins = size(xbinvec, 2);ybins = size(ybinvec, 2);rbins = size(rbinvec, 2);

% a, d are the first term and common difference for the A.P. formed% by xbinvec and ybinvec which are cells in the h-space of circle centersxa = xbinvec(1);ya = ybinvec(1);xd = xbinvec(2) - xa;yd = ybinvec(2) - ya;

% rows, cois contain edge pixel co-ordinates[rows, cois] = find(edgeimage);

% hspace is our accumulator arrayhspace(1 .ybins, 1:xbins, 1, 1:rbins) = 0;

fprintf('xbins %d ybins %d rbins %d\n', xbins, ybins, rbins);fprintf('edge pixels %d\n\, 1));

forecount = 1:size(rows, 1)fprintf('edge pixels processed: %d\ total: %d\n', ecount, size(rows,1));xp = cols(ecount);yp = rows(ecount);

for rcount = 1: rbinsradius = rbinvec(rcount);rsqr = radius * radius;

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 271: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D. 19 -

xstart = fastsearch(xp-(radius/sqrt(2)), xa, xbins, xd, 1);xfinish = fastsearch(xp+(rad¡us/sqrt(2)), xa, xbins, xd, 1);ystart = fastsearch(yp-(radius/sqrt(2)), ya, ybins, yd, 1);yfinish - fastsearch(yp+(radius/sqrt(2)), ya, ybins, yd, 1);

%fill cells along x-axis spanning an angle starting 45 degrees to the%left of the vertical and ending 45 degrees to the right of verticalfor xcount = xstaitxfinish

xc = xbinvec( xcount);

xsqr = (xp - xc)*(xp - xc);

if (rsqr >= xsqr)ysqrt = sqrt(rsqr - xsqr);

ye = yp + ysqrt;ycount = fastsearch(yc, ya, ybins, yd);if (ycount ~= 0)

acc_count = hspace(ycount, xcount, 1, rcount);hspace(ycount, xcount, 1, rcount) = acc_count + 1;

end

ye = yp - ysqrt;ycount = fastsearch(yc, ya, ybins, yd);íf (ycount ~= 0)acc_count = hspace(ycount, xcount, 1, rcount);hspace(ycount, xcount, 1, rcount) = acc_count+ 1;end

end

end %for xcount

%fíll cells along y-axis spanning an angle starting 45 degrees%above the horizontal and ending 45 degrees below the horizontalfor ycount = ystartyfinish

ye = ybinvec(ycount);

ysqr=(yp-yc)*(yp-yc);

if (rsqr >= ysqr)xsqrt = sqrt(rsqr - ysqr);

xc = xp + xsqrt;xcount = fastsearch(xc, xa, xbins, xd);if (xcount ~= 0)

acc_count = hspace(ycount, xcount, 1, rcount);hspace(ycount, xcount, 1, rcount) = acc_count + 1;

end

xc = xp - xsqrt;xcount = fastsearchfxc, xa, xbins, xd);if (xcount ~= 0)

acc_count = hspace(ycount, xcount, 1, rcount);hspace(ycount, xcount, 1, rcount) = acc_count + 1;

end

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 272: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA _ D.20 -

end

end %for ycount

end

end

% rescale the hough image to original size by interpolaronfor rcount = 1:rbins

himg(:, :, 1, rcount) = imresize(hspace(:p :, 1, rcount), yd, 'bicubic');himg(:, :, 1, rcount) = himg(:,:, 1, rcount)/max(max(himg(:,:, 1, rcount)));

end%imagesc(himg)

function [circimg] = mark_c¡rcles(inimg, himg, rbv)

imsize = size(inimg);

circgray(1:imsize(1), 1:imsize(2)) = 0;

for rcount = 1 :size(rbv,2)

% thrshold hough space to get points with maximal chance of being% the centers of a circle.% label the image and compute centroid of each point cluster% consider the centroids as the centers of the detected circles

bwh = im2bw(himg(:,:l1,rcount), 0.67);bwh = imdilate(bwh, ones(3, 3));bwh = imerode(bwh, ones(3, 3));bwh = bwlabel(bwh);

stat= imfeature(bwh, 'Centroid1);

for coin = 1:size(stat,1)center = stat(coin). Centroid;circgray = circgray + draw_circle(center, rbv(rcount), imsize);

end

end

circimg = im2double(inimg);circimg(:,:,1) = circimg(:,:,1) + circgray;%circimg{:.:,2) = circimg(:,:,2) + circgray;%circimg(:,:,3) = circimgC,:^) + circgray;circimg = imadjust(circimg, [O 1], [O 1]);

function [count] = fastsearch(value, a, n, d, varargin)

% compute integer Índices corresponding to nearest bin in which% valué falls.% a - first element of the bin% d - distance between valúes in adjacent bins% n - number of bins% nargin > 4 => satúrate bin number if valué is out of bounds% elsejust return 0.

count = ((valué - a)/d) + 1;count = round(count);

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 273: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.21 -

if ((count < 1) | (count > n))if (nargin == 4)count = 0;

elseif (count < 1)count = 1;

elseif (count > n)count = n;

endeíse% ,e(orintf('%d %d %d %d %d\n',a, n, d, valué, count);end

% EXTRACTCIRCLES%% Function takes an image and its circle Hough transform, finds the% significant circles and draws them over the image%% Usage: extractcircles(im, h, rmin, thresh)%% arguments:% im - The original image% h - Its Hough Transform% rmin - Mínimum radius encoded in the Hough Transform.% thresh - The threshold level to use in the Hough Transform to% decide whether a peak in the Transform is significant

function extractcircles(im, h, rmin, thresh)

%hGTP is a matrix which is 1 where the valué of the corresponding position in h%is greater than h.

hGTP = h >= thresh;

%find connected components with bwlabeín[bwl, nregions] = bwlabeln(hGTP);

nregions

imshow(irn);

%find circle with máximum votes for each labelfor n = 1: nregions

mask = bwl == n;región = mask.*h;maxSoFar = 0;[rows.cols.arrays] = size(h);

%determine máximum circle[maxvaljayer] = max(max(max(region)));[x y I] = findfregion == maxval);

%display ciclesxmod(y.cols)layer+rmin

%draw circlecircle([x mod(y,cols)],layer+rmin);

end

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH

Page 274: ESCUELA POLITÉCNICA NACIONALbibdigital.epn.edu.ec/bitstream/15000/5481/1/T2256.pdf3.3.1 Principio del análisis de lsa Transformada de Hough 71 3.3.2 L Transformada a de Hough estándar

ANEXO D: LISTADO DEL PROGRAMA - D.22 -

function [circle] = draw_circle(center, radius, imgsize)

% draws a circle given the center and radius and the size of image% to return.

xsize = imgsize(2);ysize = imgsize(1)¡

circle(1:ysize, 1:xsize) = 0;

fortheta=1:1:360

pt = center + radius * [cos(theía*pi/180) sin(theta*p¡/180)];xp = fastsearch(pt(1), 1, xsize, 1);yp = fastsearch(pt(2), 1, ysize, 1);

i f ( (xp~=0)&(yp~=0))circle(yp, xp) = 1.0;

end

end

F. WLADIMIRO BASANTES M. PROCESAMIENTO DIGITAL DE IMÁGENES USANDO LA TRANSFORMADA DE HOUGH