source: trunk/src/civ_matlab.m @ 337

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

Added the reverse_pair (need to uncomment line 57)

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