source: trunk/src/series/merge_proj.m @ 109

Last change on this file since 109 was 109, checked in by sommeria, 14 years ago

merge_proj.m, proj_field.m: bugs repaired merging of images
plot_field.m: minor cleaning
imadoc2struct: introduce the possibility of readying the calibration point coordinates
sub_field.m:bugs repaired
geometry_calib, create_grid: introduction of new calibration methods, improvement of detect_grid

File size: 17.5 KB
Line 
1function GUI_input=merge_proj(num_i1,num_i2,num_j1,num_j2,Series)
2
3%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
4if ~exist('num_i1','var')
5    GUI_input={'RootPath';'two';...%nbre of possible input series (options 'on'/'two'/'many', default:'one')
6        'SubDir';'on';... % subdirectory of derived files (PIV fields), ('on' by default)
7        'RootFile';'on';... %root input file name ('on' by default)
8        'FileExt';'on';... %input file extension ('on' by default)
9        'NomType';'on';...%type of file indexing ('on' by default)
10        'NbSlice';'on'; ...%nbre of slices ('off' by default)
11        'VelTypeMenu';'one';...% menu for selecting the velocity type (civ1,..) options 'off'/'one'/'two', 'off' by default)
12        'FieldMenu';'one';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
13        'CoordType';'on';...%can use a transform function 'off' by default
14        'GetObject';'on';...%can use projection object ,'off' by default
15        %'GetMask';'on'...%can use mask option   ,'off' by default
16        %'PARAMETER'; options: name of the user defined parameter',repeat a line for each parameter
17               ''};
18    return %exit the function
19end
20
21%-------------------------------------------------
22hseries=guidata(Series.hseries);%handles of the GUI series
23WaitbarPos=get(hseries.waitbar_frame,'Position'); %positiopn of waitbar frame
24%-------------------------------------------------
25
26%projection object
27test_object=get(hseries.GetObject,'Value');
28if test_object
29    hset_object=findobj(allchild(0),'tag','set_object');
30    ProjObject=read_set_object(guidata(hset_object));
31    if ~isfield(ProjObject,'Style')
32            msgbox_uvmat('ERROR','Undefined projection object style')
33            return
34    end
35    if ~isequal(ProjObject.Style,'plane')
36            msgbox_uvmat('ERROR','The projection object must be a plane')
37            return
38    end
39    %answeryes=questdlg({['field series projected on ' Series.ProjObject.Style]});
40    answeryes=msgbox_uvmat('INPUT_Y-N',['field series projected on ' ProjObject.Style]);
41    if ~isequal(answeryes,'Yes')
42        return
43    end
44end
45
46%numbers of view fields (nbre of inputs in RootPath)
47testcell=iscell(Series.RootFile);
48if ~testcell
49    Series.RootPath={Series.RootPath};
50    Series.RootFile={Series.RootFile};
51    Series.SubDir={Series.SubDir};
52    Series.FileExt={Series.FileExt};
53    Series.NomType={Series.NomType};
54    num_i1={num_i1};
55    num_i2={num_i2};
56    num_j1={num_j1};
57    num_j2={num_j2};
58end
59nbview=length(Series.RootFile);%number of views (file series to merge)
60nbfield=size(num_i1{1},1)*size(num_i1{1},2);%number of fields in the time series
61% transform=Series.CoordType; %  field transform function
62hhh=which('mmreader');
63for iview=1:nbview
64    test_movie(iview)=0;
65    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
66        if isequal(lower(Series.FileExt{iview}),'.avi')
67            MovieObject{iview}=mmreader(fullfile(Series.RootPath{iview},[Series.RootFile{iview} Series.FileExt{iview}]));
68            test_movie(iview)=1;
69        end
70    end
71end
72
73%Calibration data and timing: read the ImaDoc files
74% mode=''; %default
75timecell={};
76itime=0;
77NbSlice_calib={}; %test for z index
78for iview=1:nbview%Loop on views
79    XmlData{iview}=[];%default
80    filebase{iview}=fullfile(Series.RootPath{iview},Series.RootFile{iview});
81    if exist([filebase{iview} '.xml'],'file')
82        [XmlData{iview},error]=imadoc2struct([filebase{iview} '.xml']);
83        if isfield(XmlData{iview},'Time')
84            itime=itime+1;
85            timecell{itime}=XmlData{iview}.Time;
86        end
87        if isfield(XmlData{iview},'GeometryCalib') && isfield(XmlData{iview}.GeometryCalib,'SliceCoord')
88            NbSlice_calib{iview}=size(XmlData{iview}.GeometryCalib.SliceCoord,1);
89            if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
90                msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
91            end
92        end   
93    elseif exist([filebase{iview} '.civ'],'file')
94        [error,time,TimeUnit,mode,npx,npy,pxcmx,pxcmy]=read_imatext([filebase{iview} '.civ']);
95        itime=itime+1;
96        timecell{itime}=time;
97        XmlData{iview}.Time=time;
98        GeometryCalib.R=[pxcmx 0 0; 0 pxcmy 0;0 0 0];
99        GeometryCalib.Tx=0;
100        GeometryCalib.Ty=0;
101        GeometryCalib.Tz=1;
102        GeometryCalib.dpx=1;
103        GeometryCalib.dpy=1;
104        GeometryCalib.sx=1;
105        GeometryCalib.Cx=0;
106        GeometryCalib.Cy=0;
107        GeometryCalib.f=1;
108        GeometryCalib.kappa1=0;
109        GeometryCalib.CoordUnit='cm';
110        XmlData{iview}.GeometryCalib=GeometryCalib;
111        if error==1
112            msgbox_uvmat('WARNING','inconsistent number of fields in the .civ file');
113        end
114    end
115end
116
117%check coincidence in time
118multitime=0;
119if isempty(timecell)
120    time=[];
121elseif length(timecell)==1
122    time=timecell{1};
123elseif length(timecell)>1
124    multitime=1;
125    for icell=1:length(timecell)
126        if ~isequal(size(timecell{icell}),size(timecell{1}))
127            msgbox_uvmat('WARNING','inconsistent time array dimensions in ImaDoc fields, the time for the first series is used')
128            time=timecell{1};
129            multitime=0;
130            break
131        end
132    end
133end
134if multitime
135    for icell=1:length(timecell)
136        time(icell,:,:)=timecell{icell};
137    end
138    diff_time=max(max(diff(time)));
139    if diff_time>0
140        msgbox_uvmat('WARNING',['times of series differ by more than ' num2str(diff_time)])
141    end   
142end
143if size(time,2) < num_i2{1}(end) || size(time,3) < num_j2{1}(end)% ime array absent or too short in ImaDoc xml file'
144    time=[];
145end
146
147% coordinate transform or other user defined transform
148transform_fct=[];%default
149if isfield(Series,'transform_fct')
150    transform_fct=Series.transform_fct;
151end
152
153% Field and velocity type (the same for all views)
154FieldName='';
155if strcmp(get(hseries.FieldMenu,'Visible'),'on')
156Field_str=get(hseries.FieldMenu,'String');
157val=get(hseries.FieldMenu,'Value');
158FieldName=Field_str(val);%the same set of fields for all views
159VelType_str=get(hseries.VelTypeMenu,'String');
160VelType_val=get(hseries.VelTypeMenu,'Value');
161VelType=VelType_str{VelType_val}; %the same for all views
162if strcmp(FieldName,'')
163    msgbox_uvmat('ERROR','no input field defined in FieldMenu')
164elseif strcmp(FieldName,'get_field...')
165    hget_field=findobj(allchild(0),'Name','get_field');%find the get_field... GUI
166    SubField=get_field('read_get_field',hObject,eventdata,hget_field); %read the names of the variables to plot in the get_field GUI
167end
168end
169%detect whether all the files are 'images' or 'netcdf'
170testima=0;
171testvol=0;
172testcivx=0;
173testnc=0;
174FileExt=get(hseries.FileExt,'String');
175for iview=1:nbview
176     ext=FileExt{iview};
177     form=imformats(ext(2:end));
178     if isequal(lower(ext),'.vol')
179         testvol=testvol+1;
180     elseif ~isempty(form)||isequal(lower(ext),'.avi')% if the extension corresponds to an image format recognized by Matlab
181         testima=testima+1;
182     elseif isequal(ext,'.nc')
183         testnc=testnc+1;
184     end
185end
186if testvol
187    msgbox_uvmat('ERROR','volume images not implemented yet')
188    return
189end
190if testnc~=nbview && testima~=nbview && testvol~=nbview
191    msgbox_uvmat('ERROR','need a set of images or a set of netcdf files with the same fields as input')
192    return
193end
194if ~isequal(FieldName,'get_field...')
195    testcivx=testnc;
196end
197
198%name of output files and directory:
199% res_subdir=fullfile(Series.RootPath{1},[Series.SubDir{1} '_STAT']);
200ProjectDir=fileparts(fileparts(Series.RootPath{1}));% preoject directory (GERK)
201prompt={['result directory (in' ProjectDir ')']};
202RootPath=get(hseries.RootPath,'String');
203SubDir=get(hseries.SubDir,'String');
204if isequal(length(RootPath),1)
205    fulldir=RootPath{1};
206    subdir='merge_proj';
207    res_subdir=fullfile(fulldir,subdir);
208else
209    def={fullfile(ProjectDir,'0_RESULTS')};
210    dlgTitle='result directory';
211    lineNo=1;
212    answer=msgbox_uvmat('INPUT_TXT',dlgTitle,def);
213    fulldir=answer{1};
214    subdir=[];
215    dirlist=sort(Series.RootFile);
216    for iview=1:nbview
217        if ~isempty(subdir)
218            subdir=[subdir '-'];
219        end
220        subdir=[subdir dirlist{iview}];
221    end 
222    res_subdir=fullfile(fulldir,subdir);
223end
224ext=FileExt{1};
225if ~exist(fulldir,'dir')
226    msgbox_uvmat('ERROR',['directory ' fulldir ' needs to be created'])
227    return
228end
229if ~exist(res_subdir,'dir')
230    dircur=pwd;
231    cd(fulldir)
232    error=mkdir(subdir);
233    cd(dircur)
234end
235filebasesub=fullfile(res_subdir,Series.RootFile{1});
236filebase_merge=fullfile(res_subdir,'merged');%root name for the merged files
237
238    %MAIN LOOP
239for ifile=1:nbfield               
240    stopstate=get(hseries.RUN,'BusyAction');
241    if isequal(stopstate,'queue')% enable STOP command from the 'series' interface
242         update_waitbar(hseries.waitbar,WaitbarPos,ifile/nbfield)
243%          Amerge=0;
244         
245         %----------LOOP ON VIEWS----------------------
246        nbtime=0;
247        for iview=1:nbview
248            %name of the current file
249            filename=name_generator(filebase{iview},num_i1{iview}(ifile),num_j1{iview}(ifile),Series.FileExt{iview},Series.NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile),SubDir{iview});
250            if ~exist(filename,'file')
251                msgbox_uvmat('ERROR',['missing input file' filename])
252                break
253            end
254
255            %reading the current file
256            if testima
257                if test_movie(iview)
258                    Field{iview}.A=read(MovieObject{iview},num_i1{iview}(ifile));
259                else
260                    Field{iview}.A=imread(filename);
261                end % TODO: introduce ListVarName
262                npxy=size(Field{iview}.A);
263                Field{iview}.ListVarName={'AX','AY','A'};
264                Field{iview}.VarDimName={'AX','AY',{'AY','AX'}};
265                Field{iview}.AX=[0.5 npxy(2)-0.5]; % coordinates of the first and last pixel centers
266                Field{iview}.AY=[npxy(1)-0.5 0.5];
267                Field{iview}.CoordType='px';
268                Field{iview}.AName='image';
269                timeread(iview)=0;
270            else
271                if testcivx
272                    [Field{iview},VelTypeOut]=read_civxdata(filename,FieldName,VelType);
273                else
274                    [Field{iview},var_detect]=nc2struct(filename,SubField.ListVarName); %read the corresponding input data               
275                    Field{iview}.VarAttribute=SubField.VarAttribute;
276                end
277                if isfield(Field{iview},'Txt')
278                    msgbox_uvmat('ERROR',Field{iview}.Txt)
279                    return
280                end
281                if isfield(Field{iview},'Time')
282                    timeread(iview)=Field{iview}.Time;
283                    nbtime=nbtime+1;
284                end
285            end
286            % coord transform
287            % z index
288            if ~isempty(NbSlice_calib)
289                Field{iview}.ZIndex=mod(num_i1{iview}(ifile)-1,NbSlice_calib{1})+1;
290            end
291            if ~isempty(transform_fct)
292                Field{iview}=transform_fct(Field{iview},XmlData{iview});%transform to phys if requested
293            end
294            if testcivx
295                Field{iview}=calc_field(FieldName,Field{iview});
296            end
297
298            %projection on object (gridded plane)
299            if test_object
300                Field{iview}=proj_field(Field{iview},ProjObject);
301            end
302        end   
303       
304         %----------END LOOP ON VIEWS----------------------
305         
306        %merge the nbview fields
307        MergeData=merge_field(Field);
308        if isfield(MergeData,'Txt')
309            msgbox_uvmat('ERROR',MergeData.Txt)
310            return
311        end
312       
313        % generating the name of the merged field
314        mergename=name_generator(filebase_merge,num_i1{iview}(ifile),num_j1{iview}(ifile),Series.FileExt{iview},Series.NomType{iview},1,num_i2{iview}(ifile),num_j2{iview}(ifile));
315       
316        % time:
317        time_i=0;%default
318        if isempty(time)% time from ImaDoc prevails
319            time_i=sum(timeread)/nbtime;
320        else
321            time_i=(time(iview,num_i1{iview}(ifile),num_j1{iview}(ifile))+time(iview,num_i2{iview}(ifile),num_j2{iview}(ifile)))/2;
322        end
323       
324        % recording the merged field
325        if testima    %in case of input images an image is produced   
326            if isa(MergeData.A,'uint8')
327                bitdepth=8;
328            elseif isa(MergeData.A,'uint16')
329                bitdepth=16;
330            end
331            imwrite(MergeData.A,mergename,'BitDepth',bitdepth);
332            %write xml calibration file
333            siz=size(MergeData.A);
334            npy=siz(1);
335            npx=siz(2);
336            if isfield(MergeData,'VarAttribute')&&isfield(MergeData.VarAttribute{1},'Coord_2')&&isfield(MergeData.VarAttribute{1},'Coord_1')
337                Rangx=MergeData.VarAttribute{1}.Coord_2;
338                Rangy=MergeData.VarAttribute{1}.Coord_1;
339            elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
340                Rangx=[MergeData.AX(1) MergeData.AX(end)];
341                Rangy=[MergeData.AY(1) MergeData.AY(end)];
342            else
343                Rangx=[0.5 npx-0.5];
344                Rangy=[npy-0.5 0.5];%default
345            end
346            pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
347            pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
348            T_x=-pxcmx*Rangx(1)+0.5;
349            T_y=-pxcmy*Rangy(2)+0.5;
350            GeometryCal.focal=1;
351            GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
352            GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
353            ImaDoc.GeometryCalib=GeometryCal;
354            t=struct2xml(ImaDoc);
355            t=set(t,1,'name','ImaDoc');
356            save(t,[filebase_merge '.xml'])     
357            display([filebase_merge '.xml saved'])
358        else
359            MergeData.ListGlobalAttribute={'Project','InputFile_1','InputFile_end','nb_coord','nb_dim','dt','Time','civ'};       
360            MergeData.nb_coord=2;
361            MergeData.nb_dim=2;
362            dt=[];
363            if isfield(Field{1},'dt')&& isnumeric(Field{1}.dt)
364                dt=Field{1}.dt;
365            end
366            for iview =2:numel(Field)
367                if ~(isfield(Field{iview},'dt')&& isequal(Field{iview}.dt,dt))
368                    dt=[];%dt not the same for all fields
369                end
370            end
371            if isempty(dt)
372                MergeData.ListGlobalAttribute(6)=[];
373            else
374               MergeData.dt=dt;
375            end
376            %MergeData.dt=1;
377            MergeData.Time=time_i;
378            error=struct2nc(mergename,MergeData); %save result file
379            if isempty(error)
380                display(['output file ' mergename ' written'])
381            else
382                display(error)
383            end
384        end
385    end
386end
387
388%--------------------------------------------------------------------------   
389function MergeData=merge_field(Data)
390% initiate Matlab  structure for physical field
391if isempty(Data)||~iscell(Data)
392    MergeData=[];
393    return
394end
395MergeData=Data{1};%default
396error=0;
397nbview=length(Data);
398if nbview==1
399    return
400end
401% for iview=1:nbview
402%     if ~isequal(MergeData.ListDimName,Data{iview}.ListDimName)
403%         error=1;
404%     end
405%     if ~isequal(MergeData.ListVarName,Data{iview}.ListVarName)
406%         error=1;
407%     end
408% end
409% if error
410%     MergeData.Txt='ERROR: attempt at merging fields of incompatible type';
411%     return
412% end
413%
414%group the variables (fields of 'FieldData') in cells of variables with the same dimensions
415[CellVarIndex,NbDim,VarTypeCell]=find_field_indices(Data{1});
416%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
417% CellVarIndex=cells of variable index arrays
418ivar_new=0; % index of the current variable in the projected field
419for icell=1:length(CellVarIndex)
420    if NbDim(icell)==1
421        continue
422    end
423    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
424    VarType=VarTypeCell{icell};
425    ivar_X=VarType.coord_x;
426    ivar_Y=VarType.coord_y;
427    ivar_FF=VarType.errorflag;
428    if isempty(ivar_X)
429        test_grid=1;%test for input data on regular grid (e.g. image)coordinates
430    else
431        if length(ivar_Y)~=1
432                msgbox_uvmat('ERROR','y coordinate missing in proj_field.m')
433                return
434        end
435        test_grid=0;
436    end
437    %case of input fields with unstructured coordinates
438    if ~test_grid
439        for ivar=VarIndex
440            VarName=MergeData.ListVarName{ivar};
441            for iview=1:nbview
442                eval(['MergeData.' VarName '=[MergeData.' VarName '; Data{iview}.' VarName '];'])
443            end
444        end
445    %case of fields defined on a structured  grid
446    else 
447        testFF=0;
448        for iview=2:nbview
449            for ivar=VarIndex
450                VarName=MergeData.ListVarName{ivar};
451                if isfield(MergeData,'VarAttribute')
452                    if length(MergeData.VarAttribute)>=ivar && isfield(MergeData.VarAttribute{ivar},'Role') && isequal(MergeData.VarAttribute{ivar}.Role,'errorflag')
453                        testFF=1;
454                    end
455                end
456                eval(['MergeData.' VarName '=MergeData.' VarName '+ Data{iview}.' VarName ';'])
457            end
458        end
459        if testFF
460            nbaver=nbview-MergeData.FF;
461            indgood=find(nbaver>0);
462            for ivar=VarIndex
463                VarName=MergeData.ListVarName{ivar};
464                eval(['MergeData.' VarName '(indgood)=double(MergeData.' VarName '(indgood))./nbaver(indgood);'])
465            end
466        else
467            for ivar=VarIndex
468                VarName=MergeData.ListVarName{ivar};
469                eval(['MergeData.' VarName '=double(MergeData.' VarName ')./nbview;'])
470            end   
471        end
472    end
473end
474   
Note: See TracBrowser for help on using the repository browser.