Visión - dccia.ua.es · • Los pesos se denominan el kernel (o máscara) del filtro • Ejemplo:...

Preview:

Citation preview

VisiónSesión 2: Filtrado de imágenes

Departamento CCIAhttp://www.jtech.ua.es/vision/2011/

Hoy

• Representación de imágenes• Tipos de datos e imágenes en OpenCV• Filtros lineales• Suavizado del ruido• Resaltado de aristas con filtros lineales• Operadores morfológicos• Filtros y operaciones en OpenCV

• Referencias• Svetlana Lazebnik• Michael J. Black• Derek Hoeim

2

Imágenes como funciones

• Podemos pensar en una imagen como una función f, de R2 to R:

• f ( x, y ) devuelve la intensidad en la posición ( x, y )

• En la realidad, la imagen sólo está definida sobre un rectángulo [a,b]x[c,d]

• Una imagen de color son tres funciones juntas. Podemos formalizar este concepto con una función color image is just three functions pasted together. We can write this as a “vector-valued” function:

3

(S. Seitz)

¿Qué es una imagen digital?

• Trabajamos con imágenes digitales (discretas):• Muestreamos al espacio 2D sobre una rejilla regular• Discretizamos cada muestra (se redondea hasta el

entero más cercano)

• Si nuestras muestras están separadas en Δ, podemos escribir esto como:• f[i ,j] = Quantize{ f(i Δ, j Δ) }

• La imagen puede representarse entonces como una matriz de valores enteros

4

Discretización

• Array de sensores

• Perfil real 1D

5

Sensor Array

CMOS sensor

©Michael J. Black CS143 Intro to Computer Vision

Actual 1D profile

Imágenes digitales

• Niveles de gris

• Color, 3 canales (R,G,B)

6

The raster image (pixel matrix)0.92 0.93 0.94 0.97 0.62 0.37 0.85 0.97 0.93 0.92 0.990.95 0.89 0.82 0.89 0.56 0.31 0.75 0.92 0.81 0.95 0.910.89 0.72 0.51 0.55 0.51 0.42 0.57 0.41 0.49 0.91 0.920.96 0.95 0.88 0.94 0.56 0.46 0.91 0.87 0.90 0.97 0.950.71 0.81 0.81 0.87 0.57 0.37 0.80 0.88 0.89 0.79 0.850.49 0.62 0.60 0.58 0.50 0.60 0.58 0.50 0.61 0.45 0.330.86 0.84 0.74 0.58 0.51 0.39 0.73 0.92 0.91 0.49 0.740.96 0.67 0.54 0.85 0.48 0.37 0.88 0.90 0.94 0.82 0.930.69 0.49 0.56 0.66 0.43 0.42 0.77 0.73 0.71 0.90 0.990.79 0.73 0.90 0.67 0.33 0.61 0.69 0.79 0.73 0.93 0.970.91 0.94 0.89 0.49 0.41 0.78 0.78 0.77 0.89 0.99 0.93

Color ImageR

G

B

(Hoeim)

Tipos de datos de OpenCV

• Tipos de datos en OpenCV

• Matrices e imágenes• CvArr: clase abstracta• CvMat: matriz 2D multi-canal

• Constructor: CreateMat(filas: int, columnas: int, tipo: int)• tipo = CV_<bit_depth><S|U|F>C<num_channels>

• Ejemplo: CreateaMat(200,200, cv.CV_32FC3) devuelve una matriz formada por tuplas de 3 números reales de 32 bits

• Otros constructores:• CreateMatHeader(filas: int, columnas: int, tipo: int)• CreateData(array: CvArr)

• IplImage: imagen. Añade algunos elementos a CvMat propios de imágenes.• CreateImage (size: CvSize, depth: int, channels: int)

7

Estructura de imagen en OpenCV

• Las matrices se mapean en memoria como una secuencia de números del tipo especificado

• Para recorrer las matrices de forma eficiente (C):

• Posición de un punto en la matriz

• ROI: Región de interés• xOffset, yOffset, height, weight

8

Filtros

• Transforman imágenes in nuevas imágenes • Aplicaciones:

• Suavizado del ruido• Resaltado de aristas y otras características de la

imagen• Búsqueda de plantillas

• Filtros lineales y convolución• Muestreo y aliasing• Filtros como plantillas• Pirámides gaussianas

9

Hybrid Images, Oliva et al., http://cvcl.mit.edu/hybridimage.htm

Filtro lineal

• Operador de vecindad: el valor resultante de un píxel se calcula como una función de su vecindad

• Filtro lineal:

