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

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

testcivadded

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