source: trunk/src/civ_matlab.m @ 319

Last change on this file since 319 was 319, checked in by sommeria, 12 years ago

civ: bugs for displacement mode repaired
civ and civ_matlab prepared for batch in Matlab (file .civ.xml created)

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