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

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

Testpatch_fixed

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