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

Last change on this file since 829 was 826, checked in by sommeria, 10 years ago

extract_rdvision updated to treat all cameras at once

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