source: trunk/src/civ_matlab.m @ 317

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

bug repaired in name2display (names in _000001) and civ.m

File size: 35.7 KB
Line 
1%'civ_matlab': Matlab version of the PIV programs CivX
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   patch: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_uvmat(Param,ncfile)
8%
9%OUTPUT
10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, default=''
12% resul_conv: image inter-correlation function for the last grid point (used for tests)
13%
14%INPUT:
15% Param: input images and processing parameters
16% ncfile: name of a netcdf file to be created for the result (extension .nc)
17%
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
20%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
21%     This is part of the toolbox UVMAT.
22%
23%     UVMAT is free software; you can redistribute it and/or modify
24%     it under the terms of the GNU General Public License as published by
25%     the Free Software Foundation; either version 2 of the License, or
26%     (at your option) any later version.
27%
28%     UVMAT is distributed in the hope that it will be useful,
29%     but WITHOUT ANY WARRANTY; without even the implied warranty of
30%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
32%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
33
34function [Data,errormsg,result_conv]= civ_matlab(Param,ncfile)
35errormsg='';
36Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
37Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
38Data.Program='civ_matlab';
39Data.CivStage=0;%default
40ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
41ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
42mask='';
43maskname='';%default
44check_civx=0;%default
45check_civ1=0;%default
46check_patch1=0;%default
47
48%% Civ1
49if isfield (Param,'Civ1')
50    check_civ1=1;% test for further use of civ1 results
51    % caluclate velocity data (y and v in indices, reverse to y component)
52    [xtable ytable utable vtable ctable F result_conv errormsg] = civ (Param.Civ1);
53    if ~isempty(errormsg)
54        return
55    end
56    list_param=(fieldnames(Param.Civ1))';
57    Civ1_param=list_param;%default
58    for ilist=1:length(list_param)
59        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
60        %         eval(['Data.Civ1_' list_param{ilist} '=Param.Civ1.' list_param{ilist} ';'])
61        Data.(['Civ1_' list_param{ilist}])=Param.Civ1.(list_param{ilist});
62    end
63    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];% {'Civ1_Time','Civ1_Dt'}];
64%     if exist('ncfile','var')% TEST for use interactively with mouse_motion (no file created)
65        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'};%  cell array containing the names of the fields to record
66        Data.VarDimName={'nbvec1','nbvec1','nbvec1','nbvec1','nbvec1','nbvec1'};
67        Data.VarAttribute{1}.Role='coord_x';
68        Data.VarAttribute{2}.Role='coord_y';
69        Data.VarAttribute{3}.Role='vector_x';
70        Data.VarAttribute{4}.Role='vector_y';
71        Data.VarAttribute{5}.Role='warnflag';
72    Data.Civ1_X=reshape(xtable,[],1);
73    Data.Civ1_Y=reshape(Param.Civ1.ImageHeight-ytable+1,[],1);
74    Data.Civ1_U=reshape(utable,[],1);
75    Data.Civ1_V=reshape(-vtable,[],1);
76    Data.Civ1_C=reshape(ctable,[],1);
77    Data.Civ1_F=reshape(F,[],1);
78    Data.CivStage=1;
79
80else
81    Data=nc2struct(ncfile,'ListGlobalAttribute','absolut_time_T0') %look for the constant 'absolut_time_T0' to detect old civx data format
82    if isfield(Data,'Txt')
83            errormsg=Data.Txt;
84        return
85    end
86    if ~isempty(Data.absolut_time_T0')%read civx file
87        check_civx=1;% test for old civx data format
88        [Data,vardetect,ichoice]=nc2struct(ncfile);%read the variables in the netcdf file
89    else
90        if isfield(Param,'Fix1')
91            Data=nc2struct(ncfile,ListVarCiv1);%read civ1 data in the existing netcdf file
92        else
93            Data=nc2struct(ncfile,ListVarFix1);%read civ1 and fix1 data in the existing netcdf file
94        end
95    end
96
97end
98
99%% Fix1
100if isfield (Param,'Fix1')
101    ListFixParam=fieldnames(Param.Fix1);
102    for ilist=1:length(ListFixParam)
103        ParamName=ListFixParam{ilist};
104        ListName=['Fix1_' ParamName];
105        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
106        eval(['Data.' ListName '=Param.Fix1.' ParamName ';'])
107    end
108    if check_civx
109        if ~isfield(Data,'fix')
110            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
111            Data.fix=1;
112            Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
113            Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
114        end
115        Data.vec_FixFlag=fix(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
116    else
117        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
118        Data.VarDimName=[Data.VarDimName {'nbvec1'}];
119        nbvar=length(Data.ListVarName);
120        Data.VarAttribute{nbvar}.Role='errorflag';   
121        Data.Civ1_FF=fix(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
122        Data.CivStage=2;   
123    end
124end   
125%% Patch1
126if isfield (Param,'Patch1')
127    check_patch1=1;
128    Param.Patch1
129    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
130    Data.Patch1_Rho=Param.Patch1.SmoothingParam;
131    Data.Patch1_Threshold=Param.Patch1.MaxDiff;
132    Data.Patch1_SubDomain=Param.Patch1.SubdomainSize;
133    Data.ListVarName=[Data.ListVarName {'Civ1_U_Diff','Civ1_V_Diff','Civ1_X_SubRange','Civ1_Y_SubRange','Civ1_NbSites','Civ1_X_tps','Civ1_Y_tps','Civ1_U_tps','Civ1_V_tps'}];
134    Data.VarDimName=[Data.VarDimName {'NbVec1','NbVec1',{'NbSubDomain1','Two'},{'NbSubDomain1','Two'},'NbSubDomain1',...
135             {'NbVec1Sub','NbSubDomain1'},{'NbVec1Sub','NbSubDomain1'},{'Nbtps1','NbSubDomain1'},{'Nbtps1','NbSubDomain1'}}];
136    nbvar=length(Data.ListVarName);
137    Data.VarAttribute{nbvar-1}.Role='vector_x';
138    Data.VarAttribute{nbvar}.Role='vector_y';
139    Data.Civ1_U_Diff=zeros(size(Data.Civ1_X));
140    Data.Civ1_V_Diff=zeros(size(Data.Civ1_X));
141    if isfield(Data,'Civ1_FF')
142        ind_good=find(Data.Civ1_FF==0);
143    else
144       
145        ind_good=1:numel(Data.Civ1_X);
146    end
147    [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
148                            patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
149      Data.Civ1_U_Diff(ind_good)=Data.Civ1_U(ind_good)-Ures;
150      Data.Civ1_V_Diff(ind_good)=Data.Civ1_V(ind_good)-Vres;
151      Data.Civ1_FF(ind_good)=FFres;
152      Data.CivStage=3;                             
153end   
154
155%% Civ2
156if isfield (Param,'Civ2')
157    par_civ2=Param.Civ2;
158    if ~check_civ1 || ~strcmp(par_civ1.filename_ima_a,par_civ2.filename_ima_a)
159            par_civ2.ImageA=imread(par_civ2.filename_ima_a);%read first image if not already done for civ1
160    end
161    if ~check_civ1|| ~strcmp(par_civ1.filename_ima_b,par_civ2.filename_ima_b)
162            par_civ2.ImageB=imread(par_civ2.filename_ima_b);%read second image if not already done for civ1
163    end
164%     stepx=str2double(par_civ2.dx);
165%     stepy=str2double(par_civ2.dy);
166    ibx2=ceil(str2double(par_civ2.ibx)/2);
167    iby2=ceil(str2double(par_civ2.iby)/2);
168    isx2=ibx2+2;
169    isy2=iby2+2;
170
171    %get the previous guess for displacement
172   
173    if ~check_patch1
174        [Data,VelType]=read_civdata(ObjectName,InputField,ParamIn.VelType);%TO DEVELOP
175    end
176   
177    Guess =interp_tps(Data,X,Y)
178%         Data.Civ1_U_Diff=zeros(size(Data.Civ1_X));
179%         Data.Civ1_V_Diff=zeros(size(Data.Civ1_X));
180%         if isfield(Data,'Civ1_FF')
181%             ind_good=find(Data.Civ1_FF==0);
182%         else
183%             ind_good=1:numel(Data.Civ1_X);
184%         end
185%             [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
186%                                 patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
187%         end
188%     shiftx=str2num(par_civ1.shiftx);
189%     shifty=str2num(par_civ1.shifty);
190% TO GET shift from par_civ2.filename_nc1
191    % shiftx=velocity interpolated at position
192    miniy=max(1+isy2+shifty,1+iby2);
193    minix=max(1+isx2-shiftx,1+ibx2);
194    maxiy=min(size(par_civ2.ImageA,1)-isy2+shifty,size(par_civ2.ImageA,1)-iby2);
195    maxix=min(size(par_civ2.ImageA,2)-isx2-shiftx,size(par_civ2.ImageA,2)-ibx2);
196    [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
197    PointCoord(:,1)=reshape(GridX,[],1);
198    PointCoord(:,2)=reshape(GridY,[],1);
199    if ~isempty(par_civ2.maskname)&& ~strcmp(maskname,par_civ2.maskname)% mask exist, not already read in civ1
200        mask=imread(par_civ2.maskname);
201    end
202    % caluclate velocity data (y and v in indices, reverse to y component)
203    [xtable ytable utable vtable ctable F] = civ (par_civ2.ImageA,par_civ1.ImageB,ibx2,iby2,isx2,isy2,shiftx,-shifty,PointCoord,str2num(par_civ1.rho),mask);
204    list_param=(fieldnames(par_civ1))';
205    list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
206    index=zeros(size(list_param));
207    for ilist=1:length(list_remove)
208        index=strcmp(list_remove{ilist},list_param);
209        if ~isempty(find(index,1))
210            list_param(index)=[];
211        end
212    end
213    for ilist=1:length(list_param)
214        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
215        eval(['Data.Civ1_' list_param{ilist} '=Param.Civ1.' list_param{ilist} ';'])
216    end
217    if isfield(Data,'Civ1_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
218        Data.Civ1_gridname='';
219    end
220    if isfield(Data,'Civ1_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
221        Data.Civ1_maskname='';
222    end
223    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param {'Civ1_Time','Civ1_Dt'}];
224    Data.Civ1_Time=str2double(par_civ1.T0);
225    Data.Civ1_Dt=str2double(par_civ1.Dt);
226    Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'};%  cell array containing the names of the fields to record
227    Data.VarDimName={'nbvec1','nbvec1','nbvec1','nbvec1','nbvec1','nbvec1'};
228    Data.VarAttribute{1}.Role='coord_x';
229    Data.VarAttribute{2}.Role='coord_y';
230    Data.VarAttribute{3}.Role='vector_x';
231    Data.VarAttribute{4}.Role='vector_y';
232    Data.VarAttribute{5}.Role='warnflag';
233    Data.Civ1_X=reshape(xtable,[],1);
234    Data.Civ1_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
235    Data.Civ1_U=reshape(utable,[],1);
236    Data.Civ1_V=reshape(-vtable,[],1);
237    Data.Civ1_C=reshape(ctable,[],1);
238    Data.Civ1_F=reshape(F,[],1);
239    Data.CivStage=Data.CivStage+1;
240end
241
242%% Fix2
243if isfield (Param,'Fix2')
244    ListFixParam=fieldnames(Param.Fix2);
245    for ilist=1:length(ListFixParam)
246        ParamName=ListFixParam{ilist};
247        ListName=['Fix1_' ParamName];
248        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
249        eval(['Data.' ListName '=Param.Fix2.' ParamName ';'])
250    end
251    if check_civx
252        if ~isfield(Data,'fix2')
253            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
254            Data.fix2=1;
255            Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
256            Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
257        end
258        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
259    else
260        Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
261        Data.VarDimName=[Data.VarDimName {'nbvec2'}];
262        nbvar=length(Data.ListVarName);
263        Data.VarAttribute{nbvar}.Role='errorflag';   
264        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
265        Data.CivStage=5;   
266    end
267   
268end   
269
270%% Patch2
271if isfield (Param,'Patch2')
272    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
273    Data.Patch2_Rho=str2double(Param.Patch2.Rho);
274    Data.Patch2_Threshold=str2double(Param.Patch2.Threshold);
275    Data.Patch2_SubDomain=str2double(Param.Patch2.SubDomain);
276    Data.ListVarName=[Data.ListVarName {'Civ2_U_Diff','Civ2_V_Diff','Civ2_X_SubRange','Civ2_Y_SubRange','Civ2_NbSites','Civ2_X_tps','Civ2_Y_tps','Civ2_U_tps','Civ2_V_tps'}];
277    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2',{'NbSubDomain2','Two'},{'NbSubDomain2','Two'},'NbSubDomain2',...
278             {'NbVec2Sub','NbSubDomain2'},{'NbVec2Sub','NbSubDomain2'},{'Nbtps2','NbSubDomain2'},{'Nbtps2','NbSubDomain2'}}];
279    nbvar=length(Data.ListVarName);
280    Data.VarAttribute{nbvar-1}.Role='vector_x';
281    Data.VarAttribute{nbvar}.Role='vector_y';
282    Data.Civ2_U_Diff=zeros(size(Data.Civ2_X));
283    Data.Civ2_V_Diff=zeros(size(Data.Civ2_X));
284    if isfield(Data,'Civ2_FF')
285        ind_good=find(Data.Civ2_FF==0);
286    else
287        ind_good=1:numel(Data.Civ2_X);
288    end
289    [Data.Civ2_X_SubRange,Data.Civ2_Y_SubRange,Data.Civ2_NbSites,FFres,Ures, Vres,Data.Civ2_X_tps,Data.Civ2_Y_tps,Data.Civ2_U_tps,Data.Civ2_V_tps]=...
290                            patch(Data.Civ2_X(ind_good)',Data.Civ2_Y(ind_good)',Data.Civ2_U(ind_good)',Data.Civ2_V(ind_good)',Data.Patch2_Rho,Data.Patch2_Threshold,Data.Patch2_SubDomain);
291      Data.Civ2_U_Diff(ind_good)=Data.Civ2_U(ind_good)-Ures;
292      Data.Civ2_V_Diff(ind_good)=Data.Civ2_V(ind_good)-Vres;
293      Data.Civ2_FF(ind_good)=FFres;
294      Data.CivStage=6;                             
295end   
296
297%% write result in a netcdf file if requested
298if exist('ncfile','var') && ~(isfield(Param,'CheckOuputFile')&&Param.CheckOuputFile)
299    errormsg=struct2nc(ncfile,Data);
300end
301
302% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
303%--------------------------------------------------------------------------
304% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
305%
306% OUTPUT:
307% xtable: set of x coordinates
308% ytable: set of y coordiantes
309% utable: set of u displacements (along x)
310% vtable: set of v displacements (along y)
311% ctable: max image correlation for each vector
312% typevector: set of flags, =1 for good, =0 for NaN vectors
313%
314%INPUT:
315% image1:first image (matrix)
316% image2: second image (matrix)
317% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
318% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
319% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
320% step: mesh of the measurement points (in px)
321% subpixfinder=1 or 2 controls the curve fitting of the image correlation
322% mask: =[] for no mask
323% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
324function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
325%this funtion performs the DCC PIV analysis. Recent window-deformation
326%methods perform better and will maybe be implemented in the future.
327
328%% prepare grid
329ibx2=ceil(par_civ.Bx/2);
330iby2=ceil(par_civ.By/2);
331isx2=ceil(par_civ.Searchx/2);
332isy2=ceil(par_civ.Searchy/2);
333shiftx=par_civ.Shiftx;
334shifty=-par_civ.Shifty;% sign minus because image j index increases when y decreases
335if isfield(par_civ,'Grid')
336    if ischar(par_civ.Grid)
337        par_civ.Grid;
338        par_civ.Grid=dlmread(par_civ.Grid);
339        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
340    end
341else% automatic measurement grid
342    ibx2=ceil(par_civ.Bx/2);
343    iby2=ceil(par_civ.By/2);
344    isx2=ceil(par_civ.Searchx/2);
345    isy2=ceil(par_civ.Searchy/2);
346    shiftx=par_civ.Shiftx;
347    shifty=-par_civ.Shifty;
348    miniy=max(1+isy2+shifty,1+iby2);
349    minix=max(1+isx2-shiftx,1+ibx2);
350    maxiy=min(par_civ.ImageHeight-isy2+shifty,par_civ.ImageHeight-iby2);
351    maxix=min(par_civ.ImageWidth-isx2-shiftx,par_civ.ImageWidth-ibx2);
352    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
353    par_civ.Grid(:,1)=reshape(GridX,[],1);
354    par_civ.Grid(:,2)=reshape(GridY,[],1);
355end
356
357%% Default output
358nbvec=size(par_civ.Grid,1);
359xtable=par_civ.Grid(:,1);
360ytable=par_civ.Grid(:,2);
361utable=zeros(nbvec,1);
362vtable=zeros(nbvec,1);
363ctable=zeros(nbvec,1);
364F=zeros(nbvec,1);
365result_conv=[];
366errormsg='';
367
368%% prepare mask
369if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
370    if strcmp(par_civ.Mask,'all')
371        return    % get the grid only, no civ calculation
372    elseif ischar(par_civ.Mask)
373        par_civ.Mask=imread(par_civ.Mask);
374    end
375end
376check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
377check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
378
379%% prepare images
380if ischar(par_civ.ImageA)
381    par_civ.ImageA=imread(par_civ.ImageA);
382end
383if ischar(par_civ.ImageB)
384    par_civ.ImageB=imread(par_civ.ImageB);
385end
386[npy_ima npx_ima]=size(par_civ.ImageA);
387if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
388    errormsg='image pair with unequal size';
389    return
390end
391par_civ.ImageA=double(par_civ.ImageA);
392par_civ.ImageB=double(par_civ.ImageB);
393
394
395%% Apply mask
396    % Convention for mask
397    % mask >200 : velocity calculated
398    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
399    % 150>=mask >100: velocity not calculated, nor interpolated
400    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries) TO IMPLEMENT
401    %  20>=mask: velocity=0
402checkmask=0;
403if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
404   checkmask=1;
405   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
406        errormsg='mask must be an image with the same size as the images';
407        return
408   end
409  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
410    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=100 );
411    par_civ.ImageA(check_undefined)=min(min(par_civ.ImageA));% put image A to zero (i.e. the min image value) in the undefined  area
412    par_civ.ImageB(check_undefined)=min(min(par_civ.ImageB));% put image B to zero (i.e. the min image value) in the undefined  area
413end
414
415%% compute image correlations: MAINLOOP on velocity vectors
416corrmax=0;
417sum_square=1;% default
418% vector=[0 0];%default
419for ivec=1:nbvec
420    iref=par_civ.Grid(ivec,1);% xindex on the image A for the middle of the correlation box
421    jref=par_civ.Grid(ivec,2);% yindex on the image B for the middle of the correlation box
422%     xtable(ivec)=iref;
423%     ytable(ivec)=jref;%default
424    if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
425        if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth
426            F(ivec)=3;
427        else
428            image1_crop=par_civ.ImageA(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from image A
429            image2_crop=par_civ.ImageB(jref+shifty-isy2:jref+shifty+isy2,iref+shiftx-isx2:iref+shiftx+isx2);%extract a larger subimage (search box) from image B
430            image1_mean=mean(mean(image1_crop));
431            image2_mean=mean(mean(image2_crop));
432            %threshold on image minimum
433            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
434                F(ivec)=3;
435            end
436        end
437        %threshold on image maximum
438        if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
439            F(ivec)=3;
440        end
441        if F(ivec)~=3
442            image1_crop=image1_crop-image1_mean;%substract the mean
443            image2_crop=image2_crop-image2_mean;
444            sum_square=sum(sum(image1_crop.*image1_crop));
445            %reference: Oliver Pust, PIV: Direct Cross-Correlation
446            result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
447            corrmax= max(max(result_conv));
448            result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
449            %Find the correlation max, at 255
450            [y,x] = find(result_conv==255,1);
451            if ~isempty(y) && ~isempty(x)
452                try
453                    if par_civ.Rho==1
454                        [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
455                    elseif par_civ.Rho==2
456                        [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
457                    end
458                    utable(ivec)=vector(1)+shiftx;
459                    vtable(ivec)=vector(2)+shifty;
460                    xtable(ivec)=iref+utable(ivec)/2;% convec flow (velocity taken at the point middle from imgae1 and 2)
461                    ytable(ivec)=jref+vtable(ivec)/2;
462                    iref=round(xtable(ivec));% image index for the middle of the vector
463                    jref=round(ytable(ivec));
464                    if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
465                        utable(ivec)=0;
466                        vtable(ivec)=0;
467                        F(ivec)=3;
468                    end
469                    ctable(ivec)=corrmax/sum_square;% correlation value
470                catch ME
471                    %                     vector=[0 0]; %if something goes wrong with cross correlation.....
472                    F(ivec)=3;
473                end
474            else
475                F(ivec)=3;
476            end
477        end
478    end
479   
480    %Create the vector matrix x, y, u, v
481end
482result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
483
484%------------------------------------------------------------------------
485% --- Find the maximum of the correlation function after interpolation
486function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
487%------------------------------------------------------------------------
488vector=[0 0]; %default
489F=0;
490[npy,npx]=size(result_conv);
491
492% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
493    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion – Israel Institute of Technology
494    %http://urapiv.wordpress.com
495    peaky = y;
496    if y <= npy-1 && y >= 1
497        f0 = log(result_conv(y,x));
498        f1 = real(log(result_conv(y-1,x)));
499        f2 = real(log(result_conv(y+1,x)));
500        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
501    else
502        F=-2; % warning flag for vector truncated by the limited search box
503    end
504    peakx=x;
505    if x <= npx-1 && x >= 1
506        f0 = log(result_conv(y,x));
507        f1 = real(log(result_conv(y,x-1)));
508        f2 = real(log(result_conv(y,x+1)));
509        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
510    else
511        F=-2; % warning flag for vector truncated by the limited search box
512    end
513    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
514
515%------------------------------------------------------------------------
516% --- Find the maximum of the correlation function after interpolation
517function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
518%------------------------------------------------------------------------
519vector=[0 0]; %default
520F=-2;
521peaky=y;
522peakx=x;
523[npy,npx]=size(result_conv);
524if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
525    F=0;
526    for i=-1:1
527        for j=-1:1
528            %following 15 lines based on
529            %H. Nobach Æ M. Honkanen (2005)
530            %Two-dimensional Gaussian regression for sub-pixel displacement
531            %estimation in particle image velocimetry or particle position
532            %estimation in particle tracking velocimetry
533            %Experiments in Fluids (2005) 38: 511–515
534            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
535            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
536            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
537            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
538            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
539        end
540    end
541    c10=(1/6)*sum(sum(c10));
542    c01=(1/6)*sum(sum(c01));
543    c11=(1/4)*sum(sum(c11));
544    c20=(1/6)*sum(sum(c20));
545    c02=(1/6)*sum(sum(c02));
546    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
547    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
548    if abs(deltax)<1
549        peakx=x+deltax;
550    end
551    if abs(deltay)<1
552        peaky=y+deltay;
553    end
554end
555vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
556
557%'RUN_FIX': function for fixing velocity fields:
558%-----------------------------------------------
559% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
560%
561%filename: name of the netcdf file (used as input and output)
562%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
563    %.vel_type='civ1' or 'civ2';
564    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
565    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
566%flagindex: flag specifying which values of vec_f are removed:
567        % if flagindex(1)=1: vec_f=-2 vectors are removed
568        % if flagindex(2)=1: vec_f=3 vectors are removed
569        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
570%iter=1 for civ1 fields and iter=2 for civ2 fields
571%thresh_vecC: threshold in the image correlation vec_C
572%flag_mask: =1 mask used to remove vectors (0 else)
573%maskname: name of the mask image file for fix
574%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
575%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
576%fileref: .nc file name for a reference velocity (='': refrence 0 used)
577%fieldref: 'civ1','filter1'...feld used in fileref
578
579function FF=fix(Param,F,C,U,V,X,Y)
580FF=zeros(size(F));%default
581Param
582
583%criterium on warn flags
584FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
585FlagVal=[-2 2 3 4];
586for iflag=1:numel(FlagName)
587    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
588        FF=(FF==1| F==FlagVal(iflag));
589% if isfield (Param,'WarnFlags')
590%     for iflag=1:numel(Param.WarnFlags)
591%         FF=(FF==1| F==Param.WarnFlags(iflag));
592%     end
593% end
594    end
595end
596%criterium on correlation values
597if isfield (Param,'MinCorr')
598    FF=FF==1 | C<Param.MinCorr;
599end
600if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
601    Umod= U.*U+V.*V;
602    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
603        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
604    end
605    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
606        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
607    end
608end
609return
610
611%
612% if isfield (Param,'LowerBoundVel')&& ~isequal(Param.LowerBoundVel,0)
613%     thresh=Param.LowerBoundVel*Param.LowerBoundVel;
614%     FF=FF==1 | (U.*U+V.*V)<thresh;
615% end
616% if isfield (Param,'UpperBoundVel')&& ~isequal(Param.UpperBoundVel,0)
617%     thresh=Param.UpperBoundVel*Param.UpperBoundVel;
618%     FF=FF==1 | (U.*U+V.*V)>thresh;
619% end
620% if isfield(Param,'MaskName')
621%    M=imread(Param.MaskName);
622%    nxy=size(M);
623%    M=reshape(M,1,[]);
624%    rangx0=[0.5 nxy(2)-0.5];
625%    rangy0=[0.5 nxy(1)-0.5];
626%    vec_x1=X-U/2;%beginning points
627%    vec_x2=X+U/2;%end points of vectors
628%    vec_y1=Y-V/2;%beginning points
629%    vec_y2=Y+V/2;%end points of vectors
630%    indx=1+round((nxy(2)-1)*(vec_x1-rangx0(1))/(rangx0(2)-rangx0(1)));% image index x at abcissa vec_x1
631%    indy=1+round((nxy(1)-1)*(vec_y1-rangy0(1))/(rangy0(2)-rangy0(1)));% image index y at ordinate vec_y1   
632%    check_in=~(indx < 1 |indy < 1 | indx > nxy(2) |indy > nxy(1)); %=0 out of the mask image, 1 inside
633%    indx=indx.*check_in+(1-check_in); %replace indx by 1 out of the mask range
634%    indy=indy.*check_in+(1-check_in); %replace indy by 1 out of the mask range
635%    ICOMB=((indx-1)*nxy(1)+(nxy(1)+1-indy));%determine the indices in the image reshaped in a Matlab vector
636%    Mvalues=M(ICOMB);
637%    flag7b=((20 < Mvalues) & (Mvalues < 200))| ~check_in';
638%    indx=1+round((nxy(2)-1)*(vec_x2-rangx0(1))/(rangx0(2)-rangx0(1)));% image index x at abcissa vec_x2
639%    indy=1+round((nxy(1)-1)*(vec_y2-rangy0(1))/(rangy0(2)-rangy0(1)));% image index y at ordinate vec_y2
640%    check_in=~(indx < 1 |indy < 1 | indx > nxy(2) |indy > nxy(1)); %=0 out of the mask image, 1 inside
641%    indx=indx.*check_in+(1-check_in); %replace indx by 1 out of the mask range
642%    indy=indy.*check_in+(1-check_in); %replace indy by 1 out of the mask range
643%    ICOMB=((indx-1)*nxy(1)+(nxy(1)+1-indy));%determine the indices in the image reshaped in a Matlab vector
644%    Mvalues=M(ICOMB);
645%    flag7e=((Mvalues > 20) & (Mvalues < 200))| ~check_in';
646%    FF=FF==1 |(flag7b|flag7e)';
647% end
648% %    flag7=0;
649% % end   
650%
651
652FF=double(FF);
653%
654% % criterium on velocity values
655% delta_u=Field.U;%default without ref file
656% delta_v=Field.V;
657% if exist('fileref','var') && ~isempty(fileref)
658%     if ~exist(fileref,'file')
659%         error='reference file not found in RUN_FIX.m';
660%         display(error);
661%         return
662%     end
663%     FieldRef=read_civxdata(fileref,[],fieldref);   
664%     if isfield(FieldRef,'FF')
665%         index_true=find(FieldRef.FF==0);
666%         FieldRef.X=FieldRef.X(index_true);
667%         FieldRef.Y=FieldRef.Y(index_true);
668%         FieldRef.U=FieldRef.U(index_true);
669%         FieldRef.V=FieldRef.V(index_true);
670%     end
671%     if ~isfield(FieldRef,'X') || ~isfield(FieldRef,'Y') || ~isfield(FieldRef,'U') || ~isfield(FieldRef,'V')
672%         error='reference file is not a velocity field in RUN_FIX.m '; %bad input file
673%         return
674%     end
675%     if length(FieldRef.X)<=1
676%         errordlg('reference field with one vector or less in RUN_FIX.m')
677%         return
678%     end
679%     vec_U_ref=griddata_uvmat(FieldRef.X,FieldRef.Y,FieldRef.U,Field.X,Field.Y);  %interpolate vectors in the ref field
680%     vec_V_ref=griddata_uvmat(FieldRef.X,FieldRef.Y,FieldRef.V,Field.X,Field.Y);  %interpolate vectors in the ref field to the positions  of the main field     
681%     delta_u=Field.U-vec_U_ref;%take the difference with the interpolated ref field
682%     delta_v=Field.V-vec_V_ref;
683% end
684% thresh_vel_x=thresh_vel;
685% thresh_vel_y=thresh_vel;
686% if isequal(inf_sup,1)
687%     flag5=abs(delta_u)<thresh_vel_x & abs(delta_v)<thresh_vel_y &(flag1~=1)&(flag2~=1)&(flag3~=1)&(flag4~=1);
688% elseif isequal(inf_sup,2)
689%     flag5=(abs(delta_u)>thresh_vel_x | abs(delta_v)>thresh_vel_y) &(flag1~=1)&(flag2~=1)&(flag3~=1)&(flag4~=1);
690% end
691%
692%             % flag7 introduce a grey mask, matrix M
693
694% flagmagenta=flag1|flag2|flag3|flag4|flag5|flag7;
695% fixflag_unit=Field.FF-10*floor(Field.FF/10); %unity term of fix_flag
696
697
698
699%------------------------------------------------------------------------
700% patch function
701function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch(X,Y,U,V,Rho,Threshold,SubDomain)
702%subdomain decomposition
703warning off
704U=reshape(U,[],1);
705V=reshape(V,[],1);
706X=reshape(X,[],1);
707Y=reshape(Y,[],1);
708nbvec=numel(X);
709NbSubDomain=ceil(nbvec/SubDomain);
710MinX=min(X);
711MinY=min(Y);
712MaxX=max(X);
713MaxY=max(Y);
714RangX=MaxX-MinX;
715RangY=MaxY-MinY;
716AspectRatio=RangY/RangX;
717NbSubDomainX=max(floor(sqrt(NbSubDomain/AspectRatio)),1);
718NbSubDomainY=max(floor(sqrt(NbSubDomain*AspectRatio)),1);
719NbSubDomain=NbSubDomainX*NbSubDomainY;
720SizX=RangX/NbSubDomainX;%width of subdomains
721SizY=RangY/NbSubDomainY;%height of subdomains
722CentreX=linspace(MinX+SizX/2,MaxX-SizX/2,NbSubDomainX);
723CentreY=linspace(MinY+SizY/2,MaxY-SizY/2,NbSubDomainY);
724[CentreX,CentreY]=meshgrid(CentreX,CentreY);
725CentreY=reshape(CentreY,1,[]);% Y positions of subdomain centres
726CentreX=reshape(CentreX,1,[]);% X positions of subdomain centres
727rho=SizX*SizY*Rho/1000000;%optimum rho increase as the area of the subdomain (division by 10^6 to reach good values with the default GUI input)
728U_tps_sub=zeros(length(X),NbSubDomain);%default spline
729V_tps_sub=zeros(length(X),NbSubDomain);%default spline
730U_smooth=zeros(length(X),1);
731V_smooth=zeros(length(X),1);
732
733nb_select=zeros(length(X),1);
734FF=zeros(length(X),1);
735check_empty=zeros(1,NbSubDomain);
736for isub=1:NbSubDomain
737    SubRangx(isub,:)=[CentreX(isub)-SizX/2 CentreX(isub)+SizX/2];
738    SubRangy(isub,:)=[CentreY(isub)-SizY/2 CentreY(isub)+SizY/2];
739    ind_sel_previous=[];
740    ind_sel=0;
741    while numel(ind_sel)>numel(ind_sel_previous) %increase the subdomain during four iterations at most
742        ind_sel_previous=ind_sel;
743        ind_sel=find(X>SubRangx(isub,1) & X<SubRangx(isub,2) & Y>SubRangy(isub,1) & Y<SubRangy(isub,2));
744        % if no vector in the subdomain, skip the subdomain
745        if isempty(ind_sel)
746            check_empty(isub)=1;   
747            U_tps(1,isub)=0;%define U_tps and V_tps by default
748            V_tps(1,isub)=0;
749            break
750            % if too few selected vectors, increase the subrange for next iteration
751        elseif numel(ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
752            SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
753            SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
754            SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
755            SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
756        else
757            [U_smooth_sub,U_tps_sub]=tps_coeff(X(ind_sel),Y(ind_sel),U(ind_sel),rho);
758            [V_smooth_sub,V_tps_sub]=tps_coeff(X(ind_sel),Y(ind_sel),V(ind_sel),rho);
759            UDiff=U_smooth_sub-U(ind_sel);
760            VDiff=V_smooth_sub-V(ind_sel);
761            NormDiff=UDiff.*UDiff+VDiff.*VDiff;
762            FF(ind_sel)=20*(NormDiff>Threshold);%put FF value to 20 to identify the criterium of elimmination
763            ind_ind_sel=find(FF(ind_sel)==0); % select the indices of ind_sel corresponding to the remaining vectors
764            % no value exceeds threshold, the result is recorded
765            if isequal(numel(ind_ind_sel),numel(ind_sel))
766                U_smooth(ind_sel)=U_smooth(ind_sel)+U_smooth_sub;
767                V_smooth(ind_sel)=V_smooth(ind_sel)+V_smooth_sub;
768                nbpoints(isub)=numel(ind_sel);
769                X_tps(1:nbpoints(isub),isub)=X(ind_sel);
770                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel);
771                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
772                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;         
773                nb_select(ind_sel)=nb_select(ind_sel)+1;
774                 display('good')
775                break
776                % too few selected vectors, increase the subrange for next iteration
777            elseif numel(ind_ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
778                SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
779                SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
780                SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
781                SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
782%                 display('fewsmooth')
783                % interpolation-smoothing is done again with the selected vectors
784            else
785                [U_smooth_sub,U_tps_sub]=tps_coeff(X(ind_sel(ind_ind_sel)),Y(ind_sel(ind_ind_sel)),U(ind_sel(ind_ind_sel)),rho);
786                [V_smooth_sub,V_tps_sub]=tps_coeff(X(ind_sel(ind_ind_sel)),Y(ind_sel(ind_ind_sel)),V(ind_sel(ind_ind_sel)),rho);
787                U_smooth(ind_sel(ind_ind_sel))=U_smooth(ind_sel(ind_ind_sel))+U_smooth_sub;
788                V_smooth(ind_sel(ind_ind_sel))=V_smooth(ind_sel(ind_ind_sel))+V_smooth_sub;
789                nbpoints(isub)=numel(ind_ind_sel);
790                X_tps(1:nbpoints(isub),isub)=X(ind_sel(ind_ind_sel));
791                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel(ind_ind_sel));
792                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
793                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;
794                nb_select(ind_sel(ind_ind_sel))=nb_select(ind_sel(ind_ind_sel))+1;
795                display('good2')
796                break
797            end
798        end
799    end
800end
801ind_empty=find(check_empty);
802%remove empty subdomains
803if ~isempty(ind_empty)
804    SubRangx(ind_empty,:)=[];
805    SubRangy(ind_empty,:)=[];
806    X_tps(:,ind_empty)=[];
807    Y_tps(:,ind_empty)=[];
808    U_tps(:,ind_empty)=[];
809    V_tps(:,ind_empty)=[];
810end
811nb_select(nb_select==0)=1;%ones(size(find(nb_select==0)));
812U_smooth=U_smooth./nb_select;
813V_smooth=V_smooth./nb_select;
814
815
816
817
818
Note: See TracBrowser for help on using the repository browser.