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

Last change on this file since 339 was 335, checked in by sommeria, 13 years ago

bug corrected in merge_proj: result images are now writen as .png

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