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

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

bugrepair

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