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

Last change on this file since 1198 was 1198, checked in by sommeria, 3 days ago

parfor introduced in civ.m

File size: 55.0 KB
RevLine 
[598]1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
[1143]4%   detect_false: put a flag to false vectors after detection by various criteria
[1169]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.
[1169]17%     Param.Action.RUN = 0 (to set the status of the GUI series) or =1 to RUN the computation
[855]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
[1131]23%                      .Civ1: parameters for civ1cc
[1143]24%                      .Fix1: parameters for detect_false1
[859]25%                      .Patch1:
[855]26%                      .Civ2: for civ2
[859]27%                      .Fix2:
[855]28%                      .Patch2:
29
[924]30%=======================================================================
[1126]31% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
[924]32%   http://www.legi.grenoble-inp.fr
[1127]33%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.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
[1175]53    if 0==1 %never satisfied but trigger compilation with the appropriate transform functions ('eval' inactive for compilation)
54        ima_rescale
55    end
[763]56    path_series=fileparts(which('series'));
57    addpath(fullfile(path_series,'series'))
[598]58    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
[1148]59    % TODO: change from guide to App: modify the input procedure, adapt read_GUI function
60    %App=civ_input_App
[1089]61    %Data=civ_input_App(Param);% introduce the civ parameters using the GUI civ_input
[1148]62    % if isempty(App)
63    %     Data=Param;% if  civ_input has been cancelled, keep previous parameters
64    % end
[606]65    Data.Program=mfilename;%gives the name of the current function
66    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
67    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
68    Data.NbSlice='off'; %nbre of slices ('off' by default)
69    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
[781]70    Data.FieldName='on';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
[1181]71    Data.FieldTransform = 'off';%can use a transform function
[606]72    Data.ProjObject='off';%can use projection object(option 'off'/'on',
73    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
74    Data.OutputDirExt='.civ';%set the output dir extension
[711]75    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]76    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
[904]77    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
[1170]78    if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices') && isequal(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
[1156]79        Data.IndexRange_j='off';%no j index display in series
80    else
81        Data.IndexRange_j='on';% j index display in series if relevant
[993]82    end
[598]83    return
[597]84end
85
86%% read input parameters from an xml file if input is a file name (batch mode)
87checkrun=1;
88if ischar(Param)
89    Param=xml2struct(Param);% read Param as input file (batch case)
90    checkrun=0;
91end
[855]92
93%% test input
[668]94if ~isfield(Param,'ActionInput')
[859]95    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
96    return
[668]97end
[597]98
[1195]99inv_scale_factor=100; % scale factor of displacements for uin16 records in netcdf files (dx expressed in pixels)
100%inv_scale_factor=[];% no scale factor, displacements written as single precision real
101
102%% input files and indexing
[1169]103hseries=findobj(allchild(0),'Tag','series');
104RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
105WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
106MaxIndex_i=Param.IndexRange.MaxIndex_i;
107MinIndex_i=Param.IndexRange.MinIndex_i;
108MaxIndex_j=ones(size(MaxIndex_i));MinIndex_j=ones(size(MinIndex_i));
109if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
110    MaxIndex_j=Param.IndexRange.MaxIndex_j;
111    MinIndex_j=Param.IndexRange.MinIndex_j;
112end
113if isfield(Param,'InputTable')
114    [filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
115    iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
116    if Param.ActionInput.CheckCiv1
117        iview_A=1;% usual PIV, the image series is on the first line of the table
118    else % Civ1 has been already stored in a netcdf file input
119        iview_A=2;% the second line is used for the input images
[609]120    end
[1169]121    RootPath_A=Param.InputTable{iview_A,1};
122    RootFile_A=Param.InputTable{iview_A,3};
123    SubDir_A=Param.InputTable{iview_A,2};
124    NomType_A=Param.InputTable{iview_A,4};
125    FileExt_A=Param.InputTable{iview_A,5};
126    if iview_B==0
127        iview_B=iview_A;% the second image series is the same as the first
128    end
129    RootPath_B=Param.InputTable{iview_B,1};
130    RootFile_B=Param.InputTable{iview_B,3};
131    SubDir_B=Param.InputTable{iview_B,2};
132    NomType_B=Param.InputTable{iview_B,4};
133    FileExt_B=Param.InputTable{iview_B,5};
134    PairCiv2='';
135   
136    switch Param.ActionInput.ListCompareMode
137        case 'PIV'
138            PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
139            if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
140                PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;%string which determines the civ2 pair
[758]141            end
[1169]142            if iview_A==1% if Civ1 is performed
143                [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
144                    find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
145                if ~isempty(PairCiv2)
146                    [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
147                        find_pair_indices(PairCiv2,i1_series{1},j1_series{1},MinIndex_i(1),MaxIndex_i(1),MinIndex_j(1),MaxIndex_j(1));
148                    check_bounds=check_bounds | check_bounds_Civ2;
[761]149                end
[1169]150            else% we start from an existing Civ1 file
151                i1_series_Civ1=i1_series{1};
152                i2_series_Civ1=i2_series{1};
153                j1_series_Civ1=j1_series{1};
154                j2_series_Civ1=j2_series{1};
155                NomTypeNc=Param.InputTable{1,4};
156                if ~isempty(PairCiv2)
157                    [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds,NomTypeNc]=...
158                        find_pair_indices(PairCiv2,i1_series{2},j1_series{2},MinIndex_i(2),MaxIndex_i(2),MinIndex_j(2),MaxIndex_j(2));
[761]159                end
[1169]160            end
161        case 'displacement'
162            if isfield(Param.ActionInput,'OriginIndex')
[855]163                i1_series_Civ1=Param.ActionInput.OriginIndex*ones(size(i1_series{1}));
[1169]164            else
165                i1_series_Civ1=ones(size(i1_series{1}));
[1020]166            end
[1169]167            i1_series_Civ2=i1_series_Civ1;
168            i2_series_Civ1=i1_series{1};
169            i2_series_Civ2=i1_series{1};
170            j1_series_Civ1=[];% no j index variation for the ref image
171            j1_series_Civ2=[];
172            if isempty(j1_series{1})
173                j2_series_Civ1=ones(size(i1_series_Civ1));
[855]174            else
[1169]175                j2_series_Civ1=j1_series{1};% if j index exist
[855]176            end
[1169]177            j2_series_Civ2=j2_series_Civ1;
178            NomTypeNc='_1';
179    end
180    %determine frame indices for input with movie or other multiframe input file
181    if isempty(j1_series_Civ1)% simple movie with index i
182        FrameIndex_A_Civ1=i1_series_Civ1;
183        FrameIndex_B_Civ1=i2_series_Civ1;
184        j1_series_Civ1=ones(size(i1_series_Civ1));
185        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
186            j2_series_Civ1=ones(size(i1_series_Civ1));
[758]187        end
[1195]188        Check_j_Civ1=false;
[1169]189    else % movie for each burst or volume (index j)
190        FrameIndex_A_Civ1=j1_series_Civ1;
191        FrameIndex_B_Civ1=j2_series_Civ1;
[1195]192        Check_j_Civ1=true;
[855]193    end
[1169]194    if isempty(PairCiv2)
195        FrameIndex_A_Civ2=FrameIndex_A_Civ1;
196        FrameIndex_B_Civ2=FrameIndex_B_Civ1;
197    else
198        if isempty(j1_series_Civ2)
199            FrameIndex_A_Civ2=i1_series_Civ2;
200            FrameIndex_B_Civ2=i2_series_Civ2;
201            j1_series_Civ2=ones(size(i1_series_Civ2));
202            if strcmp(Param.ActionInput.ListCompareMode,'PIV')
203                j2_series_Civ2=ones(size(i1_series_Civ2));
204            end
[1195]205            Check_j_Civ2=false;
[819]206        else
[1169]207            FrameIndex_A_Civ2=j1_series_Civ2;
208            FrameIndex_B_Civ2=j2_series_Civ2;
[1195]209            Check_j_Civ2=true;
[781]210        end
[758]211    end
[1169]212    if isempty(i1_series_Civ1)||(~isempty(PairCiv2) && isempty(i1_series_Civ2))
213        disp_uvmat('ERROR','no image pair for civ in the input file index range',checkrun)
214        return
215    end
[758]216end
217
[1169]218%% check the first image pair
219if Param.ActionInput.CheckCiv1% Civ1 is performed
220    NbField=numel(i1_series_Civ1);
221elseif Param.ActionInput.CheckCiv2 % Civ2 is performed without Civ1
222    NbField=numel(i1_series_Civ2);
223else
224    NbField=numel(i1_series_Civ1);% no image used (only detect_false or patch) TO CHECK
225end
226
[855]227%% prepare output Data
[1169]228OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[886]229ListGlobalAttribute={'Conventions','Program','CivStage'};
[1195]230Data.Conventions='uvmat/civdata/compress';% states the conventions used for the description of field variables and attributes
[605]231Data.Program='civ_series';
[1154]232if isfield(Param,'UvmatRevision')
233    Data.Program=[Data.Program ', uvmat r' Param.UvmatRevision];
234end
[605]235Data.CivStage=0;%default
236
[606]237%% get timing from the ImaDoc file or input video
[1169]238% if iview_A~=0
239XmlFileName=find_imadoc(RootPath_A,SubDir_A);
240Time=[];
241if ~isempty(XmlFileName)
242    XmlData=imadoc2struct(XmlFileName);%read the time from XmlFileName
243    if isfield(XmlData,'Time')
244        Time=XmlData.Time;
245    end
246    if isfield(XmlData,'Camera')
247        if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
248            NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
249            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
250                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
[609]251            end
252        end
[1169]253        if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
254            TimeUnit=XmlData.Camera.TimeUnit;
255        end
[833]256    end
[610]257end
[1180]258
259%% File relabeling documented by the xml file (e.g. PCO)
[1188]260CheckRelabel=isfield(Param.IndexRange,'Relabel' )&& Param.IndexRange.Relabel;%=true for index relabeling (PCO)
[609]261
[598]262%%%%% MAIN LOOP %%%%%%
[1010]263maskoldname='';% initiate the mask name
[1176]264backgroundoldname='';
[997]265FileType_A='';
266FileType_B='';
[904]267CheckOverwrite=1;%default
268if isfield(Param,'CheckOverwrite')
269    CheckOverwrite=Param.CheckOverwrite;
270end
[598]271for ifield=1:NbField
[1131]272    tstart=tic;
273    time_civ1=0;
[1164]274    time_patch1=0;
275    time_civ2=0;
276    time_patch2=0;
[855]277    if ~isempty(RUNHandle)% update the waitbar in interactive mode with GUI series  (checkrun=1)
[905]278        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
[855]279            disp('program stopped by user')
280            break
281        end
[624]282    end
[1169]283    OutputPath=fullfile(Param.OutputPath,Param.Experiment,Param.Device);
[1178]284    if CheckRelabel
[1195]285        RootFileOut=index2filename(XmlData.FileSeries,1,1,MaxIndex_j);
[1178]286    else
287        RootFileOut=RootFile_A;
288    end
[1169]289    if strcmp(Param.ActionInput.ListCompareMode,'PIV')
[1178]290        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
[1169]291            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
292    else
[1178]293        ncfile=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
[1169]294            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
295    end
296    ncfile_out=ncfile;% by default
297   
298    if isfield (Param.ActionInput,'Civ2')
299        i1_civ2=i1_series_Civ2(ifield);
300        i2_civ2=i1_civ2;
301        if ~isempty(i2_series_Civ2)
302            i2_civ2=i2_series_Civ2(ifield);
[822]303        end
[1169]304        j1_civ2=1;
305        if ~isempty(j1_series_Civ2)
306            j1_civ2=j1_series_Civ2(ifield);
[904]307        end
[1169]308        j2_civ2=i1_civ2;
309        if ~isempty(j2_series_Civ2)
310            j2_civ2=j2_series_Civ2(ifield);
[912]311        end
[1169]312        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
[1178]313            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i1_civ2,i2_civ2,j1_civ2,j2_civ2);
[1169]314        else % displacement
[1178]315            ncfile_out=fullfile_uvmat(OutputPath,OutputDir,RootFileOut,'.nc',NomTypeNc,i2_civ2,[],j2_civ2);
[1169]316        end
[761]317    end
[1169]318    if ~CheckOverwrite && exist(ncfile_out,'file')
319        disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
320        continue% skip iteration if the mode overwrite is desactivated and the result file already exists
321    end
322    %     end
[1122]323    ImageName_A='';ImageName_B='';%default
324    VideoObject_A=[];VideoObject_B=[];
[1195]325    Civ_FF=[];%default
[1143]326   
[598]327    %% Civ1
[707]328    % if Civ1 computation is requested
[1164]329    if Param.ActionInput.CheckCiv1
[1198]330        tstart_civ1=tic;
[1169]331        disp('civ1 started')
[1020]332        par_civ1=Param.ActionInput.Civ1;% parameters for civ1
[1169]333        %if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
334        try
335            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
336                ImageName_A=Param.ActionInput.RefFile;
[1187]337                FrameIndex_A=1;
[1178]338            elseif CheckRelabel
[1188]339                [RootFile,FrameIndex_A]=index2filename(XmlData.FileSeries,i1_series_Civ1(ifield),j1_series_Civ1(ifield),MaxIndex_j);
340                ImageName_A=fullfile(RootPath_A,SubDir_A,RootFile);
[1169]341            else
342                ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
[1178]343                FrameIndex_A=FrameIndex_A_Civ1(ifield);
[1169]344            end
345            if strcmp(FileExt_A,'.nc')% case of input images in format netcdf
346                FieldName_A=Param.InputFields.FieldName;
347                [DataIn,~,~,errormsg]=nc2struct(ImageName_A,{FieldName_A});
348                par_civ1.ImageA=DataIn.(FieldName_A);
349            else % usual image formats for image A
350                if isempty(FileType_A)% open the image object if not already done in case of movie input
351                    [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A);
352                    FileType_A=FileInfo_A.FileType;
[1187]353                    if isempty(Time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video','cine_phantom','telopsIR'}), 1))% case of video inputFrameIndex_A
[1180]354                        Time=zeros(FileInfo_A.NumberOfFrames+1,2);
[1169]355                        Time(:,2)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate)';
[1180]356                        if ~isempty(j1_series_Civ1) && j1_series_Civ1~=1
357                            Time=Time';
358                        end
[997]359                    end
[1169]360                    if ~isempty(FileType_A) && isempty(Time)% Time = index i +0.001 index j by default
361                        MaxIndex_i=max(i2_series_Civ1);
362                        MaxIndex_j=max(j2_series_Civ1);
363                        Time=(1:MaxIndex_i)'*ones(1,MaxIndex_j);
364                        Time=Time+0.001*ones(MaxIndex_i,1)*(1:MaxIndex_j);
365                        Time=[zeros(1,MaxIndex_j);Time];% insert a first line of zeros
366                        Time=[zeros(MaxIndex_i+1,1) Time];% insert a first column of zeros
[997]367                    end
[855]368                end
[1169]369                if isempty(regexp(ImageName_A,'(^http://)|(^https://)', 'once')) && ~exist(ImageName_A,'file')
370                    disp([ImageName_A ' missing'])
[1164]371                    continue
372                end
[1169]373                tsart_input=tic;
[1178]374                [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A);
[1169]375                time_input=toc(tsart_input);
[781]376            end
[1180]377            if CheckRelabel
[1188]378                [RootFile,FrameIndex_B]=index2filename(XmlData.FileSeries,i2_series_Civ1(ifield),j2_series_Civ1(ifield),MaxIndex_j);
[1180]379                ImageName_B=fullfile(RootPath_B,SubDir_B,RootFile);
380            else
381                ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
382                FrameIndex_B=FrameIndex_B_Civ1(ifield);
383            end
[1169]384            if isempty(FileType_B)% determine the image type for the first field
385                [FileInfo_B,VideoObject_B]=get_file_info(ImageName_B);
386                FileType_B=FileInfo_B.FileType;
[781]387            end
[1169]388            if isempty(regexp(ImageName_B,'(^http://)|(^https://)', 'once')) && ~exist(ImageName_B,'file')
389                disp([ImageName_B ' missing'])
390                continue
[758]391            end
[1178]392            [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B);
[1195]393           
[1169]394        catch ME % display errors in reading input images
395            if ~isempty(ME.message)
396                disp_uvmat('ERROR', ['error reading input image: ' ME.message],checkrun)
397                continue
[855]398            end
[1169]399        end
[1195]400       
401        % case of background image to subtract
[1176]402        if par_civ1.CheckBackground &&~isempty(par_civ1.Background)
403            [RootPath_background,SubDir_background,RootFile_background,~,~,~,~,Ext_background]=fileparts_uvmat(Param.ActionInput.Civ1.Background);
404            if ~isempty(i2_series_Civ1)% case of volume,backgrounds act on different j levels
[1195]405                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',j1_series_Civ1(ifield));
[1176]406            elseif isfield(par_civ1,'NbSlice')
407                i1_background=mod(i1-1,par_civ1.NbSlice)+1;
408                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',i1_background);
409                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, background index refers to j index
410                    par_civ1.NbSlice_j=par_civ1.NbSlice;
411                end
412            else
413                backgroundname=Param.ActionInput.Civ1.Background;
414            end
415            if strcmp(backgroundoldname,backgroundname)% background exist, not already read in civ1
416                par_civ1.Background=background; %use background already opened
417            else
418                if ~isempty(regexp(backgroundname,'(^http://)|(^https://)', 'once'))|| exist(backgroundname,'file')
419                    try
420                        par_civ1.Background=imread(backgroundname);%update the background, an store it for future use
421                    catch ME
422                        if ~isempty(ME.message)
423                            errormsg=['error reading input image: ' ME.message];
424                            disp_uvmat('ERROR',errormsg,checkrun)
425                            return
426                        end
427                    end
428                else
429                    par_civ1.Background=[];
430                end
431                background=par_civ1.Background;
432                backgroundoldname=backgroundname;
433            end
434            par_civ1.ImageA=par_civ1.ImageA-par_civ1.Background;
435            par_civ1.ImageB=par_civ1.ImageB-par_civ1.Background;
436        end
[1195]437       
438        % case of image luminosity rescaling
439        if par_civ1.CheckRescale &&~isempty(par_civ1.Maxtanh)
440            par_civ1.ImageA =par_civ1.Maxtanh*tanh(double(par_civ1.ImageA)/par_civ1.Maxtanh);
441            par_civ1.ImageB=par_civ1.Maxtanh*tanh(double(par_civ1.ImageB)/par_civ1.Maxtanh);
[1175]442        end
[1169]443       
444        % par_civ1.ImageWidth=size(par_civ1.ImageA,2);
445        % par_civ1.ImageHeight=size(par_civ1.ImageA,1);
446        list_param=(fieldnames(Param.ActionInput.Civ1))';
447        list_param(strcmp('TestCiv1',list_param))=[];% remove the parameter TestCiv1 from the list
448        Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
449        Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
450        %indicate the values of all the global attributes in the output data
451        Data.Civ1_ImageA=ImageName_A;
452        Data.Civ1_ImageB=ImageName_B;
453        i1=i1_series_Civ1(ifield);
454        i2=i1;
455        if ~isempty(i2_series_Civ1)
456            i2=i2_series_Civ1(ifield);
457        end
[1195]458       
459        j1=j1_series_Civ1(ifield);
460       
[1169]461        j2=j1;
[1195]462        if Check_j_Civ1
[1169]463            j2=j2_series_Civ1(ifield);
464        end
465        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
466            Data.Civ1_Time=Time(i2+1,j2+1);% the Time is the Time of the second image
467            Data.Civ1_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
[1097]468        else
[1169]469            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
470            Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
[597]471        end
[1169]472        for ilist=1:length(list_param)
473            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
474        end
475        Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
476        Data.CivStage=1;
477       
[598]478        % set the list of variables
[1195]479        %         Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_FF'};%  cell array containing the names of the fields to record
480        %         Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
481        %         Data.VarAttribute{1}.Role='coord_x';
482        %         Data.VarAttribute{2}.Role='coord_y';
483        %         Data.VarAttribute{3}.Role='vector_x';
484        %         Data.VarAttribute{4}.Role='vector_y';
485        %         Data.VarAttribute{5}.Role='ancillary';
486        %         Data.VarAttribute{6}.Role='errorflag';
[1164]487       
[1010]488        % case of mask
[856]489        if par_civ1.CheckMask&&~isempty(par_civ1.Mask)
[1163]490            [RootPath_mask,SubDir_mask,RootFile_mask,~,~,~,~,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ1.Mask);
[1195]491            if Check_j_Civ1
[1163]492                j1=j1_series_Civ1(ifield);
[1195]493            else
494                j1=[];
[1163]495            end
[1183]496            if ~isempty(i2_series_Civ1)&& ~isequal(i1_series_Civ1,i2_series_Civ1)% case of volume,masks act on different j levels
[1163]497                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',j1);
498            elseif isfield(par_civ1,'NbSlice')
[1010]499                i1_mask=mod(i1-1,par_civ1.NbSlice)+1;
500                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
[1164]501                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, mask index refers to j index
502                    par_civ1.NbSlice_j=par_civ1.NbSlice;
503                end
[1165]504            else
505                maskname=Param.ActionInput.Civ1.Mask;
[1010]506            end
[1165]507            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
508                par_civ1.Mask=mask; %use mask already opened
509            else
510                if ~isempty(regexp(maskname,'(^http://)|(^https://)', 'once'))|| exist(maskname,'file')
511                    try
512                        par_civ1.Mask=imread(maskname);%update the mask, an store it for future use
513                    catch ME
514                        if ~isempty(ME.message)
515                            errormsg=['error reading input image: ' ME.message];
516                            disp_uvmat('ERROR',errormsg,checkrun)
517                            return
518                        end
[861]519                    end
[1165]520                else
521                    par_civ1.Mask=[];
[1187]522                    disp_uvmat('ERROR',[maskname ' does not exist'],checkrun);
523                    return
[861]524                end
[1165]525                mask=par_civ1.Mask;
526                maskoldname=maskname;
[856]527            end
528        end
[1195]529       
[1163]530        % case of input grid
531        if par_civ1.CheckGrid &&~isempty(par_civ1.Grid)
532            GridData=nc2struct(Param.ActionInput.Civ1.Grid);
533            par_civ1.Grid=GridData.Grid;
534            par_civ1.CorrBoxSize=GridData.CorrBox;
[597]535        end
[1164]536       
537        % caluclate velocity data
[1195]538        %   [Data.Civ1_X,Data.Civ1_Y,Data.Civ1_U,Data.Civ1_V,Data.Civ1_C,Data.Civ1_FF, result_conv, errormsg] = civ (par_civ1);
539        [Civ_X,Civ_Y,Civ_U,Civ_V,Civ_C,Civ_FF, result_conv, errormsg] = civ (par_civ1);
540        Civ_X_shifted=Civ_X-0.5+Civ_U/2;% get the exact positions
541        Civ_Y_shifted=Civ_Y-0.5+Civ_V/2;
[1163]542        if ~isempty(errormsg)
543            disp_uvmat('ERROR',errormsg,checkrun)
544            return
545        end
[1198]546        time_civ1=toc(tstart_civ1);
[597]547    end
548   
[1169]549   
[598]550    %% Fix1
551    if isfield (Param.ActionInput,'Fix1')
[1143]552        disp('detect_false1 started')
[822]553        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
554            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
555            Data.ListGlobalAttribute(Fix1_attr)=[];
556            for ilist=1:numel(Fix1_attr)
557                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
558            end
[859]559        end
[852]560        list_param=fieldnames(Param.ActionInput.Fix1)';
561        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]562        %indicate the values of all the global attributes in the output data
[852]563        for ilist=1:length(list_param)
564            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
[598]565        end
[852]566        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
[1195]567        % Data.Civ1_FF=uint8(detect_false(Param.ActionInput.Fix1,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V,Data.Civ1_FF));
568        Civ_FF=uint8(detect_false(Param.ActionInput.Fix1,Civ_C,Civ_U,Civ_V,Civ_FF));
[859]569        Data.CivStage=2;
[597]570    end
[598]571    %% Patch1
[1169]572    if Param.ActionInput.CheckPatch1 && isfield (Param.ActionInput,'Patch1')
[896]573        disp('patch1 started')
[1169]574        tstart_patch1=tic;
575       
[855]576        % record the processing parameters of Patch1 as global attributes in the result nc file
[852]577        list_param=fieldnames(Param.ActionInput.Patch1)';
[855]578        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
579        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
[852]580        for ilist=1:length(list_param)
581            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
582        end
[855]583        Data.CivStage=3;% record the new state of processing
[852]584        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
[598]585       
[855]586        % list the variables to record
[1195]587        %         nbvar=length(Data.ListVarName);
588        %         Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
589        %         Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
590        %             {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
591        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
592        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
593        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
594        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
595        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
596        %Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
597        %Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
598        %         if isfield(Data,'Civ1_FF')
599        if isempty(Civ_FF)
600            ind_good=1:numel(Civ_X);
[597]601        else
[1195]602            ind_good=find(Civ_FF==0);
[597]603        end
[1115]604        if isempty(ind_good)
[1169]605            disp_uvmat('ERROR','all vectors of civ1 are bad, check input parameters' ,checkrun)
606            return
[1115]607        end
[1169]608       
[859]609        % perform Patch calculation using the UVMAT fct 'filter_tps'
[1195]610        [SubRange,NbCentres,Coord_tps,U_tps,V_tps,~,Ures, Vres,~,FFres]=...
611            filter_tps([Civ_X_shifted(ind_good),Civ_Y_shifted(ind_good)],Civ_U(ind_good),Civ_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
612        Civ_U_smooth=Civ_U;% false vectors kept unchanged
613        Civ_V_smooth=Civ_V;
614        Civ_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
615        Civ_V_smooth(ind_good)=Vres;
616        Civ_FF(ind_good)=uint8(4*FFres);%set FF to value =4 for vectors eliminated by filter_tps
[1131]617        time_patch1=toc(tstart_patch1);
[896]618        disp('patch1 performed')
[597]619    end
620   
[598]621    %% Civ2
622    if isfield (Param.ActionInput,'Civ2')
[896]623        disp('civ2 started')
[1131]624        tstart_civ2=tic;
[598]625        par_civ2=Param.ActionInput.Civ2;
[1169]626        %         if CheckInputFile % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
627        par_civ2.ImageA=[];
628        par_civ2.ImageB=[];
629        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
630            ImageName_A_Civ2=Param.ActionInput.RefFile;
[1178]631        elseif CheckRelabel
[1188]632            [RootFile,FrameIndex_A_2]=index2filename(XmlData.FileSeries,i1_series_Civ2(ifield),j1_series_Civ2(ifield),MaxIndex_j);
[1180]633            ImageName_A_Civ2=fullfile(RootPath_A,SubDir_A,RootFile);
634        else
[1169]635            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
[1178]636            FrameIndex_A_2=FrameIndex_A_Civ2(ifield);
[597]637        end
[1178]638        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A,FrameIndex_A_2)
[1169]639            par_civ2.ImageA=par_civ1.ImageA;
640        else
[1178]641            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_2);
[1169]642        end
[1178]643        if CheckRelabel
[1188]644            [RootFile,FrameIndex_B_2]=index2filename(XmlData.FileSeries,i2_civ2,j2_civ2,MaxIndex_j);
[1180]645            ImageName_B_Civ2=fullfile(RootPath_B,SubDir_B,RootFile);
646        else
647            ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
648            FrameIndex_B_2=FrameIndex_B_Civ2(ifield);
[1178]649        end
650        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_2,FrameIndex_B)
[1169]651            par_civ2.ImageB=par_civ1.ImageB;
652        else
[1178]653            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_2);
[1169]654        end
655        %  [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A_Civ2);
656        npy_ima=size(par_civ2.ImageA,1);
657        npx_ima=size(par_civ2.ImageA,2);
658        if par_civ2.CheckGrid &&~isempty(par_civ2.Grid) % case of input grid
659            GridData=nc2struct(Param.ActionInput.Civ2.Grid);
660            par_civ2.Grid=GridData.Grid;
661            par_civ2.CorrBoxSize=GridData.CorrBox;
662        else% automatic grid
663            nbinterv_x=floor((npx_ima-1)/par_civ2.Dx);
664            gridlength_x=nbinterv_x*par_civ2.Dx;
665            minix=ceil((npx_ima-gridlength_x)/2);
666            nbinterv_y=floor((npy_ima-1)/par_civ2.Dy);
667            gridlength_y=nbinterv_y*par_civ2.Dy;
668            miniy=ceil((npy_ima-gridlength_y)/2);
669            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:npx_ima-1,miniy:par_civ2.Dy:npy_ima-1);
670            par_civ2.Grid=zeros(numel(GridX),2);
671            par_civ2.Grid(:,1)=reshape(GridX,[],1);
672            par_civ2.Grid(:,2)=reshape(GridY,[],1);% increases with array index
673        end
674       
[1195]675        %                 %% user defined image transform
676        %         if ~isempty(transform_fct)
677        %                par_civ2 =transform_fct(par_civ2,Param);
678        %         end
679        %% case of image luminosity rescaling
680        if par_civ2.CheckRescale &&~isempty(par_civ2.Maxtanh)
681            par_civ2.ImageA =par_civ2.Maxtanh*tanh(double(par_civ2.ImageA)/par_civ2.Maxtanh);
682            par_civ2.ImageB=par_civ2.Maxtanh*tanh(double(par_civ2.ImageB)/par_civ2.Maxtanh);
[1175]683        end
684       
[856]685        % get the guess from patch1 or patch2 (case 'CheckCiv3')
[1169]686        if iview_A==2 && isfield (par_civ2,'CheckCiv3') && strcmp(par_civ2.CheckCiv3,'iterate(civ3)') %get the guess from  patch2% Civ1 data read in a netcdf file
687            [DataIn,~,~,errormsg]=nc2struct(filecell{1,ifield});
688            if ~isempty(errormsg)
689                disp(errormsg)
690                return
691            end
692            SubRange= DataIn.Civ2_SubRange;
693            NbCentres=DataIn.Civ2_NbCentres;
694            Coord_tps=DataIn.Civ2_Coord_tps;
695            U_tps=DataIn.Civ2_U_tps;
696            V_tps=DataIn.Civ2_V_tps;
697            Civ1_Dt=DataIn.Civ2_Dt;
[1163]698            Data=[];%reinitialise the result structure Data
699            Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
700            Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
701            Data.Program='civ_series';
[859]702            Data.ListVarName={};
703            Data.VarDimName={};
[1163]704        else % get the guess from patch1
[1195]705            %             SubRange= Data.Civ_SubRange;
706            %             NbCentres=Data.Civ_NbCentres;
707            %             Coord_tps=Data.Civ_Coord_tps;
708            %             U_tps=Data.Civ_U_tps;
709            %             V_tps=Data.Civ_V_tps;
[1163]710            Civ1_Dt=Data.Civ1_Dt;
[851]711        end
[1195]712        Data.CivStage=4;
[1169]713        Shiftx=zeros(size(par_civ2.Grid,1),1);% initialise the shift expected from civ1 data
[856]714        Shifty=zeros(size(par_civ2.Grid,1),1);
715        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
[862]716        if par_civ2.CheckDeformation
717            DUDX=zeros(size(par_civ2.Grid,1),1);
718            DUDY=zeros(size(par_civ2.Grid,1),1);
719            DVDX=zeros(size(par_civ2.Grid,1),1);
720            DVDY=zeros(size(par_civ2.Grid,1),1);
721        end
[856]722        NbSubDomain=size(SubRange,3);
[761]723        for isub=1:NbSubDomain% for each sub-domain of Patch1
[851]724            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
725            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
[862]726                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
[859]727            if ~isempty(ind_sel)
[862]728                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
[859]729                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
[862]730                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
[1163]731                CentreX=(SubRange(1,1,isub)+SubRange(1,2,isub))/2; %x posiion of the subdomain center
732                CentreY=(SubRange(2,1,isub)+SubRange(2,2,isub))/2; %y posiion of the subdomain center
733                xwidth=(SubRange(1,2,isub)-SubRange(1,1,isub))/pi;
734                ywidth=(SubRange(2,2,isub)-SubRange(2,1,isub))/pi;
735                x_dist=(epoints(:,1)-CentreX)/xwidth;
736                y_dist=(epoints(:,2)-CentreY)/ywidth;
737                weight=cos(x_dist).*cos(y_dist);%weighting fct =1 at the rectangle center and 0 at edge
738                nbval(ind_sel)=nbval(ind_sel)+weight;% records the number of values for each interpolation point (in case of subdomain overlap)
739                Shiftx(ind_sel)=Shiftx(ind_sel)+weight.*(EM*U_tps(1:nbvec_sub+3,isub));%velocity shift estimated by tps from civ1
740                Shifty(ind_sel)=Shifty(ind_sel)+weight.*(EM*V_tps(1:nbvec_sub+3,isub));
[859]741                if par_civ2.CheckDeformation
742                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
[1163]743                    DUDX(ind_sel)=DUDX(ind_sel)+weight.*(EMDX*U_tps(1:nbvec_sub+3,isub));
744                    DUDY(ind_sel)=DUDY(ind_sel)+weight.*(EMDY*U_tps(1:nbvec_sub+3,isub));
745                    DVDX(ind_sel)=DVDX(ind_sel)+weight.*(EMDX*V_tps(1:nbvec_sub+3,isub));
746                    DVDY(ind_sel)=DVDY(ind_sel)+weight.*(EMDY*V_tps(1:nbvec_sub+3,isub));
[859]747                end
[597]748            end
749        end
[1163]750        Shiftx(nbval>0)=Shiftx(nbval>0)./nbval(nbval>0);
751        Shifty(nbval>0)=Shifty(nbval>0)./nbval(nbval>0);
[1169]752       
[1163]753        % introduce mask
754        if par_civ2.CheckMask && ~isempty(par_civ2.Mask)
755            [RootPath_mask,SubDir_mask,RootFile_mask,~,~,~,~,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
[1183]756            if ~isempty(i2_series_Civ2) && ~isequal(i1_series_Civ2,i2_series_Civ2) % we do PIV among indices i,  at given indices j (volume scan), mask depends on position j
[1195]757                if Check_j_Civ2
758                    j1=j1_series_Civ2(ifield);
759                else
760                    j1=[];
[1163]761                end
762                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',j1);
763            elseif isfield(par_civ2,'NbSlice')
764                i1=i1_series_Civ2(ifield);
[1010]765                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
766                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
[1164]767                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, mask index refers to j index
768                    par_civ2.NbSlice_j=par_civ2.NbSlice;
769                end
[1010]770            else
771                maskname=Param.ActionInput.Civ2.Mask;
772            end
773            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
[856]774                par_civ2.Mask=mask; %use mask already opened
775            else
[1187]776                if exist(maskname,'file')|| ~isempty(regexp(maskname,'(^http://)|(^https://)', 'once'))
[1163]777                    try
778                        par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
779                    catch ME
780                        if ~isempty(ME.message)
781                            errormsg=['error reading input image: ' ME.message];
782                            disp_uvmat('ERROR',errormsg,checkrun)
783                            return
784                        end
[1010]785                    end
[1062]786                else
787                    par_civ2.Mask=[];
[1187]788                    disp_uvmat('ERROR',[maskname ' does not exist'],checkrun);
789                    return
[1062]790                end
[856]791                mask=par_civ2.Mask;
[1010]792                maskoldname=maskname;
[856]793            end
[598]794        end
[1169]795       
[1177]796        % case of background image to subtract
797        if par_civ2.CheckBackground &&~isempty(par_civ2.Background)
798            [RootPath_background,SubDir_background,RootFile_background,~,~,~,~,Ext_background]=fileparts_uvmat(Param.ActionInput.Civ1.Background);
799            j1=1;
800            if ~isempty(j1_series_Civ1)
801                j1=j1_series_Civ1(ifield);
802            end
803            if ~isempty(i2_series_Civ1)% case of volume,backgrounds act on different j levels
804                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',j1);
805            elseif isfield(par_civ2,'NbSlice')
806                i1_background=mod(i1-1,par_civ2.NbSlice)+1;
807                backgroundname=fullfile_uvmat(RootPath_background,SubDir_background,RootFile_background,Ext_background,'_1',i1_background);
808                if strcmp(Param.ActionInput.PairIndices.ListPairMode,'series(Di)')% case of volume, background index refers to j index
809                    par_civ2.NbSlice_j=par_civ2.NbSlice;
810                end
811            else
812                backgroundname=Param.ActionInput.Civ1.Background;
813            end
814            if strcmp(backgroundoldname,backgroundname)% background exist, not already read in civ2
815                par_civ2.Background=background; %use background already opened
816            else
817                if ~isempty(regexp(backgroundname,'(^http://)|(^https://)', 'once'))|| exist(backgroundname,'file')
818                    try
819                        par_civ2.Background=imread(backgroundname);%update the background, an store it for future use
820                    catch ME
821                        if ~isempty(ME.message)
822                            errormsg=['error reading input image: ' ME.message];
823                            disp_uvmat('ERROR',errormsg,checkrun)
824                            return
825                        end
826                    end
827                else
828                    par_civ2.Background=[];
829                end
830                background=par_civ2.Background;
831                backgroundoldname=backgroundname;
832            end
833            par_civ2.ImageA=par_civ2.ImageA-par_civ2.Background;
834            par_civ2.ImageB=par_civ2.ImageB-par_civ2.Background;
835        end
[1169]836       
837        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
838            Civ1_Dt=1;
839            Civ2_Dt=1;
840        else
841            Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
[856]842        end
[1163]843        par_civ2.SearchBoxShift=zeros(size(par_civ2.Grid));
[1169]844        par_civ2.SearchBoxShift(:,1)=(Civ2_Dt/Civ1_Dt)*Shiftx;%rescale the shift in case of Dt different for Civ1 and Civ2
[1163]845        par_civ2.SearchBoxShift(:,2)=(Civ2_Dt/Civ1_Dt)*Shifty;
[1169]846       
[598]847        if par_civ2.CheckDeformation
[1163]848            par_civ2.DUDX(nbval>0)=DUDX(nbval>0)./nbval(nbval>0);
849            par_civ2.DUDY(nbval>0)=DUDY(nbval>0)./nbval(nbval>0);
850            par_civ2.DVDX(nbval>0)=DVDX(nbval>0)./nbval(nbval>0);
851            par_civ2.DVDY(nbval>0)=DVDY(nbval>0)./nbval(nbval>0);
[598]852        end
[1169]853       
[862]854        % calculate velocity data (y and v in image indices, reverse to y component)
[1169]855       
[1195]856        [Civ_X,Civ_Y,Civ_U,Civ_V,Civ_C,Civ_FF,~, errormsg] = civ (par_civ2);
857        Civ_X_shifted=Civ_X-0.5+Civ_U/2;% get the exact positions
858        Civ_Y_shifted=Civ_Y-0.5+Civ_V/2;
[598]859        list_param=(fieldnames(Param.ActionInput.Civ2))';
[859]860        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
[606]861        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
862        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
[856]863        %indicate the values of all the global attributes in the output data
864        if exist('ImageName_A','var')
[859]865            Data.Civ2_ImageA=ImageName_A;
866            Data.Civ2_ImageB=ImageName_B;
[997]867            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
[950]868                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
869                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
[997]870            else
871                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
872                Data.Civ2_Dt=Civ2_Dt;
873            end
[856]874        end
[598]875        for ilist=1:length(list_param)
[606]876            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
[598]877        end
[606]878        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
[1169]879       
[1195]880        %        nbvar=numel(Data.ListVarName);
[859]881        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
[1195]882        %         if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
883        %             Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_C','Civ2_FF'}];%  cell array containing the names of the fields to record
884        %             Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
885        %             Data.VarAttribute{nbvar+1}.Role='coord_x';
886        %             Data.VarAttribute{nbvar+2}.Role='coord_y';
887        %             Data.VarAttribute{nbvar+3}.Role='vector_x';
888        %             Data.VarAttribute{nbvar+4}.Role='vector_y';
889        %             Data.VarAttribute{nbvar+5}.Role='ancillary';
890        %             Data.VarAttribute{nbvar+6}.Role='errorflag';
891        %         end
[896]892        disp('civ2 performed')
[1131]893        time_civ2=toc(tstart_civ2);
[1195]894    elseif Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2') % we start there, using existing Civ2 data
[860]895        if exist('ncfile','var')
896            CivFile=ncfile;
[1169]897            [Data,~,~,errormsg]=nc2struct(CivFile);%read civ1 and detect_false1 data in the existing netcdf file
[860]898            if ~isempty(errormsg)
899                disp_uvmat('ERROR',errormsg,checkrun)
900                return
[997]901            end
[860]902        end
[598]903    end
[1169]904   
[598]905    %% Fix2
[1195]906    if (Param.ActionInput.CheckFix2 && isfield (Param.ActionInput,'Fix2'))||(Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2'))%% if Fix2 computation is requested
[1143]907        disp('detect_false2 started')
[856]908        list_param=fieldnames(Param.ActionInput.Fix2)';
[852]909        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]910        %indicate the values of all the global attributes in the output data
[852]911        for ilist=1:length(list_param)
912            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
[598]913        end
[1163]914        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
[1195]915        Civ_FF=uint8(detect_false(Param.ActionInput.Fix2,Civ_C,Civ_U,Civ_V,Civ_FF));
[1144]916        Data.CivStage=Data.CivStage+1;
[598]917    end
918   
919    %% Patch2
[1169]920    if Param.ActionInput.CheckPatch2 && isfield (Param.ActionInput,'Patch2')% if Patch2 computation is requested
921       
[896]922        disp('patch2 started')
[1131]923        tstart_patch2=tic;
[859]924        list_param=fieldnames(Param.ActionInput.Patch2)';
925        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
[852]926        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
[859]927        %indicate the values of all the global attributes in the output data
[852]928        for ilist=1:length(list_param)
929            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
930        end
931        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
932       
[1195]933        %  nbvar=length(Data.ListVarName);
934        %         Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
935        %         Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
936        %             {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
[598]937       
[1195]938        %         Data.VarAttribute{nbvar+1}.Role='vector_x';
939        %         Data.VarAttribute{nbvar+2}.Role='vector_y';
940        %         Data.VarAttribute{nbvar+5}.Role='coord_tps';
941        %         Data.VarAttribute{nbvar+6}.Role='vector_x';
942        %         Data.VarAttribute{nbvar+7}.Role='vector_y';
943       
944        if isempty(Civ_FF)
945            ind_good=1:numel(Civ_X);
[597]946        else
[1195]947            ind_good=find(Civ_FF==0);
[597]948        end
[1169]949        if isempty(ind_good)
950            disp_uvmat('ERROR','all vectors of civ2 are bad, check input parameters' ,checkrun)
951            return
952        end
953       
[1195]954        [Civ_SubRange,Civ_NbCentres,Civ_Coord_tps,Civ_U_tps,Civ_V_tps,~,Ures,Vres,~,FFres]=...
955            filter_tps([Civ_X_shifted(ind_good) Civ_Y_shifted(ind_good)],Civ_U(ind_good),Civ_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
956        Civ_U_smooth=Civ_U;% keep the false vectors unchanged
957        Civ_V_smooth=Civ_V;
958        Civ_U_smooth(ind_good)=Ures;
959        Civ_V_smooth(ind_good)=Vres;
960        Civ_FF(ind_good)=uint8(4*FFres);
[598]961        Data.CivStage=Data.CivStage+1;
[1131]962        time_patch2=toc(tstart_patch2);
[896]963        disp('patch2 performed')
[597]964    end
[598]965   
[1169]966    %% write result in a netcdf file
[1195]967   
968    Data.ListVarName={'X','Y','U','V','C','FF'};%  cell array containing the names of the fields to record
969    Data.VarDimName={'nb_vec','nb_vec','nb_vec','nb_vec','nb_vec','nb_vec'};
970    Data.VarAttribute{1}.Role='coord_x';
971    Data.VarAttribute{2}.Role='coord_y';
972    Data.VarAttribute{3}.Role='vector_x';
973    Data.VarAttribute{3}.scale_factor=1/inv_scale_factor;
974    Data.VarAttribute{4}.Role='vector_y';
975    Data.VarAttribute{4}.scale_factor=1/inv_scale_factor;
976    Data.VarAttribute{5}.Role='ancillary';
[1196]977    Data.VarAttribute{5}.scale_factor=1/100;%scla factor for correlation
[1195]978    Data.VarAttribute{6}.Role='errorflag';
979    Data.X=uint16(Civ_X);
980    Data.Y=uint16(Civ_Y);
981    Data.U=int16(inv_scale_factor*Civ_U);
982    Data.V=int16(inv_scale_factor*Civ_V);
[1196]983    Data.C=uint8(100*Civ_C);
[1195]984    Data.FF=uint8(Civ_FF);
[1196]985    % add smoothed field if ptch is done
[1195]986    if (Param.ActionInput.CheckPatch1 && ~Param.ActionInput.CheckCiv2) ||Param.ActionInput.CheckPatch2
987        nbvar=6;
988        Data.ListVarName=[Data.ListVarName {'U_smooth','V_smooth'}];
989        Data.VarDimName=[Data.VarDimName {'nb_vec','nb_vec'}];
990        Data.VarAttribute{nbvar+1}.Role='vector_x';
991        Data.VarAttribute{nbvar+1}.scale_factor=1/inv_scale_factor;
992        Data.VarAttribute{nbvar+2}.Role='vector_y';
993        Data.VarAttribute{nbvar+2}.scale_factor=1/inv_scale_factor;
994        Data.U_smooth=int16(inv_scale_factor*Civ_U_smooth);
995        Data.V_smooth=int16(inv_scale_factor*Civ_V_smooth);
996    end
[1169]997    errormsg=struct2nc(ncfile_out,Data);
998    if isempty(errormsg)
999        disp([ncfile_out ' written'])
1000    else
1001        disp(errormsg)
[598]1002    end
[1169]1003    time_total=toc(tstart);
1004    disp(['ellapsed time ' num2str(time_total/60,2) ' minutes'])
1005    disp(['time civ1 ' num2str(time_civ1,2) ' s'])
1006    disp(['time patch1 ' num2str(time_patch1,2) ' s'])
1007    disp(['time civ2 ' num2str(time_civ2,2) ' s'])
1008    disp(['time patch2 ' num2str(time_patch2,2) ' s'])
1009    if exist('time_input','var')
1010        disp(['time image reading ' num2str(time_input,2) ' s'])
1011        disp(['time other ' num2str((time_total-time_input-time_civ1-time_patch1-time_civ2-time_patch2),2) ' s'])
1012    end
[597]1013end
1014
[1169]1015
1016
[598]1017%------------------------------------------------------------------------
1018% --- determine the list of index pairs of processing file
1019function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
[635]1020    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
[598]1021%------------------------------------------------------------------------
[610]1022i1_series=i_series;% set of first image indexes
[598]1023i2_series=i_series;
[819]1024j1_series=j_series;%ones(size(i_series));% set of first image numbers
1025j2_series=j_series;%ones(size(i_series));
[610]1026r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
[598]1027if ~isempty(r)
1028    mode=['D' r.ind];
1029    ind1=str2num(r.num1);
1030    ind2=str2num(r.num2);
1031else
[668]1032    mode='j1-j2';
[598]1033    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1034    if ~isempty(r)
1035        NomTypeNc='_1ab';
1036    else
1037        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1038        if ~isempty(r)
1039            NomTypeNc='_1AB';
[597]1040        else
[598]1041            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1042            if ~isempty(r)
1043                NomTypeNc='_1_1-2';
[859]1044            end
[597]1045        end
1046    end
[598]1047    if isempty(r)
1048        display('wrong pair mode input option')
1049    else
[859]1050        ind1=stra2num(r.num1);
1051        ind2=stra2num(r.num2);
[598]1052    end
[597]1053end
[819]1054switch mode
1055    case 'Di'
1056        i1_series=i_series-ind1;% set of first image numbers
1057        i2_series=i_series+ind2;
1058        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1059        if isempty(j_series)
1060            NomTypeNc='_1-2';
1061        else
1062            j1_series=j_series;
1063            j2_series=j_series;
1064            NomTypeNc='_1-2_1';
1065        end
1066    case 'Dj'
1067        j1_series=j_series-ind1;
1068        j2_series=j_series+ind2;
1069        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1070        NomTypeNc='_1_1-2';
1071    otherwise %bursts
1072        i1_series=i_series(1,:);% do not sweep the j index
1073        i2_series=i_series(1,:);
1074        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1075        j2_series=ind2*ones(1,size(i_series,2));
1076        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
[598]1077end
[597]1078
[1169]1079%------------------------------------------------------------------------
1080% --- set the flag for false vectors
[1163]1081function FF=detect_false(Param,C,U,V,FFIn)
1082FF=FFIn;%default, good vectors
1083% FF=1, for correlation max at edge, not set in this function
1084% FF=2, for too small correlation
1085% FF=3, for velocity outside bounds
1086% FF=4 for exclusion by difference with the smoothed field, set by call to function filter_tps
[598]1087
[1163]1088if isfield (Param,'MinCorr')
1089     FF(C<Param.MinCorr & FFIn==0)=2;
1090end
1091if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1092    Umod= U.*U+V.*V;
1093    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1094        U2Min=Param.MinVel*Param.MinVel;
1095        FF(Umod<U2Min & FFIn==0)=3;
1096    end
1097    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1098         U2Max=Param.MaxVel*Param.MaxVel;
1099        FF(Umod>U2Max & FFIn==0)=3;
1100    end
1101end
[598]1102
[1195]1103% % --- compress the data using integers instead of (single precision)floating reals
1104% function DataOut=compress_data(DataIn,inv_scale_factor)
1105% DataOut=DataIn; %default
1106% DataOut.Conventions= 'uvmat/civdata/compress';
1107% ListVarName=DataIn.ListVarName;
1108% for ilist=1:numel(ListVarName)
1109%     switch ListVarName{ilist}
1110%         case {'Civ1_C','Civ2_C'}
1111%             DataOut.(ListVarName{ilist})=uint8(inv_scale_factor*DataIn.(ListVarName{ilist}));
1112%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1113%         case {'Civ1_U','Civ1_V','Civ2_U','Civ2_V','Civ1_U_smooth','Civ1_V_smooth','Civ2_U_smooth','Civ2_V_smooth'}
1114%             DataOut.(ListVarName{ilist})=int16(inv_scale_factor*DataIn.(ListVarName{ilist}));
1115%             DataOut.VarAttribute{ilist}.scale_factor=1/inv_scale_factor;
1116%         case 'Civ1_X'
1117%             DataOut.Civ1_X=uint16(DataIn.Civ1_X);
1118%         case 'Civ1_Y'
1119%             DataOut.Civ1_Y=uint16(DataIn.Civ1_Y);
1120%        case 'Civ2_X'
1121%             DataOut.Civ2_X=uint16(DataIn.Civ2_X);
1122%         case 'Civ2_Y'
1123%             DataOut.Civ2_Y=uint16(DataIn.Civ2_Y);
1124%     end
1125% end
Note: See TracBrowser for help on using the repository browser.