• El componente h se denomina el núcleo o máscara del filtro y los valores k,l representan la vecindad del píxel i,j

• La operación anterior es una correlación

• Convolución:

10

f

Convolución

• Reemplazamos cada píxel con la media ponderada de los píxeles vecinos

• Los pesos se denominan el kernel (o máscara) del filtro

• Ejemplo: la media de los 9 puntos vecinos se calcula con el siguiente kernel (mean filter)

• Filtros de imagen en OpenCV

• Filter2D realiza una convolución

11

111111111

Propiedades de los filtros lineales

• Linealidad:

filter(f1 + f2) = filter(f1) + filter(f2) filter(a f1 + b f2) = a filter(f1) + b filter(f2)

• Invarianza al desplazamiento (shift invariance): el mismo comportamiento independientemente de la posición del pixel:

filter(shift(f)) = shift(filter(f))

• Resultado teórico: cualquier operador lineal invariante al desplazamiento se puede representar con una convolución

• La linealidad nos permite construir filtros complejos:

12

Propiedades de los filtros lineales

• Linealidad:

filter(f1 + f2) = filter(f1) + filter(f2) filter(a f1 + b f2) = a filter(f1) + b filter(f2)

• Invarianza al desplazamiento (shift invariance): el mismo comportamiento independientemente de la posición del pixel:

filter(shift(f)) = shift(filter(f))

• Resultado teórico: cualquier operador lineal invariante al desplazamiento se puede representar con una convolución

• La linealidad nos permite construir filtros complejos:

12

Gaussianunit impulse

Laplacian of Gaussian

Ejemplos con distintas máscaras

13

• Blur

Sharpening

14

original smoothed (5x5)

detail

=

sharpened

=+

original detail

El problema del borde

• Cuando la máscara llega a los puntos del borde de la imagen no es posible hacer la convolución

• Varias técnicas posibles para “inventarse” los nuevos puntos:

• CopyMakeBorder es la función de OpenCV

15

Ruido en las imágenes

• Distintos tipos de ruido

• Ruido de sal y pimienta (salt and pepper noise): ocurrencias aleatorias de píxeles blancos y negros

• Ruido de impulso (impulse noise): ocurrencias aleatorias de píxeles blancos

• Ruido gausiano (gaussian noise): variaciones en la intensidad generadas por una distribución gausiana normal

16

Ruido gaussiano

• Modela bien el ruido real: suma de múltiples factores

• Ejemplo: ruido en imágenes reales• Comparativa de 5 cámaras: iPhone 4S, iPhone 4,

Samsung Galaxy SII, Olympus XZ-1, Canon 20D

17

Ars Technica: Can the iPhone 4S replace a "real" digital camera?

Suavizado del ruido con el filtro de media

• El filtro de media reemplaza un pixel por la media de valores de su vecindad

• Se denomina también filtro de caja (box filter)• Suaviza la imagen, eliminando las diferencias y,

por tanto, el ruido

• Mejora: filtrado gausiano, sustituimos el kernel por un kernel gaussiano que da más peso al centro y menos a los bordes

18

1 2 12 4 21 2 1

Kernel gaussiano

• Distintos valores de la σ y del tamaño del kernel cambian la forma de la gaussiana

• Consejo: el ancho del kernel debe ser 6σ

19

Choosing kernel width• The Gaussian function has infinite support,

but discrete filters use finite kernels

Source: K. Grauman

Choosing kernel width• Rule of thumb: set filter half-width to about 3ı

Separabilidad del filtro gaussiano

• Aplicado a convolución de un kernel gaussiano:

20

Separability example

2D convolution(center location only)( y)

The filter factorse e ac o sinto a product of 1D

filters:

* =Perform convolutionalong rows:

* =Followed by convolutionl th i i l

Source: K. Grauman

along the remaining column:

Filtrado gaussiano para eliminar ruido

• Aplicación de un filtro gaussiano y de caja

• Distintos valores de σ tienen distintos efectos en el filtrado del ruido. Mayores σ eliminan más ruido, pero difuminan más la imagen

21

Filtrado de mediana

• El filtro gaussiano no funciona bien con ruido sal y pimienta

• Filtro de mediana

• La mediana es un estimador robusto frente a outliers

22

Noise

• Salt and pepper noise: contains random occurrencesrandom occurrences of black and white pixels

• Impulse noise: contains random occurrences of white

Original Salt and pepper noise

occurrences of white pixels

• Gaussian noise: variations invariations in intensity drawn from a Gaussian normal distributiondistribution

Gaussian noiseImpulse noise

Source: S. Seitz

