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

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

bug corrected in sub_background. test_patch1 introduced in civ_series

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