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

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