Original 3x3 5x5 7x7

Filtrado de mediana

• El filtro gaussiano no funciona bien con ruido sal y pimienta

• Filtro de mediana

• La mediana es un estimador robusto frente a outliers

22

Noise

• Salt and pepper noise: contains random occurrencesrandom occurrences of black and white pixels

• Impulse noise: contains random occurrences of white

Original Salt and pepper noise

occurrences of white pixels

• Gaussian noise: variations invariations in intensity drawn from a Gaussian normal distributiondistribution

Gaussian noiseImpulse noise

Source: S. Seitz

Original 3x3 5x5 7x7

Ejemplos del filtro de mediana

23

108 3 Image processing

(a) (b) (c) (d)

(e) (f) (g) (h)

Figure 3.18 Median and bilateral filtering: (a) original image with Gaussian noise; (b) Gaussian filtered; (c)median filtered; (d) bilaterally filtered; (e) original image with shot noise; (f) Gaussian filtered; (g) median filtered;(h) bilaterally filtered. Note that the bilateral filter fails to remove the shot noise because the noisy pixels are toodifferent from their neighbors.

3.3 More neighborhood operatorsAs we have just seen, linear filters can perform a wide variety of image transformations.However non-linear filters, such as edge-preserving median or bilateral filters, can sometimesperform even better. Other examples of neighborhood operators include morphological oper-ators that operate on binary images, as well as semi-global operators that compute distancetransforms and find connected components in binary images (Figure 3.11f–h).

3.3.1 Non-linear filtering

The filters we have looked at so far have all been linear, i.e., their response to a sum of twosignals is the same as the sum of the individual responses. This is equivalent to saying thateach output pixel is a weighted summation of some number of input pixels (3.19). Linearfilters are easier to compose and are amenable to frequency response analysis (Section 3.4).

In many cases, however, better performance can be obtained by using a non-linear com-bination of neighboring pixels. Consider for example the image in Figure 3.18e, where thenoise, rather than being Gaussian, is shot noise, i.e., it occasionally has very large values. Inthis case, regular blurring with a Gaussian filter fails to remove the noisy pixels and insteadturns them into softer (but still visible) spots (Figure 3.18f).

Median filtering

A better filter to use in this case is the median filter, which selects the median value from eachpixel’s neighborhood (Figure 3.19a). Median values can be computed in expected linear timeusing a randomized select algorithm (Cormen 2001) and incremental variants have also been

Original con ruido Filtro mediana

Original con ruido

108 3 Image processing

(a) (b) (c) (d)

(e) (f) (g) (h)

Figure 3.18 Median and bilateral filtering: (a) original image with Gaussian noise; (b) Gaussian filtered; (c)median filtered; (d) bilaterally filtered; (e) original image with shot noise; (f) Gaussian filtered; (g) median filtered;(h) bilaterally filtered. Note that the bilateral filter fails to remove the shot noise because the noisy pixels are toodifferent from their neighbors.

3.3 More neighborhood operatorsAs we have just seen, linear filters can perform a wide variety of image transformations.However non-linear filters, such as edge-preserving median or bilateral filters, can sometimesperform even better. Other examples of neighborhood operators include morphological oper-ators that operate on binary images, as well as semi-global operators that compute distancetransforms and find connected components in binary images (Figure 3.11f–h).

3.3.1 Non-linear filtering

The filters we have looked at so far have all been linear, i.e., their response to a sum of twosignals is the same as the sum of the individual responses. This is equivalent to saying thateach output pixel is a weighted summation of some number of input pixels (3.19). Linearfilters are easier to compose and are amenable to frequency response analysis (Section 3.4).

In many cases, however, better performance can be obtained by using a non-linear com-bination of neighboring pixels. Consider for example the image in Figure 3.18e, where thenoise, rather than being Gaussian, is shot noise, i.e., it occasionally has very large values. Inthis case, regular blurring with a Gaussian filter fails to remove the noisy pixels and insteadturns them into softer (but still visible) spots (Figure 3.18f).

Median filtering

A better filter to use in this case is the median filter, which selects the median value from eachpixel’s neighborhood (Figure 3.19a). Median values can be computed in expected linear timeusing a randomized select algorithm (Cormen 2001) and incremental variants have also been

Filtro gaussiano Filtro de mediana

El filtro de suavizado en OpenCV

• Smooth realiza un suavizado de la imagen aplicando distintos tipos de filtros

24

Filtrado para resaltar aristas

• Aristas: píxeles de la imagen donde se produce un fuerte gradiente (tanto positivo como negativo)

