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

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

various bug repair

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