source: trunk/src/civ_matlab.m @ 331

Last change on this file since 331 was 331, checked in by sommeria, 12 years ago

further step toward civ2

File size: 32.6 KB
Line 
1%'civ_matlab': Matlab version of the PIV programs CivX
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   patch: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_uvmat(Param,ncfile)
8%
9%OUTPUT
10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, default=''
12% resul_conv: image inter-correlation function for the last grid point (used for tests)
13%
14%INPUT:
15% Param: input images and processing parameters
16% ncfile: name of a netcdf file to be created for the result (extension .nc)
17%
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
20%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
21%     This is part of the toolbox UVMAT.
22%
23%     UVMAT is free software; you can redistribute it and/or modify
24%     it under the terms of the GNU General Public License as published by
25%     the Free Software Foundation; either version 2 of the License, or
26%     (at your option) any later version.
27%
28%     UVMAT is distributed in the hope that it will be useful,
29%     but WITHOUT ANY WARRANTY; without even the implied warranty of
30%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
32%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
33
34function [Data,errormsg,result_conv]= civ_matlab(Param,ncfile)
35errormsg='';
36Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
37Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
38Data.Program='civ_matlab';
39Data.CivStage=0;%default
40ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
41ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
42mask='';
43maskname='';%default
44check_civx=0;%default
45check_civ1=0;%default
46check_patch1=0;%default
47
48if ischar(Param)
49    Param=xml2struct(Param);
50end
51
52%% Civ1
53if isfield (Param,'Civ1')
54    check_civ1=1;% test for further use of civ1 results
55    % caluclate velocity data (y and v in indices, reverse to y component)
56    [xtable ytable utable vtable ctable F result_conv errormsg] = civ (Param.Civ1);
57    if ~isempty(errormsg)
58        return
59    end
60    list_param=(fieldnames(Param.Civ1))';
61    Civ1_param=list_param;%default
62    for ilist=1:length(list_param)
63        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
64        %         eval(['Data.Civ1_' list_param{ilist} '=Param.Civ1.' list_param{ilist} ';'])
65        Data.(['Civ1_' list_param{ilist}])=Param.Civ1.(list_param{ilist});
66    end
67    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];% {'Civ1_Time','Civ1_Dt'}];
68    %     if exist('ncfile','var')% TEST for use interactively with mouse_motion (no file created)
69    Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'};%  cell array containing the names of the fields to record
70    Data.VarDimName={'NbVec1','NbVec1','NbVec1','NbVec1','NbVec1','NbVec1'};
71    Data.VarAttribute{1}.Role='coord_x';
72    Data.VarAttribute{2}.Role='coord_y';
73    Data.VarAttribute{3}.Role='vector_x';
74    Data.VarAttribute{4}.Role='vector_y';
75    Data.VarAttribute{5}.Role='warnflag';
76    Data.Civ1_X=reshape(xtable,[],1);
77    Data.Civ1_Y=reshape(Param.Civ1.ImageHeight-ytable+1,[],1);
78    Data.Civ1_U=reshape(utable,[],1);
79    Data.Civ1_V=reshape(-vtable,[],1);
80    Data.Civ1_C=reshape(ctable,[],1);
81    Data.Civ1_F=reshape(F,[],1);
82    Data.CivStage=1;
83   
84else
85    if exist('ncfile','var')
86        CivFile=ncfile;
87    elseif isfield(Param.Patch1,'CivFile')
88        CivFile=Param.Patch1.CivFile;
89    end
90    Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0') %look for the constant 'absolut_time_T0' to detect old civx data format
91    if isfield(Data,'Txt')
92        errormsg=Data.Txt;
93        return
94    end
95    if ~isempty(Data.absolut_time_T0')%read civx file
96        check_civx=1;% test for old civx data format
97        [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
98    else
99        if isfield(Param,'Fix1')
100            Data=nc2struct(CivFile,ListVarCiv1);%read civ1 data in the existing netcdf file
101        else
102            Data=nc2struct(CivFile,ListVarFix1);%read civ1 and fix1 data in the existing netcdf file
103        end
104    end
105end
106
107%% Fix1
108if isfield (Param,'Fix1')
109    ListFixParam=fieldnames(Param.Fix1);
110    for ilist=1:length(ListFixParam)
111        ParamName=ListFixParam{ilist};
112        ListName=['Fix1_' ParamName];
113        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
114        eval(['Data.' ListName '=Param.Fix1.' ParamName ';'])
115    end
116    if check_civx
117        if ~isfield(Data,'fix')
118            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
119            Data.fix=1;
120            Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
121            Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
122        end
123        Data.vec_FixFlag=fix(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
124    else
125        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
126        Data.VarDimName=[Data.VarDimName {'NbVec1'}];
127        nbvar=length(Data.ListVarName);
128        Data.VarAttribute{nbvar}.Role='errorflag';   
129        Data.Civ1_FF=fix(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
130        Data.CivStage=2;   
131    end
132end   
133%% Patch1
134if isfield (Param,'Patch1')
135    if check_civx
136        errormsg='Civ Matlab input needed for patch';
137        return
138    end
139    check_patch1=1;
140    Param.Patch1
141    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
142    Data.Patch1_Rho=Param.Patch1.SmoothingParam;
143    Data.Patch1_Threshold=Param.Patch1.MaxDiff;
144    Data.Patch1_SubDomain=Param.Patch1.SubdomainSize;
145    Data.ListVarName=[Data.ListVarName {'Civ1_U_Diff','Civ1_V_Diff','Civ1_X_SubRange','Civ1_Y_SubRange','Civ1_NbSites','Civ1_X_tps','Civ1_Y_tps','Civ1_U_tps','Civ1_V_tps'}];
146    Data.VarDimName=[Data.VarDimName {'NbVec1','NbVec1',{'NbSubDomain1','Two'},{'NbSubDomain1','Two'},'NbSubDomain1',...
147             {'NbVec1Sub','NbSubDomain1'},{'NbVec1Sub','NbSubDomain1'},{'Nbtps1','NbSubDomain1'},{'Nbtps1','NbSubDomain1'}}];
148    nbvar=length(Data.ListVarName);
149    Data.VarAttribute{nbvar-1}.Role='vector_x';
150    Data.VarAttribute{nbvar}.Role='vector_y';
151    Data.Civ1_U_Diff=zeros(size(Data.Civ1_X));
152    Data.Civ1_V_Diff=zeros(size(Data.Civ1_X));
153    if isfield(Data,'Civ1_FF')
154        ind_good=find(Data.Civ1_FF==0);
155    else
156       
157        ind_good=1:numel(Data.Civ1_X);
158    end
159    [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
160                            patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
161      Data.Civ1_U_Diff(ind_good)=Data.Civ1_U(ind_good)-Ures;
162      Data.Civ1_V_Diff(ind_good)=Data.Civ1_V(ind_good)-Vres;
163      Data.Civ1_FF(ind_good)=FFres;
164      Data.CivStage=3;                             
165end   
166
167%% Civ2
168if isfield (Param,'Civ2')
169    par_civ2=Param.Civ2;
170    if ~check_civ1 || ~strcmp(par_civ1.filename_ima_a,par_civ2.filename_ima_a)
171            par_civ2.ImageA=imread(par_civ2.filename_ima_a);%read first image if not already done for civ1
172    end
173    if ~check_civ1|| ~strcmp(par_civ1.filename_ima_b,par_civ2.filename_ima_b)
174            par_civ2.ImageB=imread(par_civ2.filename_ima_b);%read second image if not already done for civ1
175    end
176%     stepx=str2double(par_civ2.dx);
177%     stepy=str2double(par_civ2.dy);
178    ibx2=ceil(str2double(par_civ2.ibx)/2);
179    iby2=ceil(str2double(par_civ2.iby)/2);
180    isx2=ibx2+2;
181    isy2=iby2+2;
182
183
184%         Data.Civ1_U_Diff=zeros(size(Data.Civ1_X));
185%         Data.Civ1_V_Diff=zeros(size(Data.Civ1_X));
186%         if isfield(Data,'Civ1_FF')
187%             ind_good=find(Data.Civ1_FF==0);
188%         else
189%             ind_good=1:numel(Data.Civ1_X);
190%         end
191%             [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
192%                                 patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
193%         end
194%     shiftx=str2num(par_civ1.shiftx);
195%     shifty=str2num(par_civ1.shifty);
196% TO GET shift from par_civ2.filename_nc1
197    % shiftx=velocity interpolated at position
198    miniy=max(1+isy2+shifty,1+iby2);
199    minix=max(1+isx2-shiftx,1+ibx2);
200    maxiy=min(size(par_civ2.ImageA,1)-isy2+shifty,size(par_civ2.ImageA,1)-iby2);
201    maxix=min(size(par_civ2.ImageA,2)-isx2-shiftx,size(par_civ2.ImageA,2)-ibx2);
202    [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
203    PointCoord(:,1)=reshape(GridX,[],1);
204    PointCoord(:,2)=reshape(GridY,[],1);
205
206    Guess = tps_eval(PointCoord,[Data.Civ1_X_tps Data.Civ1_Y_tps])
207    Shiftx=Guess*Data.Civ1_U_tps;
208    Shifty=Guess*Data.Civ1_V_tps;
209   
210    if ~isempty(par_civ2.maskname)&& ~strcmp(maskname,par_civ2.maskname)% mask exist, not already read in civ1
211        mask=imread(par_civ2.maskname);
212    end
213    % caluclate velocity data (y and v in indices, reverse to y component)
214    [xtable ytable utable vtable ctable F] = civ (par_civ2.ImageA,par_civ1.ImageB,ibx2,iby2,isx2,isy2,shiftx,-shifty,PointCoord,str2num(par_civ1.rho),mask);
215    list_param=(fieldnames(par_civ1))';
216    list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
217    index=zeros(size(list_param));
218    for ilist=1:length(list_remove)
219        index=strcmp(list_remove{ilist},list_param);
220        if ~isempty(find(index,1))
221            list_param(index)=[];
222        end
223    end
224    for ilist=1:length(list_param)
225        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
226        eval(['Data.Civ1_' list_param{ilist} '=Param.Civ1.' list_param{ilist} ';'])
227    end
228    if isfield(Data,'Civ1_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
229        Data.Civ1_gridname='';
230    end
231    if isfield(Data,'Civ1_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
232        Data.Civ1_maskname='';
233    end
234    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param {'Civ1_Time','Civ1_Dt'}];
235    Data.Civ1_Time=str2double(par_civ1.T0);
236    Data.Civ1_Dt=str2double(par_civ1.Dt);
237    Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'};%  cell array containing the names of the fields to record
238    Data.VarDimName={'NbVec1','NbVec1','NbVec1','NbVec1','NbVec1','NbVec1'};
239    Data.VarAttribute{1}.Role='coord_x';
240    Data.VarAttribute{2}.Role='coord_y';
241    Data.VarAttribute{3}.Role='vector_x';
242    Data.VarAttribute{4}.Role='vector_y';
243    Data.VarAttribute{5}.Role='warnflag';
244    Data.Civ1_X=reshape(xtable,[],1);
245    Data.Civ1_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
246    Data.Civ1_U=reshape(utable,[],1);
247    Data.Civ1_V=reshape(-vtable,[],1);
248    Data.Civ1_C=reshape(ctable,[],1);
249    Data.Civ1_F=reshape(F,[],1);
250    Data.CivStage=Data.CivStage+1;
251end
252
253%% Fix2
254if isfield (Param,'Fix2')
255    ListFixParam=fieldnames(Param.Fix2);
256    for ilist=1:length(ListFixParam)
257        ParamName=ListFixParam{ilist};
258        ListName=['Fix1_' ParamName];
259        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
260        eval(['Data.' ListName '=Param.Fix2.' ParamName ';'])
261    end
262    if check_civx
263        if ~isfield(Data,'fix2')
264            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
265            Data.fix2=1;
266            Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
267            Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
268        end
269        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
270    else
271        Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
272        Data.VarDimName=[Data.VarDimName {'nbvec2'}];
273        nbvar=length(Data.ListVarName);
274        Data.VarAttribute{nbvar}.Role='errorflag';   
275        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
276        Data.CivStage=5;   
277    end
278   
279end   
280
281%% Patch2
282if isfield (Param,'Patch2')
283    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
284    Data.Patch2_Rho=str2double(Param.Patch2.Rho);
285    Data.Patch2_Threshold=str2double(Param.Patch2.Threshold);
286    Data.Patch2_SubDomain=str2double(Param.Patch2.SubDomain);
287    Data.ListVarName=[Data.ListVarName {'Civ2_U_Diff','Civ2_V_Diff','Civ2_X_SubRange','Civ2_Y_SubRange','Civ2_NbSites','Civ2_X_tps','Civ2_Y_tps','Civ2_U_tps','Civ2_V_tps'}];
288    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2',{'NbSubDomain2','Two'},{'NbSubDomain2','Two'},'NbSubDomain2',...
289             {'NbVec2Sub','NbSubDomain2'},{'NbVec2Sub','NbSubDomain2'},{'Nbtps2','NbSubDomain2'},{'Nbtps2','NbSubDomain2'}}];
290    nbvar=length(Data.ListVarName);
291    Data.VarAttribute{nbvar-1}.Role='vector_x';
292    Data.VarAttribute{nbvar}.Role='vector_y';
293    Data.Civ2_U_Diff=zeros(size(Data.Civ2_X));
294    Data.Civ2_V_Diff=zeros(size(Data.Civ2_X));
295    if isfield(Data,'Civ2_FF')
296        ind_good=find(Data.Civ2_FF==0);
297    else
298        ind_good=1:numel(Data.Civ2_X);
299    end
300    [Data.Civ2_X_SubRange,Data.Civ2_Y_SubRange,Data.Civ2_NbSites,FFres,Ures, Vres,Data.Civ2_X_tps,Data.Civ2_Y_tps,Data.Civ2_U_tps,Data.Civ2_V_tps]=...
301                            patch(Data.Civ2_X(ind_good)',Data.Civ2_Y(ind_good)',Data.Civ2_U(ind_good)',Data.Civ2_V(ind_good)',Data.Patch2_Rho,Data.Patch2_Threshold,Data.Patch2_SubDomain);
302      Data.Civ2_U_Diff(ind_good)=Data.Civ2_U(ind_good)-Ures;
303      Data.Civ2_V_Diff(ind_good)=Data.Civ2_V(ind_good)-Vres;
304      Data.Civ2_FF(ind_good)=FFres;
305      Data.CivStage=6;                             
306end   
307
308%% write result in a netcdf file if requested
309if exist('ncfile','var')
310    errormsg=struct2nc(ncfile,Data);
311end
312
313% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
314%--------------------------------------------------------------------------
315% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
316%
317% OUTPUT:
318% xtable: set of x coordinates
319% ytable: set of y coordiantes
320% utable: set of u displacements (along x)
321% vtable: set of v displacements (along y)
322% ctable: max image correlation for each vector
323% typevector: set of flags, =1 for good, =0 for NaN vectors
324%
325%INPUT:
326% image1:first image (matrix)
327% image2: second image (matrix)
328% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
329% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
330% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
331% step: mesh of the measurement points (in px)
332% subpixfinder=1 or 2 controls the curve fitting of the image correlation
333% mask: =[] for no mask
334% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
335function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
336%this funtion performs the DCC PIV analysis. Recent window-deformation
337%methods perform better and will maybe be implemented in the future.
338
339%% prepare grid
340ibx2=ceil(par_civ.Bx/2);
341iby2=ceil(par_civ.By/2);
342isx2=ceil(par_civ.Searchx/2);
343isy2=ceil(par_civ.Searchy/2);
344shiftx=par_civ.Shiftx;
345shifty=-par_civ.Shifty;% sign minus because image j index increases when y decreases
346if isfield(par_civ,'Grid')
347    if ischar(par_civ.Grid)
348        par_civ.Grid;
349        par_civ.Grid=dlmread(par_civ.Grid);
350        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
351    end
352else% automatic measurement grid
353    ibx2=ceil(par_civ.Bx/2);
354    iby2=ceil(par_civ.By/2);
355    isx2=ceil(par_civ.Searchx/2);
356    isy2=ceil(par_civ.Searchy/2);
357    shiftx=par_civ.Shiftx;
358    shifty=-par_civ.Shifty;
359    miniy=max(1+isy2+shifty,1+iby2);
360    minix=max(1+isx2-shiftx,1+ibx2);
361    maxiy=min(par_civ.ImageHeight-isy2+shifty,par_civ.ImageHeight-iby2);
362    maxix=min(par_civ.ImageWidth-isx2-shiftx,par_civ.ImageWidth-ibx2);
363    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
364    par_civ.Grid(:,1)=reshape(GridX,[],1);
365    par_civ.Grid(:,2)=reshape(GridY,[],1);
366end
367
368%% Default output
369nbvec=size(par_civ.Grid,1);
370xtable=par_civ.Grid(:,1);
371ytable=par_civ.Grid(:,2);
372utable=zeros(nbvec,1);
373vtable=zeros(nbvec,1);
374ctable=zeros(nbvec,1);
375F=zeros(nbvec,1);
376result_conv=[];
377errormsg='';
378
379%% prepare mask
380if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
381    if strcmp(par_civ.Mask,'all')
382        return    % get the grid only, no civ calculation
383    elseif ischar(par_civ.Mask)
384        par_civ.Mask=imread(par_civ.Mask);
385    end
386end
387check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
388check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
389
390%% prepare images
391if ischar(par_civ.ImageA)
392    par_civ.ImageA=imread(par_civ.ImageA);
393end
394if ischar(par_civ.ImageB)
395    par_civ.ImageB=imread(par_civ.ImageB);
396end
397[npy_ima npx_ima]=size(par_civ.ImageA);
398if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
399    errormsg='image pair with unequal size';
400    return
401end
402par_civ.ImageA=double(par_civ.ImageA);
403par_civ.ImageB=double(par_civ.ImageB);
404
405
406%% Apply mask
407    % Convention for mask
408    % mask >200 : velocity calculated
409    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
410    % 150>=mask >100: velocity not calculated, nor interpolated
411    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries) TO IMPLEMENT
412    %  20>=mask: velocity=0
413checkmask=0;
414if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
415   checkmask=1;
416   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
417        errormsg='mask must be an image with the same size as the images';
418        return
419   end
420  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
421    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=100 );
422    par_civ.ImageA(check_undefined)=min(min(par_civ.ImageA));% put image A to zero (i.e. the min image value) in the undefined  area
423    par_civ.ImageB(check_undefined)=min(min(par_civ.ImageB));% put image B to zero (i.e. the min image value) in the undefined  area
424end
425
426%% compute image correlations: MAINLOOP on velocity vectors
427corrmax=0;
428sum_square=1;% default
429% vector=[0 0];%default
430for ivec=1:nbvec
431    iref=par_civ.Grid(ivec,1);% xindex on the image A for the middle of the correlation box
432    jref=par_civ.Grid(ivec,2);% yindex on the image B for the middle of the correlation box
433    %     xtable(ivec)=iref;
434    %     ytable(ivec)=jref;%default
435    if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
436        if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth% we are outside the image
437            F(ivec)=3;
438        else
439            image1_crop=par_civ.ImageA(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from image A
440            image2_crop=par_civ.ImageB(jref+shifty-isy2:jref+shifty+isy2,iref+shiftx-isx2:iref+shiftx+isx2);%extract a larger subimage (search box) from image B
441            image1_mean=mean(mean(image1_crop));
442            image2_mean=mean(mean(image2_crop));
443            %threshold on image minimum
444            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
445                F(ivec)=3;
446            end
447            %threshold on image maximum
448            if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
449                F(ivec)=3;
450            end
451        end
452       
453        if F(ivec)~=3
454            image1_crop=image1_crop-image1_mean;%substract the mean
455            image2_crop=image2_crop-image2_mean;
456            sum_square=sum(sum(image1_crop.*image1_crop));
457            %reference: Oliver Pust, PIV: Direct Cross-Correlation
458            result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
459            corrmax= max(max(result_conv));
460            result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
461            %Find the correlation max, at 255
462            [y,x] = find(result_conv==255,1);
463            if ~isempty(y) && ~isempty(x)
464                try
465                    if par_civ.Rho==1
466                        [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
467                    elseif par_civ.Rho==2
468                        [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
469                    end
470                    utable(ivec)=vector(1)+shiftx;
471                    vtable(ivec)=vector(2)+shifty;
472                    xtable(ivec)=iref+utable(ivec)/2;% convec flow (velocity taken at the point middle from imgae1 and 2)
473                    ytable(ivec)=jref+vtable(ivec)/2;
474                    iref=round(xtable(ivec));% image index for the middle of the vector
475                    jref=round(ytable(ivec));
476                    if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
477                        utable(ivec)=0;
478                        vtable(ivec)=0;
479                        F(ivec)=3;
480                    end
481                    ctable(ivec)=corrmax/sum_square;% correlation value
482                catch ME
483                    %                     vector=[0 0]; %if something goes wrong with cross correlation.....
484                    F(ivec)=3;
485                end
486            else
487                F(ivec)=3;
488            end
489        end
490    end
491   
492    %Create the vector matrix x, y, u, v
493end
494result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
495
496%------------------------------------------------------------------------
497% --- Find the maximum of the correlation function after interpolation
498function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
499%------------------------------------------------------------------------
500vector=[0 0]; %default
501F=0;
502[npy,npx]=size(result_conv);
503
504% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
505    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion – Israel Institute of Technology
506    %http://urapiv.wordpress.com
507    peaky = y;
508    if y <= npy-1 && y >= 1
509        f0 = log(result_conv(y,x));
510        f1 = real(log(result_conv(y-1,x)));
511        f2 = real(log(result_conv(y+1,x)));
512        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
513    else
514        F=-2; % warning flag for vector truncated by the limited search box
515    end
516    peakx=x;
517    if x <= npx-1 && x >= 1
518        f0 = log(result_conv(y,x));
519        f1 = real(log(result_conv(y,x-1)));
520        f2 = real(log(result_conv(y,x+1)));
521        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
522    else
523        F=-2; % warning flag for vector truncated by the limited search box
524    end
525    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
526
527%------------------------------------------------------------------------
528% --- Find the maximum of the correlation function after interpolation
529function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
530%------------------------------------------------------------------------
531vector=[0 0]; %default
532F=-2;
533peaky=y;
534peakx=x;
535[npy,npx]=size(result_conv);
536if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
537    F=0;
538    for i=-1:1
539        for j=-1:1
540            %following 15 lines based on
541            %H. Nobach Æ M. Honkanen (2005)
542            %Two-dimensional Gaussian regression for sub-pixel displacement
543            %estimation in particle image velocimetry or particle position
544            %estimation in particle tracking velocimetry
545            %Experiments in Fluids (2005) 38: 511–515
546            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
547            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
548            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
549            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
550            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
551        end
552    end
553    c10=(1/6)*sum(sum(c10));
554    c01=(1/6)*sum(sum(c01));
555    c11=(1/4)*sum(sum(c11));
556    c20=(1/6)*sum(sum(c20));
557    c02=(1/6)*sum(sum(c02));
558    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
559    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
560    if abs(deltax)<1
561        peakx=x+deltax;
562    end
563    if abs(deltay)<1
564        peaky=y+deltay;
565    end
566end
567vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
568
569%'RUN_FIX': function for fixing velocity fields:
570%-----------------------------------------------
571% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
572%
573%filename: name of the netcdf file (used as input and output)
574%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
575    %.vel_type='civ1' or 'civ2';
576    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
577    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
578%flagindex: flag specifying which values of vec_f are removed:
579        % if flagindex(1)=1: vec_f=-2 vectors are removed
580        % if flagindex(2)=1: vec_f=3 vectors are removed
581        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
582%iter=1 for civ1 fields and iter=2 for civ2 fields
583%thresh_vecC: threshold in the image correlation vec_C
584%flag_mask: =1 mask used to remove vectors (0 else)
585%maskname: name of the mask image file for fix
586%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
587%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
588%fileref: .nc file name for a reference velocity (='': refrence 0 used)
589%fieldref: 'civ1','filter1'...feld used in fileref
590
591function FF=fix(Param,F,C,U,V,X,Y)
592FF=zeros(size(F));%default
593Param
594
595%criterium on warn flags
596FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
597FlagVal=[-2 2 3 4];
598for iflag=1:numel(FlagName)
599    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
600        FF=(FF==1| F==FlagVal(iflag));
601    end
602end
603%criterium on correlation values
604if isfield (Param,'MinCorr')
605    FF=FF==1 | C<Param.MinCorr;
606end
607if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
608    Umod= U.*U+V.*V;
609    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
610        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
611    end
612    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
613        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
614    end
615end
616return
617
618
619FF=double(FF);
620
621
622
623%------------------------------------------------------------------------
624% patch function
625% OUTPUT:
626% SubRangx,SubRangy(NbSubdomain,2): range (min, max) of the coordiantes x and y respectively, for each subdomain
627% nbpoints(NbSubdomain): number of source points for each subdomain
628% FF: false flags
629% U_smooth, V_smooth: filtered velocity components at the positions of the initial data
630% X_tps,Y_tps,U_tps,V_tps: positions and weight of the tps for each subdomain
631%
632% INPUT:
633% X, Y: set of coordinates of the initial data
634% U,V: set of velocity components of the initial data
635% Rho: smoothing parameter
636% Threshold: max diff accepted between smoothed and initial data
637% Subdomain: estimated number of data points in each subdomain
638
639function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch(X,Y,U,V,Rho,Threshold,SubDomain)
640%subdomain decomposition
641warning off
642U=reshape(U,[],1);
643V=reshape(V,[],1);
644X=reshape(X,[],1);
645Y=reshape(Y,[],1);
646nbvec=numel(X);
647NbSubDomain=ceil(nbvec/SubDomain);
648MinX=min(X);
649MinY=min(Y);
650MaxX=max(X);
651MaxY=max(Y);
652RangX=MaxX-MinX;
653RangY=MaxY-MinY;
654AspectRatio=RangY/RangX;
655NbSubDomainX=max(floor(sqrt(NbSubDomain/AspectRatio)),1);
656NbSubDomainY=max(floor(sqrt(NbSubDomain*AspectRatio)),1);
657NbSubDomain=NbSubDomainX*NbSubDomainY;
658SizX=RangX/NbSubDomainX;%width of subdomains
659SizY=RangY/NbSubDomainY;%height of subdomains
660CentreX=linspace(MinX+SizX/2,MaxX-SizX/2,NbSubDomainX);
661CentreY=linspace(MinY+SizY/2,MaxY-SizY/2,NbSubDomainY);
662[CentreX,CentreY]=meshgrid(CentreX,CentreY);
663CentreY=reshape(CentreY,1,[]);% Y positions of subdomain centres
664CentreX=reshape(CentreX,1,[]);% X positions of subdomain centres
665rho=SizX*SizY*Rho/1000000;%optimum rho increase as the area of the subdomain (division by 10^6 to reach good values with the default GUI input)
666U_tps_sub=zeros(length(X),NbSubDomain);%default spline
667V_tps_sub=zeros(length(X),NbSubDomain);%default spline
668U_smooth=zeros(length(X),1);
669V_smooth=zeros(length(X),1);
670
671nb_select=zeros(length(X),1);
672FF=zeros(length(X),1);
673check_empty=zeros(1,NbSubDomain);
674SubRangx=zeros(NbSubDomain,2);%initialise the positions of subdomains
675SubRangy=zeros(NbSubDomain,2);
676for isub=1:NbSubDomain
677    SubRangx(isub,:)=[CentreX(isub)-0.55*SizX CentreX(isub)+0.55*SizX];
678    SubRangy(isub,:)=[CentreY(isub)-0.55*SizY CentreY(isub)+0.55*SizY];
679    ind_sel_previous=[];
680    ind_sel=0;
681    while numel(ind_sel)>numel(ind_sel_previous) %increase the subdomain during four iterations at most
682        ind_sel_previous=ind_sel;
683        ind_sel=find(X>=SubRangx(isub,1) & X<=SubRangx(isub,2) & Y>=SubRangy(isub,1) & Y<=SubRangy(isub,2));
684        % if no vector in the subdomain, skip the subdomain
685        if isempty(ind_sel)
686            check_empty(isub)=1;   
687            U_tps(1,isub)=0;%define U_tps and V_tps by default
688            V_tps(1,isub)=0;
689            break
690            % if too few selected vectors, increase the subrange for next iteration
691        elseif numel(ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
692            SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
693            SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
694            SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
695            SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
696        else
697            [U_smooth_sub,U_tps_sub]=tps_coeff(X(ind_sel),Y(ind_sel),U(ind_sel),rho);
698            [V_smooth_sub,V_tps_sub]=tps_coeff(X(ind_sel),Y(ind_sel),V(ind_sel),rho);
699            UDiff=U_smooth_sub-U(ind_sel);
700            VDiff=V_smooth_sub-V(ind_sel);
701            NormDiff=UDiff.*UDiff+VDiff.*VDiff;
702            FF(ind_sel)=20*(NormDiff>Threshold);%put FF value to 20 to identify the criterium of elimmination
703            ind_ind_sel=find(FF(ind_sel)==0); % select the indices of ind_sel corresponding to the remaining vectors
704            % no value exceeds threshold, the result is recorded
705            if isequal(numel(ind_ind_sel),numel(ind_sel))
706                U_smooth(ind_sel)=U_smooth(ind_sel)+U_smooth_sub;
707                V_smooth(ind_sel)=V_smooth(ind_sel)+V_smooth_sub;
708                nbpoints(isub)=numel(ind_sel);
709                X_tps(1:nbpoints(isub),isub)=X(ind_sel);
710                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel);
711                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
712                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;         
713                nb_select(ind_sel)=nb_select(ind_sel)+1;
714                 display('good')
715                break
716                % too few selected vectors, increase the subrange for next iteration
717            elseif numel(ind_ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
718                SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
719                SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
720                SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
721                SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
722%                 display('fewsmooth')
723                % interpolation-smoothing is done again with the selected vectors
724            else
725                [U_smooth_sub,U_tps_sub]=tps_coeff(X(ind_sel(ind_ind_sel)),Y(ind_sel(ind_ind_sel)),U(ind_sel(ind_ind_sel)),rho);
726                [V_smooth_sub,V_tps_sub]=tps_coeff(X(ind_sel(ind_ind_sel)),Y(ind_sel(ind_ind_sel)),V(ind_sel(ind_ind_sel)),rho);
727                U_smooth(ind_sel(ind_ind_sel))=U_smooth(ind_sel(ind_ind_sel))+U_smooth_sub;
728                V_smooth(ind_sel(ind_ind_sel))=V_smooth(ind_sel(ind_ind_sel))+V_smooth_sub;
729                nbpoints(isub)=numel(ind_ind_sel);
730                X_tps(1:nbpoints(isub),isub)=X(ind_sel(ind_ind_sel));
731                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel(ind_ind_sel));
732                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
733                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;
734                nb_select(ind_sel(ind_ind_sel))=nb_select(ind_sel(ind_ind_sel))+1;
735                display('good2')
736                break
737            end
738        end
739    end
740end
741ind_empty=find(check_empty);
742%remove empty subdomains
743if ~isempty(ind_empty)
744    SubRangx(ind_empty,:)=[];
745    SubRangy(ind_empty,:)=[];
746    X_tps(:,ind_empty)=[];
747    Y_tps(:,ind_empty)=[];
748    U_tps(:,ind_empty)=[];
749    V_tps(:,ind_empty)=[];
750end
751nb_select(nb_select==0)=1;%ones(size(find(nb_select==0)));
752U_smooth=U_smooth./nb_select;
753V_smooth=V_smooth./nb_select;
754
755
756
757
758
Note: See TracBrowser for help on using the repository browser.