source: trunk/src/civ_matlab.m @ 329

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

bug corrected in patch matlab. regexrep introduced in uvmat

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