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

Last change on this file since 1071 was 1071, checked in by g7moreau, 4 years ago
  • Update COPYRIGHT
File size: 68.2 KB
RevLine 
[598]1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
[597]6%------------------------------------------------------------------------
[855]7% function [Data,errormsg,result_conv]= civ_series(Param)
[597]8%
9%OUTPUT
[598]10% Data=structure containing the PIV results and information on the processing parameters
[995]11% errormsg=error message char string, decd ..fault=''
[598]12% resul_conv: image inter-correlation function for the last grid point (used for tests)
[597]13%
14%INPUT:
[855]15% Param: Matlab structure of input  parameters
16%     Param contains info of the GUI series using the fct read_GUI.
17%     Param.Action.RUN = 0 (to set the status of the GUI series) or =1 to RUN the computation
18%     Param.InputTable: sets the input file(s)
19%           if absent, the fct looks for input data in Param.ActionInput     (test mode)
20%     Param.OutputSubDir: sets the folder name of output file(s,
21%           if absent no file is produced, result in the output structure Data (test mode)
[859]22%     Param.ActionInput: substructure with the parameters provided by the GUI civ_input
[855]23%                      .Civ1: parameters for civ1
24%                      .Fix1: parameters for fix1
[859]25%                      .Patch1:
[855]26%                      .Civ2: for civ2
[859]27%                      .Fix2:
[855]28%                      .Patch2:
29
[924]30%=======================================================================
[1071]31% Copyright 2008-2020, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
[924]32%   http://www.legi.grenoble-inp.fr
33%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
[859]34%
[924]35%     This file is part of the toolbox UVMAT.
36%
[598]37%     UVMAT is free software; you can redistribute it and/or modify
[924]38%     it under the terms of the GNU General Public License as published
39%     by the Free Software Foundation; either version 2 of the license,
40%     or (at your option) any later version.
[859]41%
[598]42%     UVMAT is distributed in the hope that it will be useful,
43%     but WITHOUT ANY WARRANTY; without even the implied warranty of
44%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
[924]45%     GNU General Public License (see LICENSE.txt) for more details.
46%=======================================================================
[597]47
[724]48function [Data,errormsg,result_conv]= civ_series(Param)
[598]49errormsg='';
[763]50
[606]51%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
[859]52if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
[763]53    path_series=fileparts(which('series'));
54    addpath(fullfile(path_series,'series'))
[598]55    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
[668]56    if isempty(Data)
57        Data=Param;% if  civ_input has been cancelled, keep previous parameters
58    end
[606]59    Data.Program=mfilename;%gives the name of the current function
60    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
61    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
62    Data.NbSlice='off'; %nbre of slices ('off' by default)
63    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
[781]64    Data.FieldName='on';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
[606]65    Data.FieldTransform = 'off';%can use a transform function
66    Data.ProjObject='off';%can use projection object(option 'off'/'on',
67    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
68    Data.OutputDirExt='.civ';%set the output dir extension
[711]69    Data.OutputSubDirMode='last'; %select the last subDir in the input table as root of the output subdir name (option 'all'/'first'/'last', 'all' by default)
[645]70    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
[904]71    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
[1020]72    if isfield(Data.ActionInput,'PairIndices') && strcmp(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
[993]73        if isfield(Data.ActionInput.PairIndices,'ListPairCiv2')
74            str_civ=Data.ActionInput.PairIndices.ListPairCiv2;
75        else
76            str_civ=Data.ActionInput.PairIndices.ListPairCiv1;
77        end
78        r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
79        if isempty(r)
80            r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
81            if isempty(r)
82                r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
83            end
84        end
85        if ~isempty(r)
86            Data.j_index_1=stra2num(r.num1);
87            Data.j_index_2=stra2num(r.num2);
88        end
89    end
[1065]90    % estimated CPUTime
[1068]91    CPUtime_unit=0.01;%estimated time for a multiplication (in microsecond)
92    if isfield(Param.SeriesData,'FileInfo')&&isfield(Param.SeriesData.FileInfo{1},'Height')&&isfield(Param.SeriesData.FileInfo{1},'Width')
93        pixnbre=Param.SeriesData.FileInfo{1}.Height*Param.SeriesData.FileInfo{1}.Width; % total number of pxels for input images 
94        CPUtime=0;
95        if isfield(Data.ActionInput,'Civ1')
96            %BoxSize=Data.ActionInput.Civ1.CorrBoxSize(1)*Data.ActionInput.Civ1.CorrBoxSize(2);
97            tic
98            testboxa=rand(Data.ActionInput.Civ1.CorrBoxSize(1),Data.ActionInput.Civ1.CorrBoxSize(2));
99            testboxb=rand(Data.ActionInput.Civ1.SearchBoxSize(1),Data.ActionInput.Civ1.SearchBoxSize(2));
100            anss=conv2(testboxa,testboxb);
101            CPUtime_unit=toc;
102            nb_box=pixnbre/(Data.ActionInput.Civ1.Dx*Data.ActionInput.Civ1.Dy);   
103            %nbpos=Data.ActionInput.Civ1.SearchBoxSize-Data.ActionInput.Civ1.CorrBoxSize;
104            CPUtime=2*CPUtime_unit*nb_box%*BoxSize*nbpos(1)*nbpos(2);% adjustement factor 2 used
105        end
106        if isfield(Data.ActionInput,'Patch1')
107            CPUtime=2*CPUtime;
108        end
109        if isfield(Data.ActionInput,'Civ2')
110            tic
111            testboxa=rand(Data.ActionInput.Civ2.CorrBoxSize(1),Data.ActionInput.Civ2.CorrBoxSize(2));
112            testboxb=rand(Data.ActionInput.Civ2.SearchBoxSize(1),Data.ActionInput.Civ2.SearchBoxSize(2));
113            anss=conv2(testboxa,testboxb);
114            CPUtime_unit=toc;
115            nb_box=pixnbre/(Data.ActionInput.Civ2.Dx*Data.ActionInput.Civ2.Dy);
116            %BoxSize=Data.ActionInput.Civ2.CorrBoxSize(1)*Data.ActionInput.Civ2.CorrBoxSize(2);
117            %nbpos=Data.ActionInput.Civ2.SearchBoxSize-Data.ActionInput.Civ2.CorrBoxSize;
118            CPUtime=CPUtime+2*CPUtime_unit*nb_box;%*BoxSize*nbpos(1)*nbpos(2);
119        end
120        if isfield(Data.ActionInput,'Patch2')
121            CPUtime=(4/3)*CPUtime;
122        end
123        Data.CPUTime=ceil(CPUtime/6); % estimated CPU time per field pair in minute
124        Data.CPUTime=Data.CPUTime/10; % displqy CPU time with 1 digit beyond dot
125    end
[598]126    return
[597]127end
128
129%% read input parameters from an xml file if input is a file name (batch mode)
130checkrun=1;
131if ischar(Param)
132    Param=xml2struct(Param);% read Param as input file (batch case)
133    checkrun=0;
134end
[855]135
136%% test input
[668]137if ~isfield(Param,'ActionInput')
[859]138    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
139    return
[668]140end
[855]141iview_A=0;%default values
142NbField=1;
143RUNHandle=[];
144CheckInputFile=isfield(Param,'InputTable');%= 1 in test use for TestCiv (no nc file involved)
145CheckOutputFile=isfield(Param,'OutputSubDir');%= 1 in test use for TestPatch (no nc file produced)
[597]146
[855]147%% input files and indexing (skipped in Test mode)
148if CheckInputFile
149    hseries=findobj(allchild(0),'Tag','series');
150    RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
151    WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
152    MaxIndex_i=Param.IndexRange.MaxIndex_i;
153    MinIndex_i=Param.IndexRange.MinIndex_i;
154    MaxIndex_j=ones(size(MaxIndex_i));MinIndex_j=ones(size(MinIndex_i));
155    if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
156        MaxIndex_j=Param.IndexRange.MaxIndex_j;
157        MinIndex_j=Param.IndexRange.MinIndex_j;
[609]158    end
[855]159    if isfield(Param,'InputTable')
160        [tild,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
161        iview_A=0;% series index (iview) for the first image series
162        iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
163        if Param.ActionInput.CheckCiv1
164            iview_A=1;% usual PIV, the image series is on the first line of the table
165        elseif Param.ActionInput.CheckCiv2 % civ2 is performed without Civ1, a netcdf file series is needed in the first table line
166            iview_A=2;% the second line is used for the input images of Civ2
[610]167        end
[1020]168%         if strcmp(Param.ActionInput.ListCompareMode,'shift')
169%             iview_B=iview_A+1; % the second image series is on the next line of the input table
170%         end
[855]171        if iview_A~=0
172            RootPath_A=Param.InputTable{iview_A,1};
173            RootFile_A=Param.InputTable{iview_A,3};
174            SubDir_A=Param.InputTable{iview_A,2};
175            NomType_A=Param.InputTable{iview_A,4};
176            FileExt_A=Param.InputTable{iview_A,5};
177            if iview_B==0
178                iview_B=iview_A;% the second image series is the same as the first
[758]179            end
[855]180            RootPath_B=Param.InputTable{iview_B,1};
181            RootFile_B=Param.InputTable{iview_B,3};
182            SubDir_B=Param.InputTable{iview_B,2};
183            NomType_B=Param.InputTable{iview_B,4};
184            FileExt_B=Param.InputTable{iview_B,5};
185        end
186       
187        PairCiv2='';
188        switch Param.ActionInput.ListCompareMode
189            case 'PIV'
190                PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
191                if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
192                    PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;%string which determines the civ2 pair
[761]193                end
[855]194                if iview_A==1% if Civ1 is performed
195                    [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
196                        find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
197                    if ~isempty(PairCiv2)
198                        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
199                            find_pair_indices(PairCiv2,i1_series{1},j1_series{1},MinIndex_i(1),MaxIndex_i(1),MinIndex_j(1),MaxIndex_j(1));
200                        check_bounds=check_bounds | check_bounds_Civ2;
201                    end
202                else% we start from an existing Civ1 file
203                    i1_series_Civ1=i1_series{1};
204                    i2_series_Civ1=i2_series{1};
205                    j1_series_Civ1=j1_series{1};
206                    j2_series_Civ1=j2_series{1};
207                    NomTypeNc=Param.InputTable{1,4};
208                    if ~isempty(PairCiv2)
209                        [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds,NomTypeNc]=...
210                            find_pair_indices(PairCiv2,i1_series{2},j1_series{2},MinIndex_i(2),MaxIndex_i(2),MinIndex_j(2),MaxIndex_j(2));
211                    end
[761]212                end
[855]213            case 'displacement'
[1041]214                if isfield(Param.ActionInput,'OriginIndex')
[855]215                i1_series_Civ1=Param.ActionInput.OriginIndex*ones(size(i1_series{1}));
[1041]216                else
217                    i1_series_Civ1=ones(size(i1_series{1}));
218                end
[1020]219                i1_series_Civ2=i1_series_Civ1;
220                i2_series_Civ1=i1_series{1};
221                i2_series_Civ2=i1_series{1};
222                j1_series_Civ1=[];% no j index variation for the ref image
223                j1_series_Civ2=[];
224                if isempty(j1_series{1})
225                    j2_series_Civ1=ones(size(i1_series_Civ1));
[855]226                else
[1020]227                    j2_series_Civ1=j1_series{1};% if j index exist 
[855]228                end
229                j2_series_Civ2=j2_series_Civ1;
[1020]230                NomTypeNc='_1';
[855]231            case 'PIV volume'
232                % TODO, TODO
233        end
[1020]234        %determine frame indices for input with movie or other multiframe input file
235        if isempty(j1_series_Civ1)% simple movie with index i
[855]236            FrameIndex_A_Civ1=i1_series_Civ1;
237            FrameIndex_B_Civ1=i2_series_Civ1;
238            j1_series_Civ1=ones(size(i1_series_Civ1));
[1020]239            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
[855]240            j2_series_Civ1=ones(size(i1_series_Civ1));
[1020]241            end
242        else % movie for each burst or volume (index j)
[855]243            FrameIndex_A_Civ1=j1_series_Civ1;
244            FrameIndex_B_Civ1=j2_series_Civ1;
245        end
246        if isempty(PairCiv2)
[824]247            FrameIndex_A_Civ2=FrameIndex_A_Civ1;
248            FrameIndex_B_Civ2=FrameIndex_B_Civ1;
[758]249        else
[855]250            if isempty(j1_series_Civ2)
251                FrameIndex_A_Civ2=i1_series_Civ2;
252                FrameIndex_B_Civ2=i2_series_Civ2;
253                j1_series_Civ2=ones(size(i1_series_Civ2));
[1020]254                if strcmp(Param.ActionInput.ListCompareMode,'PIV')
[855]255                j2_series_Civ2=ones(size(i1_series_Civ2));
[1020]256                end
[855]257            else
258                FrameIndex_A_Civ2=j1_series_Civ2;
259                FrameIndex_B_Civ2=j2_series_Civ2;
260            end
[758]261        end
[855]262        if isempty(i1_series_Civ1)||(~isempty(PairCiv2) && isempty(i1_series_Civ2))
[993]263            disp_uvmat('ERROR','no image pair for civ in the input file index range',checkrun)
[758]264            return
265        end
[855]266    end
267   
268    %% check the first image pair
269        if Param.ActionInput.CheckCiv1% Civ1 is performed
270            NbField=numel(i1_series_Civ1);
271        elseif Param.ActionInput.CheckCiv2 % Civ2 is performed without Civ1
272            NbField=numel(i1_series_Civ2);
[819]273        else
[855]274            NbField=numel(i1_series_Civ1);% no image used (only fix or patch) TO CHECK
[781]275        end
[1007]276
[855]277    %% Output directory
278    OutputDir='';
279    if CheckOutputFile
[859]280        OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[758]281    end
282end
283
[855]284%% prepare output Data
[886]285ListGlobalAttribute={'Conventions','Program','CivStage'};
[605]286Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
287Data.Program='civ_series';
288Data.CivStage=0;%default
289check_civx=0;%default
290
[606]291%% get timing from the ImaDoc file or input video
[822]292if iview_A~=0
[833]293    XmlFileName=find_imadoc(RootPath_A,SubDir_A,RootFile_A,FileExt_A);
[950]294    Time=[];
[833]295    if ~isempty(XmlFileName)
296        XmlData=imadoc2struct(XmlFileName);
[609]297        if isfield(XmlData,'Time')
[950]298            Time=XmlData.Time;
[609]299        end
300        if isfield(XmlData,'Camera')
301            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
302                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
303                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
304                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
305                end
306            end
307            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
308                TimeUnit=XmlData.Camera.TimeUnit;
309            end
310        end
[833]311    end
[610]312end
[609]313
[598]314%%%%% MAIN LOOP %%%%%%
[1010]315maskoldname='';% initiate the mask name
[997]316FileType_A='';
317FileType_B='';
[904]318CheckOverwrite=1;%default
319if isfield(Param,'CheckOverwrite')
320    CheckOverwrite=Param.CheckOverwrite;
321end
[598]322for ifield=1:NbField
[997]323    tic
[855]324    if ~isempty(RUNHandle)% update the waitbar in interactive mode with GUI series  (checkrun=1)
325        update_waitbar(WaitbarHandle,ifield/NbField)
[905]326        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
[855]327            disp('program stopped by user')
328            break
329        end
[624]330    end
[855]331    if CheckInputFile
332        if iview_A==0 % no nc file has been entered
333            ncfile=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},Param.InputTable{1,5},...
334                NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),j1_series_Civ1(ifield),j2_series_Civ1(ifield));
335        else% an existing nc file has been entered
336            if iview_A==1% if Civ1 is performed
337                Civ1Dir=OutputDir;
338            else
339                Civ1Dir=Param.InputTable{1,2};
340            end
341            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
342                ncfile=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
343                    j1_series_Civ1(ifield),j2_series_Civ1(ifield));
344            else
345                ncfile=fullfile_uvmat(RootPath_A,Civ1Dir,RootFile_A,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
346                    j1_series_Civ1(ifield),j2_series_Civ1(ifield));
347            end
[822]348        end
[997]349        ncfile_out=ncfile;% by default
[912]350        if isfield (Param.ActionInput,'Civ2')
351            i1_civ2=i1_series_Civ2(ifield);
352            i2_civ2=i1_civ2;
353            if ~isempty(i2_series_Civ2)
354                i2_civ2=i2_series_Civ2(ifield);
355            end
356            j1_civ2=1;
357            if ~isempty(j1_series_Civ2)
358                j1_civ2=j1_series_Civ2(ifield);
359            end
360            j2_civ2=i1_civ2;
361            if ~isempty(j2_series_Civ2)
362                j2_civ2=j2_series_Civ2(ifield);
363            end
364            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
365                ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1_civ2,i2_civ2,j1_civ2,j2_civ2);
366            else % displacement
367                ncfile_out=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i2_civ2,[],j2_civ2);
368            end
[904]369        end
[912]370        if ~CheckOverwrite && exist(ncfile_out,'file')
371            disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
372            continue% skip iteration if the mode overwrite is desactivated and the result file already exists
373        end
[761]374    end
[598]375    %% Civ1
[707]376    % if Civ1 computation is requested
[598]377    if isfield (Param.ActionInput,'Civ1')
[897]378        if CheckInputFile
[997]379            disp('civ1 started')
[897]380        end
[1020]381        par_civ1=Param.ActionInput.Civ1;% parameters for civ1
[856]382        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
[855]383            try
[1020]384                if strcmp(Param.ActionInput.ListCompareMode,'displacement')
385                    ImageName_A=Param.ActionInput.RefFile;
386                else
[855]387                ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
[1020]388                end
[997]389                if strcmp(FileExt_A,'.nc')% case of input images in format netcdf
[855]390                    FieldName_A=Param.InputFields.FieldName;
391                    [DataIn,tild,tild,errormsg]=nc2struct(ImageName_A,{FieldName_A});
392                    par_civ1.ImageA=DataIn.(FieldName_A);
393                else % usual image formats for image A
[1020]394                    if isempty(FileType_A)% open the image object if not already done in case of movie input
[997]395                        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
396                        FileType_A=FileInfo_A.FileType;
397                        if isempty(Time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video','cine_phantom'})))% case of video input
398                            Time=zeros(FileInfo_A.NumberOfFrames+1,2);
399                            Time(:,2)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate)';
400                        end
401                        if ~isempty(FileType_A) && isempty(Time)% Time = index i +0.001 index j by default
402                            MaxIndex_i=max(i2_series_Civ1);
403                            MaxIndex_j=max(j2_series_Civ1);
404                            Time=(1:MaxIndex_i)'*ones(1,MaxIndex_j);
405                            Time=Time+0.001*ones(MaxIndex_i,1)*(1:MaxIndex_j);
406                            Time=[zeros(1,MaxIndex_j);Time];% insert a first line of zeros
407                            Time=[zeros(MaxIndex_i+1,1) Time];% insert a first column of zeros
408                        end
409                    end
410                    if ~exist(ImageName_A,'file')
411                        disp([ImageName_A ' missing'])
412                        continue
413                    end
[855]414                    [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(ifield));
415                end
416                ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
[997]417                if strcmp(FileExt_B,'.nc') % case of input images in format netcdf
[855]418                    FieldName_B=Param.InputFields.FieldName;
419                    [DataIn,tild,tild,errormsg]=nc2struct(ImageName_B,{FieldName_B});
420                    par_civ1.ImageB=DataIn.(FieldName_B);
421                else % usual image formats for image B
[997]422                    if isempty(FileType_B)
423                        [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
424                        FileType_B=FileInfo_B.FileType;
425                    end
426                    if ~exist(ImageName_B,'file')
427                        disp([ImageName_B ' missing'])
428                        continue
429                    end
[855]430                    [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(ifield));
431                end
432            catch ME % display errors in reading input images
433                if ~isempty(ME.message)
434                    disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
[993]435                    continue
[855]436                end
[781]437            end
[996]438            par_civ1.ImageWidth=size(par_civ1.ImageA,2);
439            par_civ1.ImageHeight=size(par_civ1.ImageA,1);
[855]440            list_param=(fieldnames(Param.ActionInput.Civ1))';
441            list_param(strcmp('TestCiv1',list_param))=[];% remove the parameter TestCiv1 from the list
442            Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
443            Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
444            %indicate the values of all the global attributes in the output data
445            Data.Civ1_ImageA=ImageName_A;
446            Data.Civ1_ImageB=ImageName_B;
447            i1=i1_series_Civ1(ifield);
448            i2=i1;
449            if ~isempty(i2_series_Civ1)
450                i2=i2_series_Civ1(ifield);
[781]451            end
[855]452            j1=1;
453            if ~isempty(j1_series_Civ1)
454                j1=j1_series_Civ1(ifield);
[758]455            end
[855]456            j2=j1;
457            if ~isempty(j2_series_Civ1)
458                j2=j2_series_Civ1(ifield);
459            end
[861]460            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
[950]461                Data.Civ1_Time=Time(i2+1,j2+1);% the Time is the Time of the secodn image
462                Data.Civ1_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
[861]463            else
[997]464                Data.Civ1_Time=(Time(i2+1,j2+1)+Time(i1+1,j1+1))/2;% the Time is the Time at the middle of the image pair
465                Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
[861]466            end
[855]467            for ilist=1:length(list_param)
468                Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
469            end
[886]470            Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
[855]471            Data.CivStage=1;
[597]472        end
[598]473        % set the list of variables
474        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
475        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
476        Data.VarAttribute{1}.Role='coord_x';
477        Data.VarAttribute{2}.Role='coord_y';
478        Data.VarAttribute{3}.Role='vector_x';
479        Data.VarAttribute{4}.Role='vector_y';
480        Data.VarAttribute{5}.Role='warnflag';
[1010]481        % case of mask
[856]482        if par_civ1.CheckMask&&~isempty(par_civ1.Mask)
[1010]483            if isfield(par_civ1,'NbSlice')
484                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ1.Mask);
485                i1_mask=mod(i1-1,par_civ1.NbSlice)+1;
486                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
487            else
488                maskname=Param.ActionInput.Civ1.Mask;
489            end
490            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
[856]491                par_civ1.Mask=mask; %use mask already opened
492            else
[1062]493                if exist(maskname,'file')
494                    try
495                        par_civ1.Mask=imread(maskname);%update the mask, an store it for future use
496                    catch ME
497                        if ~isempty(ME.message)
498                            errormsg=['error reading input image: ' ME.message];
499                            disp_uvmat('ERROR',errormsg,checkrun)
500                            return
501                        end
[861]502                    end
[1062]503                else
504                    par_civ1.Mask=[];
[861]505                end
[856]506                mask=par_civ1.Mask;
[1010]507                maskoldname=maskname;
[856]508            end
509        end
[598]510        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
511            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
512            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
513            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
514            for ivol=1:NbSlice
515                % caluclate velocity data (y and v in indices, reverse to y component)
[856]516                [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
[598]517                if ~isempty(errormsg)
[859]518                    disp_uvmat('ERROR',errormsg,checkrun)
[598]519                    return
520                end
521                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
522                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
523                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
524                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
525                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
526                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
527                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
528            end
529        else %usual PIV
530            % caluclate velocity data (y and v in indices, reverse to y component)
[856]531            [xtable, ytable, utable, vtable, ctable, F, result_conv, errormsg] = civ (par_civ1);
[597]532            if ~isempty(errormsg)
[703]533                disp_uvmat('ERROR',errormsg,checkrun)
[597]534                return
535            end
[598]536            Data.Civ1_X=reshape(xtable,[],1);
537            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
538            Data.Civ1_U=reshape(utable,[],1);
539            Data.Civ1_V=reshape(-vtable,[],1);
540            Data.Civ1_C=reshape(ctable,[],1);
541            Data.Civ1_F=reshape(F,[],1);
[597]542        end
[707]543    else% we use existing Civ1 data
[598]544        if exist('ncfile','var')
545            CivFile=ncfile;
[855]546            [Data,tild,tild,errormsg]=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
547            if ~isempty(errormsg)
548                disp_uvmat('ERROR',errormsg,checkrun)
549                return
550            end
[859]551            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
[856]552        elseif isfield(Param,'Civ1_X')
[855]553            Data.ListGlobalAttribute={};
554            Data.ListVarName={};
555            Data.VarDimName={};
556            Data.Civ1_X=Param.Civ1_X;
557            Data.Civ1_Y=Param.Civ1_Y;
558            Data.Civ1_U=Param.Civ1_U;
559            Data.Civ1_V=Param.Civ1_V;
[859]560            Data.Civ1_FF=Param.Civ1_FF;
[598]561        end
[597]562    end
563   
[598]564    %% Fix1
565    if isfield (Param.ActionInput,'Fix1')
[997]566        disp('fix1 started')
[822]567        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
568            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
569            Data.ListGlobalAttribute(Fix1_attr)=[];
570            for ilist=1:numel(Fix1_attr)
571                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
572            end
[859]573        end
[852]574        list_param=fieldnames(Param.ActionInput.Fix1)';
575        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]576        %indicate the values of all the global attributes in the output data
[852]577        for ilist=1:length(list_param)
578            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
[598]579        end
[852]580        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
[859]581        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
582        Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
583        nbvar=length(Data.ListVarName);
584        Data.VarAttribute{nbvar}.Role='errorflag';
[944]585        Data.Civ1_FF=int8(fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V));
[859]586        Data.CivStage=2;
[597]587    end
[598]588    %% Patch1
589    if isfield (Param.ActionInput,'Patch1')
[896]590        disp('patch1 started')
[598]591        if check_civx
592            errormsg='Civ Matlab input needed for patch';
[703]593            disp_uvmat('ERROR',errormsg,checkrun)
[598]594            return
595        end
[855]596       
597        % record the processing parameters of Patch1 as global attributes in the result nc file
[852]598        list_param=fieldnames(Param.ActionInput.Patch1)';
[855]599        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
600        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
[852]601        for ilist=1:length(list_param)
602            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
603        end
[855]604        Data.CivStage=3;% record the new state of processing
[852]605        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
[598]606       
[855]607        % list the variables to record
[598]608        nbvar=length(Data.ListVarName);
609        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
610        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
611            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
612        Data.VarAttribute{nbvar+1}.Role='vector_x';
613        Data.VarAttribute{nbvar+2}.Role='vector_y';
614        Data.VarAttribute{nbvar+5}.Role='coord_tps';
615        Data.VarAttribute{nbvar+6}.Role='vector_x';
616        Data.VarAttribute{nbvar+7}.Role='vector_y';
[855]617        Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
618        Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
[598]619        if isfield(Data,'Civ1_FF')
620            ind_good=find(Data.Civ1_FF==0);
[597]621        else
[598]622            ind_good=1:numel(Data.Civ1_X);
[597]623        end
[855]624       
[859]625        % perform Patch calculation using the UVMAT fct 'filter_tps'
[598]626        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
627            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);
[949]628        Data.Civ1_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
[598]629        Data.Civ1_V_smooth(ind_good)=Vres;
[944]630        Data.Civ1_FF(ind_good)=int8(FFres);
[896]631        disp('patch1 performed')
[597]632    end
633   
[598]634    %% Civ2
635    if isfield (Param.ActionInput,'Civ2')
[896]636        disp('civ2 started')
[598]637        par_civ2=Param.ActionInput.Civ2;
[856]638        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
639            par_civ2.ImageA=[];
640            par_civ2.ImageB=[];
[1020]641            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
642                    ImageName_A_Civ2=Param.ActionInput.RefFile;
643                else
[912]644            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
[1020]645            end
[856]646            if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
647                par_civ2.ImageA=par_civ1.ImageA;
648            else
649                [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
650            end
[912]651            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
[856]652            if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
653                par_civ2.ImageB=par_civ1.ImageB;
654            else
655                [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
656            end
657            par_civ2.ImageWidth=FileInfo_A.Width;
658            par_civ2.ImageHeight=FileInfo_A.Height;
659            if isfield(par_civ2,'Grid')% grid points set as input file
660                if ischar(par_civ2.Grid)%read the grid file if the input is a file name
661                    par_civ2.Grid=dlmread(par_civ2.Grid);
662                    par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
663                end
664            else% automatic grid
665                minix=floor(par_civ2.Dx/2)-0.5;
666                maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
667                miniy=floor(par_civ2.Dy/2)-0.5;
668                maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
669                [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
670                par_civ2.Grid(:,1)=reshape(GridX,[],1);
671                par_civ2.Grid(:,2)=reshape(GridY,[],1);
672            end
[597]673        end
[851]674       
[856]675        % get the guess from patch1 or patch2 (case 'CheckCiv3')
676        if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
677            if isfield (par_civ2,'CheckCiv3') && par_civ2.CheckCiv3 %get the guess from  patch2
678                SubRange= Data.Civ2_SubRange;
679                NbCentres=Data.Civ2_NbCentres;
680                Coord_tps=Data.Civ2_Coord_tps;
681                U_tps=Data.Civ2_U_tps;
682                V_tps=Data.Civ2_V_tps;
[859]683                CivStage=Data.CivStage;%store the current CivStage
[856]684                Civ1_Dt=Data.Civ2_Dt;
685                Data=[];%reinitialise the result structure Data
686                Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
687                Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
688                Data.Program='civ_series';
[859]689                Data.CivStage=CivStage+1;%update the current civStage after reinitialisation of Data
[856]690                Data.ListVarName={};
691                Data.VarDimName={};
692            else % get the guess from patch1
693                SubRange= Data.Civ1_SubRange;
694                NbCentres=Data.Civ1_NbCentres;
695                Coord_tps=Data.Civ1_Coord_tps;
696                U_tps=Data.Civ1_U_tps;
697                V_tps=Data.Civ1_V_tps;
698                Civ1_Dt=Data.Civ1_Dt;
[859]699                Data.CivStage=4;
[856]700            end
701        else
702            SubRange= par_civ2.Civ1_SubRange;
703            NbCentres=par_civ2.Civ1_NbCentres;
704            Coord_tps=par_civ2.Civ1_Coord_tps;
705            U_tps=par_civ2.Civ1_U_tps;
706            V_tps=par_civ2.Civ1_V_tps;
707            Civ1_Dt=par_civ2.Civ1_Dt;
[858]708            Civ2_Dt=par_civ2.Civ1_Dt;
[859]709            Data.ListVarName={};
710            Data.VarDimName={};
[851]711        end
[856]712        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
713        Shifty=zeros(size(par_civ2.Grid,1),1);
714        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
[862]715        if par_civ2.CheckDeformation
716            DUDX=zeros(size(par_civ2.Grid,1),1);
717            DUDY=zeros(size(par_civ2.Grid,1),1);
718            DVDX=zeros(size(par_civ2.Grid,1),1);
719            DVDY=zeros(size(par_civ2.Grid,1),1);
720        end
[856]721        NbSubDomain=size(SubRange,3);
[761]722        for isub=1:NbSubDomain% for each sub-domain of Patch1
[851]723            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
724            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
[862]725                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
[859]726            if ~isempty(ind_sel)
[862]727                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
[859]728                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
729                nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for each interpolation point (in case of subdomain overlap)
[862]730                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
731                Shiftx(ind_sel)=Shiftx(ind_sel)+EM*U_tps(1:nbvec_sub+3,isub);%velocity shift estimated by tps from civ1
[859]732                Shifty(ind_sel)=Shifty(ind_sel)+EM*V_tps(1:nbvec_sub+3,isub);
733                if par_civ2.CheckDeformation
734                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
735                    DUDX(ind_sel)=DUDX(ind_sel)+EMDX*U_tps(1:nbvec_sub+3,isub);
736                    DUDY(ind_sel)=DUDY(ind_sel)+EMDY*U_tps(1:nbvec_sub+3,isub);
737                    DVDX(ind_sel)=DVDX(ind_sel)+EMDX*V_tps(1:nbvec_sub+3,isub);
738                    DVDY(ind_sel)=DVDY(ind_sel)+EMDY*V_tps(1:nbvec_sub+3,isub);
739                end
[597]740            end
741        end
[1010]742        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)       
743            if isfield(par_civ2,'NbSlice')
744                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
745                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
746                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
747            else
748                maskname=Param.ActionInput.Civ2.Mask;
749            end
750            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
[856]751                par_civ2.Mask=mask; %use mask already opened
752            else
[1062]753                if exist(maskname,'file')
[1010]754                try
755                    par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
756                catch ME
757                    if ~isempty(ME.message)
758                        errormsg=['error reading input image: ' ME.message];
759                        disp_uvmat('ERROR',errormsg,checkrun)
760                        return
761                    end
762                end
[1062]763                else
764                    par_civ2.Mask=[];
765                end
[856]766                mask=par_civ2.Mask;
[1010]767                maskoldname=maskname;
[856]768            end
[598]769        end
[1010]770
[858]771        if CheckInputFile % else Dt given by par_civ2
772            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
773                Civ1_Dt=1;
774                Civ2_Dt=1;
775            else
[950]776                Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
[858]777            end
[856]778        end
[851]779        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
[862]780        % shift the grid points by half the expected shift to provide the correlation box position in image A
[873]781        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];
[598]782        if par_civ2.CheckDeformation
[876]783            par_civ2.DUDX=DUDX(nbval>=1)./nbval(nbval>=1);
784            par_civ2.DUDY=DUDY(nbval>=1)./nbval(nbval>=1);
785            par_civ2.DVDX=DVDX(nbval>=1)./nbval(nbval>=1);
786            par_civ2.DVDY=DVDY(nbval>=1)./nbval(nbval>=1);
[598]787        end
[859]788       
[862]789        % calculate velocity data (y and v in image indices, reverse to y component)
[856]790        [xtable, ytable, utable, vtable, ctable, F,result_conv,errormsg] = civ (par_civ2);
791       
[598]792        list_param=(fieldnames(Param.ActionInput.Civ2))';
[859]793        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
[606]794        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
795        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
[856]796        %indicate the values of all the global attributes in the output data
797        if exist('ImageName_A','var')
[859]798            Data.Civ2_ImageA=ImageName_A;
799            Data.Civ2_ImageB=ImageName_B;
[997]800            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
[950]801                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
802                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
[997]803            else
804                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
805                Data.Civ2_Dt=Civ2_Dt;
806            end
[856]807        end
[598]808        for ilist=1:length(list_param)
[606]809            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
[598]810        end
[606]811        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
812       
[598]813        nbvar=numel(Data.ListVarName);
[859]814        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
815        if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
816            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
817            Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
818            Data.VarAttribute{nbvar+1}.Role='coord_x';
819            Data.VarAttribute{nbvar+2}.Role='coord_y';
820            Data.VarAttribute{nbvar+3}.Role='vector_x';
821            Data.VarAttribute{nbvar+4}.Role='vector_y';
822            Data.VarAttribute{nbvar+5}.Role='warnflag';
823        end
[598]824        Data.Civ2_X=reshape(xtable,[],1);
825        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
826        Data.Civ2_U=reshape(utable,[],1);
827        Data.Civ2_V=reshape(-vtable,[],1);
828        Data.Civ2_C=reshape(ctable,[],1);
829        Data.Civ2_F=reshape(F,[],1);
[896]830        disp('civ2 performed')
[860]831    elseif ~isfield(Data,'ListVarName') % we start there, using existing Civ2 data
832        if exist('ncfile','var')
833            CivFile=ncfile;
834            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
835            if ~isempty(errormsg)
836                disp_uvmat('ERROR',errormsg,checkrun)
837                return
[997]838            end
[860]839        elseif isfield(Param,'Civ2_X')% use Civ2 data as input in Param (test mode)
840            Data.ListGlobalAttribute={};
841            Data.ListVarName={};
842            Data.VarDimName={};
843            Data.Civ2_X=Param.Civ2_X;
844            Data.Civ2_Y=Param.Civ2_Y;
845            Data.Civ2_U=Param.Civ2_U;
846            Data.Civ2_V=Param.Civ2_V;
847            Data.Civ2_FF=Param.Civ2_FF;
848        end
[598]849    end
850   
851    %% Fix2
852    if isfield (Param.ActionInput,'Fix2')
[896]853        disp('fix2 started')
[856]854        list_param=fieldnames(Param.ActionInput.Fix2)';
[852]855        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]856        %indicate the values of all the global attributes in the output data
[852]857        for ilist=1:length(list_param)
858            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
[598]859        end
[859]860        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
861        %
862        %         ListFixParam=fieldnames(Param.ActionInput.Fix2);
863        %         for ilist=1:length(ListFixParam)
864        %             ParamName=ListFixParam{ilist};
865        %             ListName=['Fix2_' ParamName];
866        %             eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
867        %             eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
868        %         end
[598]869        if check_civx
870            if ~isfield(Data,'fix2')
871                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
872                Data.fix2=1;
873                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
874                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
875            end
876            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
[597]877        else
[598]878            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
879            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
880            nbvar=length(Data.ListVarName);
881            Data.VarAttribute{nbvar}.Role='errorflag';
[822]882            Data.Civ2_FF=double(fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V));
[598]883            Data.CivStage=Data.CivStage+1;
[597]884        end
[598]885    end
886   
887    %% Patch2
888    if isfield (Param.ActionInput,'Patch2')
[896]889        disp('patch2 started')
[859]890        list_param=fieldnames(Param.ActionInput.Patch2)';
891        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
[852]892        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]893        %indicate the values of all the global attributes in the output data
[852]894        for ilist=1:length(list_param)
895            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
896        end
897        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
898       
[598]899        nbvar=length(Data.ListVarName);
900        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
901        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
902            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
903       
904        Data.VarAttribute{nbvar+1}.Role='vector_x';
905        Data.VarAttribute{nbvar+2}.Role='vector_y';
906        Data.VarAttribute{nbvar+5}.Role='coord_tps';
907        Data.VarAttribute{nbvar+6}.Role='vector_x';
908        Data.VarAttribute{nbvar+7}.Role='vector_y';
[997]909        Data.Civ2_U_smooth=Data.Civ2_U;
910        Data.Civ2_V_smooth=Data.Civ2_V;
[598]911        if isfield(Data,'Civ2_FF')
912            ind_good=find(Data.Civ2_FF==0);
[597]913        else
[598]914            ind_good=1:numel(Data.Civ2_X);
[597]915        end
[949]916        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures,Vres,tild,FFres]=...
[598]917            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);
918        Data.Civ2_U_smooth(ind_good)=Ures;
919        Data.Civ2_V_smooth(ind_good)=Vres;
920        Data.Civ2_FF(ind_good)=FFres;
921        Data.CivStage=Data.CivStage+1;
[896]922        disp('patch2 performed')
[597]923    end
[598]924   
925    %% write result in a netcdf file if requested
[859]926    if CheckOutputFile
[912]927        errormsg=struct2nc(ncfile_out,Data);
[598]928        if isempty(errormsg)
[912]929            disp([ncfile_out ' written'])
[938]930            %[success,msg] = fileattrib(ncfile_out ,'+w','g');% done in struct2nc
[598]931        else
932            disp(errormsg)
933        end
[904]934        disp(['ellapsed time ' num2str(toc/60,2) ' minutes'])
[598]935    end
[597]936end
937
[894]938
[598]939% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
940%--------------------------------------------------------------------------
941% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
942%
943% OUTPUT:
944% xtable: set of x coordinates
945% ytable: set of y coordiantes
946% utable: set of u displacements (along x)
947% vtable: set of v displacements (along y)
948% ctable: max image correlation for each vector
949% typevector: set of flags, =1 for good, =0 for NaN vectors
950%
951%INPUT:
952% par_civ: structure of input parameters, with fields:
[856]953%  .ImageA: first image for correlation (matrix)
954%  .ImageB: second image for correlation(matrix)
955%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
956%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
957%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
958%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
959%  .ImageWidth: nb of pixels of the image in x
960%  .Dx, Dy: mesh for the PIV calculation
[862]961%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
[856]962%  .Mask: name of a mask file or mask image matrix itself
963%  .MinIma: thresholds for image luminosity
[598]964%  .MaxIma
[856]965%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
966%  .DUDX: matrix of deformation obtained from patch at each grid point
967%  .DUDY
968%  .DVDX:
969%  .DVDY
970
[855]971function [xtable,ytable,utable,vtable,ctable,F,result_conv,errormsg] = civ (par_civ)
[598]972
973%% prepare measurement grid
[862]974if isfield(par_civ,'Grid')% grid points set as input, central positions of the sub-images in image A
975    if ischar(par_civ.Grid)%read the grid file if the input is a file name (grid in x, y image coordinates)
[598]976        par_civ.Grid=dlmread(par_civ.Grid);
977        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
978    end
[862]979    % else par_civ.Grid is already an array, no action here
980else% automatic grid in x, y image coordinates
[598]981    minix=floor(par_civ.Dx/2)-0.5;
982    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
[862]983    miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
[598]984    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
985    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
986    par_civ.Grid(:,1)=reshape(GridX,[],1);
[862]987    par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
[597]988end
[598]989nbvec=size(par_civ.Grid,1);
990
[859]991%% prepare correlation and search boxes
[876]992ibx2=floor(par_civ.CorrBoxSize(1)/2);
993iby2=floor(par_civ.CorrBoxSize(2)/2);
994isx2=floor(par_civ.SearchBoxSize(1)/2);
995isy2=floor(par_civ.SearchBoxSize(2)/2);
[862]996shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
[598]997shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
998if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
999    shiftx=shiftx*ones(nbvec,1);
1000    shifty=shifty*ones(nbvec,1);
1001end
1002
[862]1003%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
1004xtable=round(par_civ.Grid(:,1)+0.5)-0.5;
1005ytable=round(par_civ.ImageHeight-par_civ.Grid(:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
1006utable=shiftx;%zeros(nbvec,1);
1007vtable=shifty;%zeros(nbvec,1);
[598]1008ctable=zeros(nbvec,1);
1009F=zeros(nbvec,1);
1010result_conv=[];
1011errormsg='';
[859]1012
[598]1013%% prepare mask
1014if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
1015    if strcmp(par_civ.Mask,'all')
1016        return    % get the grid only, no civ calculation
1017    elseif ischar(par_civ.Mask)
[856]1018        par_civ.Mask=imread(par_civ.Mask);% read the mask if not allready done
[598]1019    end
1020end
1021check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
1022check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
1023
1024par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
1025par_civ.ImageB=sum(double(par_civ.ImageB),3);
1026[npy_ima npx_ima]=size(par_civ.ImageA);
1027if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
1028    errormsg='image pair with unequal size';
[597]1029    return
1030end
1031
[598]1032%% Apply mask
[859]1033% Convention for mask IDEAS TO IMPLEMENT ?
1034% mask >200 : velocity calculated
1035%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
1036% 150>=mask >100: velocity not calculated, nor interpolated
1037%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
1038%  20>=mask: velocity=0
[598]1039checkmask=0;
1040MinA=min(min(par_civ.ImageA));
[873]1041%MinB=min(min(par_civ.ImageB));
[879]1042%check_undefined=false(size(par_civ.ImageA));
[598]1043if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
[859]1044    checkmask=1;
1045    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
[598]1046        errormsg='mask must be an image with the same size as the images';
1047        return
[859]1048    end
[598]1049    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
[997]1050    %     par_civ.ImageA(check_undefined)=0;% put image A to zero (i.e. the min image value) in the undefined  area
1051    %     par_civ.ImageB(check_undefined)=0;% put image B to zero (i.e. the min image value) in the undefined  area
[598]1052end
1053
1054%% compute image correlations: MAINLOOP on velocity vectors
1055corrmax=0;
1056sum_square=1;% default
1057mesh=1;% default
[856]1058CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
1059if CheckDeformation
1060    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
[885]1061    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
[598]1062end
[862]1063
1064if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
[856]1065    for ivec=1:nbvec
1066        iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
[862]1067        jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);%  j index  for the middle of the correlation box in the image A
[856]1068        F(ivec)=0;
1069        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
1070        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
1071        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
1072        subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
1073        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
1074        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
1075        check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
1076        check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
1077        check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
[859]1078        check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
[856]1079        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
1080        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
[879]1081        if checkmask
1082            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
1083            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
1084            mask1_crop(check1_y,check1_x)=check_undefined(subrange1_y(check1_y),subrange1_x(check1_x));%extract a mask subimage (correlation box) from image A
1085            mask2_crop(check2_y,check2_x)=check_undefined(subrange2_y(check2_y),subrange2_x(check2_x));%extract a mask subimage (search box) from image B
1086            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
1087            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
1088                F(ivec)=3; %
[910]1089                utable(ivec)=0;
1090                vtable(ivec)=0;
[879]1091            else
1092                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
1093                image2_crop=image2_crop.*~mask2_crop;
1094                image1_mean=mean(mean(image1_crop))/(1-sizemask);
1095                image2_mean=mean(mean(image2_crop))/(1-sizemask);
1096            end
[873]1097        else
[879]1098            image1_mean=mean(mean(image1_crop));
1099            image2_mean=mean(mean(image2_crop));
[856]1100        end
[879]1101        %threshold on image minimum
[856]1102        if F(ivec)~=3
[880]1103            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
1104                F(ivec)=3;
1105                %threshold on image maximum
1106            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
1107                F(ivec)=3;
[879]1108            end
[910]1109            if F(ivec)==3
1110                utable(ivec)=0;
1111                vtable(ivec)=0;
1112            else
[880]1113                %mask
1114                if checkmask
1115                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
1116                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
1117                else
1118                    image1_crop=(image1_crop-image1_mean);
1119                    image2_crop=(image2_crop-image2_mean);
1120                end
1121                %deformation
1122                if CheckDeformation
1123                    xi=(1:mesh:size(image1_crop,2));
1124                    yi=(1:mesh:size(image1_crop,1))';
1125                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
[883]1126                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
1127                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
[880]1128                    image1_crop=interp2(image1_crop,XIant,YIant);
1129                    image1_crop(isnan(image1_crop))=0;
1130                    xi=(1:mesh:size(image2_crop,2));
1131                    yi=(1:mesh:size(image2_crop,1))';
1132                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
1133                    image2_crop(isnan(image2_crop))=0;
1134                end
1135                sum_square=sum(sum(image1_crop.*image1_crop));
1136                %reference: Oliver Pust, PIV: Direct Cross-Correlation
1137                result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
1138                corrmax= max(max(result_conv));
1139                result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
1140                %Find the correlation max, at 255
1141                [y,x] = find(result_conv==255,1);
1142                subimage2_crop=image2_crop(y:y+2*iby2/mesh,x:x+2*ibx2/mesh);%subimage of image 2 corresponding to the optimum displacement of first image
1143                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
1144                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
1145                if ~isempty(y) && ~isempty(x)
1146                    try
1147                        if par_civ.CorrSmooth==1
1148                            [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
1149                        elseif par_civ.CorrSmooth==2
1150                            [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
1151                        else
1152                            [vector,F(ivec)] = quadr_fit(result_conv,x,y);
1153                        end
1154                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
1155                        vtable(ivec)=vector(2)*mesh+shifty(ivec);
1156                        xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
1157                        ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
[911]1158                        iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
1159                        jref=round(ytable(ivec)+0.5);
[880]1160                        % eliminate vectors located in the mask
[911]1161                        if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
[880]1162                            utable(ivec)=0;
1163                            vtable(ivec)=0;
1164                            F(ivec)=3;
1165                        end
1166                        ctable(ivec)=corrmax/sum_square;% correlation value
1167                    catch ME
[856]1168                        F(ivec)=3;
[910]1169                        disp(ME.message)
[856]1170                    end
[880]1171                else
[598]1172                    F(ivec)=3;
1173                end
[597]1174            end
1175        end
[598]1176    end
1177end
1178result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
1179
1180%------------------------------------------------------------------------
1181% --- Find the maximum of the correlation function after interpolation
[862]1182% OUPUT:
1183% vector = optimum displacement vector with subpixel correction
1184% F =flag: =0 OK
1185%           =-2 , warning: max too close to the edge of the search box (1 pixel margin)
1186% INPUT:
1187% x,y: position of the maximum correlation at integer values
1188
[598]1189function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
1190%------------------------------------------------------------------------
[862]1191% vector=[0 0]; %default
[598]1192F=0;
1193[npy,npx]=size(result_conv);
[911]1194result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
[993]1195%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ??? Israel Institute of Technology
[731]1196%http://urapiv.wordpress.com
1197peaky = y;
[911]1198if y < npy && y > 1
[731]1199    f0 = log(result_conv(y,x));
1200    f1 = log(result_conv(y-1,x));
1201    f2 = log(result_conv(y+1,x));
1202    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
1203else
1204    F=-2; % warning flag for vector truncated by the limited search box
1205end
1206peakx=x;
[911]1207if x < npx-1 && x > 1
[731]1208    f0 = log(result_conv(y,x));
1209    f1 = log(result_conv(y,x-1));
1210    f2 = log(result_conv(y,x+1));
1211    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1212else
1213    F=-2; % warning flag for vector truncated by the limited search box
1214end
1215vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
[598]1216
1217%------------------------------------------------------------------------
1218% --- Find the maximum of the correlation function after interpolation
1219function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1220%------------------------------------------------------------------------
[862]1221% vector=[0 0]; %default
[598]1222F=-2;
1223peaky=y;
1224peakx=x;
[731]1225result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
[598]1226[npy,npx]=size(result_conv);
[911]1227if (x < npx) && (y < npy) && (x > 1) && (y > 1)
[598]1228    F=0;
1229    for i=-1:1
1230        for j=-1:1
1231            %following 15 lines based on
[993]1232            %H. Nobach ??? M. Honkanen (2005)
[598]1233            %Two-dimensional Gaussian regression for sub-pixel displacement
1234            %estimation in particle image velocimetry or particle position
1235            %estimation in particle tracking velocimetry
[993]1236            %Experiments in Fluids (2005) 38: 511???515
[598]1237            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1238            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1239            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1240            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1241            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1242        end
1243    end
1244    c10=(1/6)*sum(sum(c10));
1245    c01=(1/6)*sum(sum(c01));
1246    c11=(1/4)*sum(sum(c11));
1247    c20=(1/6)*sum(sum(c20));
[859]1248    c02=(1/6)*sum(sum(c02));
[598]1249    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1250    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1251    if abs(deltax)<1
1252        peakx=x+deltax;
1253    end
1254    if abs(deltay)<1
1255        peaky=y+deltay;
1256    end
1257end
1258vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1259
[876]1260%------------------------------------------------------------------------
1261% --- Find the maximum of the correlation function after quadratic interpolation
1262function [vector,F] = quadr_fit(result_conv,x,y)
1263[npy,npx]=size(result_conv);
1264if x<4 || y<4 || npx-x<4 ||npy-y <4
1265    F=-2;
1266    vector=[x y];
1267else
1268    F=0;
1269    x_ind=x-4:x+4;
1270    y_ind=y-4:y+4;
1271    x_vec=0.25*(x_ind-x);
1272    y_vec=0.25*(y_ind-y);
1273    [X,Y]=meshgrid(x_vec,y_vec);
1274    coord=[reshape(X,[],1) reshape(Y,[],1)];
1275    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1276   
1277   
1278    % n=numel(X);
1279    % x=[X Y];
1280    % X=X-0.5;
1281    % Y=Y+0.5;
1282    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1283    p = polyfitn(coord,result_conv,2);
1284    A(1,1)=2*p.Coefficients(1);
1285    A(1,2)=p.Coefficients(2);
1286    A(2,1)=p.Coefficients(2);
1287    A(2,2)=2*p.Coefficients(4);
1288    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1289    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1290    % zg = polyvaln(p,coord);
1291    % figure
1292    % surf(x_vec,y_vec,reshape(zg,9,9))
1293    % hold on
1294    % plot3(X,Y,reshape(result_conv,9,9),'o')
1295    % hold off
1296end
1297
[598]1298%'RUN_FIX': function for fixing velocity fields:
1299%-----------------------------------------------
1300% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
1301%
1302%filename: name of the netcdf file (used as input and output)
1303%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
[859]1304%.vel_type='civ1' or 'civ2';
1305%.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
1306%.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
1307%flagindex: flag specifying which values of vec_f are removed:
1308% if flagindex(1)=1: vec_f=-2 vectors are removed
1309% if flagindex(2)=1: vec_f=3 vectors are removed
1310% if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
[598]1311%iter=1 for civ1 fields and iter=2 for civ2 fields
1312%thresh_vecC: threshold in the image correlation vec_C
1313%flag_mask: =1 mask used to remove vectors (0 else)
1314%maskname: name of the mask image file for fix
1315%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
1316%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
1317%fileref: .nc file name for a reference velocity (='': refrence 0 used)
1318%fieldref: 'civ1','filter1'...feld used in fileref
1319
1320function FF=fix(Param,F,C,U,V,X,Y)
1321FF=zeros(size(F));%default
1322
1323%criterium on warn flags
1324FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
1325FlagVal=[-2 2 3 4];
1326for iflag=1:numel(FlagName)
1327    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
1328        FF=(FF==1| F==FlagVal(iflag));
1329    end
1330end
1331%criterium on correlation values
1332if isfield (Param,'MinCorr')
1333    FF=FF==1 | C<Param.MinCorr;
1334end
1335if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1336    Umod= U.*U+V.*V;
1337    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1338        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
1339    end
1340    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1341        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
1342    end
1343end
1344
1345
1346%------------------------------------------------------------------------
1347% --- determine the list of index pairs of processing file
1348function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
[635]1349    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
[598]1350%------------------------------------------------------------------------
[610]1351i1_series=i_series;% set of first image indexes
[598]1352i2_series=i_series;
[819]1353j1_series=j_series;%ones(size(i_series));% set of first image numbers
1354j2_series=j_series;%ones(size(i_series));
[610]1355r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
[598]1356if ~isempty(r)
1357    mode=['D' r.ind];
1358    ind1=str2num(r.num1);
1359    ind2=str2num(r.num2);
1360else
[668]1361    mode='j1-j2';
[598]1362    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1363    if ~isempty(r)
1364        NomTypeNc='_1ab';
1365    else
1366        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1367        if ~isempty(r)
1368            NomTypeNc='_1AB';
[597]1369        else
[598]1370            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1371            if ~isempty(r)
1372                NomTypeNc='_1_1-2';
[859]1373            end
[597]1374        end
1375    end
[598]1376    if isempty(r)
1377        display('wrong pair mode input option')
1378    else
[859]1379        ind1=stra2num(r.num1);
1380        ind2=stra2num(r.num2);
[598]1381    end
[597]1382end
[819]1383switch mode
1384    case 'Di'
1385        i1_series=i_series-ind1;% set of first image numbers
1386        i2_series=i_series+ind2;
1387        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1388        if isempty(j_series)
1389            NomTypeNc='_1-2';
1390        else
1391            j1_series=j_series;
1392            j2_series=j_series;
1393            NomTypeNc='_1-2_1';
1394        end
1395    case 'Dj'
1396        j1_series=j_series-ind1;
1397        j2_series=j_series+ind2;
1398        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1399        NomTypeNc='_1_1-2';
1400    otherwise %bursts
1401        i1_series=i_series(1,:);% do not sweep the j index
1402        i2_series=i_series(1,:);
1403        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1404        j2_series=ind2*ones(1,size(i_series,2));
1405        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
[598]1406end
[597]1407
[598]1408
1409
1410
Note: See TracBrowser for help on using the repository browser.