source: trunk/src/series/extract_rdvision_new.m @ 894

Last change on this file since 894 was 894, checked in by sommeria, 8 years ago

extract rdvision new

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