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

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

civ_input corrected to handle the new fct 'stereo_civ'

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