# Source code for pysteg.features.ale

```##  \$Id\$
## -*- coding: utf-8 -*-

"""
:Module:    pysteg.features.ale
:Date:      \$Date\$
:Revision:  \$Revision\$
:Author:    © 2012: Hans Georg Schaathun <georg@schaathun.net>
"""

from .cm import cooccurrence
import numpy as np

__all__ = [ "ale1d", "ale2d" ]

# 1D ALE features
# ===============

def alepts(h,S):
"""
Return a list of local extrema on the histogram h
restricted to the set S.
"""
return [ x for x in S if (h[x] - h[x-1])*(h[x] - h[x+1]) > 0 ]
def alef1(h,E):
"Calculate the ALE feature based on the list E of local extrema."
return sum( [ abs(2*h[x] - h[x-1] - h[x+1]) for x in E ] )
[docs]def ale1d(I):
"""Return the first-order ALE features f_1 and f_2."""
if I == None:
return [ "ALE1D-f1", "ALE1D-f2", ]
h = np.histogram(I.flatten(),bins=list(xrange(257)))[0]
E1 = alepts(h,xrange(3,253))
f1 = alef1(h,E1)
E2 = alepts(h,[1,2,253,254])
f2 = alef1(h,E2)
return [f1,f2]
def ale0(I):
"""Return the original ALE feature f_0."""
h = np.histogram(I.flatten(),bins=list(xrange(257)))[0]
E0 = alepts(h,xrange(1,255))
f0 = alef1(h,E0)
return f0

# 2D ALE features
# ===============

def andf(x,y):
return x&y

[docs]def ale2d(I,dir=None):
"""Return the second-order ALE features for the given direction dir."""
if dir == None:
L = [ ale2d(I,d) for d in [ "h", "v", "d", "m" ] ]
if I == None:
return [ "ALE2D-%s-A" % (dir,), "ALE2D-%s-d" % (dir,), ]
h = cooccurrence(I,dir)[0]
A = h[1:-1,1:-1]
AT = [h[:-2,1:-1],h[2:,1:-1],h[1:-1,:-2],h[1:-1,2:]]
T  = reduce( andf, [ ( A < x ) for x in AT ] )
T |= reduce( andf, [ ( A > x ) for x in AT ] )
T &= T.transpose()
X = sum( np.abs(4*A[T] - sum( [ x[T] for x in AT ] )) )
(M,N) = h.shape
assert M == N
d = sum( [ h[k,k] for k in xrange(M) ] )
return [X,d]
```