source: trunk/src/series/sub_background.m @ 474

Last change on this file since 474 was 474, checked in by sommeria, 12 years ago

functions adpated to mode background

File size: 21.0 KB
RevLine 
[457]1%'sub_background': substract a sliding background to an image series
2% This is an example of action on a series of input images
[169]3%------------------------------------------------------------------------
[24]4% Method:
5    %calculate the background image by sorting the luminosity of each point
6    % over a sliding sub-sequence of 'nbaver_ima' images.
7    % The luminosity value of rank 'rank' is selected as the
8    % 'background'. rank=nbimages/2 gives the median value.  Smaller values are appropriate
9    % for a dense set of particles. The extrem value rank=1 gives the true minimum
10    % luminosity, but it can be polluted by noise.
11% Organization of image indices:
[454]12    % The program is working on a series of images,
13    % The processing can be done over groups of nbfield2 consecutive files in slices (parameter NbSlice)
14    % In the mode 'volume', nbfield2=1 (1 image at each level)and NbSlice (=nbfield_j)
15    % Else nbfield2=nbfield_j =nbre of images in a burst (j index)
[451]16   
[457]17% function GUI_config=sub_background(Param)
[169]18%
[451]19%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
[457]20%
21% This function is used in four modes by the GUI series:
22%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
23%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
24%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
25%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
26%
[451]27%OUTPUT
[454]28% GUI_series_config=list of options in the GUI series.fig needed for the function
[451]29%
30%INPUT:
31% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
32% In batch mode, Param is the name of the corresponding xml file containing the same information
33% In the absence of input (as activated when the current Action is selected
[454]34% in series), the function ouput GUI_series_config set the activation of the needed GUI elements
[451]35%
36% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
37%    .InputTable: cell of input file names, (several lines for multiple input)
38%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
39%    .OutputSubDir: name of the subdirectory for data outputs
[474]40%    .OutputDirExt: extension for the directory for data outputs
[451]41%    .Action: .ActionName: name of the current activated function
42%             .ActionPath:   path of the current activated function
43%    .IndexRange: set the file or frame indices on which the action must be performed
44%    .FieldTransform: .TransformName: name of the selected transform function
45%                     .TransformPath:   path  of the selected transform function
46%                     .TransformHandle: corresponding function handle
47%    .InputFields: sub structure describing the input fields withfields
48%              .FieldName: name of the field
49%              .VelType: velocity type
50%              .FieldName_1: name of the second field in case of two input series
51%              .VelType_1: velocity type of the second field in case of two input series
52%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
53%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
54
55   
[459]56function ParamOut=sub_background (Param)
[24]57
[451]58%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
59if ~exist('Param','var') % case with no input parameter
[474]60    ParamOut={'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
[457]61        'WholeIndexRange';'on';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
[24]62        'NbSlice';'on'; ...%nbre of slices ('off' by default)
[451]63        'VelType';'off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
64        'FieldName';'off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
65        'FieldTransform'; 'off';...%can use a transform function
66        'ProjObject';'off';...%can use projection object(option 'off'/'on',
67        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
[454]68        'OutputDirExt';'.sback';...%set the output dir extension
[24]69               ''};
[451]70        return
[24]71end
72
[451]73%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
[457]74%% select different modes,  RUN, parameter input, BATCH
[451]75% BATCH  case: read the xml file for batch case
[457]76if ischar(Param)
[454]77        Param=xml2struct(Param);
78        checkrun=0;
[457]79% RUN case: parameters introduced as the input structure Param
[454]80else
[374]81    hseries=guidata(Param.hseries);%handles of the GUI series
[451]82    WaitbarPos=get(hseries.waitbar_frame,'Position');%position of the waitbar on the GUI series
[462]83    if isfield(Param,'Specific')&& strcmp(Param.Specific,'?')
84        checkrun=1;% will search input parameters (preparation of BATCH mode)
85    else
86        checkrun=2; % indicate the RUN option is used
87    end
[374]88end
[462]89ParamOut=Param; %default output
[474]90OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[457]91
92%% root input file(s) and type
93RootPath=Param.InputTable(:,1);
94RootFile=Param.InputTable(:,3);
95SubDir=Param.InputTable(:,2);
96NomType=Param.InputTable(:,4);
97FileExt=Param.InputTable(:,5);
[451]98[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
[474]99%%%%%%%%%%%%
100% The cell array filecell is the list of input file names, while
101% filecell{iview,fileindex}:
[451]102%        iview: line in the table corresponding to a given file series
103%        fileindex: file index within  the file series,
104% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
105% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
[474]106%%%%%%%%%%%%
[451]107NbSlice=1;%default
[457]108if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
[451]109    NbSlice=Param.IndexRange.NbSlice;
[54]110end
[454]111nbview=numel(i1_series);%number of input file series (lines in InputTable)
112nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
113nbfield_i=size(i1_series{1},2); %nb of fields for the i index
114nbfield=nbfield_j*nbfield_i; %total number of fields
115nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
116nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
[451]117
118%determine the file type on each line from the first input file
[454]119ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
[451]120
[454]121[FileType{1},FileInfo{1},MovieObject{1}]=get_file_type(filecell{1,1});
122CheckImage{1}=~isempty(find(strcmp(FileType,ImageTypeOptions)));% =1 for images
123if ~isempty(j1_series{1})
124    frame_index{1}=j1_series{1};
125else
126    frame_index{1}=i1_series{1};
127end
[451]128
129%% calibration data and timing: read the ImaDoc files
130%not relevant here
131
132%% check coincidence in time for several input file series
133%not relevant here
134
135%% coordinate transform or other user defined transform
136%not relevant here
137
138%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
139 % EDIT FROM HERE
140
141 %% check the validity of  input file types
[454]142if CheckImage{1}
[451]143    FileExtOut='.png'; % write result as .png images for image inputs
[454]144    if strcmp(lower(NomType{1}(end)),'a')
145        NomTypeOut=NomType{1};%case of letter appendix
[462]146    elseif isempty(j1_series)
147        NomTypeOut='_1';
[454]148    else
149        NomTypeOut='_1_1';% caseof purely numerical indexing
150    end
[451]151else
152    msgbox_uvmat('ERROR',['invalid file type input: ' FileType{1} ' not an image'])
[54]153    return
154end
155
[451]156%% Set field names and velocity types
157%not relevant here
158
159%% Initiate output fields
160%not relevant here
161 
162%%% SPECIFIC PART BEGINS HERE
163NbSlice=Param.IndexRange.NbSlice; %number of slices
[454]164%siz=size(i1_series);
[24]165nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
[394]166j1=[];%default
[24]167
[214]168%% adjust the proposed number of images in the sliding average to include an integer number of bursts
[454]169if nbfield_i~=1
170    nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
[24]171    if isequal(floor(nbaver/2),nbaver)
172        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
173    end
[454]174    nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
[24]175end
176
[457]177%% input of specific parameters
178if checkrun %get specific parameters interactively
[454]179    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
180        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
181    dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' Param.OutputDir];
182    num_lines= 3;
183    def     = { 'No';num2str(nbaver_init);'0.1'};
184    answer = inputdlg(prompt,dlg_title,num_lines,def);
185   
186    %check input consistency
187    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
188        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
189        if ~strcmp(check,'Yes')
190            return
191        end
192    end
193    if strcmp(answer{1},'Yes')
194        step=1;
195    else
196        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
197    end
198    nbaver_ima=str2num(answer{2});%number of images for the sliding background
199    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
200    if isequal(floor(nbaver/2),nbaver)
201        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
202    end
203    nbaver_ima=nbaver*step;
204    if nbaver_ima > nbfield
205        msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
206        return
207    end
[459]208    ParamOut.Specific.CheckVolume=strcmp(answer{1},'Yes');
209    ParamOut.Specific.SlidingSequenceSize=nbaver_ima;
210    ParamOut.Specific.BrightnessRankThreshold=str2num(answer{3});
[454]211   
212    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
213    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
[459]214    ParamOut.Specific.CheckLevelTransform=strcmp(answer,'Yes');
215    if checkrun==1
[457]216         return
217    end
218    %%%%%%%%%%%%%%%%%%%%%%  STOP HERE FOR PAMETER INPUT MODE  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[24]219else
[459]220    if isequal(Param.Specific.CheckVolume,1)
[454]221        step=1;
[24]222    else
[454]223        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
[24]224    end
[459]225    nbaver_ima=Param.Specific.SlidingSequenceSize;%number of images for the sliding background
[454]226    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
227    if isequal(floor(nbaver/2),nbaver)
228        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
229    end
230    nbaver_ima=nbaver*step;
231    if nbaver_ima > nbfield
232        msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
[24]233        return
234    end
235end
[454]236
237% calculate absolute brightness rank
[459]238rank=floor(ParamOut.Specific.BrightnessRankThreshold*nbaver_ima);
[24]239if rank==0
240    rank=1;%rank selected in the sorted image series
241end
242
[239]243%% prealocate memory for the sliding background
[394]244try
[454]245    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
246    [npy,npx]=size(Afirst);
247    if strcmp(class(Afirst),'uint8') % case of 8bit images
248        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
249        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
250    else
251        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
252        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
253    end
[239]254catch ME
255    msgbox_uvmat('ERROR',ME.message)
256    return
257end
258
[442]259%% update the xml file
[454]260% SubDirBase=regexprep(Param.InputTable{1,2},'\..*','');%take the root part of SubDir, before the first dot '.'
261% filexml=fullfile(RootPath{1},[SubDirBase '.xml']);
262% if ~exist(filexml,'file') && exist([fullfile(RootPath{1},SubDir{1},RootFile{1}) '.xml'],'file')% xml inside the image directory
263%     copyfile([filebase '.xml'],filexml);% copy the .xml file
264% end
265% if exist(filexml,'file')
266%     t=xmltree(filexml); 
267%     %update information on the first image name in the series
268%     uid_Heading=find(t,'ImaDoc/Heading');
269%     if isempty(uid_Heading)
270%         [t,uid_Heading]=add(t,1,'element','Heading');
271%     end
272%     uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
273%     if ~isempty(j1_series{1})
274%         j1=j1_series{1}(1);
275%     end
276%     ImageName=fullfile_uvmat([dir_images term],'',RootFile{1},'.png',NomType,i1_series(1,1),[],j1);
277%     [pth,ImageName]=fileparts(ImageName);
278%     ImageName=[ImageName '.png'];
279%     if isempty(uid_ImageName)
280%         [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
281%     end
282%     uid_value=children(t,uid_ImageName);
283%     if isempty(uid_value)
284%         t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
285%     else
286%         t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
287%     end
288%     
289%     %add information about image transform
290%     [t,new_uid]=add(t,1,'element','ImageTransform');
291%     [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
292%     [t]=add(t,NameFunction_uid,'chardata','sub_background');
293%     if GUI_config.CheckLevel
294%         [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
295%         [t]=add(t,NameFunction_uid,'chardata','levels');
296%     end
297%     [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
298%     [t]=add(t,new_uid,'chardata',num2str(NbSlice));
299%     [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
300%     [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
301%     [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
302%     [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
303%     save(t,filexml)
304% end
[24]305%copy the mask
[442]306% if exist([filebase '_1mask_1'],'file')
307%     copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
308% end
[24]309
310%MAIN LOOP ON SLICES
[451]311for islice=1:NbSlice
[214]312    %% select the series of image indices at the level islice
[454]313    indselect=islice:NbSlice*step:nbfield;% select file indices of the slice
314    for ifield=1:step-1
315        indselect=[indselect;indselect(end,:)+1];
[394]316    end
[214]317   
318    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
[24]319    for ifield = 1:nbaver_ima
[54]320        ifile=indselect(ifield);
[394]321        filename=filecell{1,ifile};
[454]322        Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
323        if ndims(Aread)==3;%color images
324            Aread=sum(double(Aread),3);% take the sum of color components
325        end
[394]326        Ak(:,:,ifield)=Aread;
[24]327    end
328    Asort=sort(Ak,3);%sort the luminosity of images at each point
329    B=Asort(:,:,rank);%background image
[394]330    display( 'first background image will be substracted')
[454]331    nbfirst=(ceil(nbaver/2))*step;
[24]332    for ifield=1:nbfirst
[394]333        Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
334        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
335        ifile=indselect(ifield);
336        if ~isempty(j1_series{1})
337            j1=j1_series{1}(ifile);
338        end
[474]339        newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[454]340       
341        %write result file
[459]342        if ParamOut.Specific.CheckLevelTransform
[454]343            C=levels(Acor);
[394]344            imwrite(C,newname,'BitDepth',8); % save the new image
345        else
[454]346            if isequal(FileInfo{1}.BitDepth,16)
347                C=uint16(Acor);
348                imwrite(C,newname,'BitDepth',16); % save the new image
349            else
350                C=uint8(Acor);
351                imwrite(C,newname,'BitDepth',8); % save the new image
352            end
[394]353        end
[454]354        display([newname ' written'])
[24]355    end
[214]356   
[454]357    %% repeat the operation on a sliding series of images
[214]358    display('sliding background image will be substracted')
[454]359    if nbfield_i > nbaver_ima
360        for ifield = step*ceil(nbaver/2)+1:step:nbfield_i-step*floor(nbaver/2)
[442]361            if checkrun
362                stopstate=get(hseries.RUN,'BusyAction');
[454]363                update_waitbar(hseries.waitbar_frame,WaitbarPos,(ifield+(islice-1)*nbfield_i)/(nbfield_i*NbSlice))
[442]364            else
365                stopstate='queue';
366            end
367            if isequal(stopstate,'queue')% enable STOP command
[240]368                Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
[24]369                %incorporate next burst in the current image series
370                for iburst=1:step
371                    ifile=indselect(ifield+step*floor(nbaver/2)+iburst-1);
[454]372                    filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1_series{1}(ifile));
373                    Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
374                    if ndims(Aread)==3;%color images
375                        Aread=sum(double(Aread),3);% take the sum of color components
376                    end
[24]377                    Ak(:,:,nbaver_ima-step+iburst)=Aread;
378                end
379                Asort=sort(Ak,3);%sort the new current image series by luminosity
380                B=Asort(:,:,rank);%current background image
381                for iburst=1:step
382                    index=step*floor(nbaver/2)+iburst;
383                    Acor=double(Ak(:,:,index))-double(B);
384                    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
385                    ifile=indselect(ifield+iburst-1);
[394]386                    if ~isempty(j1_series{1})
387                        j1=j1_series{1}(ifile);
388                    end
[474]389                    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[454]390                    %write result file
[459]391                    if ParamOut.Specific.CheckLevelTransform
[454]392                        C=levels(Acor);
[214]393                        imwrite(C,newname,'BitDepth',8); % save the new image
394                    else
[454]395                        if isequal(FileInfo{1}.BitDepth,16)
396                            C=uint16(Acor);
397                            imwrite(C,newname,'BitDepth',16); % save the new image
398                        else
399                            C=uint8(Acor);
400                            imwrite(C,newname,'BitDepth',8); % save the new image
401                        end
[214]402                    end
[454]403                    display([newname ' written'])
404                   
[214]405                end
[24]406            else
407                return
408            end
409        end
410    end
[394]411   
412    %% substract the background from the last images
[214]413    display('last background image will be substracted')
[454]414    ifield=nbfield_i-(step*ceil(nbaver/2))+1:nbfield_i;
415    for ifield=nbfield_i-(step*floor(nbaver/2))+1:nbfield_i
416        index=ifield-nbfield_i+step*(2*floor(nbaver/2)+1);
[394]417        Acor=double(Ak(:,:,index))-double(B);
418        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
419        ifile=indselect(ifield);
420        if ~isempty(j1_series{1})
421            j1=j1_series{1}(ifile);
422        end
[474]423        newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[454]424       
425        %write result file
[459]426        if ParamOut.Specific.CheckLevelTransform
[454]427            C=levels(Acor);
[394]428            imwrite(C,newname,'BitDepth',8); % save the new image
429        else
[454]430            if isequal(FileInfo{1}.BitDepth,16)
431                C=uint16(Acor);
432                imwrite(C,newname,'BitDepth',16); % save the new image
433            else
434                C=uint8(Acor);
435                imwrite(C,newname,'BitDepth',8); % save the new image
436            end
[394]437        end
[454]438        display([newname ' written'])
[394]439    end
[24]440end
441
442%finish the waitbar
[442]443if checkrun
444    update_waitbar(hseries.waitbar,WaitbarPos,1)
445end
[24]446   
[214]447
448function C=levels(A)
449%whos A;
450B=double(A(:,:,1));
451windowsize=round(min(size(B,1),size(B,2))/20);
452windowsize=floor(windowsize/2)*2+1;
[239]453ix=1/2-windowsize/2:-1/2+windowsize/2;%
[214]454%del=np/3;
455%fct=exp(-(ix/del).^2);
456fct2=cos(ix/(windowsize-1)/2*pi/2);
457%Mfiltre=(ones(5,5)/5^2);
458%Mfiltre=fct2';
459Mfiltre=fct2'*fct2;
460Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
461
462C=filter2(Mfiltre,B);
463C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
464C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
465C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
466C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
467C=tanh(B./(2*C));
468[n,c]=hist(reshape(C,1,[]),100);
469% figure;plot(c,n);
470
471[m,i]=max(n);
472c_max=c(i);
473[dummy,index]=sort(abs(c-c(i)));
474n=n(index);
475c=c(index);
476i_select = find(cumsum(n)<0.95*sum(n));
477if isempty(i_select)
478    i_select = 1:length(c);
479end
480c_select=c(i_select);
481n_select=n(i_select);
482cmin=min(c_select);
483cmax=max(c_select);
484C=(C-cmin)/(cmax-cmin)*256;
485C=uint8(C);
Note: See TracBrowser for help on using the repository browser.