source: trunk/src/civ_matlab.m @ 493

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

various bugs repaired, tests in Windows OS

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