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

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