source: trunk/src/series/stereo_civ.m @ 846

Last change on this file since 846 was 846, checked in by sommeria, 9 years ago

small correction

File size: 47.1 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
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_series(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-2014, LEGI / CNRS UJF G-INP, 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]= stereo_civ(Param)
41Data=[];
42errormsg='';
43
44%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
45if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
46    if size(Param.InputTable,1)<2
47        msgbox_uvmat('WARNING','two input file series must be entered')
48        return
49    end
50    path_series=fileparts(which('series'));
51    addpath(fullfile(path_series,'series'))
52    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
53    if isempty(Data)
54        Data=Param;% if  civ_input has been cancelled, keep previous parameters
55    end
56    Data.Program=mfilename;%gives the name of the current function
57    Data.AllowInputSort='on';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
58    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
59    Data.NbSlice='off'; %nbre of slices ('off' by default)
60    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
61    Data.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
62    Data.FieldTransform = 'off';%can use a transform function (use it by force, no input option)
63    Data.ProjObject='off';%can use projection object(option 'off'/'on',
64    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
65    Data.OutputDirExt='.stereo';%set the output dir extension
66    Data.OutputSubDirMode='auto'; %select the last subDir in the input table as root of the output subdir name (option 'all'/'first'/'last', 'all' by default)
67    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
68    return
69end
70
71%% read input parameters from an xml file if input is a file name (batch mode)
72checkrun=1;
73if ischar(Param)
74    Param=xml2struct(Param);% read Param as input file (batch case)
75    checkrun=0;
76end
77if ~isfield(Param,'ActionInput')
78    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
79    return
80end
81hseries=findobj(allchild(0),'Tag','series');
82RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
83WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
84
85%% input files and indexing
86MaxIndex_i=Param.IndexRange.MaxIndex_i;
87MinIndex_i=Param.IndexRange.MinIndex_i;
88if ~isfield(Param,'InputTable')
89    disp_uvmat('ERROR', 'no input field',checkrun)
90    return
91end
92[tild,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
93for iview=1:size(Param.InputTable,1)
94    XmlFileName=find_imadoc(Param.InputTable{iview,1},Param.InputTable{iview,2},Param.InputTable{iview,3},Param.InputTable{iview,5});
95    if isempty(XmlFileName)
96        disp_uvmat('ERROR', [XmlFileName ' not found'],checkrun)
97        return
98    end
99    XmlData{iview}=imadoc2struct(XmlFileName);
100    if isfield(XmlData{iview},'Time')
101        time=XmlData{iview}.Time;
102        TimeSource='xml';
103    end
104    if isfield(XmlData{iview},'Camera')
105        if isfield(XmlData{iview}.Camera,'NbSlice')&& ~isempty(XmlData{iview}.Camera.NbSlice)
106            NbSlice_calib{iview}=XmlData{iview}.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
107            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
108                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
109            end
110        end
111        if isfield(XmlData{iview}.Camera,'TimeUnit')&& ~isempty(XmlData{iview}.Camera.TimeUnit)
112            TimeUnit=XmlData{iview}.Camera.TimeUnit;
113        end
114    end
115end
116   
117
118iview_A=1;% series index (iview) for the first image series
119iview_B=2;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
120
121RootPath_A=Param.InputTable{1,1};
122RootFile_A=Param.InputTable{1,3};
123SubDir_A=Param.InputTable{1,2};
124NomType_A=Param.InputTable{1,4};
125FileExt_A=Param.InputTable{1,5};
126RootPath_B=Param.InputTable{2,1};
127RootFile_B=Param.InputTable{2,3};
128SubDir_B=Param.InputTable{2,2};
129NomType_B=Param.InputTable{2,4};
130FileExt_B=Param.InputTable{2,5};
131PairCiv2='';
132
133i1_series_Civ1=i1_series{1};i1_series_Civ2=i1_series{1};
134i2_series_Civ1=i1_series{2};i2_series_Civ2=i1_series{2};
135if isempty(j1_series{1})
136    j1_series_Civ1=ones(size(i1_series{1}));
137    j2_series_Civ1=ones(size(i1_series{2}));
138else
139    j1_series_Civ1=j1_series{1};
140    j2_series_Civ1=j1_series{2};
141end
142j1_series_Civ2=j1_series_Civ1;
143j2_series_Civ2=j2_series_Civ1;
144NomTypeNc=NomType_A;
145if isempty(j1_series_Civ1)
146    FrameIndex_A_Civ1=i1_series_Civ1;
147    FrameIndex_B_Civ1=i2_series_Civ1;
148    j1_series_Civ1=ones(size(i1_series_Civ1));
149    j2_series_Civ1=ones(size(i1_series_Civ1));
150else
151    FrameIndex_A_Civ1=j1_series_Civ1;
152    FrameIndex_B_Civ1=j2_series_Civ1;
153end
154if isempty(PairCiv2)
155    FrameIndex_A_Civ2=FrameIndex_A_Civ1;
156    FrameIndex_B_Civ2=FrameIndex_B_Civ1;
157else
158    if isempty(j1_series_Civ2)
159        FrameIndex_A_Civ2=i1_series_Civ2;
160        FrameIndex_B_Civ2=i2_series_Civ2;
161        j1_series_Civ2=ones(size(i1_series_Civ2));
162        j2_series_Civ2=ones(size(i1_series_Civ2));
163    else
164        FrameIndex_A_Civ2=j1_series_Civ2;
165        FrameIndex_B_Civ2=j2_series_Civ2;
166    end
167end
168if isempty(i1_series_Civ1)||(~isempty(PairCiv2) && isempty(i1_series_Civ2))
169    disp_uvmat('ERROR','no image pair fo civ in the input file index range',checkrun)
170    return
171end
172
173%% check the first image pair
174try
175    if Param.ActionInput.CheckCiv1% Civ1 is performed
176        ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(1),[],j1_series_Civ1(1));
177        if ~exist(ImageName_A,'file')
178            disp_uvmat('ERROR',['first input image ' ImageName_A ' does not exist'],checkrun)
179            return
180        end
181        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
182        FileType_A=FileInfo_A.FileType;
183        if strcmp(FileInfo_A.FileType,'netcdf')
184            FieldName_A=Param.InputFields.FieldName;
185            [DataIn,tild,tild,errormsg]=nc2struct(ImageName_A,{FieldName_A});
186            par_civ1.ImageA=DataIn.(FieldName_A);
187        else
188            [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(1));
189        end
190        ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(1),[],j2_series_Civ1(1));
191        if ~exist(ImageName_B,'file')
192            disp_uvmat('ERROR',['first input image ' ImageName_B ' does not exist'],checkrun)
193            return
194        end
195        [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
196        FileType_B=FileInfo_B.FileType;
197        if strcmp(FileInfo_B.FileType,'netcdf')
198            FieldName_B=Param.InputFields.FieldName;
199            [DataIn,tild,tild,errormsg]=nc2struct(ImageName_B,{FieldName_B});
200            par_civ1.ImageB=DataIn.(FieldName_B);
201        else
202            [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(1));
203        end
204        NbField=numel(i1_series_Civ1);
205    elseif Param.ActionInput.CheckCiv2 % Civ2 is performed without Civ1
206        ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ2(1),[],j1_series_Civ2(1));
207        if ~exist(ImageName_A,'file')
208            disp_uvmat('ERROR',['first input image ' ImageName_A ' does not exist'],checkrun)
209            return
210        end
211        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
212        FileType_A=FileInfo_A.FileType;
213        [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileInfo_A.FileType,VideoObject_A,FrameIndex_A_Civ2(1));
214        ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ2(1),[],j2_series_Civ2(1));
215        if ~exist(ImageName_B,'file')
216            disp_uvmat('ERROR',['first input image ' ImageName_B ' does not exist'],checkrun)
217            return
218        end
219        [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
220        FileType_B=FileInfo_B.FileType;
221        [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ2(1));
222        NbField=numel(i1_series_Civ2);
223    else
224        NbField=numel(i1_series_Civ1);% no image used (only fix or patch) TO CHECK
225    end
226catch ME
227    if ~isempty(ME.message)
228        disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
229        return
230    end
231end
232
233
234%% Output directory
235OutputDir=[Param.OutputSubDir Param.OutputDirExt];
236
237Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
238Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
239Data.Program=mfilename;%gives the name of the current function;
240Data.CivStage=0;%default
241maskname='';%default
242check_civx=0;%default
243
244%% get timing from input video
245if isempty(time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video'})))% case of video input
246    time=zeros(FileInfo_A.NumberOfFrames+1,2);
247    time(:,2)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate)';
248    TimeSource='video';
249    ColorType='truecolor';
250end
251if isempty(time)% time = index i  by default
252    MaxIndex_i=max(i2_series_Civ1);
253    MaxIndex_j=max(j2_series_Civ1);
254    time=(1:MaxIndex_i)'*ones(1,MaxIndex_j);
255    time=[zeros(1,MaxIndex_j);time];% insert a first line of zeros
256    time=[zeros(MaxIndex_i+1,1) time];% insert a first column of zeros
257end
258
259if length(FileInfo_A) >1 %case of image with multiple frames
260    nbfield=length(FileInfo_A);
261    nbfield_j=1;
262end
263
264
265%%%%% MAIN LOOP %%%%%%
266for ifield=1:NbField
267    update_waitbar(WaitbarHandle,ifield/NbField)
268    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
269        disp('program stopped by user')
270        break
271    end
272    Civ1Dir=OutputDir;
273
274        ncfile=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
275            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
276    %% Civ1
277    % if Civ1 computation is requested
278    if isfield (Param.ActionInput,'Civ1')
279        par_civ1=Param.ActionInput.Civ1;
280        try
281            ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
282            [A{1},VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(ifield));
283            ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
284            [A{2},VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(ifield));
285        catch ME
286            if ~isempty(ME.message)
287                disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
288                return
289            end
290        end
291        [A,Rangx,Rangy]=phys_ima(A,XmlData,1);
292        [Npy,Npx]=size(A{1});
293        PhysImageA=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.png','_1a',i1_series_Civ1(ifield),[],1);
294        PhysImageB=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.png','_1a',i1_series_Civ1(ifield),[],2);
295        imwrite(A{1},PhysImageA)
296        imwrite(A{2},PhysImageB)
297        par_civ1.ImageA=A{1};
298        par_civ1.ImageB=A{2};
299        par_civ1.ImageWidth=size(par_civ1.ImageA,2);%FileInfo_A.Width;
300        par_civ1.ImageHeight=size(par_civ1.ImageA,1);%FileInfo_A.Height;
301        list_param=(fieldnames(Param.ActionInput.Civ1))';
302        Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
303        Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
304        %indicate the values of all the global attributes in the output data
305        Data.Civ1_ImageA=ImageName_A;
306        Data.Civ1_ImageB=ImageName_B;
307        i1=i1_series_Civ1(ifield);
308        i2=i1;
309        if ~isempty(i2_series_Civ1)
310            i2=i2_series_Civ1(ifield);
311        end
312        j1=1;
313        if ~isempty(j1_series_Civ1)
314            j1=j1_series_Civ1(ifield);
315        end
316        j2=j1;
317        if ~isempty(j2_series_Civ1)
318            j2=j2_series_Civ1(ifield);
319        end
320        Data.Civ1_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
321        Data.Civ1_Dt=time(i2+1,j2+1)-time(i1+1,j1+1);
322        for ilist=1:length(list_param)
323            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
324        end
325        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
326        Data.CivStage=1;
327       
328        % set the list of variables
329        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C','Xphys','Yphys','Zphys','Civ1_E'};%  cell array containing the names of the fields to record
330        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
331        Data.VarAttribute{1}.Role='coord_x';
332        Data.VarAttribute{2}.Role='coord_y';
333        Data.VarAttribute{3}.Role='vector_x';
334        Data.VarAttribute{4}.Role='vector_y';
335        Data.VarAttribute{5}.Role='warnflag';
336       
337       
338        % calculate velocity data (y and v in indices, reverse to y component)
339        [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
340        Data.Civ1_X=reshape(xtable,[],1);
341        Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
342        % get z from u and v (displacements)
343        Data.Civ1_U=reshape(utable,[],1);
344        Data.Civ1_V=reshape(-vtable,[],1);     
345        Data.Civ1_C=reshape(ctable,[],1);
346        Data.Civ1_F=reshape(F,[],1);
347        Data.Xphys=Rangx(1)+(Rangx(2)-Rangx(1))*(Data.Civ1_X-0.5)/(Npx-1);
348        Data.Yphys=Rangy(1)+(Rangy(2)-Rangy(1))*(Data.Civ1_Y-0.5)/(Npy-1);
349        U=Data.Civ1_U*(Rangx(2)-Rangx(1))/(Npx-1);
350        V=Data.Civ1_V*(Rangy(2)-Rangy(1))/(Npy-1);
351        [Data.Zphys,Data.Civ1_E]=shift2z(Data.Xphys,Data.Yphys,U,V,XmlData);
352        if ~isempty(errormsg)
353            disp_uvmat('ERROR',errormsg,checkrun)
354            return
355        end
356    end
357   
358    %% Fix1
359    if isfield (Param.ActionInput,'Fix1')
360        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
361            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
362            Data.ListGlobalAttribute(Fix1_attr)=[];
363            for ilist=1:numel(Fix1_attr)
364                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
365            end
366        end
367        ListFixParam=fieldnames(Param.ActionInput.Fix1);
368        for ilist=1:length(ListFixParam)
369            ParamName=ListFixParam{ilist};
370            ListName=['Fix1_' ParamName];
371            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
372            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
373        end
374        if check_civx
375            if ~isfield(Data,'fix')
376                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
377                Data.fix=1;
378                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
379                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
380            end
381            Data.vec_FixFlag=fix(Param.ActionInput.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
382        else
383            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
384            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
385            nbvar=length(Data.ListVarName);
386            Data.VarAttribute{nbvar}.Role='errorflag';
387            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
388            Data.CivStage=2;
389        end
390    end
391    %% Patch1
392    if isfield (Param.ActionInput,'Patch1')
393        if check_civx
394            errormsg='Civ Matlab input needed for patch';
395            disp_uvmat('ERROR',errormsg,checkrun)
396            return
397        end
398       
399        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
400        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
401        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
402        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
403        nbvar=length(Data.ListVarName);
404        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
405        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
406            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
407        Data.VarAttribute{nbvar+1}.Role='vector_x';
408        Data.VarAttribute{nbvar+2}.Role='vector_y';
409        Data.VarAttribute{nbvar+5}.Role='coord_tps';
410        Data.VarAttribute{nbvar+6}.Role='vector_x';
411        Data.VarAttribute{nbvar+7}.Role='vector_y';
412        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
413        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
414        if isfield(Data,'Civ1_FF')
415            ind_good=find(Data.Civ1_FF==0);
416        else
417            ind_good=1:numel(Data.Civ1_X);
418        end
419        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
420            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
421        Data.Civ1_U_smooth(ind_good)=Ures;
422        Data.Civ1_V_smooth(ind_good)=Vres;
423        Data.Civ1_FF(ind_good)=FFres;
424        Data.CivStage=3;
425    end
426   
427    %% Civ2
428    if isfield (Param.ActionInput,'Civ2')
429        par_civ2=Param.ActionInput.Civ2;
430        par_civ2.ImageA=par_civ1.ImageA;
431        par_civ2.ImageB=par_civ1.ImageB;
432        %         if ~isfield(Param.Civ1,'ImageA')
433        i1=i1_series_Civ2(ifield);
434        i2=i1;
435        if ~isempty(i2_series_Civ2)
436            i2=i2_series_Civ2(ifield);
437        end
438        j1=1;
439        if ~isempty(j1_series_Civ2)
440            j1=j1_series_Civ2(ifield);
441        end
442        j2=j1;
443        if ~isempty(j2_series_Civ2)
444            j2=j2_series_Civ2(ifield);
445        end
446        par_civ2.ImageWidth=FileInfo_A.Width;
447        par_civ2.ImageHeight=FileInfo_A.Height;
448       
449        if isfield(par_civ2,'Grid')% grid points set as input file
450            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
451                par_civ2.Grid=dlmread(par_civ2.Grid);
452                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
453            end
454        else% automatic grid
455            minix=floor(par_civ2.Dx/2)-0.5;
456            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
457            miniy=floor(par_civ2.Dy/2)-0.5;
458            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
459            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
460            par_civ2.Grid(:,1)=reshape(GridX,[],1);
461            par_civ2.Grid(:,2)=reshape(GridY,[],1);
462        end
463        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
464        Shifty=zeros(size(par_civ2.Grid,1),1);
465        nbval=zeros(size(par_civ2.Grid,1),1);
466        if par_civ2.CheckDeformation
467            DUDX=zeros(size(par_civ2.Grid,1),1);
468            DUDY=zeros(size(par_civ2.Grid,1),1);
469            DVDX=zeros(size(par_civ2.Grid,1),1);
470            DVDY=zeros(size(par_civ2.Grid,1),1);
471        end
472        NbSubDomain=size(Data.Civ1_SubRange,3);
473        % get the guess from patch1
474        for isub=1:NbSubDomain% for each sub-domain of Patch1
475            nbvec_sub=Data.Civ1_NbCentres(isub);% nbre of Civ1 vectors in the subdomain
476            ind_sel=find(par_civ2.Grid(:,1)>=Data.Civ1_SubRange(1,1,isub) & par_civ2.Grid(:,1)<=Data.Civ1_SubRange(1,2,isub) &...
477                par_civ2.Grid(:,2)>=Data.Civ1_SubRange(2,1,isub) & par_civ2.Grid(:,2)<=Data.Civ1_SubRange(2,2,isub));
478            epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites
479            ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
480            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
481            EM = tps_eval(epoints,ctrs);
482            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
483            Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
484            if par_civ2.CheckDeformation
485                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
486                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
487                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
488                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
489                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
490            end
491        end
492        mask='';
493        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
494            mask=imread(par_civ2.Mask);
495        end
496        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
497        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
498%         par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
499%         par_civ2.SearchBoxSize(2)=2*iby2+9;
500        par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
501        par_civ2.Grid=[par_civ2.Grid(nbval>=1,1)-par_civ2.SearchBoxShift(:,1)/2 par_civ2.Grid(nbval>=1,2)-par_civ2.SearchBoxShift(:,2)/2];% grid taken at the extrapolated origin of the displacement vectors
502        if par_civ2.CheckDeformation
503            par_civ2.DUDX=DUDX./nbval;
504            par_civ2.DUDY=DUDY./nbval;
505            par_civ2.DVDX=DVDX./nbval;
506            par_civ2.DVDY=DVDY./nbval;
507        end
508        % calculate velocity data (y and v in indices, reverse to y component)
509        [xtable ytable utable vtable ctable F] = civ (par_civ2);
510        list_param=(fieldnames(Param.ActionInput.Civ2))';
511        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
512        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
513        %indicate the values of all the global attributes in the output data
514        Data.Civ2_ImageA=ImageName_A;
515        Data.Civ2_ImageB=ImageName_B;
516        Data.Civ2_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
517        Data.Civ2_Dt=0;
518        for ilist=1:length(list_param)
519            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
520        end
521        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
522       
523        nbvar=numel(Data.ListVarName);
524        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
525        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
526        Data.VarAttribute{nbvar+1}.Role='coord_x';
527        Data.VarAttribute{nbvar+2}.Role='coord_y';
528        Data.VarAttribute{nbvar+3}.Role='vector_x';
529        Data.VarAttribute{nbvar+4}.Role='vector_y';
530        Data.VarAttribute{nbvar+5}.Role='warnflag';
531        Data.Civ2_X=reshape(xtable,[],1);
532        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
533        Data.Civ2_U=reshape(utable,[],1);
534        Data.Civ2_V=reshape(-vtable,[],1);
535        Data.Civ2_C=reshape(ctable,[],1);
536        Data.Civ2_F=reshape(F,[],1);
537        Data.CivStage=Data.CivStage+1;
538    end
539   
540    %% Fix2
541    if isfield (Param.ActionInput,'Fix2')
542        ListFixParam=fieldnames(Param.ActionInput.Fix2);
543        for ilist=1:length(ListFixParam)
544            ParamName=ListFixParam{ilist};
545            ListName=['Fix2_' ParamName];
546            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
547            eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
548        end
549        if check_civx
550            if ~isfield(Data,'fix2')
551                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
552                Data.fix2=1;
553                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
554                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
555            end
556            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
557        else
558            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
559            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
560            nbvar=length(Data.ListVarName);
561            Data.VarAttribute{nbvar}.Role='errorflag';
562            Data.Civ2_FF=double(fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V));
563            Data.CivStage=Data.CivStage+1;
564        end
565       
566    end
567   
568    %% Patch2
569    if isfield (Param.ActionInput,'Patch2')
570        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
571        Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
572        Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
573        Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
574        nbvar=length(Data.ListVarName);
575        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
576        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
577            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
578       
579        Data.VarAttribute{nbvar+1}.Role='vector_x';
580        Data.VarAttribute{nbvar+2}.Role='vector_y';
581        Data.VarAttribute{nbvar+5}.Role='coord_tps';
582        Data.VarAttribute{nbvar+6}.Role='vector_x';
583        Data.VarAttribute{nbvar+7}.Role='vector_y';
584        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
585        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
586        if isfield(Data,'Civ2_FF')
587            ind_good=find(Data.Civ2_FF==0);
588        else
589            ind_good=1:numel(Data.Civ2_X);
590        end
591        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
592            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
593        Data.Civ2_U_smooth(ind_good)=Ures;
594        Data.Civ2_V_smooth(ind_good)=Vres;
595        Data.Civ2_FF(ind_good)=FFres;
596        Data.CivStage=Data.CivStage+1;
597    end
598   
599    %% write result in a netcdf file if requested
600    if exist('ncfile','var')
601        errormsg=struct2nc(ncfile,Data);
602        if isempty(errormsg)
603            disp([ncfile ' written'])
604        else
605            disp(errormsg)
606        end
607    end
608end
609
610% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
611%--------------------------------------------------------------------------
612% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
613%
614% OUTPUT:
615% xtable: set of x coordinates
616% ytable: set of y coordiantes
617% utable: set of u displacements (along x)
618% vtable: set of v displacements (along y)
619% ctable: max image correlation for each vector
620% typevector: set of flags, =1 for good, =0 for NaN vectors
621%
622%INPUT:
623% par_civ: structure of input parameters, with fields:
624%  .CorrBoxSize
625%  .SearchBoxSize
626%  .SearchBoxShift
627%  .ImageHeight
628%  .ImageWidth
629%  .Dx, Dy
630%  .Grid
631%  .Mask
632%  .MinIma
633%  .MaxIma
634%  .image1:first image (matrix)
635% image2: second image (matrix)
636% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
637% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
638% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
639% step: mesh of the measurement points (in px)
640% subpixfinder=1 or 2 controls the curve fitting of the image correlation
641% mask: =[] for no mask
642% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
643function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
644%this funtion performs the DCC PIV analysis. Recent window-deformation
645%methods perform better and will maybe be implemented in the future.
646
647%% prepare measurement grid
648if isfield(par_civ,'Grid')% grid points set as input
649    if ischar(par_civ.Grid)%read the drid file if the input is a file name
650        par_civ.Grid=dlmread(par_civ.Grid);
651        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
652    end
653else% automatic grid
654    minix=floor(par_civ.Dx/2)-0.5;
655    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
656    miniy=floor(par_civ.Dy/2)-0.5;
657    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
658    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
659    par_civ.Grid(:,1)=reshape(GridX,[],1);
660    par_civ.Grid(:,2)=reshape(GridY,[],1);
661end
662nbvec=size(par_civ.Grid,1);
663
664%% prepare correlation and search boxes
665ibx2=ceil(par_civ.CorrBoxSize(1)/2);
666iby2=ceil(par_civ.CorrBoxSize(2)/2);
667isx2=ceil(par_civ.SearchBoxSize(1)/2);
668isy2=ceil(par_civ.SearchBoxSize(2)/2);
669shiftx=round(par_civ.SearchBoxShift(:,1));
670shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
671if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
672    shiftx=shiftx*ones(nbvec,1);
673    shifty=shifty*ones(nbvec,1);
674end
675
676%% Default output
677xtable=par_civ.Grid(:,1);
678ytable=par_civ.Grid(:,2);
679utable=zeros(nbvec,1);
680vtable=zeros(nbvec,1);
681ctable=zeros(nbvec,1);
682F=zeros(nbvec,1);
683result_conv=[];
684errormsg='';
685
686%% prepare mask
687if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
688    if strcmp(par_civ.Mask,'all')
689        return    % get the grid only, no civ calculation
690    elseif ischar(par_civ.Mask)
691        par_civ.Mask=imread(par_civ.Mask);
692    end
693end
694check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
695check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
696
697% %% prepare images
698% if isfield(par_civ,'reverse_pair')
699%     if par_civ.reverse_pair
700%         if ischar(par_civ.ImageB)
701%             temp=par_civ.ImageA;
702%             par_civ.ImageA=imread(par_civ.ImageB);
703%         end
704%         if ischar(temp)
705%             par_civ.ImageB=imread(temp);
706%         end
707%     end
708% else
709%     if ischar(par_civ.ImageA)
710%         par_civ.ImageA=imread(par_civ.ImageA);
711%     end
712%     if ischar(par_civ.ImageB)
713%         par_civ.ImageB=imread(par_civ.ImageB);
714%     end
715% end
716par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
717par_civ.ImageB=sum(double(par_civ.ImageB),3);
718[npy_ima npx_ima]=size(par_civ.ImageA);
719if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
720    errormsg='image pair with unequal size';
721    return
722end
723
724%% Apply mask
725    % Convention for mask IDEAS TO IMPLEMENT ?
726    % mask >200 : velocity calculated
727    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
728    % 150>=mask >100: velocity not calculated, nor interpolated
729    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
730    %  20>=mask: velocity=0
731checkmask=0;
732MinA=min(min(par_civ.ImageA));
733MinB=min(min(par_civ.ImageB));
734if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
735   checkmask=1;
736   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
737        errormsg='mask must be an image with the same size as the images';
738        return
739   end
740  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
741    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
742    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
743    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
744end
745
746%% compute image correlations: MAINLOOP on velocity vectors
747corrmax=0;
748sum_square=1;% default
749mesh=1;% default
750CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
751if CheckDecimal
752    mesh=0.2;%mesh in pixels for subpixel image interpolation
753    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
754end
755% vector=[0 0];%default
756for ivec=1:nbvec
757    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
758    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
759    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
760    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
761    %               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
762    %             F(ivec)=3;
763    %         else
764    F(ivec)=0;
765    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
766    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
767    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
768    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
769    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
770    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
771    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
772    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
773    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
774    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
775   
776    image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
777    image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
778    image1_mean=mean(mean(image1_crop));
779    image2_mean=mean(mean(image2_crop));
780    %threshold on image minimum
781    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
782        F(ivec)=3;
783    end
784    %threshold on image maximum
785    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
786        F(ivec)=3;
787    end
788    %         end
789    if F(ivec)~=3
790        image1_crop=image1_crop-image1_mean;%substract the mean
791        image2_crop=image2_crop-image2_mean;
792        if CheckDecimal
793            xi=(1:mesh:size(image1_crop,2));
794            yi=(1:mesh:size(image1_crop,1))';
795            if CheckDeformation
796                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
797                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
798                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
799                image1_crop=interp2(image1_crop,XIant,YIant);
800            else
801                image1_crop=interp2(image1_crop,xi,yi);
802            end
803            xi=(1:mesh:size(image2_crop,2));
804            yi=(1:mesh:size(image2_crop,1))';
805            image2_crop=interp2(image2_crop,xi,yi);
806        end
807        sum_square=sum(sum(image1_crop.*image1_crop));
808        %reference: Oliver Pust, PIV: Direct Cross-Correlation
809        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
810        corrmax= max(max(result_conv));
811        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
812        %Find the correlation max, at 255
813        [y,x] = find(result_conv==255,1);
814        if ~isempty(y) && ~isempty(x)
815            try
816                if par_civ.CorrSmooth==1
817                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
818                elseif par_civ.CorrSmooth==2
819                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
820                end
821                utable(ivec)=vector(1)*mesh+shiftx(ivec);
822                vtable(ivec)=vector(2)*mesh+shifty(ivec);
823                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
824                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
825                iref=round(xtable(ivec));% image index for the middle of the vector
826                jref=round(ytable(ivec));
827                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
828                    utable(ivec)=0;
829                    vtable(ivec)=0;
830                    F(ivec)=3;
831                end
832                ctable(ivec)=corrmax/sum_square;% correlation value
833            catch ME
834                F(ivec)=3;
835            end
836        else
837            F(ivec)=3;
838        end
839    end
840end
841result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
842
843%------------------------------------------------------------------------
844% --- Find the maximum of the correlation function after interpolation
845function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
846%------------------------------------------------------------------------
847vector=[0 0]; %default
848F=0;
849[npy,npx]=size(result_conv);
850result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
851%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ᅵ Israel Institute of Technology
852%http://urapiv.wordpress.com
853peaky = y;
854if y <= npy-1 && y >= 1
855    f0 = log(result_conv(y,x));
856    f1 = log(result_conv(y-1,x));
857    f2 = log(result_conv(y+1,x));
858    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
859else
860    F=-2; % warning flag for vector truncated by the limited search box
861end
862peakx=x;
863if x <= npx-1 && x >= 1
864    f0 = log(result_conv(y,x));
865    f1 = log(result_conv(y,x-1));
866    f2 = log(result_conv(y,x+1));
867    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
868else
869    F=-2; % warning flag for vector truncated by the limited search box
870end
871vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
872
873%------------------------------------------------------------------------
874% --- Find the maximum of the correlation function after interpolation
875function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
876%------------------------------------------------------------------------
877vector=[0 0]; %default
878F=-2;
879peaky=y;
880peakx=x;
881result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
882[npy,npx]=size(result_conv);
883if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
884    F=0;
885    for i=-1:1
886        for j=-1:1
887            %following 15 lines based on
888            %H. Nobach ï¿œ M. Honkanen (2005)
889            %Two-dimensional Gaussian regression for sub-pixel displacement
890            %estimation in particle image velocimetry or particle position
891            %estimation in particle tracking velocimetry
892            %Experiments in Fluids (2005) 38: 511ï¿œ515
893            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
894            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
895            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
896            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
897            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
898        end
899    end
900    c10=(1/6)*sum(sum(c10));
901    c01=(1/6)*sum(sum(c01));
902    c11=(1/4)*sum(sum(c11));
903    c20=(1/6)*sum(sum(c20));
904    c02=(1/6)*sum(sum(c02));
905    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
906    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
907    if abs(deltax)<1
908        peakx=x+deltax;
909    end
910    if abs(deltay)<1
911        peaky=y+deltay;
912    end
913end
914vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
915
916%'RUN_FIX': function for fixing velocity fields:
917%-----------------------------------------------
918% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
919%
920%filename: name of the netcdf file (used as input and output)
921%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
922    %.vel_type='civ1' or 'civ2';
923    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
924    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
925%flagindex: flag specifying which values of vec_f are removed:
926        % if flagindex(1)=1: vec_f=-2 vectors are removed
927        % if flagindex(2)=1: vec_f=3 vectors are removed
928        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
929%iter=1 for civ1 fields and iter=2 for civ2 fields
930%thresh_vecC: threshold in the image correlation vec_C
931%flag_mask: =1 mask used to remove vectors (0 else)
932%maskname: name of the mask image file for fix
933%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
934%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
935%fileref: .nc file name for a reference velocity (='': refrence 0 used)
936%fieldref: 'civ1','filter1'...feld used in fileref
937
938function FF=fix(Param,F,C,U,V,X,Y)
939FF=zeros(size(F));%default
940
941%criterium on warn flags
942FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
943FlagVal=[-2 2 3 4];
944for iflag=1:numel(FlagName)
945    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
946        FF=(FF==1| F==FlagVal(iflag));
947    end
948end
949%criterium on correlation values
950if isfield (Param,'MinCorr')
951    FF=FF==1 | C<Param.MinCorr;
952end
953if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
954    Umod= U.*U+V.*V;
955    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
956        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
957    end
958    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
959        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
960    end
961end
962
963
964%------------------------------------------------------------------------
965% --- determine the list of index pairs of processing file
966function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
967    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
968%------------------------------------------------------------------------
969i1_series=i_series;% set of first image indexes
970i2_series=i_series;
971j1_series=j_series;%ones(size(i_series));% set of first image numbers
972j2_series=j_series;%ones(size(i_series));
973r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
974if ~isempty(r)
975    mode=['D' r.ind];
976    ind1=str2num(r.num1);
977    ind2=str2num(r.num2);
978else
979    mode='j1-j2';
980    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
981    if ~isempty(r)
982        NomTypeNc='_1ab';
983    else
984        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
985        if ~isempty(r)
986            NomTypeNc='_1AB';
987        else
988            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
989            if ~isempty(r)
990                NomTypeNc='_1_1-2';
991            end           
992        end
993    end
994    if isempty(r)
995        display('wrong pair mode input option')
996    else
997    ind1=stra2num(r.num1);
998    ind2=stra2num(r.num2);
999    end
1000end
1001switch mode
1002    case 'Di'
1003        i1_series=i_series-ind1;% set of first image numbers
1004        i2_series=i_series+ind2;
1005        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1006        if isempty(j_series)
1007            NomTypeNc='_1-2';
1008        else
1009            j1_series=j_series;
1010            j2_series=j_series;
1011            NomTypeNc='_1-2_1';
1012        end
1013    case 'Dj'
1014        j1_series=j_series-ind1;
1015        j2_series=j_series+ind2;
1016        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1017        NomTypeNc='_1_1-2';
1018    otherwise %bursts
1019        i1_series=i_series(1,:);% do not sweep the j index
1020        i2_series=i_series(1,:);
1021        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1022        j2_series=ind2*ones(1,size(i_series,2));
1023        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1024end
1025
1026%INPUT:
1027% xmid- u/2: set of apparent phys x coordinates in the ref plane, image A
1028% ymid- v/2: set of apparent phys y coordinates in the ref plane, image A
1029% xmid+ u/2: set of apparent phys x coordinates in the ref plane, image B
1030% ymid+ v/2: set of apparent phys y coordinates in the ref plane, image B
1031% XmlData: content of the xml files containing geometric calibration parameters
1032function [z,error]=shift2z(xmid, ymid, u, v,XmlData)
1033z=0;
1034error=0;
1035
1036%% first image
1037Calib_A=XmlData{1}.GeometryCalib;
1038R=(Calib_A.R)';
1039x_a=xmid- u/2;
1040y_a=ymid- v/2;
1041z_a=R(7)*x_a+R(8)*y_a+R(9)*Calib_A.SliceCoord(1,3);
1042X=(R(1)*x_a+R(2)*y_a+R(3)*Calib_A.SliceCoord(1,3))./z_a;
1043Y=(R(4)*x_a+R(5)*y_a+R(6)*Calib_A.SliceCoord(1,3))./z_a;
1044A_1_1=R(1)-R(7)*x_a;
1045A_1_2=R(2)-R(8)*x_a;
1046A_1_3=R(3)-R(9)*x_a;
1047A_2_1=R(4)-R(7)*y_a;
1048A_2_2=R(5)-R(8)*y_a;
1049A_2_3=R(6)-R(9)*y_a;
1050Det=A_1_1.*A_2_2-A_1_2.*A_2_1;
1051Dxa=(A_1_2.*A_2_3-A_2_2.*A_1_3)./Det;
1052Dya=(A_2_1.*A_1_3-A_1_1.*A_2_3)./Det;
1053
1054%% second image
1055Calib_A=XmlData{1}.GeometryCalib;
1056R=(Calib_A.R)';
1057x_a=xmid+ u/2;
1058y_a=ymid+ v/2;
1059z_a=R(7)*x_a+R(8)*y_a+R(9)*Calib_A.SliceCoord(1,3);
1060X=(R(1)*x_a+R(2)*y_a+R(3)*Calib_A.SliceCoord(1,3))./z_a;
1061Y=(R(4)*x_a+R(5)*y_a+R(6)*Calib_A.SliceCoord(1,3))./z_a;
1062A_1_1=R(1)-R(7)*x_a;
1063A_1_2=R(2)-R(8)*x_a;
1064A_1_3=R(3)-R(9)*x_a;
1065A_2_1=R(4)-R(7)*y_a;
1066A_2_2=R(5)-R(8)*y_a;
1067A_2_3=R(6)-R(9)*y_a;
1068Det=A_1_1.*A_2_2-A_1_2.*A_2_1;
1069Dxb=(A_1_2.*A_2_3-A_2_2.*A_1_3)./Det;
1070Dyb=(A_2_1.*A_1_3-A_1_1.*A_2_3)./Det;
1071
1072%% result
1073Den=(Dxb-Dxa).*(Dxb-Dxa)+(Dyb-Dya).*(Dyb-Dya);
1074error=((Dyb-Dya).*u-(Dxb-Dxa).*v)./Den;
1075z=((Dxb-Dxa).*u-(Dyb-Dya).*v)./Den;
Note: See TracBrowser for help on using the repository browser.