function param = est_condens_PLS_Multi(frm, tmpl, param, opt)

%% Copyright (C) Qing Wang.
%% All rights reserved.

n = opt.numsample;
sz = size(tmpl.mean);
N = sz(1)*sz(2);

param.param = repmat(affparam2geom(param.est(:)), [1,n]); %param.est存储的是affparam2mat格式的参数

param.param = param.param + randn(6,n).*repmat(opt.affsig(:),[1,n]); %以上一组参数为均值，以设定的参数为标准差，得到预测结果
wimgs = warpimg(frm, affparam2mat(param.param), sz);

tmp = tmpl.template;
tmp(:,sum(abs(tmpl.template),1)==0) = [];
num_tmpl = size(tmp,2);
num = min(num_tmpl, opt.num_tmpl);
distance = zeros(1,num);
index = zeros(1,num);
for i=1:num
    mean = tmpl.mean(:,:,i);
    mean = mean(:);
    template = tmpl.template(:,i);
    W = tmpl.W(:,:,i);
    diff = reshape(wimgs,[N,n]) -  repmat(mean,[1,n]);     
    coef = W'*diff;   
    diff = coef - repmat(template,[1,n]); 
    diff = sum(diff.^2);
    [mindis,minidx] = min(diff);
    distance(i) = mindis;
    index(i) = minidx;    
end
[mindis,minidx] = min(distance);
param.mini_t_idx = minidx;
param.mini_t_dis = mindis;
[maxdis,maxidx] = max(distance);
param.max_t_idx = maxidx;
param.max_t_dis = maxdis;
minidx = index(minidx);


param.est = affparam2mat(param.param(:,minidx));
param.wimg = wimgs(:,:,minidx);


