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

Last change on this file since 851 was 851, checked in by sommeria, 9 years ago

various

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