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

Last change on this file since 1200 was 1200, checked in by sommeria, 26 hours ago

bug repaired for civ image rescale

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