Monday, May 14, 2012

Hierarchical Difference

The idea is that larger regions should have more weight than smaller regions. Let R=0 be the largest scale, where the picture is represented by one pixel. Then R=1 is the next smallest scale, where the picture is represented by four pixels, and R=2 is the scale where the picture is represented by 16 pixels, and so on. Then we can calculate the difference between two images at multiple scales. We can also weight the different scales so that larger scales are more important. Here is some code:

def hierarchical_scale( x ):
    scales = list()
    rows, cols = x.shape
    dim = np.max( x.shape )
    R = int( np.log2( dim ) )
    for r in range( R ):
        means = list()
        for i in range( 2**r ):
            for j in range( 2**r ):
                ibin =   i   * rows / 2**r
                ifin = (i+1) * rows / 2**r
                jbin =   j   * cols / 2**r
                jfin = (j+1) * cols / 2**r
                means.append(np.mean(x[ibin:ifin,jbin:jfin]))
        scales.append( means )
    return scales

We then calculate the difference using the function:

def hierarchical_difference( x, y, scaled=True ):
    hsx, hsy = hierarchical_scale( x ), hierarchical_scale( y )
    s = 0
    for i in range( min( [ len( hsx ), len( hsy ) ] ) ):
        d = [ (hsx[i][j]-hsy[i][j])**2 for j in range(len(hsx[i])) ]
        if scaled:
            d = np.array( d ) * ( 1.0 / 2**(i) )
        else:
            d = np.array( d ) * ( 1.0 / 2**(0) )
        m = np.mean( d )
        s += m
    return s

 We can view all scales of an image using this function:

def view_all_scales( data ):
    scales = hierarchical_scale( data )
    no_scales = len( scales )
    for i in range( no_scales ):
        s = scales[ i ]
        a = np.array(s).reshape((np.sqrt(len(s)), np.sqrt(len(s)) ))
        matshow( a, cmap='gray' ) ;

No comments:

Post a Comment