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

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