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

Last change on this file since 823 was 822, checked in by sommeria, 10 years ago

various

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