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

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

various bug fix

File size: 55.6 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_series(Param,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        ind_remove=find(strcmp('TestCiv1',list_param));
378        list_param(ind_remove)=[];
379        Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
380        Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
381        %indicate the values of all the global attributes in the output data
382        Data.Civ1_ImageA=ImageName_A;
383        Data.Civ1_ImageB=ImageName_B;
384        i1=i1_series_Civ1(ifield);
385        i2=i1;
386        if ~isempty(i2_series_Civ1)
387            i2=i2_series_Civ1(ifield);
388        end
389        j1=1;
390        if ~isempty(j1_series_Civ1)
391            j1=j1_series_Civ1(ifield);
392        end
393        j2=j1;
394        if ~isempty(j2_series_Civ1)
395            j2=j2_series_Civ1(ifield);
396        end
397        Data.Civ1_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
398        Data.Civ1_Dt=time(i2+1,j2+1)-time(i1+1,j1+1);
399        for ilist=1:length(list_param)
400            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
401        end
402        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
403        Data.CivStage=1;
404       
405        % set the list of variables
406        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
407        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
408        Data.VarAttribute{1}.Role='coord_x';
409        Data.VarAttribute{2}.Role='coord_y';
410        Data.VarAttribute{3}.Role='vector_x';
411        Data.VarAttribute{4}.Role='vector_y';
412        Data.VarAttribute{5}.Role='warnflag';
413       
414        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
415            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
416            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
417            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
418            for ivol=1:NbSlice
419                % caluclate velocity data (y and v in indices, reverse to y component)
420                [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
421                if ~isempty(errormsg)
422                     disp_uvmat('ERROR',errormsg,checkrun)
423                    return
424                end
425                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
426                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
427                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
428                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
429                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
430                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
431                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
432            end
433        else %usual PIV
434            % caluclate velocity data (y and v in indices, reverse to y component)
435            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
436            if ~isempty(errormsg)
437                disp_uvmat('ERROR',errormsg,checkrun)
438                return
439            end
440            Data.Civ1_X=reshape(xtable,[],1);
441            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
442            Data.Civ1_U=reshape(utable,[],1);
443            Data.Civ1_V=reshape(-vtable,[],1);
444            Data.Civ1_C=reshape(ctable,[],1);
445            Data.Civ1_F=reshape(F,[],1);
446        end
447    else% we use existing Civ1 data
448        if exist('ncfile','var')
449            CivFile=ncfile;
450        elseif isfield(Param.Patch1,'CivFile')
451            CivFile=Param.Patch1.CivFile;
452        end
453        [Data,tild,tild,errormsg]=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
454        if ~isempty(errormsg)
455            disp_uvmat('ERROR',errormsg,checkrun)
456            return
457        end
458        if ~isempty(Data.absolut_time_T0')%read civx file
459            check_civx=1;% test for old civx data format
460            [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
461        else
462            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
463        end
464    end
465   
466    %% Fix1
467    if isfield (Param.ActionInput,'Fix1')
468        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
469            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
470            Data.ListGlobalAttribute(Fix1_attr)=[];
471            for ilist=1:numel(Fix1_attr)
472                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
473            end
474        end
475        list_param=fieldnames(Param.ActionInput.Fix1)';
476        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
477        %indicate the values of all the global attributes in the output data
478        for ilist=1:length(list_param)
479            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
480        end
481        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
482%         
483%         for ilist=1:length(ListFixParam)
484%             ParamName=ListFixParam{ilist};
485%             ListName=['Fix1_' ParamName];
486%             eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
487%             eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
488%         end
489        if check_civx
490            if ~isfield(Data,'fix')
491                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
492                Data.fix=1;
493                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
494                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
495            end
496            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);
497        else
498            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
499            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
500            nbvar=length(Data.ListVarName);
501            Data.VarAttribute{nbvar}.Role='errorflag';
502            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
503            Data.CivStage=2;
504        end
505    end
506    %% Patch1
507    if isfield (Param.ActionInput,'Patch1')
508        if check_civx
509            errormsg='Civ Matlab input needed for patch';
510            disp_uvmat('ERROR',errormsg,checkrun)
511            return
512        end
513        list_param=fieldnames(Param.ActionInput.Patch1)';
514                   ind_remove=find(strcmp('TestPatch1',list_param));
515        list_param(ind_remove)=[];
516        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Fix1_' before  each string in ListFixParam
517        %indicate the values of all the global attributes in the output data
518        for ilist=1:length(list_param)
519            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
520        end
521        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
522       
523%         Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_FieldSmooth','Patch1_MaxDiff','Patch1_SubDomainSize'}];
524%         Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
525%         Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
526%         Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
527        nbvar=length(Data.ListVarName);
528        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
529        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
530            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
531        Data.VarAttribute{nbvar+1}.Role='vector_x';
532        Data.VarAttribute{nbvar+2}.Role='vector_y';
533        Data.VarAttribute{nbvar+5}.Role='coord_tps';
534        Data.VarAttribute{nbvar+6}.Role='vector_x';
535        Data.VarAttribute{nbvar+7}.Role='vector_y';
536        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
537        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
538        if isfield(Data,'Civ1_FF')
539            ind_good=find(Data.Civ1_FF==0);
540        else
541            ind_good=1:numel(Data.Civ1_X);
542        end
543        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
544            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);
545        Data.Civ1_U_smooth(ind_good)=Ures;
546        Data.Civ1_V_smooth(ind_good)=Vres;
547        Data.Civ1_FF(ind_good)=FFres;
548        Data.CivStage=3;
549    end
550   
551    %% Civ2
552    if isfield (Param.ActionInput,'Civ2')
553        par_civ2=Param.ActionInput.Civ2;
554        par_civ2.ImageA=[];
555        par_civ2.ImageB=[];
556        %         if ~isfield(Param.Civ1,'ImageA')
557         i1=i1_series_Civ2(ifield);
558        i2=i1;
559        if ~isempty(i2_series_Civ2)
560            i2=i2_series_Civ2(ifield);
561        end
562        j1=1;
563        if ~isempty(j1_series_Civ2)
564            j1=j1_series_Civ2(ifield);
565        end
566        j2=j1;
567        if ~isempty(j2_series_Civ2)
568            j2=j2_series_Civ2(ifield);
569        end
570        ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1,[],j1);
571
572        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
573            par_civ2.ImageA=par_civ1.ImageA;
574        else
575            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
576        end
577        ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2,[],j2);
578        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
579            par_civ2.ImageB=par_civ1.ImageB;
580        else
581            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
582        end     
583       
584        ncfile=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1,i2,j1,j2);
585        par_civ2.ImageWidth=FileInfo_A.Width;
586        par_civ2.ImageHeight=FileInfo_A.Height;
587       
588        if isfield(par_civ2,'Grid')% grid points set as input file
589            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
590                par_civ2.Grid=dlmread(par_civ2.Grid);
591                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
592            end
593        else% automatic grid
594            minix=floor(par_civ2.Dx/2)-0.5;
595            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
596            miniy=floor(par_civ2.Dy/2)-0.5;
597            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
598            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
599            par_civ2.Grid(:,1)=reshape(GridX,[],1);
600            par_civ2.Grid(:,2)=reshape(GridY,[],1);
601        end
602        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
603        Shifty=zeros(size(par_civ2.Grid,1),1);
604        nbval=zeros(size(par_civ2.Grid,1),1);
605        if par_civ2.CheckDeformation
606            DUDX=zeros(size(par_civ2.Grid,1),1);
607            DUDY=zeros(size(par_civ2.Grid,1),1);
608            DVDX=zeros(size(par_civ2.Grid,1),1);
609            DVDY=zeros(size(par_civ2.Grid,1),1);
610        end
611       
612         % get the guess from patch1 or patch2 (case 'iterate')
613        if isfield (par_civ2,'iterate') && strcmp(par_civ2.iterate,'iterate')
614           SubRange= Data.Civ2_SubRange;
615           NbCentres=Data.Civ2_NbCentres;
616           Coord_tps=Data.Civ2_Coord_tps;
617           U_tps=Data.Civ2_U_tps;
618           V_tps=Data.Civ2_V_tps;
619           CivStage=Data.CivStage;
620           Civ1_Dt=Data.Civ2_Dt;
621           Data=[];%reinitialise the result structure Data
622           Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
623           Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
624           Data.Program='civ_series';
625           Data.CivStage=CivStage;
626           Data.ListVarName={};
627           Data.VarDimName={};
628        else
629           SubRange= Data.Civ1_SubRange;
630           NbCentres=Data.Civ1_NbCentres;
631           Coord_tps=Data.Civ1_Coord_tps;
632           U_tps=Data.Civ1_U_tps;
633           V_tps=Data.Civ1_V_tps;
634           Civ1_Dt=Data.Civ1_Dt;
635        end
636        NbSubDomain=size(SubRange,3);       
637        for isub=1:NbSubDomain% for each sub-domain of Patch1
638            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
639            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
640                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));
641            epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites
642            ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
643            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
644            EM = tps_eval(epoints,ctrs);               
645            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*U_tps(1:nbvec_sub+3,isub);
646            Shifty(ind_sel)=Shifty(ind_sel)+EM*V_tps(1:nbvec_sub+3,isub);
647            if par_civ2.CheckDeformation
648                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
649                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*U_tps(1:nbvec_sub+3,isub);
650                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*U_tps(1:nbvec_sub+3,isub);
651                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*V_tps(1:nbvec_sub+3,isub);
652                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*V_tps(1:nbvec_sub+3,isub);
653            end
654        end
655        mask='';
656        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
657            mask=imread(par_civ2.Mask);
658        end
659        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
660        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
661        par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
662        par_civ2.SearchBoxSize(2)=2*iby2+9;
663        Civ2_Dt=time(i2+1,j2+1)-time(i1+1,j1+1);
664        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
665        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
666        if par_civ2.CheckDeformation
667            par_civ2.DUDX=DUDX./nbval;
668            par_civ2.DUDY=DUDY./nbval;
669            par_civ2.DVDX=DVDX./nbval;
670            par_civ2.DVDY=DVDY./nbval;
671        end
672        % calculate velocity data (y and v in indices, reverse to y component)
673        [xtable ytable utable vtable ctable F] = civ (par_civ2);
674        list_param=(fieldnames(Param.ActionInput.Civ2))';
675        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
676        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
677        %indicate the values of all the global attributes in the output data
678        Data.Civ2_ImageA=ImageName_A;
679        Data.Civ2_ImageB=ImageName_B;
680        Data.Civ2_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
681        Data.Civ2_Dt=Civ2_Dt;
682%         Data.Civ2_Time=1;
683%         Data.Civ2_Dt=1;
684        for ilist=1:length(list_param)
685            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
686        end
687        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
688       
689        nbvar=numel(Data.ListVarName);
690        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
691        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
692        Data.VarAttribute{nbvar+1}.Role='coord_x';
693        Data.VarAttribute{nbvar+2}.Role='coord_y';
694        Data.VarAttribute{nbvar+3}.Role='vector_x';
695        Data.VarAttribute{nbvar+4}.Role='vector_y';
696        Data.VarAttribute{nbvar+5}.Role='warnflag';
697        Data.Civ2_X=reshape(xtable,[],1);
698        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
699        Data.Civ2_U=reshape(utable,[],1);
700        Data.Civ2_V=reshape(-vtable,[],1);
701        Data.Civ2_C=reshape(ctable,[],1);
702        Data.Civ2_F=reshape(F,[],1);
703        Data.CivStage=Data.CivStage+1;
704    end
705   
706    %% Fix2
707    if isfield (Param.ActionInput,'Fix2')
708                list_param=fieldnames(Param.ActionInput.Fix2)';
709        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
710        %indicate the values of all the global attributes in the output data
711        for ilist=1:length(list_param)
712            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
713        end
714        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];     
715%         
716%         ListFixParam=fieldnames(Param.ActionInput.Fix2);
717%         for ilist=1:length(ListFixParam)
718%             ParamName=ListFixParam{ilist};
719%             ListName=['Fix2_' ParamName];
720%             eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
721%             eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
722%         end
723        if check_civx
724            if ~isfield(Data,'fix2')
725                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
726                Data.fix2=1;
727                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
728                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
729            end
730            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
731        else
732            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
733            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
734            nbvar=length(Data.ListVarName);
735            Data.VarAttribute{nbvar}.Role='errorflag';
736            Data.Civ2_FF=double(fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V));
737            Data.CivStage=Data.CivStage+1;
738        end
739       
740    end
741   
742    %% Patch2
743    if isfield (Param.ActionInput,'Patch2')
744                list_param=fieldnames(Param.ActionInput.Patch2)';
745        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
746        %indicate the values of all the global attributes in the output data
747        for ilist=1:length(list_param)
748            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
749        end
750        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
751       
752       
753%         Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_FieldSmooth','Patch2_MaxDiff','Patch2_SubDomainSize'}];
754%         Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
755%         Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
756%         Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
757        nbvar=length(Data.ListVarName);
758        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
759        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
760            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
761       
762        Data.VarAttribute{nbvar+1}.Role='vector_x';
763        Data.VarAttribute{nbvar+2}.Role='vector_y';
764        Data.VarAttribute{nbvar+5}.Role='coord_tps';
765        Data.VarAttribute{nbvar+6}.Role='vector_x';
766        Data.VarAttribute{nbvar+7}.Role='vector_y';
767        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
768        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
769        if isfield(Data,'Civ2_FF')
770            ind_good=find(Data.Civ2_FF==0);
771        else
772            ind_good=1:numel(Data.Civ2_X);
773        end
774        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
775            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);
776        Data.Civ2_U_smooth(ind_good)=Ures;
777        Data.Civ2_V_smooth(ind_good)=Vres;
778        Data.Civ2_FF(ind_good)=FFres;
779        Data.CivStage=Data.CivStage+1;
780    end
781   
782    %% write result in a netcdf file if requested
783    if exist('ncfile','var')
784        errormsg=struct2nc(ncfile,Data);
785        if isempty(errormsg)
786            disp([ncfile ' written'])
787        else
788            disp(errormsg)
789        end
790    end
791end
792
793% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
794%--------------------------------------------------------------------------
795% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
796%
797% OUTPUT:
798% xtable: set of x coordinates
799% ytable: set of y coordiantes
800% utable: set of u displacements (along x)
801% vtable: set of v displacements (along y)
802% ctable: max image correlation for each vector
803% typevector: set of flags, =1 for good, =0 for NaN vectors
804%
805%INPUT:
806% par_civ: structure of input parameters, with fields:
807%  .CorrBoxSize
808%  .SearchBoxSize
809%  .SearchBoxShift
810%  .ImageHeight
811%  .ImageWidth
812%  .Dx, Dy
813%  .Grid
814%  .Mask
815%  .MinIma
816%  .MaxIma
817%  .image1:first image (matrix)
818% image2: second image (matrix)
819% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
820% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
821% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
822% step: mesh of the measurement points (in px)
823% subpixfinder=1 or 2 controls the curve fitting of the image correlation
824% mask: =[] for no mask
825% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
826function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
827%this funtion performs the DCC PIV analysis. Recent window-deformation
828%methods perform better and will maybe be implemented in the future.
829
830%% prepare measurement grid
831if isfield(par_civ,'Grid')% grid points set as input
832    if ischar(par_civ.Grid)%read the drid file if the input is a file name
833        par_civ.Grid=dlmread(par_civ.Grid);
834        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
835    end
836else% automatic grid
837    minix=floor(par_civ.Dx/2)-0.5;
838    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
839    miniy=floor(par_civ.Dy/2)-0.5;
840    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
841    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
842    par_civ.Grid(:,1)=reshape(GridX,[],1);
843    par_civ.Grid(:,2)=reshape(GridY,[],1);
844end
845nbvec=size(par_civ.Grid,1);
846
847%% prepare correlation and search boxes
848ibx2=ceil(par_civ.CorrBoxSize(1)/2);
849iby2=ceil(par_civ.CorrBoxSize(2)/2);
850isx2=ceil(par_civ.SearchBoxSize(1)/2);
851isy2=ceil(par_civ.SearchBoxSize(2)/2);
852shiftx=round(par_civ.SearchBoxShift(:,1));
853shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
854if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
855    shiftx=shiftx*ones(nbvec,1);
856    shifty=shifty*ones(nbvec,1);
857end
858
859%% Default output
860xtable=par_civ.Grid(:,1);
861ytable=par_civ.Grid(:,2);
862utable=zeros(nbvec,1);
863vtable=zeros(nbvec,1);
864ctable=zeros(nbvec,1);
865F=zeros(nbvec,1);
866result_conv=[];
867errormsg='';
868
869%% prepare mask
870if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
871    if strcmp(par_civ.Mask,'all')
872        return    % get the grid only, no civ calculation
873    elseif ischar(par_civ.Mask)
874        par_civ.Mask=imread(par_civ.Mask);
875    end
876end
877check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
878check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
879
880% %% prepare images
881% if isfield(par_civ,'reverse_pair')
882%     if par_civ.reverse_pair
883%         if ischar(par_civ.ImageB)
884%             temp=par_civ.ImageA;
885%             par_civ.ImageA=imread(par_civ.ImageB);
886%         end
887%         if ischar(temp)
888%             par_civ.ImageB=imread(temp);
889%         end
890%     end
891% else
892%     if ischar(par_civ.ImageA)
893%         par_civ.ImageA=imread(par_civ.ImageA);
894%     end
895%     if ischar(par_civ.ImageB)
896%         par_civ.ImageB=imread(par_civ.ImageB);
897%     end
898% end
899par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
900par_civ.ImageB=sum(double(par_civ.ImageB),3);
901[npy_ima npx_ima]=size(par_civ.ImageA);
902if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
903    errormsg='image pair with unequal size';
904    return
905end
906
907%% Apply mask
908    % Convention for mask IDEAS TO IMPLEMENT ?
909    % mask >200 : velocity calculated
910    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
911    % 150>=mask >100: velocity not calculated, nor interpolated
912    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
913    %  20>=mask: velocity=0
914checkmask=0;
915MinA=min(min(par_civ.ImageA));
916MinB=min(min(par_civ.ImageB));
917if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
918   checkmask=1;
919   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
920        errormsg='mask must be an image with the same size as the images';
921        return
922   end
923  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
924    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
925    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
926    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
927end
928
929%% compute image correlations: MAINLOOP on velocity vectors
930corrmax=0;
931sum_square=1;% default
932mesh=1;% default
933CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
934if CheckDecimal
935    mesh=0.2;%mesh in pixels for subpixel image interpolation
936    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
937end
938% vector=[0 0];%default
939for ivec=1:nbvec
940    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
941    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
942    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
943    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
944    %               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
945    %             F(ivec)=3;
946    %         else
947    F(ivec)=0;
948    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
949    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
950    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
951    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
952    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
953    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
954    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
955    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
956    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
957    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
958   
959    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
960    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
961    image1_mean=mean(mean(image1_crop));
962    image2_mean=mean(mean(image2_crop));
963    %threshold on image minimum
964    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
965        F(ivec)=3;
966    end
967    %threshold on image maximum
968    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
969        F(ivec)=3;
970    end
971    %         end
972    if F(ivec)~=3
973        image1_crop=image1_crop-image1_mean;%substract the mean
974        image2_crop=image2_crop-image2_mean;
975        if CheckDecimal
976            xi=(1:mesh:size(image1_crop,2));
977            yi=(1:mesh:size(image1_crop,1))';
978            if CheckDeformation
979                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
980                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
981                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
982                image1_crop=interp2(image1_crop,XIant,YIant);
983            else
984                image1_crop=interp2(image1_crop,xi,yi);
985            end
986            xi=(1:mesh:size(image2_crop,2));
987            yi=(1:mesh:size(image2_crop,1))';
988            image2_crop=interp2(image2_crop,xi,yi);
989        end
990        sum_square=sum(sum(image1_crop.*image1_crop));
991        %reference: Oliver Pust, PIV: Direct Cross-Correlation
992        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
993        corrmax= max(max(result_conv));
994        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
995        %Find the correlation max, at 255
996        [y,x] = find(result_conv==255,1);
997        if ~isempty(y) && ~isempty(x)
998            try
999                if par_civ.CorrSmooth==1
1000                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
1001                elseif par_civ.CorrSmooth==2
1002                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
1003                end
1004                utable(ivec)=vector(1)*mesh+shiftx(ivec);
1005                vtable(ivec)=vector(2)*mesh+shifty(ivec);
1006                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
1007                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
1008                iref=round(xtable(ivec));% image index for the middle of the vector
1009                jref=round(ytable(ivec));
1010                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
1011                    utable(ivec)=0;
1012                    vtable(ivec)=0;
1013                    F(ivec)=3;
1014                end
1015                ctable(ivec)=corrmax/sum_square;% correlation value
1016            catch ME
1017                F(ivec)=3;
1018            end
1019        else
1020            F(ivec)=3;
1021        end
1022    end
1023end
1024result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
1025
1026%------------------------------------------------------------------------
1027% --- Find the maximum of the correlation function after interpolation
1028function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
1029%------------------------------------------------------------------------
1030vector=[0 0]; %default
1031F=0;
1032[npy,npx]=size(result_conv);
1033result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1034%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ᅵ Israel Institute of Technology
1035%http://urapiv.wordpress.com
1036peaky = y;
1037if y <= npy-1 && y >= 1
1038    f0 = log(result_conv(y,x));
1039    f1 = log(result_conv(y-1,x));
1040    f2 = log(result_conv(y+1,x));
1041    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
1042else
1043    F=-2; % warning flag for vector truncated by the limited search box
1044end
1045peakx=x;
1046if x <= npx-1 && x >= 1
1047    f0 = log(result_conv(y,x));
1048    f1 = log(result_conv(y,x-1));
1049    f2 = log(result_conv(y,x+1));
1050    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1051else
1052    F=-2; % warning flag for vector truncated by the limited search box
1053end
1054vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1055
1056%------------------------------------------------------------------------
1057% --- Find the maximum of the correlation function after interpolation
1058function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1059%------------------------------------------------------------------------
1060vector=[0 0]; %default
1061F=-2;
1062peaky=y;
1063peakx=x;
1064result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1065[npy,npx]=size(result_conv);
1066if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
1067    F=0;
1068    for i=-1:1
1069        for j=-1:1
1070            %following 15 lines based on
1071            %H. Nobach ï¿œ M. Honkanen (2005)
1072            %Two-dimensional Gaussian regression for sub-pixel displacement
1073            %estimation in particle image velocimetry or particle position
1074            %estimation in particle tracking velocimetry
1075            %Experiments in Fluids (2005) 38: 511ï¿œ515
1076            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1077            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1078            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1079            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1080            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1081        end
1082    end
1083    c10=(1/6)*sum(sum(c10));
1084    c01=(1/6)*sum(sum(c01));
1085    c11=(1/4)*sum(sum(c11));
1086    c20=(1/6)*sum(sum(c20));
1087    c02=(1/6)*sum(sum(c02));
1088    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1089    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1090    if abs(deltax)<1
1091        peakx=x+deltax;
1092    end
1093    if abs(deltay)<1
1094        peaky=y+deltay;
1095    end
1096end
1097vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1098
1099%'RUN_FIX': function for fixing velocity fields:
1100%-----------------------------------------------
1101% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
1102%
1103%filename: name of the netcdf file (used as input and output)
1104%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
1105    %.vel_type='civ1' or 'civ2';
1106    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
1107    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
1108%flagindex: flag specifying which values of vec_f are removed:
1109        % if flagindex(1)=1: vec_f=-2 vectors are removed
1110        % if flagindex(2)=1: vec_f=3 vectors are removed
1111        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
1112%iter=1 for civ1 fields and iter=2 for civ2 fields
1113%thresh_vecC: threshold in the image correlation vec_C
1114%flag_mask: =1 mask used to remove vectors (0 else)
1115%maskname: name of the mask image file for fix
1116%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
1117%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
1118%fileref: .nc file name for a reference velocity (='': refrence 0 used)
1119%fieldref: 'civ1','filter1'...feld used in fileref
1120
1121function FF=fix(Param,F,C,U,V,X,Y)
1122FF=zeros(size(F));%default
1123
1124%criterium on warn flags
1125FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
1126FlagVal=[-2 2 3 4];
1127for iflag=1:numel(FlagName)
1128    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
1129        FF=(FF==1| F==FlagVal(iflag));
1130    end
1131end
1132%criterium on correlation values
1133if isfield (Param,'MinCorr')
1134    FF=FF==1 | C<Param.MinCorr;
1135end
1136if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1137    Umod= U.*U+V.*V;
1138    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1139        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
1140    end
1141    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1142        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
1143    end
1144end
1145
1146
1147%------------------------------------------------------------------------
1148% --- determine the list of index pairs of processing file
1149function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1150    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1151%------------------------------------------------------------------------
1152i1_series=i_series;% set of first image indexes
1153i2_series=i_series;
1154j1_series=j_series;%ones(size(i_series));% set of first image numbers
1155j2_series=j_series;%ones(size(i_series));
1156r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1157if ~isempty(r)
1158    mode=['D' r.ind];
1159    ind1=str2num(r.num1);
1160    ind2=str2num(r.num2);
1161else
1162    mode='j1-j2';
1163    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1164    if ~isempty(r)
1165        NomTypeNc='_1ab';
1166    else
1167        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1168        if ~isempty(r)
1169            NomTypeNc='_1AB';
1170        else
1171            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1172            if ~isempty(r)
1173                NomTypeNc='_1_1-2';
1174            end           
1175        end
1176    end
1177    if isempty(r)
1178        display('wrong pair mode input option')
1179    else
1180    ind1=stra2num(r.num1);
1181    ind2=stra2num(r.num2);
1182    end
1183end
1184switch mode
1185    case 'Di'
1186        i1_series=i_series-ind1;% set of first image numbers
1187        i2_series=i_series+ind2;
1188        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1189        if isempty(j_series)
1190            NomTypeNc='_1-2';
1191        else
1192            j1_series=j_series;
1193            j2_series=j_series;
1194            NomTypeNc='_1-2_1';
1195        end
1196    case 'Dj'
1197        j1_series=j_series-ind1;
1198        j2_series=j_series+ind2;
1199        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1200        NomTypeNc='_1_1-2';
1201    otherwise %bursts
1202        i1_series=i_series(1,:);% do not sweep the j index
1203        i2_series=i_series(1,:);
1204        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1205        j2_series=ind2*ones(1,size(i_series,2));
1206        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1207end
1208
1209
1210
1211
Note: See TracBrowser for help on using the repository browser.