• Imagen suavizada con gaussiana

• Primera derivada

25

©Michael J. Black CS143 Intro to Computer Vision

Edges

•� Correspond to fast

changes

–� Where the magnitude

of the derivative is

large

©Michael J. Black CS143 Intro to Computer Vision

Edges

•� Correspond to fast

changes

–� Where the magnitude

of the derivative is

large

©Michael J. Black CS143 Intro to Computer Vision

Simple Signal

Discontinuous Smoothed with Gaussian

©Michael J. Black CS143 Intro to Computer Vision

Simple Signal

Discontinuous Smoothed with Gaussian

Derivadas con filtros lineales

• Podemos calcular la derivada con un filtro lineal

• En 2D tenemos que utilizar las derivadas parciales con respecto a x e y

26

©Michael J. Black CS143 Intro to Computer Vision

Compute Derivatives

We can implement this as a linear filter:

0 1 -1

1.0

0 1 -1

1.0

- [ -1 1]

Or [-1 0 1]

symmetric

¿Funciona con el ruido?

• Imagen original

• Suavizada con una gaussiana

• Derivadas

27

©Michael J. Black CS143 Intro to Computer Vision

Actual 1D profile

©Michael J. Black CS143 Intro to Computer Vision

Smoothed with a Gaussian

©Michael J. Black CS143 Intro to Computer Vision

Barbara signal and derivatives

Filtro suavizado gaussiano y derivada

• En 1D

• En 2D

28

©Michael J. Black CS143 Intro to Computer Vision

Derivatives and Smoothing

G dG

©Michael J. Black CS143 Intro to Computer Vision

In 2D

Compare with [-1 0 1] filters.

¿Funciona?

• La derivada amplifica las pequeñas variaciones

• Se podría utilizar un umbral para “detectar” las aristas

29

©Michael J. Black CS143 Intro to Computer Vision

1D Barbara signal

Smoothed Signal First Derivative

Note the “amplification” of small variations.

©Michael J. Black CS143 Intro to Computer Vision

Thresholding the

Derivative?

©Michael J. Black CS143 Intro to Computer Vision

Thresholding the

Derivative?

Una solución mejor: segunda derivada

• Cálculo de la segunda derivada

• Las aristas estarían en los cruces por el cero (zero crossing)

30

©Michael J. Black CS143 Intro to Computer Vision

Second Derivative

Filter kernel?

[1 -2 1]

©Michael J. Black CS143 Intro to Computer Vision

Maxima of first

derivative

“zero crossings”

of second

derivative

En 2D: Laplaciana

• Formulación

• Un filtro lineal

• Kernel de la Laplaciana

31

©Michael J. Black CS143 Intro to Computer Vision

The Laplacian

Just another linear filter.

©Michael J. Black CS143 Intro to Computer Vision

The Laplacian

Just another linear filter.

Aproximación de la Laplaciana

• La Laplaciana también se puede aproximar como una diferencia de gaussianas a diferentes escalas

32

©Michael J. Black CS143 Intro to Computer Vision

Approximating the Laplacian

•� Difference of Gaussians at different

scales.

©Michael J. Black CS143 Intro to Computer Vision Sept, 2007

expand

Gaussian Pyramid Laplacian Pyramid

The Laplacian Pyramid

- =

- =

- =

Pirámides de imágenes

• Las pirámides de imágenes permiten representar una imagen a múltiples escalas• Múltiples usos: características, compresión

• Pirámides gaussianas y laplacianas

33

Cruces por cero

• Imagen original

• Cruces por cero de la laplaciana

• Se denomina operador de Marr/Hildreth

34

©Michael J. Black CS143 Intro to Computer Vision

sigma=2�sigma=4�

LoG zero crossings �(where the filter response changes sign)�

Ponce & Forsyth

Otros filtros

• Sobel

• Imágenes “híbridas”, Oliva et al., http://cvcl.mit.edu/hybridimage.htm

35

Filtros morfológicos

• Filtros no lineales para imágenes binarias• Convolución de la imagen con el elemento

estructurante (kernel), seguida de una umbralización• Definimos la umbralización:

• Definimos la convolución entre una imagen f y el elemento estructurante s como el número de píxeles que están a 1 dentro del elemento estructurante de tamaño S

• Operaciones:• dilatación(f,s) = 𝜃(c,1)

• erosión(f,s) = 𝜃(c,S)

• mayoría(f,s) = 𝜃(c,S/2)

• apertura(f,s) = dilatación(erosión(f,s),s)• cierre(f,s) = erosión(dilatación(f,s),s)

38