Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Abstract—El avance de la visión artificial ha sufrido un Por todo ello y para tener una idea clara de la aplicación a
crecimiento exponencial en los últimos años. Uno de sus fines desarrollar es necesario realizar un estudio del estado del arte
es ayudar a observar detalles que al ojo humano se le escapan, para poder proponer mejoras sobre la tecnologı́a ya existente.
ya sea por su tamaño microscópico, por el entorno o incluso, por
la velocidad a la que deben ser registrados. El presente estudio
busca describir como dicha tecnologı́a, nos permite visualizar
matrı́culas eliminando las distracciones presentes en la imagen. II. E STADO DEL A RTE
Abstract—The advancement of artificial vision has exponential Actualmente existen diferentes alternativas para detectar
growth in recent years. One of its purposes is to help observe details
matrı́culas en vehı́culos. De cada metodologı́a parten multitud
that escape the human eye, either because of their microscopic size,
because of the environment or even because of the speed at which de versiones, a cada cual resuelve conflictos presentes en otras
they must be recorded. The present study seeks to describe how y viceversa, siendo de esta forma aplicaciones estandarizadas
this technology allows us to visualize license plates eliminating the para unas condiciones determinadas.
distractions present in the image. Una compañı́a que da solución a la búsqueda de matrı́culas
Index Terms—Percepción computacional, Actividad 2, proce- es OPENALPR [2], la cual posee una aplicación de código
samiento de imágenes, filtros espaciales, filtros morfológicos. abierto que emplea diferentes técnicas, las cuales serán co-
mentadas a continuación.
I. I NTRODUCCI ÓN
A · B = (A B) B (1)
Fig. 2. Ejemplo de imagen original y resultado de aplicar transformación Fig. 4. Ejemplo de imagen original y resultado de aplicar transformación
Apertura Bottom Hat
PERCEPCIÓN COMPUTACIONAL - ACTIVIDAD 2 3
5) Filtro Gaussiano: Este filtro permite eliminar el ruido IV. S OLUCI ÓN PLANTEADA
que pueda existir en una imagen produciendo un suavizado Una vez conocida la necesidad y el estado del arte de
más uniforme. El principal inconveniente es que puede llegar las soluciones existentes y las diferentes técnicas que se
a desenfocar una imagen, perdiendo la nitidez de esta. Para ello pueden aplicar para alcanzar el objetivo, en el presente trabajo
hay que controlar la desviación estándar de la distribución, ya se propone un algoritmo que encadena diferentes filtros y
que en caso de asignar una sigma demasiado alta se pueden transformaciones, dentro del ámbito de los espaciales y mor-
obtener resultados como el que se muestra en la siguiente fológicos, con el objetivo de identificar dentro de una imagen
ilustración [6]. En la Figura 5 se muestra un ejemplo de la sección de la misma que corresponde con una matrı́cula y
aplicación de este filtro. la obtención de sus contornos para una posterior segmentación
e identificación.
En concreto, la secuencia de operaciones que se propone es
la indicada a continuación:
1) Conversión de la imagen a escala de grises.
2) Aplicación de transformación Bottom Hat.
3) Aplicación de transformación Top Hat.
4) Gradiente.
5) Filtro Gaussiano.
6) Localización de la matrı́cula por intensidades.
7) Detección de bordes aplicando un filtro Canny.
Para llevar a cabo estas operaciones se hace uso de la librerı́a
Fig. 5. Ejemplo de imagen original y resultado de aplicar filtro Gaussiano
skimage de Python.
1) Conversión de la imagen a escala de grises: Las im-
6) Filtro Canny: La finalidad de este filtro es dar una agenes deben ser convertidas a escala de grises de forma
descripción a los objetos presentes. Dicho filtro aplica una que se trabajará con la iluminación de cada pı́xel, obteniendo
erosión en las zonas claras y una dilatación en las zonas un umbral adecuado para su procesado, de hecho, los filtros
oscuras obteniendo con ello dos imágenes, para posteriormente morfológicos y espaciales se comportan mejor en imágenes en
realizar una resta entra las imágenes obtenidas obteniendo el esta escala (grises) o binarizadas. Para ello se hace uso de la
contorno de los objetos presentes en la imagen de entrada [7]. función rgb2gray.
En la Figura 6 se muestra un ejemplo de aplicación de este 2) Aplicación de transformación Bottom Hat: Al aplicar
filtro. esta transformación se genera una imagen donde resaltan, entre
otras caracterı́sticas de la imagen, las letras de la matrı́cula en
un color blanco sobre fondo negro. El elemento estructural
utilizado será el de un cuadrado de tamaño 5x5. En la Figura
7 se puede observar el resultado al aplicar esta transformación,
donde lo que queda resaltado son los caractéres de la matrı́cula
y algún perfil del vehı́culo.
3) Aplicación de transformación Top Hat: El siguiente paso
en el proceso de localización de la matrı́cula es aplicar el
operador Top Hat, que devuelve una imagen con, únicamente,
los detalles que la apertura ha eliminado. Esto permite resaltar
Fig. 6. Ejemplo de imagen original y resultado de aplicar el filtro de Canny las transiciones bruscas. El elemento estructural utilizado será
el de un cuadrado de tamaño 5x5. En la Figura 8 se puede
observar el resultado al aplicar esta transformación.
III. D ESCRIPCI ÓN DEL PROBLEMA 4) Gradiente: Una vez aplicados las dos transformaciones
Primero se han de obtener las imágenes las cuales serán la anteriores, el siguiente paso es el de aplicar un gradiente fruto
entrada del algoritmo desarrollado. Estas pueden ser obtenidas de la resta de las imágenes resultantes de aplicar el Botton
a través de una cámara que se active por sensores de Hat y el Top Hat, obteniendo una imagen en escala de grises
movimiento o pueden ser frames de un vı́deo que, con las en la que se resaltan los detalles con alto contraste como las
cámaras actuales, significarı́a obtener 30 imágenes por se- letras y números de la matrı́cula y algunas zonas del interior
gundo. El algoritmo desarrollado se ha generado para que las del contorno del coche, como las llantas o el contorno de las
imágenes de entrada hayan sido realizadas con luz ambiental al ventanas. En la Figura 9 se puede ver el resultado de esta
aire libre. Aun limitando la toma de imágenes a exteriores se operación, consiguiendo que la parte con mayor intensidad de
pueden encontrar diversos problemas, tales como matrı́culas grises sea la matrı́cula.
distorsionadas por la toma de la foto o, incluso, que no se 5) Filtro Gaussiano: Una vez resaltadas las zonas candi-
encuentren centradas en la imagen formando un rectángulo con datas, el siguiente paso es aplicar un ruido Gaussiano con
ángulos de 90 grados. Estas casuı́sticas han sido contempladas una sigma ( ) lo suficientemente alta (10 en el algoritmo
tal y como se verá en los siguientes apartados. propuesto) para que, en la imagen obtenida en el gradiente,
PERCEPCIÓN COMPUTACIONAL - ACTIVIDAD 2 4
Fig. 7. Imagen original de vehı́culo y resultado de aplicar el filtro de Bottom Fig. 9. Imagen original de vehı́culo y resultado de aplicar el gradiente
Hat propuesto
se consiga un efecto similar al del cierre donde la zona que Fig. 10. Imagen original de vehı́culo y resultado de aplicar el filtro Gaussiano
a la imagen gradiente
forman los números y letras de la matrı́cula se convierta en
un bloque oscuro difuminado.
De esta forma se aumenta el contraste entre la matrı́cula 6) Localización de la matrı́cula por intensidades:
(totalmente oscura) y el resto de la imagen, lo cual facilitará su Una vez resaltada la zona donde está la matrı́cula del
localización en el punto siguiente del proceso. En la Figura 10 vehı́culo, se define una función denominada FindPlate,
se puede apreciar el resultado tras aplicar el filtro Gaussiano que recibe una imagen de entrada y devuelve la
PERCEPCIÓN COMPUTACIONAL - ACTIVIDAD 2 5
posición de la sección de la imagen más oscura para ello, se propone la aplicación de un filtro Canny con el
(rowStart, rowEnd, columnStart, columnEnd). que se detectan los bordes para el segmento localizado.
El proceso de esta función serı́a simplemente calcular los El filtro Canny identifica el mayor número de bordes de la
valores mı́nimos de intensidad para cada fila de la imagen imagen, minimizando el número de falsos negativos y falsos
y ordenarlos de menos a mayor. A continuación se busca el positivos en su identificación, que se realiza una única vez sin
bloque de filas donde haya menor intensidad. En la Figura 11 que el ruido presente en la imagen de lugar a falsos bordes.
se puede apreciar la imagen tras el filtro Guassiano junto con
su distribución de intensidades, de forma que las más bajas se
encuentran en las filas donde está la matrı́cula (marcadas en
rojo en la gráfica de la derecha).
R EFERENCES
[1] Ficha Histórica. Instituto Nacional de Estadı́stica. [Online]. Enlace:
https://www.ine.es/dyngs/IOE/es/fichaHistorica.htm?cid=1259930960724
[2] OpenALPR, OpenALPR de Rekor.[Online]. Enlace:
https://es.openalpr.com/contact
[3] López Fdez, J. M., González, J., & Galindo Vicente Arévalo, C., Re-
conocimiento automático de matrı́culas usando operadores morfológicos
y múltiples redes neuronales. 2006
Fig. 17. Proceso de localización de matrı́cula para la imagen Policia.jpg [4] Alegre E., Pajares G., de la Escalera A.Conceptos y métodos en visión
por computador. Grupo de Visión del Comité Español de Automática
4) Seat.jpg: En la Figura 18 se puede ver el resultado final (CEA). 2016
[5] Mundaca-Vidarte, G. Detección de caractéres de placas de automóviles
obtenido junto con la imagen original. mediante técnicas de visión artificial. 2016
[6] MathWorks. Filtrado gaussiano 2D de imágenes - MAT-
LAB imgaussfilt MathWorks España. [Online] Enlace:
https://es.mathworks.com/help/images/ref/imgaussfilt.html 2022
[7] MathWorks. Detección de bordes - MATLAB & SimulinkMathWorks
España. [Online] Enlace: https://es.mathworks.com/help/images/edge-
detection.html 2022
Preprocesamiento
The moving average filter replaces each pixel with the average pixel value of it and a neighborhood window of adjacent pixels . The effect is a
more smooth image with sharp features removed.
Increasing the size of a digital image is named “up sampling” and decreasing is named “down sampling”
For example, the range of values that pixels can have in a gray level of 3 bits is [0–7], while the range of values that pixels can take in a gray
level of 8 bits is [0–255]. The values that pixels have are also called the “intensity” of that pixel.
The processes applied to obtain a different version of the image on an image that does not have any deformation in its essence are included in
the operations in the Image Enhancement category
If an image is processed pixel by pixel, that is, if the process is applied to each pixel individually, it’s examined in Gray Level
Transformations and if the processes are applied to pixel groups larger than 1 pixel, it is examined in the Filtering category.
When we consider a picture matrix that can take values between 0 –255, we said that the pixels closer to 0, are closer to black
and the ones closer to 255, are closer to white.
Another linear process is to take the negative of the picture. This process is to subtract each pixel from its complement. Gamma
correction changes not only the amount of light but also the contrast settings of an image
Equalization Histogram
A histogram of an image is the graphical interpretation of the image’s pixel intensity values. It can be
interpreted as the data structure that stores the frequencies of all the pixel intens ity levels in the image
Histogram Equalization is an image processing technique that adjusts the contrast of an image by using
its histogram. To enhance the image’s contrast, it spreads out the most frequent pixel intensity values or
stretches out the intensity range of the image
Smoothing Filters are used to smooth the image. Basically when we apply this filter to an image for example via convolution
operation, we get a more smooth version of our input image.
Gaussian Filter (Gaussian Low Pass Filter) is a popular smoothing filter which is based on Gaussian Distribution where the
formula of Gaussian
Filtro de mediana
– Comúnmente empleado para eliminar artefactos (ruido)
impulsivo
– Se aplica mediante ventana deslizante de tamaño N muestras
– Desventaja: modifica el valor de las muestras que no son
anomalías
Realce de imagen
– Etapas iniciales de procesado (tras reducción de ruido)
– Capturar información relevante vs. información
prescindible
Transformación Logaritmica
Filtros Espaciales
– Promediado (integral) Elimina variaciones bruscas Atenúa el contraste entre píxeles próximos entre sí (fecuencias altas de
laseñal) LPF
– Substracción (derivada) Resalta diferencias o cambios bruscos Ensalza el contraste y atenúa áreas de valor similar de
intensidad entrepíxeles (frecuencias bajas de la señal) HPF
Operadores de Prewitt
– Máscaras 3 x 3
– Identificación de bordes en direcciones vertical y horizontal
Máscaras 3 x 3
– Identificación de bordes en direcciones vertical y hori zontal
– Menos sensible al ruido
Operador de Canny
Filtro paso-bajo de tipo gaussiano: suavizado y reducción de ruido
– Cálculo del gradiente en las diferentes direccione s
– Intensidad a 0 para los píxeles que no son un máximo local
– Umbral sobre la intensidad de los píxeles para binarizar la imagen y
quedarnos con las estructuras que potencialmente pueden
corresponderse con bordes
– Se eliminan aquellas estructuras más débiles que no están conectadas
con bordes mayores
Filtros Morfologicos
We start with finding an approximate estimate of the coins. For that, we can use the Otsu's binarization
ret, thresh = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)
Now we need to remove any small white noises in the image. For that we can use morphological
opening. To remove any small holes in the object, we can use morphological closing. So, now we know
for sure that region near to center of objects are foreground and region much away from the object are
background. Only region we are not sure is the boundary region of coins
So we need to extract the area which we are sure they are coins. Erosion removes the boundary pixels.
So whatever remaining, we can be sure it is coin. That would work if objects were not touching each
other. But since they are touching each other, another good option would be to find the distance
transform and apply a proper threshold. Next we need to find the area which we are sure they are not
coins. For that, we dilate the result. Dilation increases object boundary to background. This way, we can
make sure whatever region in background in result is really a background, since boundary region is
removed. See the image below.
The remaining regions are those which we don't have any idea, whether it is coins or background.
Watershed algorithm should find it. These areas are normally around the boundaries of coins where
foreground and background meet (Or even two different coins meet). We call it border. It can be
obtained from subtracting sure_fg area from sure_bg area.
Theory
Morphological transformations are some simple operations based on the image shape. It is
normally performed on binary images. It needs two inputs, one is our original image, second one
is called structuring element or kernel which decides the nature of operation. Two basic
morphological operators are Erosion and Dilation. Then its variant forms like Opening, Closing,
Gradient etc also comes into play. We will see them one-by-one with help of following image:
image
1. Erosion
The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of
foreground object (Always try to keep foreground in white). So what it does? The kernel slides
through the image (as in 2D convolution). A pixel in the original image (either 1 or 0) will be
considered 1 only if all the pixels under the kernel is 1, otherwise it is eroded (made to zero).
So what happends is that, all the pixels near boundary will be discarded depending upon the size
of kernel. So the thickness or size of the foreground object decreases or simply white region
decreases in the image. It is useful for removing small white noises (as we have seen in
colorspace chapter), detach two connected objects etc.
Here, as an example, I would use a 5x5 kernel with full of ones. Let's see it how it works:
import cv2 as cv
import numpy as np
img = cv.imread('j.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(img,kernel,iterations = 1)
Result:
image
2. Dilation
It is just opposite of erosion. Here, a pixel element is '1' if at least one pixel under the kernel is
'1'. So it increases the white region in the image or size of foreground object increases. Normally,
in cases like noise removal, erosion is followed by dilation. Because, erosion removes white
noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won't come back,
but our object area increases. It is also useful in joining broken parts of an object.
dilation = cv.dilate(img,kernel,iterations = 1)
Result:
image
3. Opening
Opening is just another name of erosion followed by dilation. It is useful in removing noise, as
we explained above. Here we use the function, cv.morphologyEx()
Result:
image
4. Closing
Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes
inside the foreground objects, or small black points on the object.
Result:
image
5. Morphological Gradient
Result:
image
6. Top Hat
It is the difference between input image and Opening of the image. Below example is done for a
9x9 kernel.
Result:
image
7. Black Hat
It is the difference between the closing of the input image and input image.
Result:
image
Goal
In this tutorial you will learn how to:
• Use the OpenCV function cv::Canny to implement the Canny Edge Detector.
Theory
The Canny Edge detector [40] was developed by John F. Canny in 1986. Also known to many as
the optimal detector, the Canny algorithm aims to satisfy three main criteria:
1. Filter out any noise. The Gaussian filter is used for this purpose. An example of a
Gaussian kernel of size=5 that might be used is shown below:
K=1159⎡⎣⎢⎢⎢⎢⎢⎢245424912945121512549129424542⎤⎦⎥⎥⎥⎥⎥⎥
2. Find the intensity gradient of the image. For this, we follow a procedure analogous to Sobel:
a. Apply a pair of convolution masks (in x and y directions:
Gx=⎡⎣⎢−1−2−1000+1+2+1⎤⎦⎥
Gy=⎡⎣⎢−10+1−20+2−10+1⎤⎦⎥
G=G2x+G2y−−−−−−−√θ=arctan(GyGx)
The direction is rounded to one of four possible angles (namely 0, 45, 90 or 135)
3. Non-maximum suppression is applied. This removes pixels that are not considered to be part of
an edge. Hence, only thin lines (candidate edges) will remain.
4. Hysteresis: The final step. Canny does use two thresholds (upper and lower):
a. If a pixel gradient is higher than the upper threshold, the pixel is accepted as an edge
b. If a pixel gradient value is below the lower threshold, then it is rejected.
c. If the pixel gradient is between the two thresholds, then it will be accepted only if it is
connected to a pixel that is above the upper threshold.
5. For more details, you can always consult your favorite Computer Vision book.
Purpose of Image processing
1. Image Acquisition
This is the first step or process of the fundamental steps of digital image processing. Image
acquisition could be as simple as being given an image that is already in digital form. Generally,
the image acquisition stage involves preprocessing, such as scaling etc.
2. Image Enhancement
Image enhancement is among the simplest and most appealing areas of digital image processing.
Basically, the idea behind enhancement techniques is to bring out detail that is obscured, or
simply to highlight certain features of interest in an image. Such as, changing brightness &
contrast etc.
3. Image Restoration
Image restoration is an area that also deals with improving the appearance of an image.
However, unlike enhancement, which is subjective, image restoration is objective, in the sense
that restoration techniques tend to be based on mathematical or probabilistic models of image
degradation.
Color image processing is an area that has been gaining its importance because of the significant
increase in the use of digital images over the Internet. This may include color modeling and
processing in a digital domain etc.
Wavelets are the foundation for representing images in various degrees of resolution. Images
subdivision successively into smaller regions for data compression and for pyramidal
representation.
6. Compression
Compression deals with techniques for reducing the storage required to save an image or the
bandwidth to transmit it. Particularly in the uses of internet it is very much necessary to
compress data.
7. Morphological Processing
Morphological processing deals with tools for extracting image components that are useful in th e
representation and description of shape.
8. Segmentation
Segmentation procedures partition an image into its constituent parts or objects. In general,
autonomous segmentation is one of the most difficult tasks in digital image processing. A rugged
segmentation procedure brings the process a long way toward successful solution of imaging
problems that require objects to be identified individually.
Representation and description almost always follow the output of a segmentation stage, which
usually is raw pixel data, constituting either the boundary of a region or all the points in the
region itself. Choosing a representation is only part of the solution for transforming raw data into
a form suitable for subsequent computer processing. Description deals with extracting attributes
that result in some quantitative information of interest or are basic for differentiating one class of
objects from another.
Recognition is the process that assigns a label, such as, “vehicle” to an object based on its
descriptors.
Knowledge may be as simple as detailing regions of an image where the information of interest
is known to be located, thus limiting the search that has to be conducted in se eking that
information. The knowledge base also can be quite complex, such as an interrelated list of all
major possible defects in a materials inspection problem or an image database containing high -
resolution satellite images of a region in connection with change-detection applications.