source: trunk/src/series/civ_series.m @ 719

Last change on this file since 719 was 716, checked in by sommeria, 11 years ago

fct improved by reducing the input file check when selected.

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