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

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

extract_rdvision updated for the new version and bug corrected in vector display for netcdf files

File size: 32.3 KB
Line 
1%'extract_rdvision': relabel an image series with two indices, and correct errors from the RDvision transfer program
2%------------------------------------------------------------------------
3% function ParamOut=extract_rdvision(Param)
4%------------------------------------------------------------------------
5%
6%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
7%
8%OUTPUT
9% ParamOut: sets options in the GUI series.fig needed for the function
10%
11%INPUT:
12% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
13% In batch mode, Param is the name of the corresponding xml file containing the same information
14% when Param.Action.RUN=0 (as activated when the current Action is selected
15% in series), the function ouput paramOut set the activation of the needed GUI elements
16%
17% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
18% see the current structure Param)
19%    .InputTable: cell of input file names, (several lines for multiple input)
20%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
21%    .OutputSubDir: name of the subdirectory for data outputs
22%    .OutputDirExt: directory extension for data outputs
23%    .Action: .ActionName: name of the current activated function
24%             .ActionPath:   path of the current activated function
25%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
26%             .RUN =0 for GUI input, =1 for function activation
27%             .RunMode='local','background', 'cluster': type of function  use
28%             
29%    .IndexRange: set the file or frame indices on which the action must be performed
30%    .FieldTransform: .TransformName: name of the selected transform function
31%                     .TransformPath:   path  of the selected transform function
32%    .InputFields: sub structure describing the input fields withfields
33%              .FieldName: name(s) of the field
34%              .VelType: velocity type
35%              .FieldName_1: name of the second field in case of two input series
36%              .VelType_1: velocity type of the second field in case of two input series
37%              .Coord_y: name of y coordinate variable
38%              .Coord_x: name of x coordinate variable
39%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
40%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
42%=======================================================================
43% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
44%   http://www.legi.grenoble-inp.fr
45%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
46%
47%     This file is part of the toolbox UVMAT.
48%
49%     UVMAT is free software; you can redistribute it and/or modify
50%     it under the terms of the GNU General Public License as published
51%     by the Free Software Foundation; either version 2 of the license,
52%     or (at your option) any later version.
53%
54%     UVMAT is distributed in the hope that it will be useful,
55%     but WITHOUT ANY WARRANTY; without even the implied warranty of
56%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
57%     GNU General Public License (see LICENSE.txt) for more details.
58%=======================================================================
59
60function ParamOut=extract_rdvision(Param) %default output=relabel_i_j(Param)
61
62%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
63if isstruct(Param) && isequal(Param.Action.RUN,0)
64    ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
65    ParamOut.WholeIndexRange='on';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
66    ParamOut.NbSlice='one'; ...%nbre of slices, 'one' prevents splitting in several processes, ('off' by default)
67    ParamOut.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
68    ParamOut.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
69    ParamOut.FieldTransform = 'off';...%can use a transform function
70    ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
71    ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
72    ParamOut.OutputSubDirMode='custom'; %output folder given by the program, not by the GUI series
73     % detect the set of image folder
74    RootPath=Param.InputTable{1,1};
75    ListStruct=dir(RootPath);   
76    ListCells=struct2cell(ListStruct);% transform dir struct to a cell arrray
77    check_bad=strcmp('.',ListCells(1,:))|strcmp('..',ListCells(1,:));%detect the dir '.' to exclude it
78    check_dir=cell2mat(ListCells(4,:));% =1 for directories, =0 for files
79    ListDir=ListCells(1,find(check_dir & ~check_bad));
80%     InputTable=cell(numel(ListDir),5);
81%     InputTable(:,2)=ListDir';
82    isel=0;
83    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 with respect to the xml file',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    end
280    if min(time_diff_min)<-0.005
281        disp_uvmat('WARNING',['timestamps is lower than xml time by' num2str(min(time_diff_min))],checkrun)
282        checkpreserve=1;
283    end
284    if checkpreserve
285          disp(  'max and min of timestamp-xml time for each index i:')
286          disp(time_diff_max)
287          disp(time_diff_min)           
288    end
289    [BinList,errormsg]=binread_rdv_series(RootPath,SeqData,m.Data,nbfield2,NomTypeNew);
290    if ~isempty(errormsg)
291        disp_uvmat('ERROR',errormsg,checkrun)
292        return
293    end
294    % check the existence of the expected output image files (from the xml)
295    for i1=1:npi-1
296        for j1=1:npj-1
297            OutputFile=fullfile_uvmat(RootPath,SeqData.sequencename,'img','.png',NomTypeNew,i1,[],j1);% TODO: set NomTypeNew from SeqData.mode
298            A=imread(OutputFile);% check image reading (stop if error)
299        end
300    end
301   
302    % check images
303   
304    delete(fullfile(RootPath,'Running.xml'))%delete the  xml file to indicate that processing is finished
305    if ~checkpreserve
306        for ibin=1:numel(BinList)
307            delete(BinList{ibin})
308        end
309        rmdir(fullfile(RootPath,Param.InputTable{iview,2}))
310    end
311end
312
313%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
314%--------- reads a series of bin files
315%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
316function [BinList,errormsg]=binread_rdv_series(PathDir,SeqData,SqbData,nbfield2,NomTypeNew)
317% BINREAD_RDV Permet de lire les fichiers bin gᅵnᅵrᅵs par Hiris ᅵ partir du
318% fichier seq associᅵ.
319%   [IMGS,TIMESTAMPS,NB_FRAMES] = BINREAD_RDV(FILENAME,FRAME_IDX) lit
320%   l'image d'indice FRAME_IDX de la sï¿œquence FILENAME.
321%
322%   Entrï¿œes
323%   -------
324%   FILENAME  : Nom du fichier sï¿œquence (.seq).
325%   FRAME_IDX : Indice de l'image ï¿œ lire. Si FRAME_IDX vaut -1 alors la
326%   sï¿œquence est entiï¿œrement lue. Si FRAME_IDX est un tableau d'indices
327%   alors toutes les images d'incides correspondant sont lues. Si FRAME_IDX
328%   est un tableau vide alors aucune image n'est lue mais le nombre
329%   d'images et tous les timestamps sont renvoyï¿œs. Les indices commencent ï¿œ
330%   1 et se termines ï¿œ NB_FRAMES.
331%
332%   Sorties
333%   -------
334%   IMGS        : Images de sortie.
335%   TIMESTAMPS  : Timestaps des images lues.
336%   NB_FRAMES   : Nombres d'images dans la sï¿œquence.
337NbBinFile=0;
338BinSize=0;
339fid=0;
340errormsg='';
341classname=sprintf('uint%d',SeqData.bytesperpixel*8);
342
343classname=['*' classname];
344BitDepth=8*SeqData.bytesperpixel;%needed to write images (8 or 16 bits)
345binrepertoire=fullfile(PathDir,SeqData.binrepertoire);
346OutputDir=fullfile(PathDir,SeqData.sequencename);
347if ~exist(OutputDir,'dir')
348    %     errormsg=[OutputDir ' already exist, delete it first'];
349    %     return
350    % end
351    [s,errormsg]=mkdir(OutputDir);
352   
353    if s==0
354        disp(errormsg)
355        return%not able to create new image dir
356    end
357end
358bin_file_counter=0;
359for ii=1:SeqData.nb_frames
360    j1=[];
361    if ~isequal(nbfield2,1)
362        j1=mod(ii-1,nbfield2)+1;
363    end
364    i1=floor((ii-1)/nbfield2)+1;
365    OutputFile=fullfile_uvmat(PathDir,SeqData.sequencename,'img','.png',NomTypeNew,i1,[],j1);% TODO: set NomTypeNew from SeqData.mode
366    fname=fullfile(binrepertoire,sprintf('%s%.5d.bin',SeqData.binfile,SqbData(ii).file_idx));
367    if exist(OutputFile,'file')
368        fid=0;
369    else
370        if fid==0 || ~strcmp(fname,fname_prev) % open the bin file if not in use
371            if fid~=0
372                fclose(fid);%close the previous bin file if relevant
373            end
374            [fid,msg]=fopen(fname,'rb');
375            if isequal(fid,-1)
376                errormsg=['error in opening ' fname ': ' msg];
377                return
378            else
379                disp([fname ' opened for reading'])
380                bin_file_counter=bin_file_counter+1;
381                BinList{bin_file_counter}=fname;
382            end
383            fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
384            NbBinFile=NbBinFile+1;%counter of binary files (for checking purpose)
385            BinSize(NbBinFile)=0;% strat counter for new bin file
386        else
387            fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
388        end
389        fname_prev=fname;
390        A=reshape(fread(fid,SeqData.width*SeqData.height,classname),SeqData.width,SeqData.height);%read the current image
391        A=A';
392        BinSize(NbBinFile)=BinSize(NbBinFile)+SeqData.width*SeqData.height*SeqData.bytesperpixel*8; %record bits read
393        try
394            imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
395            disp([OutputFile ' written']);
396            % [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
397            %         if ~s
398            % %             disp_uvmat('ERROR',errormsg,checkrun);
399            %             return
400            %         end
401        catch ME
402            errormsg=ME.message;
403            return
404        end
405    end
406end
407if fid~=0
408fclose(fid)
409end
410
411
412
413
414% for ifile=1:nbfield
415%             update_waitbar(WaitbarHandle,ifile/nbfield)
416%     if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
417%         disp('program stopped by user')
418%         break
419%     end
420%     [A,FileInfo,timestamps]=read_rdvision(filename,ifile);
421%     if ifile==1
422%         classA=class(A);
423%         if strcmp(classA,'uint8')
424%             BitDepth=8;
425%         else
426%         BitDepth=16;
427%         end
428%     end
429%     j1=[];
430%     if ~isequal(nbfield2,1)
431%     j1=mod(ifile-1+first_label,nbfield2)+1;
432%     end
433%     i1=floor((ifile-1+first_label)/nbfield2)+1;
434%     OutputFile=fullfile_uvmat(RootPath{1},OutputDir,'img','.png',NomTypeNew,i1,[],j1);
435%     try
436%         imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
437%     disp([OutputFile ' written']);
438%         [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
439%         if ~s
440%             disp_uvmat('ERROR',errormsg,checkrun);
441%             return
442%         end
443%     catch ME
444%         disp_uvmat('ERROR',ME.message,checkrun);
445%         return
446%     end
447%
448% end
449
450%'imadoc2struct_special': reads the xml file for image documentation
451%------------------------------------------------------------------------
452% function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
453%
454% OUTPUT:
455% s: structure representing ImaDoc
456%   s.Heading: information about the data hierarchical structure
457%   s.Time: matrix of times
458%   s.TimeUnit
459%  s.GeometryCalib: substructure containing the parameters for geometric calibration
460% errormsg: error message
461%
462% INPUT:
463% ImaDoc: full name of the xml input file with head key ImaDoc
464% option: ='GeometryCalib': read  the data of GeometryCalib, including source point coordinates
465
466function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
467
468%% default input and output
469if ~exist('option','var')
470    option='*';
471end
472errormsg=[];%default
473s.Heading=[];%default
474s.Time=[]; %default
475s.TimeUnit=[]; %default
476s.GeometryCalib=[];
477tsai=[];%default
478
479%% opening the xml file
480if exist(ImaDoc,'file')~=2, errormsg=[ ImaDoc ' does not exist']; return;end;%input file does not exist
481try
482    t=xmltree(ImaDoc);
483catch
484    errormsg={[ImaDoc ' is not a valid xml file']; lasterr};
485    display(errormsg);
486    return
487end
488uid_root=find(t,'/ImaDoc');
489if isempty(uid_root), errormsg=[ImaDoc ' is not an image documentation file ImaDoc']; return; end;%not an ImaDoc .xml file
490
491
492%% Heading
493uid_Heading=find(t,'/ImaDoc/Heading');
494if ~isempty(uid_Heading),
495    uid_Campaign=find(t,'/ImaDoc/Heading/Campaign');
496    uid_Exp=find(t,'/ImaDoc/Heading/Experiment');
497    uid_Device=find(t,'/ImaDoc/Heading/Device');
498    uid_Record=find(t,'/ImaDoc/Heading/Record');
499    uid_FirstImage=find(t,'/ImaDoc/Heading/ImageName');
500    s.Heading.Campaign=get(t,children(t,uid_Campaign),'value');
501    s.Heading.Experiment=get(t,children(t,uid_Exp),'value');
502    s.Heading.Device=get(t,children(t,uid_Device),'value');
503    if ~isempty(uid_Record)
504        s.Heading.Record=get(t,children(t,uid_Record),'value');
505    end
506    s.Heading.ImageName=get(t,children(t,uid_FirstImage),'value');
507end
508
509%% Camera  and timing
510if strcmp(option,'*') || strcmp(option,'Camera')
511    uid_Camera=find(t,'/ImaDoc/Camera');
512    if ~isempty(uid_Camera)
513        uid_ImageSize=find(t,'/ImaDoc/Camera/ImageSize');
514        if ~isempty(uid_ImageSize);
515            ImageSize=get(t,children(t,uid_ImageSize),'value');
516            xindex=findstr(ImageSize,'x');
517            if length(xindex)>=2
518                s.Npx=str2double(ImageSize(1:xindex(1)-1));
519                s.Npy=str2double(ImageSize(xindex(1)+1:xindex(2)-1));
520            end
521        end
522        uid_TimeUnit=find(t,'/ImaDoc/Camera/TimeUnit');
523        if ~isempty(uid_TimeUnit)
524            s.TimeUnit=get(t,children(t,uid_TimeUnit),'value');
525        end
526        uid_BurstTiming=find(t,'/ImaDoc/Camera/BurstTiming');
527        if ~isempty(uid_BurstTiming)
528            for k=1:length(uid_BurstTiming)
529                subt=branch(t,uid_BurstTiming(k));%subtree under BurstTiming
530                % reading Dtk
531                Frequency=get_value(subt,'/BurstTiming/FrameFrequency',1);
532                Dtj=get_value(subt,'/BurstTiming/Dtj',[]);
533                Dtj=Dtj/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
534                NbDtj=get_value(subt,'/BurstTiming/NbDtj',[]);
535                %%%% correction RDvision %%%%
536%                 NbDtj=NbDtj/numel(Dtj);
537%                 s.NbDtj=NbDtj;
538%                 %%%%
539                Dti=get_value(subt,'/BurstTiming/Dti',[]);
540                NbDti=get_value(subt,'/BurstTiming/NbDti',1);
541                 %%%% correction RDvision %%%%
542                if isempty(Dti)% series
543                     Dti=Dtj;
544                      NbDti=NbDtj;
545                     Dtj=[];
546                     s.Dti=Dti;
547                     s.NbDti=NbDti;
548                else
549                    % NbDtj=NbDtj/numel(Dtj);%bursts
550                    if ~isempty(NbDtj)
551                    s.NbDtj=NbDtj/numel(Dtj);%bursts;
552                    else
553                        s.NbDtj=1;
554                    end
555                end
556                %%%% %%%%
557                Dti=Dti/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
558
559                Time_val=get_value(subt,'/BurstTiming/Time',0);%time in TimeUnit
560                if ~isempty(Dti)
561                    Dti=reshape(Dti'*ones(1,NbDti),NbDti*numel(Dti),1); %concatene Dti vector NbDti times
562                    Time_val=[Time_val;Time_val(end)+cumsum(Dti)];%append the times defined by the intervals  Dti
563                end
564                if ~isempty(Dtj)
565                    Dtj=reshape(Dtj'*ones(1,s.NbDtj),1,s.NbDtj*numel(Dtj)); %concatene Dtj vector NbDtj times
566                    Dtj=[0 Dtj];
567                    Time_val=Time_val*ones(1,numel(Dtj))+ones(numel(Time_val),1)*cumsum(Dtj);% produce a time matrix with Dtj
568                end
569                % reading Dtk
570                Dtk=get_value(subt,'/BurstTiming/Dtk',[]);
571                NbDtk=get_value(subt,'/BurstTiming/NbDtk',1);
572                %%%% correction RDvision %%%%
573                if ~isequal(NbDtk,1)
574                    NbDtk=-1+(NbDtk+1)/(NbDti+1);
575                end
576                s.NbDtk=NbDtk;
577                %%%%%
578                if isempty(Dtk)
579                    s.Time=[s.Time;Time_val];
580                else
581                    for kblock=1:NbDtk+1
582                        Time_val_k=Time_val+(kblock-1)*Dtk;
583                        s.Time=[s.Time;Time_val_k];
584                    end
585                end
586            end
587        end
588    end
589end
590
591%% motor
592if strcmp(option,'*') || strcmp(option,'GeometryCalib')
593    uid_subtree=find(t,'/ImaDoc/TranslationMotor');
594    if length(uid_subtree)==1
595        subt=branch(t,uid_subtree);%subtree under GeometryCalib
596       [s.TranslationMotor,errormsg]=read_subtree(subt,{'Nbslice','ZStart','ZEnd'},[1 1 1],[1 1 1]);
597    end
598end
599%%  geometric calibration
600if strcmp(option,'*') || strcmp(option,'GeometryCalib')
601    uid_GeometryCalib=find(t,'/ImaDoc/GeometryCalib');
602    if ~isempty(uid_GeometryCalib)
603        if length(uid_GeometryCalib)>1
604            errormsg=['More than one GeometryCalib in ' filecivxml];
605            return
606        end
607        subt=branch(t,uid_GeometryCalib);%subtree under GeometryCalib
608        cont=get(subt,1,'contents');
609        if ~isempty(cont)
610            uid_CalibrationType=find(subt,'/GeometryCalib/CalibrationType');
611            if isequal(length(uid_CalibrationType),1)
612                tsai.CalibrationType=get(subt,children(subt,uid_CalibrationType),'value');
613            end
614            uid_CoordUnit=find(subt,'/GeometryCalib/CoordUnit');
615            if isequal(length(uid_CoordUnit),1)
616                tsai.CoordUnit=get(subt,children(subt,uid_CoordUnit),'value');
617            end
618            uid_fx_fy=find(subt,'/GeometryCalib/fx_fy');
619            focal=[];%default fro old convention (Reg Wilson)
620            if isequal(length(uid_fx_fy),1)
621                tsai.fx_fy=str2num(get(subt,children(subt,uid_fx_fy),'value'));
622            else %old convention (Reg Wilson)
623                uid_focal=find(subt,'/GeometryCalib/focal');
624                uid_dpx_dpy=find(subt,'/GeometryCalib/dpx_dpy');
625                uid_sx=find(subt,'/GeometryCalib/sx');
626                if ~isempty(uid_focal) && ~isempty(uid_dpx_dpy) && ~isempty(uid_sx)
627                    dpx_dpy=str2num(get(subt,children(subt,uid_dpx_dpy),'value'));
628                    sx=str2num(get(subt,children(subt,uid_sx),'value'));
629                    focal=str2num(get(subt,children(subt,uid_focal),'value'));
630                    tsai.fx_fy(1)=sx*focal/dpx_dpy(1);
631                    tsai.fx_fy(2)=focal/dpx_dpy(2);
632                end
633            end
634            uid_Cx_Cy=find(subt,'/GeometryCalib/Cx_Cy');
635            if ~isempty(uid_Cx_Cy)
636                tsai.Cx_Cy=str2num(get(subt,children(subt,uid_Cx_Cy),'value'));
637            end
638            uid_kc=find(subt,'/GeometryCalib/kc');
639            if ~isempty(uid_kc)
640                tsai.kc=str2double(get(subt,children(subt,uid_kc),'value'));
641            else %old convention (Reg Wilson)
642                uid_kappa1=find(subt,'/GeometryCalib/kappa1');
643                if ~isempty(uid_kappa1)&& ~isempty(focal)
644                    kappa1=str2double(get(subt,children(subt,uid_kappa1),'value'));
645                    tsai.kc=-kappa1*focal*focal;
646                end
647            end
648            uid_Tx_Ty_Tz=find(subt,'/GeometryCalib/Tx_Ty_Tz');
649            if ~isempty(uid_Tx_Ty_Tz)
650                tsai.Tx_Ty_Tz=str2num(get(subt,children(subt,uid_Tx_Ty_Tz),'value'));
651            end
652            uid_R=find(subt,'/GeometryCalib/R');
653            if ~isempty(uid_R)
654                RR=get(subt,children(subt,uid_R),'value');
655                if length(RR)==3
656                    tsai.R=[str2num(RR{1});str2num(RR{2});str2num(RR{3})];
657                end
658            end
659           
660            %look for laser plane definitions
661            uid_Angle=find(subt,'/GeometryCalib/PlaneAngle');
662            uid_Pos=find(subt,'/GeometryCalib/SliceCoord');
663            if isempty(uid_Pos)
664                uid_Pos=find(subt,'/GeometryCalib/PlanePos');%old convention
665            end
666            if ~isempty(uid_Angle)
667                tsai.PlaneAngle=str2num(get(subt,children(subt,uid_Angle),'value'));
668            end
669            if ~isempty(uid_Pos)
670                for j=1:length(uid_Pos)
671                    tsai.SliceCoord(j,:)=str2num(get(subt,children(subt,uid_Pos(j)),'value'));
672                end
673                uid_DZ=find(subt,'/GeometryCalib/SliceDZ');
674                uid_NbSlice=find(subt,'/GeometryCalib/NbSlice');
675                if ~isempty(uid_DZ) && ~isempty(uid_NbSlice)
676                    DZ=str2double(get(subt,children(subt,uid_DZ),'value'));
677                    NbSlice=get(subt,children(subt,uid_NbSlice),'value');
678                    if isequal(NbSlice,'volume')
679                        tsai.NbSlice='volume';
680                        NbSlice=NbDtj+1;
681                    else
682                        tsai.NbSlice=str2double(NbSlice);
683                    end
684                    tsai.SliceCoord=ones(NbSlice,1)*tsai.SliceCoord+DZ*(0:NbSlice-1)'*[0 0 1];
685                end
686            end   
687            tsai.SliceAngle=get_value(subt,'/GeometryCalib/SliceAngle',[0 0 0]);
688            tsai.VolumeScan=get_value(subt,'/GeometryCalib/VolumeScan','n');
689            tsai.InterfaceCoord=get_value(subt,'/GeometryCalib/InterfaceCoord',[0 0 0]);
690            tsai.RefractionIndex=get_value(subt,'/GeometryCalib/RefractionIndex',1);
691           
692            if strcmp(option,'GeometryCalib')
693                tsai.PointCoord=get_value(subt,'/GeometryCalib/SourceCalib/PointCoord',[0 0 0 0 0]);
694            end
695            s.GeometryCalib=tsai;
696        end
697    end
698end
699
700%--------------------------------------------------
701%  read a subtree
702% INPUT:
703% t: xltree
704% head_element: head elelemnt of the subtree
705% Data, structure containing
706%    .Key: element name
707%    .Type: type of element ('charg', 'float'....)
708%    .NbOccur: nbre of occurrence, NaN for un specified number
709function [s,errormsg]=read_subtree(subt,Data,NbOccur,NumTest)
710%--------------------------------------------------
711s=[];%default
712errormsg='';
713head_element=get(subt,1,'name');
714    cont=get(subt,1,'contents');
715    if ~isempty(cont)
716        for ilist=1:length(Data)
717            uid_key=find(subt,[head_element '/' Data{ilist}]);
718            if ~isequal(length(uid_key),NbOccur(ilist))
719                errormsg=['wrong number of occurence for ' Data{ilist}];
720                return
721            end
722            for ival=1:length(uid_key)
723                val=get(subt,children(subt,uid_key(ival)),'value');
724                if ~NumTest(ilist)
725                    eval(['s.' Data{ilist} '=val;']);
726                else
727                    eval(['s.' Data{ilist} '=str2double(val);'])
728                end
729            end
730        end
731    end
732
733
734%--------------------------------------------------
735%  read an xml element
736function val=get_value(t,label,default)
737%--------------------------------------------------
738val=default;
739uid=find(t,label);%find the element iud(s)
740if ~isempty(uid) %if the element named label exists
741   uid_child=children(t,uid);%find the children
742   if ~isempty(uid_child)
743       data=get(t,uid_child,'type');%get the type of child
744       if iscell(data)% case of multiple element
745           for icell=1:numel(data)
746               val_read=str2num(get(t,uid_child(icell),'value'));
747               if ~isempty(val_read)
748                   val(icell,:)=val_read;
749               end
750           end
751%           val=val';
752       else % case of unique element value
753           val_read=str2num(get(t,uid_child,'value'));
754           if ~isempty(val_read)
755               val=val_read;
756           else
757              val=get(t,uid_child,'value');%char string data
758           end
759       end
760   end
761end
762
763
764
765
Note: See TracBrowser for help on using the repository browser.