source: trunk/src/series/stereo_civ.m @ 862

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

bugs repaired

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