[iahisteq] [Up] [iadftdecompose] Lessons

iacorrdemo
Illustrate the Template Matching technique

Demo Script

Image read and pattern selection

We have a gray scale image and a pattern extracting from the image.

>>> import Numeric

                  
>>> f = iaread('cameraman.pgm')

                  
>>> f = Numeric.asarray(f).astype(Numeric.Float)

                  
>>> iashow(f)
(256, 256) Min= 0.0 Max= 251.0 Mean=137.066 Std=87.20
>>> w = f[25:25+17,106:106+17]

                  
>>> iashow(w)
(17, 17) Min= 2.0 Max= 251.0 Mean=134.907 Std=95.62
f w

Image correlation

Pure image correlation is not good for template matching because it depends on the mean gray value in the image, so light regions gives higher score than dark regions. A normalization factor can be used which improves the template matching.

>>> w1 = w[::-1,::-1]

                  
>>> iashow(w1)
(17, 17) Min= 2.0 Max= 251.0 Mean=134.907 Std=95.62
>>> g = iapconv(f, w1)

                  
>>> iashow(g)
(256, 256) Min= 116275.0 Max= 9126292.0 Mean=5343926.605 Std=2885283.80
>>> i = Numeric.ones(Numeric.shape(w1))

                  
>>> fm2 = iapconv(f*f, i)

                  
>>> g2 = g/Numeric.sqrt(fm2)

                  
>>> iashow(g2)
(256, 256) Min= 136.512532208 Max= 2809.41203813 Mean=2044.395 Std=418.20
>>> v, pos = max(Numeric.ravel(g2)), Numeric.argmax(Numeric.ravel(g2))

                  
>>> (row, col) = iaind2sub(g2.shape, pos)

                  
>>> print 'found best match at (%3.0f,%3.0f)\n' %(col,row)
found best match at (114, 33)
w1 g g2

Correlation index

A better pattern matching is achievied subtrating the mean value on the image application.

>>> import MLab

                  
>>> n = Numeric.product(w.shape)

                  
>>> wm = MLab.mean(Numeric.ravel(w))

                  
>>> fm = 1.*iapconv(f,i)/n

                  
>>> num = g - (n*fm*wm)

                  
>>> iashow(num)
(256, 256) Min= -2250890.14187 Max= 2633058.47751 Mean=0.000 Std=381927.99
>>> den = Numeric.sqrt(fm2 - (n*fm*fm))

                  
>>> iashow(den)
(256, 256) Min= 21.2707053615 Max= 1900.28035265 Mean=596.674 Std=560.60
>>> cn = 1.*num/den

                  
>>> iashow(cn)
(256, 256) Min= -1313.92423297 Max= 1622.67016905 Mean=23.587 Std=425.71
>>> v, pos = max(Numeric.ravel(cn)), Numeric.argmax(Numeric.ravel(cn))

                  
>>> (row, col) = iaind2sub(g2.shape, pos)

                  
>>> print 'found best match at (%3.0f,%3.0f)\n' %(col,row)
found best match at (114, 33)
num den
cn

[iahisteq] [Up] [iadftdecompose] http://www.python.org