function [h,J]=er_opt(x_1,x_2,N,r_1,r_2)
%ER_OPT	[h,J]=er_opt(x_1,x_2,N,r_1,r_2)
%	Computes an optized FIR filter of size NxN and returns the filter 
%	coefficients h. r_1 and r_2 are the 2D autocorrelation matrices
%	of x_1 and x_2, and if supplied, the x_1 and x_2 inputs may be [].
%	The filter is optimal with respect to the Energy Ratio (ER).
%
%	Identical to the filter design technique described in H. Singh and 
%	A. Mahalanobis, ``Correlation filters for texture recognition
%	and applications to terrain-delimitation in wide-area
%	surveillance'', Proc. ICASSP-94, pp. 153-156, volume V.
%
%	Example use
%	x1=hipsread('brodatz/D92.hips',0:127,0:127);
%	x2=hipsread('brodatz/D4.hips',0:127,0:127);
%	h=er_opt(x1,x2,6);


% Compute the correlation matrices
if nargin<4,
  r_1=corrcoeff(x_1,x_1,N);
  r_2=corrcoeff(x_2,x_2,N);
end
R_1=r2R(r_1,N);
R_2=r2R(r_2,N);

% Solve the optimization equation
[V,D]=eig(inv(R_2)*R_1);
[lambda,idx]=max(max(D));
h=V(:,idx);

J=(h'*R_1*h) / (h'*R_2*h);

h=reshape(h,N,N)';
