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

Last change on this file since 834 was 834, checked in by sommeria, 6 years ago

add stereo_civ

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