source: trunk/src/civ_matlab.m @ 321

Last change on this file since 321 was 321, checked in by gostiaux, 12 years ago

civ_matlab accepts a xml filename as input

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