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

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