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

Last change on this file since 761 was 761, checked in by sommeria, 10 years ago

turb_stat corrected
civ corrected to allow civ2 from an existing civ1 series

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