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

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

new

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