source: trunk/src/series/extract_rdvision.m @ 841

Last change on this file since 841 was 841, checked in by sommeria, 9 years ago

extract_rdvision corrected

File size: 32.0 KB
Line 
1%'extract_rdvision': relabel an image series with two indices, and correct errors from the RDvision transfer program
2%------------------------------------------------------------------------
3% function ParamOut=extract_rdvision(Param)
4%------------------------------------------------------------------------
5%
6%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
7%
8%OUTPUT
9% ParamOut: sets options in the GUI series.fig needed for the function
10%
11%INPUT:
12% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
13% In batch mode, Param is the name of the corresponding xml file containing the same information
14% when Param.Action.RUN=0 (as activated when the current Action is selected
15% in series), the function ouput paramOut set the activation of the needed GUI elements
16%
17% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
18% see the current structure Param)
19%    .InputTable: cell of input file names, (several lines for multiple input)
20%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
21%    .OutputSubDir: name of the subdirectory for data outputs
22%    .OutputDirExt: directory extension for data outputs
23%    .Action: .ActionName: name of the current activated function
24%             .ActionPath:   path of the current activated function
25%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
26%             .RUN =0 for GUI input, =1 for function activation
27%             .RunMode='local','background', 'cluster': type of function  use
28%             
29%    .IndexRange: set the file or frame indices on which the action must be performed
30%    .FieldTransform: .TransformName: name of the selected transform function
31%                     .TransformPath:   path  of the selected transform function
32%    .InputFields: sub structure describing the input fields withfields
33%              .FieldName: name(s) of the field
34%              .VelType: velocity type
35%              .FieldName_1: name of the second field in case of two input series
36%              .VelType_1: velocity type of the second field in case of two input series
37%              .Coord_y: name of y coordinate variable
38%              .Coord_x: name of x coordinate variable
39%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
40%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
42%=======================================================================
43% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
44%   http://www.legi.grenoble-inp.fr
45%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
46%
47%     This file is part of the toolbox UVMAT.
48%
49%     UVMAT is free software; you can redistribute it and/or modify
50%     it under the terms of the GNU General Public License as published
51%     by the Free Software Foundation; either version 2 of the license,
52%     or (at your option) any later version.
53%
54%     UVMAT is distributed in the hope that it will be useful,
55%     but WITHOUT ANY WARRANTY; without even the implied warranty of
56%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
57%     GNU General Public License (see LICENSE.txt) for more details.
58%=======================================================================
59
60function ParamOut=extract_rdvision(Param) %default output=relabel_i_j(Param)
61
62%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
63if isstruct(Param) && isequal(Param.Action.RUN,0)
64    ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
65    ParamOut.WholeIndexRange='on';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
66    ParamOut.NbSlice='one'; ...%nbre of slices, 'one' prevents splitting in several processes, ('off' by default)
67    ParamOut.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
68    ParamOut.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
69    ParamOut.FieldTransform = 'off';...%can use a transform function
70    ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
71    ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
72    ParamOut.OutputSubDirMode='custom'; %output folder given by the program, not by the GUI series
73     % detect the set of image folder
74    RootPath=Param.InputTable{1,1};
75    ListStruct=dir(RootPath);   
76    ListCells=struct2cell(ListStruct);% transform dir struct to a cell arrray
77    check_bad=strcmp('.',ListCells(1,:))|strcmp('..',ListCells(1,:));%detect the dir '.' to exclude it
78    check_dir=cell2mat(ListCells(4,:));% =1 for directories, =0 for files
79    ListDir=ListCells(1,find(check_dir & ~check_bad));
80    InputTable=cell(numel(ListDir),5);
81    InputTable(:,2)=ListDir';
82    isel=0;
83    for ilist=1:numel(ListDir)
84        ListStructSub=dir(fullfile(RootPath,ListDir{ilist}));
85        ListCellSub=struct2cell(ListStructSub);% transform dir struct to a cell arrray
86        detect_seq=regexp(ListCellSub(1,:),'.seq$');
87        seq_index=find(~cellfun('isempty',detect_seq),1);
88        if ~isempty(seq_index)
89%             msgbox_uvmat('ERROR',['not seq file in ' ListDir{ilist} ': please check the input folders'])
90%         else
91           isel=isel+1;
92           InputTable{isel,1}=RootPath;
93            RootFile=regexprep(ListCellSub{1,seq_index},'.seq$','');
94            InputTable{isel,3}=RootFile;
95        end
96        InputTable{isel,4}='*';
97        InputTable{isel,5}='.seq';
98    end
99    hseries=findobj(allchild(0),'Tag','series');% find the parent GUI 'series'
100    hhseries=guidata(hseries); %handles of the elements in 'series'
101    set(hhseries.InputTable,'Data',InputTable)
102    ParamOut.ActionInput.LogPath=RootPath;% indicate the path for the output info: 0_LOG ....
103return
104end
105
106ParamOut=[];
107%%%%%%%%%%%% STANDARD PART  %%%%%%%%%%%%
108%% read input parameters from an xml file if input is a file name (batch mode)
109checkrun=1;
110if ischar(Param)
111    Param=xml2struct(Param);% read Param as input file (batch case)
112    checkrun=0;
113end
114hseries=findobj(allchild(0),'Tag','series');
115RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
116WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
117
118%% root input file(s) and type
119RootPath=Param.InputTable{1,1};
120if ~isempty(find(~strcmp(RootPath,Param.InputTable(:,1))))% if the Rootpath for each camera are not identical
121    disp_uvmat('ERROR','Rootpath for all cameras must be identical',checkrun)
122    return
123end
124
125% get the set of input file names (cell array filecell), and the lists of
126% input file or frame indices i1_series,i2_series,j1_series,j2_series
127[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
128
129%OutputDir=[Param.OutputSubDir Param.OutputDirExt];
130 
131% numbers of slices and file indices
132nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
133nbfield_i=size(i1_series{1},2); %nb of fields for the i index
134nbfield=nbfield_j*nbfield_i; %total number of fields
135
136%determine the file type on each line from the first input file
137
138FileInfo=get_file_info(filecell{1,1});
139if strcmp(FileInfo.FileType,'rdvision')
140    if ~isequal(FileInfo.NumberOfFrames,nbfield)
141        msgbox_uvmat('ERROR',['the whole series of ' num2str(FileInfo.NumberOfFrames) ' images must be extracted at once'])
142        %rmfield(OutputDir)
143        return
144    end
145    %% interactive input of specific parameters (for RDvision system)
146    display('converting images from RDvision system...')
147else
148    msgbox_uvmat('ERROR','the input is not from rdvision: a .seq or .sqb file must be opened')
149    return
150end
151t=xmltree;
152save(t,fullfile(RootPath,'Running.xml'))%create an xml file to indicate that processing takes place
153
154%% calibration data and timing: read the ImaDoc files
155mode=''; %default
156timecell={};
157itime=0;
158NbSlice_calib={};
159
160%SubDirBase=regexprep(SubDir{1},'\..*','');%take the root part of SubDir, before the first dot '.'
161
162%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
163%%%  loop on the cameras ( #iview)
164%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
165for iview=1:size(Param.InputTable,1)
166    filexml=[fullfile(RootPath,Param.InputTable{iview,3}) '.xml'];%new convention: xml at the level of the image folder
167    if ~exist(filexml,'file')
168        disp_uvmat('ERROR',[filexml ' missing'],checkrun)
169        return
170    end
171    [XmlData,error]=imadoc2struct_special(filexml);
172    if isfield(XmlData,'Time')
173        itime=itime+1;
174        timecell{itime}=XmlData.Time;
175    end
176    if isfield(XmlData,'GeometryCalib') && isfield(XmlData.GeometryCalib,'SliceCoord')
177        NbSlice_calib{1}=size(XmlData.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
178        if ~isequal(NbSlice_calib{1},NbSlice_calib{1})
179            msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
180        end
181    end
182   
183   
184    % correction to RDvision xml file
185    t=xmltree(filexml);
186   
187    % correct Dtj and Dtk
188    NomTypeNew='_1_1';% new file nomencalture by default
189    ImageName='img_1_1.png';% first image name
190    if isfield(XmlData,'NbDtj')
191        uid_NbDtj=find(t,'ImaDoc/Camera/BurstTiming/NbDtj');
192        uid_value=children(t,uid_NbDtj);
193        if ~isempty(uid_value)
194            t=set(t,uid_value(1),'value',num2str(XmlData.NbDtj));
195        end
196    end
197    if isfield(XmlData,'NbDtk')
198        uid_NbDtk=find(t,'ImaDoc/Camera/BurstTiming/NbDtk');
199        uid_value=children(t,uid_NbDtk);
200        if ~isempty(uid_value)
201            t=set(t,uid_value(1),'value',num2str(XmlData.NbDtk));
202        end
203    end
204    if isempty(j1_series{1}) && isfield(XmlData,'NbDti')
205        uid_Dti=find(t,'ImaDoc/Camera/BurstTiming/Dti');
206        t=add(t,uid_Dti,'chardata',num2str(XmlData.Dti));
207        uid_NbDti=find(t,'ImaDoc/Camera/BurstTiming/NbDti');
208        t=add(t,uid_NbDti,'chardata',num2str(XmlData.NbDti));
209        uid_NbDtj=find(t,'ImaDoc/Camera/BurstTiming/NbDtj');
210        uid_NbDtk=find(t,'ImaDoc/Camera/BurstTiming/NbDtk');
211        t=delete(t,uid_NbDtj);
212        t=delete(t,uid_NbDtk);
213        uid_Dtj=find(t,'ImaDoc/Camera/BurstTiming/Dtj');
214        uid_Dtk=find(t,'ImaDoc/Camera/BurstTiming/Dtk');
215        t=delete(t,uid_Dtj);
216        t=delete(t,uid_Dtk);
217        NomTypeNew='_1';
218        ImageName='img_1.png';
219    end
220   
221    %update information of 'Heading'
222    uid_Heading=find(t,'ImaDoc/Heading');
223    if isempty(uid_Heading)
224        [t,uid_Heading]=add(t,1,'element','Heading');
225    end
226    uid_SubCampaign=find(t,'ImaDoc/Heading/SubCampaign');
227    if ~isempty(uid_SubCampaign), t=delete(t,uid_SubCampaign); end
228    uid_Experiment=find(t,'ImaDoc/Heading/Experiment');
229    if ~isempty(uid_Experiment), t=delete(t,uid_Experiment); end
230    uid_Device=find(t,'ImaDoc/Heading/Device');
231    if ~isempty(uid_Device), t=delete(t,uid_Device); end
232    uid_Record=find(t,'ImaDoc/Heading/Record');
233    if ~isempty(uid_Record), t=delete(t,uid_Record); end
234    uid_DateExp=find(t,'ImaDoc/Heading/DateExp');
235    if ~isempty(uid_DateExp), t=delete(t,uid_DateExp); end
236   
237    %indicate the name of the first image (as a check that the xml file is not moved)
238    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
239    if isempty(uid_ImageName)
240        [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
241    end
242    uid_value=children(t,uid_ImageName);
243    if isempty(uid_value)
244        t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
245    else
246        t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
247    end
248   
249    %indicate the date and time of the image acquisition start
250    % if isfield(FileInfo,'binrepertoire') && isfield(FileInfo,'starttime')
251    %     sep_pos=regexp(FileInfo.binrepertoire,'T');
252    %     DateTime=FileInfo.starttime;
253    %     if ~isempty(sep_pos)
254    %         DateTime=[FileInfo.binrepertoire(1:sep_pos-1) ' ' DateTime];
255    %     end
256    %     uid_DateTime=find(t,'ImaDoc/Heading/DateTime');
257    %     if isempty(uid_DateTime)
258    %         [t,uid_DateTime]=add(t,uid_Heading,'element','DateTime');
259    %     end
260    %     uid_value=children(t,uid_DateTime);
261    %     if isempty(uid_value)
262    %         t=add(t,uid_DateTime,'chardata',DateTime);%indicate  name of the first image, with ;png extension
263    %     else
264    %         t=set(t,uid_value(1),'value',DateTime);%indicate  name of the first image, with ;png extension
265    %     end
266    % end
267   
268    %% backup the previous xml file and save the corrected one
269    [success,message]=copyfile(filexml,[filexml '~']);%make backup
270    if success~=1
271        dips(['errror in xml file backup: ' message]);
272        return
273    end
274    save(t,filexml)
275    nbfield2=1;
276    if isfield(XmlData,'Time')
277        nbfield2=size(XmlData.Time,2);
278    end
279   
280    %% get the names of .seq and .sqb files
281    switch Param.InputTable{iview,5}
282        case {'.seq','.sqb'}
283            filename_seq=fullfile(RootPath,Param.InputTable{iview,2},[Param.InputTable{iview,3} '.seq']);
284            filename_sqb=fullfile(RootPath,Param.InputTable{iview,2},[Param.InputTable{iview,3} '.sqb']);
285        otherwise
286            errormsg='input file extension must be .seq or .sqb';
287    end
288    if ~exist(filename_seq,'file')
289        errormsg=[filename_seq ' does not exist'];
290        return
291    end
292   
293    %% get data from .seq file
294    s=ini2struct(filename_seq);
295    SeqData=s.sequenceSettings;
296    SeqData.width=str2double(SeqData.width);
297    SeqData.height=str2double(SeqData.height);
298    SeqData.bytesperpixel=str2double(SeqData.bytesperpixel);
299    SeqData.nb_frames=str2double(s.sequenceSettings.numberoffiles);
300    if isempty(SeqData.binrepertoire)%used when binrepertoire empty, strange feature of rdvision
301        SeqData.binrepertoire=regexprep(s.sequenceSettings.bindirectory,'\\$','');%tranform Windows notation to Linux
302        SeqData.binrepertoire=regexprep(SeqData.binrepertoire,'\','/');
303        [tild,binrepertoire,DirExt]=fileparts(SeqData.binrepertoire);
304        SeqData.binrepertoire=[SeqData.binrepertoire DirExt];
305    end
306%     PathDir=fileparts(PathDir);
307   
308    %% reading the .sqb file
309    m = memmapfile(filename_sqb,'Format', { 'uint32' [1 1] 'offset'; ...
310        'uint32' [1 1] 'garbage1';...
311        'double' [1 1] 'timestamp';...
312        'uint32' [1 1] 'file_idx';...
313        'uint32' [1 1] 'garbage2' },'Repeat',SeqData.nb_frames);
314    %%%%%%%BRICOLAGE in case of unreadable .sqb file
315    %     ind=[60 63:152];%indices of bin files
316    %     lengthimage=w*h*bpp;% lengthof an image record on the binary file
317    %     for ii=1:32*numel(ind)
318    %         data(ii).offset=mod(ii-1,32)*2*lengthimage+lengthimage;%Dalsa_2
319    %         %data(ii).offset=mod(ii-1,32)*2*lengthimage;%Dalsa_1
320    %         data(ii).file_idx=ind(ceil(ii/32));
321    %         data(ii).timestamp=0.2*(ii-1);
322    %     end
323    %%%%%%%
324    for ii=1: numel(m.Data)
325        timestamp(ii)=m.Data(ii).timestamp;
326    end
327    timestamp %todo: check withDt from the xml file
328    [BinSize,errormsg]=binread_rdv_series(RootPath,SeqData,m.Data,nbfield2,NomTypeNew)
329    if ~isempty(errormsg)
330        disp_uvmat('ERROR',errormsg,checkrun)
331        return
332    end
333end
334delete(fullfile(RootPath,'Running.xml'))%delete the  xml file to indicate that processing is finished
335
336%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
337%--------- reads a series of bin files
338%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
339function [BinSize,errormsg]=binread_rdv_series(PathDir,SeqData,SqbData,nbfield2,NomTypeNew)
340% BINREAD_RDV Permet de lire les fichiers bin générés par Hiris à partir du
341% fichier seq associé.
342%   [IMGS,TIMESTAMPS,NB_FRAMES] = BINREAD_RDV(FILENAME,FRAME_IDX) lit
343%   l'image d'indice FRAME_IDX de la séquence FILENAME.
344%
345%   Entrées
346%   -------
347%   FILENAME  : Nom du fichier séquence (.seq).
348%   FRAME_IDX : Indice de l'image à lire. Si FRAME_IDX vaut -1 alors la
349%   séquence est entièrement lue. Si FRAME_IDX est un tableau d'indices
350%   alors toutes les images d'incides correspondant sont lues. Si FRAME_IDX
351%   est un tableau vide alors aucune image n'est lue mais le nombre
352%   d'images et tous les timestamps sont renvoyés. Les indices commencent à
353%   1 et se termines à NB_FRAMES.
354%
355%   Sorties
356%   -------
357%   IMGS        : Images de sortie.
358%   TIMESTAMPS  : Timestaps des images lues.
359%   NB_FRAMES   : Nombres d'images dans la séquence.
360NbBinFile=0;
361BinSize=0;
362errormsg='';
363classname=sprintf('uint%d',SeqData.bytesperpixel*8);
364
365classname=['*' classname];
366BitDepth=8*SeqData.bytesperpixel;%needed to write images (8 or 16 bits)
367binrepertoire=fullfile(PathDir,SeqData.binrepertoire);
368tic
369OutputDir=fullfile(PathDir,SeqData.sequencename)
370if exist(OutputDir,'dir')
371    errormsg=[OutputDir ' already exist, delete it first'];
372    return
373end
374[s,errormsg]=mkdir(OutputDir);
375if s==0
376    return%not able to create new image dir
377end
378for ii=1:SeqData.nb_frames
379    OutputFile=fullfile_uvmat(PathDir,SeqData.sequencename,'img','.png',NomTypeNew,i1,[],j1);% TODO: set NomTypeNew from SeqData.mode
380    fname=fullfile(binrepertoire,sprintf('%s%.5d.bin',SeqData.binfile,SqbData(ii).file_idx));
381    if ii==1 || ~strcmp(fname,fname_prev) % open the bin file if not in use
382        fid=fopen(fname,'rb');
383        fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
384        NbBinFile=NbBinFile+1;%counter of binary files (for checking purpose)
385       
386        BinSize(NbBinFile)=0;% strat counter for new bin file
387    else
388        fclose(fid);%close the previous bin file
389        fid=fopen(fname,'rb');% open the new bin file
390        fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
391    end
392    fname_prev=fname;
393    A=reshape(fread(fid,SeqData.width*SeqData.height,classname),SeqData.width,SeqData.height);%read the current image
394    A=A';
395    BinSize(NbBinFile)=BinSize(NbBinFile)+SeqData.width*SeqData.height*SeqData.bytesperpixel*8; %record bits read
396    j1=[];
397    if ~isequal(nbfield2,1)
398        j1=mod(ii-1,nbfield2)+1;
399    end
400    i1=floor((ii-1)/nbfield2)+1;
401    try
402        imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
403        disp([OutputFile ' written']);
404       % [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
405%         if ~s
406% %             disp_uvmat('ERROR',errormsg,checkrun);
407%             return
408%         end
409    catch ME
410        errormsg=ME.message;
411        return
412    end
413end
414fclose(fid)
415toc
416
417
418
419% for ifile=1:nbfield
420%             update_waitbar(WaitbarHandle,ifile/nbfield)
421%     if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
422%         disp('program stopped by user')
423%         break
424%     end
425%     [A,FileInfo,timestamps]=read_rdvision(filename,ifile);
426%     if ifile==1
427%         classA=class(A);
428%         if strcmp(classA,'uint8')
429%             BitDepth=8;
430%         else
431%         BitDepth=16;
432%         end
433%     end
434%     j1=[];
435%     if ~isequal(nbfield2,1)
436%     j1=mod(ifile-1+first_label,nbfield2)+1;
437%     end
438%     i1=floor((ifile-1+first_label)/nbfield2)+1;
439%     OutputFile=fullfile_uvmat(RootPath{1},OutputDir,'img','.png',NomTypeNew,i1,[],j1);
440%     try
441%         imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
442%     disp([OutputFile ' written']);
443%         [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
444%         if ~s
445%             disp_uvmat('ERROR',errormsg,checkrun);
446%             return
447%         end
448%     catch ME
449%         disp_uvmat('ERROR',ME.message,checkrun);
450%         return
451%     end
452%     
453% end
454
455%'imadoc2struct_special': reads the xml file for image documentation
456%------------------------------------------------------------------------
457% function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
458%
459% OUTPUT:
460% s: structure representing ImaDoc
461%   s.Heading: information about the data hierarchical structure
462%   s.Time: matrix of times
463%   s.TimeUnit
464%  s.GeometryCalib: substructure containing the parameters for geometric calibration
465% errormsg: error message
466%
467% INPUT:
468% ImaDoc: full name of the xml input file with head key ImaDoc
469% option: ='GeometryCalib': read  the data of GeometryCalib, including source point coordinates
470
471function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
472
473%% default input and output
474if ~exist('option','var')
475    option='*';
476end
477errormsg=[];%default
478s.Heading=[];%default
479s.Time=[]; %default
480s.TimeUnit=[]; %default
481s.GeometryCalib=[];
482tsai=[];%default
483
484%% opening the xml file
485if exist(ImaDoc,'file')~=2, errormsg=[ ImaDoc ' does not exist']; return;end;%input file does not exist
486try
487    t=xmltree(ImaDoc);
488catch
489    errormsg={[ImaDoc ' is not a valid xml file']; lasterr};
490    display(errormsg);
491    return
492end
493uid_root=find(t,'/ImaDoc');
494if isempty(uid_root), errormsg=[ImaDoc ' is not an image documentation file ImaDoc']; return; end;%not an ImaDoc .xml file
495
496
497%% Heading
498uid_Heading=find(t,'/ImaDoc/Heading');
499if ~isempty(uid_Heading),
500    uid_Campaign=find(t,'/ImaDoc/Heading/Campaign');
501    uid_Exp=find(t,'/ImaDoc/Heading/Experiment');
502    uid_Device=find(t,'/ImaDoc/Heading/Device');
503    uid_Record=find(t,'/ImaDoc/Heading/Record');
504    uid_FirstImage=find(t,'/ImaDoc/Heading/ImageName');
505    s.Heading.Campaign=get(t,children(t,uid_Campaign),'value');
506    s.Heading.Experiment=get(t,children(t,uid_Exp),'value');
507    s.Heading.Device=get(t,children(t,uid_Device),'value');
508    if ~isempty(uid_Record)
509        s.Heading.Record=get(t,children(t,uid_Record),'value');
510    end
511    s.Heading.ImageName=get(t,children(t,uid_FirstImage),'value');
512end
513
514%% Camera  and timing
515if strcmp(option,'*') || strcmp(option,'Camera')
516    uid_Camera=find(t,'/ImaDoc/Camera');
517    if ~isempty(uid_Camera)
518        uid_ImageSize=find(t,'/ImaDoc/Camera/ImageSize');
519        if ~isempty(uid_ImageSize);
520            ImageSize=get(t,children(t,uid_ImageSize),'value');
521            xindex=findstr(ImageSize,'x');
522            if length(xindex)>=2
523                s.Npx=str2double(ImageSize(1:xindex(1)-1));
524                s.Npy=str2double(ImageSize(xindex(1)+1:xindex(2)-1));
525            end
526        end
527        uid_TimeUnit=find(t,'/ImaDoc/Camera/TimeUnit');
528        if ~isempty(uid_TimeUnit)
529            s.TimeUnit=get(t,children(t,uid_TimeUnit),'value');
530        end
531        uid_BurstTiming=find(t,'/ImaDoc/Camera/BurstTiming');
532        if ~isempty(uid_BurstTiming)
533            for k=1:length(uid_BurstTiming)
534                subt=branch(t,uid_BurstTiming(k));%subtree under BurstTiming
535                % reading Dtk
536                Frequency=get_value(subt,'/BurstTiming/FrameFrequency',1);
537                Dtj=get_value(subt,'/BurstTiming/Dtj',[]);
538                Dtj=Dtj/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
539                NbDtj=get_value(subt,'/BurstTiming/NbDtj',[]);
540                %%%% correction RDvision %%%%
541%                 NbDtj=NbDtj/numel(Dtj);
542%                 s.NbDtj=NbDtj;
543%                 %%%%
544                Dti=get_value(subt,'/BurstTiming/Dti',[]);
545                NbDti=get_value(subt,'/BurstTiming/NbDti',1);
546                 %%%% correction RDvision %%%%
547                if isempty(Dti)% series
548                     Dti=Dtj;
549                      NbDti=NbDtj;
550                     Dtj=[];
551                     s.Dti=Dti;
552                     s.NbDti=NbDti;
553                else
554                    % NbDtj=NbDtj/numel(Dtj);%bursts
555                    if ~isempty(NbDtj)
556                    s.NbDtj=NbDtj/numel(Dtj);%bursts;
557                    else
558                        s.NbDtj=1;
559                    end
560                end
561                %%%% %%%%
562                Dti=Dti/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
563
564                Time_val=get_value(subt,'/BurstTiming/Time',0);%time in TimeUnit
565                if ~isempty(Dti)
566                    Dti=reshape(Dti'*ones(1,NbDti),NbDti*numel(Dti),1); %concatene Dti vector NbDti times
567                    Time_val=[Time_val;Time_val(end)+cumsum(Dti)];%append the times defined by the intervals  Dti
568                end
569                if ~isempty(Dtj)
570                    Dtj=reshape(Dtj'*ones(1,s.NbDtj),1,s.NbDtj*numel(Dtj)); %concatene Dtj vector NbDtj times
571                    Dtj=[0 Dtj];
572                    Time_val=Time_val*ones(1,numel(Dtj))+ones(numel(Time_val),1)*cumsum(Dtj);% produce a time matrix with Dtj
573                end
574                % reading Dtk
575                Dtk=get_value(subt,'/BurstTiming/Dtk',[]);
576                NbDtk=get_value(subt,'/BurstTiming/NbDtk',1);
577                %%%% correction RDvision %%%%
578                if ~isequal(NbDtk,1)
579                    NbDtk=-1+(NbDtk+1)/(NbDti+1);
580                end
581                s.NbDtk=NbDtk;
582                %%%%%
583                if isempty(Dtk)
584                    s.Time=[s.Time;Time_val];
585                else
586                    for kblock=1:NbDtk+1
587                        Time_val_k=Time_val+(kblock-1)*Dtk;
588                        s.Time=[s.Time;Time_val_k];
589                    end
590                end
591            end
592        end
593    end
594end
595
596%% motor
597if strcmp(option,'*') || strcmp(option,'GeometryCalib')
598    uid_subtree=find(t,'/ImaDoc/TranslationMotor');
599    if length(uid_subtree)==1
600        subt=branch(t,uid_subtree);%subtree under GeometryCalib
601       [s.TranslationMotor,errormsg]=read_subtree(subt,{'Nbslice','ZStart','ZEnd'},[1 1 1],[1 1 1]);
602    end
603end
604%%  geometric calibration
605if strcmp(option,'*') || strcmp(option,'GeometryCalib')
606    uid_GeometryCalib=find(t,'/ImaDoc/GeometryCalib');
607    if ~isempty(uid_GeometryCalib)
608        if length(uid_GeometryCalib)>1
609            errormsg=['More than one GeometryCalib in ' filecivxml];
610            return
611        end
612        subt=branch(t,uid_GeometryCalib);%subtree under GeometryCalib
613        cont=get(subt,1,'contents');
614        if ~isempty(cont)
615            uid_CalibrationType=find(subt,'/GeometryCalib/CalibrationType');
616            if isequal(length(uid_CalibrationType),1)
617                tsai.CalibrationType=get(subt,children(subt,uid_CalibrationType),'value');
618            end
619            uid_CoordUnit=find(subt,'/GeometryCalib/CoordUnit');
620            if isequal(length(uid_CoordUnit),1)
621                tsai.CoordUnit=get(subt,children(subt,uid_CoordUnit),'value');
622            end
623            uid_fx_fy=find(subt,'/GeometryCalib/fx_fy');
624            focal=[];%default fro old convention (Reg Wilson)
625            if isequal(length(uid_fx_fy),1)
626                tsai.fx_fy=str2num(get(subt,children(subt,uid_fx_fy),'value'));
627            else %old convention (Reg Wilson)
628                uid_focal=find(subt,'/GeometryCalib/focal');
629                uid_dpx_dpy=find(subt,'/GeometryCalib/dpx_dpy');
630                uid_sx=find(subt,'/GeometryCalib/sx');
631                if ~isempty(uid_focal) && ~isempty(uid_dpx_dpy) && ~isempty(uid_sx)
632                    dpx_dpy=str2num(get(subt,children(subt,uid_dpx_dpy),'value'));
633                    sx=str2num(get(subt,children(subt,uid_sx),'value'));
634                    focal=str2num(get(subt,children(subt,uid_focal),'value'));
635                    tsai.fx_fy(1)=sx*focal/dpx_dpy(1);
636                    tsai.fx_fy(2)=focal/dpx_dpy(2);
637                end
638            end
639            uid_Cx_Cy=find(subt,'/GeometryCalib/Cx_Cy');
640            if ~isempty(uid_Cx_Cy)
641                tsai.Cx_Cy=str2num(get(subt,children(subt,uid_Cx_Cy),'value'));
642            end
643            uid_kc=find(subt,'/GeometryCalib/kc');
644            if ~isempty(uid_kc)
645                tsai.kc=str2double(get(subt,children(subt,uid_kc),'value'));
646            else %old convention (Reg Wilson)
647                uid_kappa1=find(subt,'/GeometryCalib/kappa1');
648                if ~isempty(uid_kappa1)&& ~isempty(focal)
649                    kappa1=str2double(get(subt,children(subt,uid_kappa1),'value'));
650                    tsai.kc=-kappa1*focal*focal;
651                end
652            end
653            uid_Tx_Ty_Tz=find(subt,'/GeometryCalib/Tx_Ty_Tz');
654            if ~isempty(uid_Tx_Ty_Tz)
655                tsai.Tx_Ty_Tz=str2num(get(subt,children(subt,uid_Tx_Ty_Tz),'value'));
656            end
657            uid_R=find(subt,'/GeometryCalib/R');
658            if ~isempty(uid_R)
659                RR=get(subt,children(subt,uid_R),'value');
660                if length(RR)==3
661                    tsai.R=[str2num(RR{1});str2num(RR{2});str2num(RR{3})];
662                end
663            end
664           
665            %look for laser plane definitions
666            uid_Angle=find(subt,'/GeometryCalib/PlaneAngle');
667            uid_Pos=find(subt,'/GeometryCalib/SliceCoord');
668            if isempty(uid_Pos)
669                uid_Pos=find(subt,'/GeometryCalib/PlanePos');%old convention
670            end
671            if ~isempty(uid_Angle)
672                tsai.PlaneAngle=str2num(get(subt,children(subt,uid_Angle),'value'));
673            end
674            if ~isempty(uid_Pos)
675                for j=1:length(uid_Pos)
676                    tsai.SliceCoord(j,:)=str2num(get(subt,children(subt,uid_Pos(j)),'value'));
677                end
678                uid_DZ=find(subt,'/GeometryCalib/SliceDZ');
679                uid_NbSlice=find(subt,'/GeometryCalib/NbSlice');
680                if ~isempty(uid_DZ) && ~isempty(uid_NbSlice)
681                    DZ=str2double(get(subt,children(subt,uid_DZ),'value'));
682                    NbSlice=get(subt,children(subt,uid_NbSlice),'value');
683                    if isequal(NbSlice,'volume')
684                        tsai.NbSlice='volume';
685                        NbSlice=NbDtj+1;
686                    else
687                        tsai.NbSlice=str2double(NbSlice);
688                    end
689                    tsai.SliceCoord=ones(NbSlice,1)*tsai.SliceCoord+DZ*(0:NbSlice-1)'*[0 0 1];
690                end
691            end   
692            tsai.SliceAngle=get_value(subt,'/GeometryCalib/SliceAngle',[0 0 0]);
693            tsai.VolumeScan=get_value(subt,'/GeometryCalib/VolumeScan','n');
694            tsai.InterfaceCoord=get_value(subt,'/GeometryCalib/InterfaceCoord',[0 0 0]);
695            tsai.RefractionIndex=get_value(subt,'/GeometryCalib/RefractionIndex',1);
696           
697            if strcmp(option,'GeometryCalib')
698                tsai.PointCoord=get_value(subt,'/GeometryCalib/SourceCalib/PointCoord',[0 0 0 0 0]);
699            end
700            s.GeometryCalib=tsai;
701        end
702    end
703end
704
705%--------------------------------------------------
706%  read a subtree
707% INPUT:
708% t: xltree
709% head_element: head elelemnt of the subtree
710% Data, structure containing
711%    .Key: element name
712%    .Type: type of element ('charg', 'float'....)
713%    .NbOccur: nbre of occurrence, NaN for un specified number
714function [s,errormsg]=read_subtree(subt,Data,NbOccur,NumTest)
715%--------------------------------------------------
716s=[];%default
717errormsg='';
718head_element=get(subt,1,'name');
719    cont=get(subt,1,'contents');
720    if ~isempty(cont)
721        for ilist=1:length(Data)
722            uid_key=find(subt,[head_element '/' Data{ilist}]);
723            if ~isequal(length(uid_key),NbOccur(ilist))
724                errormsg=['wrong number of occurence for ' Data{ilist}];
725                return
726            end
727            for ival=1:length(uid_key)
728                val=get(subt,children(subt,uid_key(ival)),'value');
729                if ~NumTest(ilist)
730                    eval(['s.' Data{ilist} '=val;']);
731                else
732                    eval(['s.' Data{ilist} '=str2double(val);'])
733                end
734            end
735        end
736    end
737
738
739%--------------------------------------------------
740%  read an xml element
741function val=get_value(t,label,default)
742%--------------------------------------------------
743val=default;
744uid=find(t,label);%find the element iud(s)
745if ~isempty(uid) %if the element named label exists
746   uid_child=children(t,uid);%find the children
747   if ~isempty(uid_child)
748       data=get(t,uid_child,'type');%get the type of child
749       if iscell(data)% case of multiple element
750           for icell=1:numel(data)
751               val_read=str2num(get(t,uid_child(icell),'value'));
752               if ~isempty(val_read)
753                   val(icell,:)=val_read;
754               end
755           end
756%           val=val';
757       else % case of unique element value
758           val_read=str2num(get(t,uid_child,'value'));
759           if ~isempty(val_read)
760               val=val_read;
761           else
762              val=get(t,uid_child,'value');%char string data
763           end
764       end
765   end
766end
767
768
769
770
Note: See TracBrowser for help on using the repository browser.