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

Last change on this file since 690 was 676, checked in by sommeria, 11 years ago

various bugs corrected

File size: 17.9 KB
RevLine 
[457]1%'sub_background': substract a sliding background to an image series
[169]2%------------------------------------------------------------------------
[24]3% Method:
4    %calculate the background image by sorting the luminosity of each point
5    % over a sliding sub-sequence of 'nbaver_ima' images.
6    % The luminosity value of rank 'rank' is selected as the
7    % 'background'. rank=nbimages/2 gives the median value.  Smaller values are appropriate
8    % for a dense set of particles. The extrem value rank=1 gives the true minimum
9    % luminosity, but it can be polluted by noise.
10% Organization of image indices:
[454]11    % The program is working on a series of images,
12    % In the mode 'volume', nbfield2=1 (1 image at each level)and NbSlice (=nbfield_j)
13    % Else nbfield2=nbfield_j =nbre of images in a burst (j index)
[451]14   
[457]15% function GUI_config=sub_background(Param)
[169]16%
[451]17%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
[457]18%
[451]19%OUTPUT
[596]20% ParamOut: sets options in the GUI series.fig needed for the function
[451]21%
22%INPUT:
23% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
24% In batch mode, Param is the name of the corresponding xml file containing the same information
[596]25% when Param.Action.RUN=0 (as activated when the current Action is selected
26% in series), the function ouput paramOut set the activation of the needed GUI elements
[451]27%
[596]28% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
29% see the current structure Param)
[451]30%    .InputTable: cell of input file names, (several lines for multiple input)
31%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
32%    .OutputSubDir: name of the subdirectory for data outputs
[596]33%    .OutputDirExt: directory extension for data outputs
[451]34%    .Action: .ActionName: name of the current activated function
35%             .ActionPath:   path of the current activated function
[596]36%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
37%             .RUN =0 for GUI input, =1 for function activation
38%             .RunMode='local','background', 'cluster': type of function  use
39%             
[451]40%    .IndexRange: set the file or frame indices on which the action must be performed
41%    .FieldTransform: .TransformName: name of the selected transform function
42%                     .TransformPath:   path  of the selected transform function
43%    .InputFields: sub structure describing the input fields withfields
[596]44%              .FieldName: name(s) of the field
[451]45%              .VelType: velocity type
46%              .FieldName_1: name of the second field in case of two input series
47%              .VelType_1: velocity type of the second field in case of two input series
[596]48%              .Coord_y: name of y coordinate variable
49%              .Coord_x: name of x coordinate variable
[451]50%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
51%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[596]52   
[459]53function ParamOut=sub_background (Param)
[24]54
[676]55%%%%%%%%%%%%%%%%%    INPUT PREPARATION MODE (no RUN)    %%%%%%%%%%%%%%%%%
[592]56if isstruct(Param) && isequal(Param.Action.RUN,0)
[605]57    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
58    ParamOut.WholeIndexRange='on';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
59    ParamOut.NbSlice='on'; %nbre of slices ('off' by default)
60    ParamOut.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
61    ParamOut.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
62    ParamOut.FieldTransform = 'off';%can use a transform function
63    ParamOut.ProjObject='off';%can use projection object(option 'off'/'on',
64    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
[592]65    ParamOut.OutputDirExt='.sback';%set the output dir extension
[605]66    ParamOut.OutputFileMode='NbInput';% '=NbInput': 1 output file per input file index, '=NbInput_i': 1 file per input file index i, '=NbSlice': 1 file per slice
[592]67   
68    %% root input file(s) and type
69    [filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
[605]70    if ~exist(filecell{1,1},'file')
71        msgbox_uvmat('WARNING','the first input file does not exist')
72        return
73    end
[592]74   
75    %% check the validity of  input file types
76    ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
77    FileType=get_file_type(filecell{1,1});
78    CheckImage=~isempty(find(strcmp(FileType,ImageTypeOptions), 1));% =1 for images
79    if ~CheckImage
[642]80        msgbox_uvmat('ERROR',['invalid file type input: ' FileType ' not an image'])
[451]81        return
[592]82    end
83   
[676]84    %% numbers of fields
85    NbSlice=1;%default
86    if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
87        NbSlice=Param.IndexRange.NbSlice;
[592]88    end
[676]89    %nbview=numel(i1_series);%number of input file series (lines in InputTable)
90    nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
91    nbfield_i=size(i1_series{1},2); %nb of fields for the i index
92    nbfield=nbfield_j*nbfield_i; %total number of fields
93    nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[592]94   
[676]95    %% setting of  parameters specific to sub_background
96    nbaver_init=23; %default number of images used for the sliding background: to be adjusted later to include an integer number of bursts 
[592]97    if nbfield_i~=1
98        nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
99        if isequal(floor(nbaver/2),nbaver)
100            nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
101        end
102        nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
103    end
104   
[676]105    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
106        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
107    dlg_title = 'get (slice by slice) a sliding background and substract to each image';
108    num_lines= 3;
109    def     = { 'No';num2str(nbaver_init);'0.1'};
110    answer = inputdlg(prompt,dlg_title,num_lines,def);
111   
112    %check input consistency
113    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
114        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
115        if ~strcmp(check,'Yes')
116            return
[592]117        end
118    end
[676]119    if strcmp(answer{1},'Yes')
120        step=1;
121    else
122        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
123    end
124    nbaver_ima=str2num(answer{2});%number of images for the sliding background
125    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
126    if isequal(floor(nbaver/2),nbaver)
127        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
128    end
129    nbaver_ima=nbaver*step;% correct the nbre of images corresponding to nbaver
[599]130    ParamOut.ActionInput.CheckVolume=strcmp(answer{1},'Yes');
131    ParamOut.ActionInput.SlidingSequenceLength=nbaver_ima;
132    ParamOut.ActionInput.BrightnessRankThreshold=str2num(answer{3});
[592]133   
134    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
135    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
[599]136    ParamOut.ActionInput.CheckLevelTransform=strcmp(answer,'Yes');
[592]137    return
[24]138end
[676]139%%%%%%%%%%%%%%%%%    STOP HERE FOR PAMETER INPUT MODE   %%%%%%%%%%%%%%%%%
[24]140
[592]141%% read input parameters from an xml file if input is a file name (batch mode)
142checkrun=1;
[457]143if ischar(Param)
[592]144    Param=xml2struct(Param);% read Param as input file (batch case)
145    checkrun=0;
[374]146end
[624]147hseries=findobj(allchild(0),'Tag','series');
148RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
149WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
[676]150
151%% input preparation
[599]152nbaver_ima=Param.ActionInput.SlidingSequenceLength;
[592]153NbSlice=Param.IndexRange.NbSlice;
154if ~isequal(NbSlice,1)
155    display(['multi-level splitting into ' num2str(NbSlice) ' slices']);
156end
[457]157RootPath=Param.InputTable(:,1);
158RootFile=Param.InputTable(:,3);
159SubDir=Param.InputTable(:,2);
160NomType=Param.InputTable(:,4);
161FileExt=Param.InputTable(:,5);
[451]162[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
[676]163%%%%%%%%%%%%
164    % The cell array filecell is the list of input file names, while
165    % filecell{iview,fileindex}:
166    %        iview: line in the table corresponding to a given file series
167    %        fileindex: file index within  the file series,
168    % 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
169    % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
170%%%%%%%%%%%%
[592]171[FileType{1},FileInfo{1},MovieObject{1}]=get_file_type(filecell{1,1});
172    if ~isempty(j1_series{1})
173        frame_index{1}=j1_series{1};
174    else
175        frame_index{1}=i1_series{1};
176    end
[454]177nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
178nbfield_i=size(i1_series{1},2); %nb of fields for the i index
179nbfield=nbfield_j*nbfield_i; %total number of fields
[592]180nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[454]181nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
[451]182
[676]183%% output
[592]184FileExtOut='.png'; % write result as .png images for image inputs
185if strcmp(lower(NomType{1}(end)),'a')
186    NomTypeOut=NomType{1};%case of letter appendix
187elseif isempty(j1_series)
188    NomTypeOut='_1';
[454]189else
[592]190    NomTypeOut='_1_1';% caseof purely numerical indexing
[454]191end
[451]192
[592]193OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[451]194
[599]195if isequal(Param.ActionInput.CheckVolume,1)
[592]196    step=1;
197else
198    step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
[54]199end
[599]200nbaver_ima=Param.ActionInput.SlidingSequenceLength;%number of images for the sliding background
[592]201nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
202if isequal(floor(nbaver/2),nbaver)
203    nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
[24]204end
[592]205nbaver_ima=nbaver*step;
206if nbaver_ima > nbfield
207    display('number of images in a slice smaller than the proposed number of images for the sliding average')
208    return
[24]209end
[454]210
211% calculate absolute brightness rank
[599]212rank=floor(Param.ActionInput.BrightnessRankThreshold*nbaver_ima);
[24]213if rank==0
214    rank=1;%rank selected in the sorted image series
215end
216
[239]217%% prealocate memory for the sliding background
[394]218try
[454]219    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
220    [npy,npx]=size(Afirst);
221    if strcmp(class(Afirst),'uint8') % case of 8bit images
222        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
223        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
224    else
225        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
226        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
227    end
[239]228catch ME
[592]229    msgbox_uvmat('ERROR',['sub_background/read_image/' ME.message])
[239]230    return
231end
232
[676]233%% summary of the parameters:
234% nbfield : total number of images treated (in case of multislices the function sub_background is repeated for each slice)
235% step: shift at each step of the sliding background (corresponding to the nbre of images in a burst)
236% nbaver_ima: length of the sequence used for the sliding background
[24]237
[676]238% nbaver=nbaver_ima/step: nbaver_ima has been adjusted so that nbaver is an odd integer
239halfnbaver=floor(nbaver/2); % half width (in unit of bursts) of the sliding background
240
241%% select the series of image indices to process
[616]242indselect=1:step:nbfield;% select file indices of the slice
243for ifield=1:step-1
244    indselect=[indselect;indselect(end,:)+1];
245end
246
247%% read the first series of nbaver_ima images and sort by luminosity at each pixel
248for ifield = 1:nbaver_ima
249    ifile=indselect(ifield);
250    filename=filecell{1,ifile};
251    Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
252    if ndims(Aread)==3;%color images
253        Aread=sum(double(Aread),3);% take the sum of color components
[394]254    end
[616]255    Ak(:,:,ifield)=Aread;
256end
257Asort=sort(Ak,3);%sort the luminosity of images at each point
258B=Asort(:,:,rank);%background image
[676]259
260%% substract the first background image to the first images
[616]261display( 'first background image will be substracted')
[676]262for ifield=1:step*(halfnbaver+1);% nbre of images treated by the first background image
[616]263    Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
264    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
265    ifile=indselect(ifield);
266    if ~isempty(j1_series{1})
267        j1=j1_series{1}(ifile);
268    end
269    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[214]270   
[616]271    %write result file
272    if Param.ActionInput.CheckLevelTransform
273        C=levels(Acor);
274        imwrite(C,newname,'BitDepth',8); % save the new image
275    else
276        if isequal(FileInfo{1}.BitDepth,16)
277            C=uint16(Acor);
278            imwrite(C,newname,'BitDepth',16); % save the new image
279        else
280            C=uint8(Acor);
281            imwrite(C,newname,'BitDepth',8); % save the new image
[454]282        end
[24]283    end
[616]284    display([newname ' written'])
285end
286
287%% repeat the operation on a sliding series of images
288display('sliding background image will be substracted')
289if nbfield_i > nbaver_ima
[676]290    for ifield = step*(halfnbaver+1):step:nbfield_i-step*(halfnbaver+1)% ifield +iburst=index of the current processed image
291        update_waitbar(WaitbarHandle,ifield/nbfield_i)
292        if ~isempty(RUNHandle) &&ishandle(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
293            disp('program stopped by user')
294            return
295        end
296        Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
297        %incorporate next burst in the current image series
298        for iburst=1:step
299            ifile=indselect(ifield+iburst+step*halfnbaver);
300            filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1_series{1}(ifile));
301            Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
302            if ndims(Aread)==3;%color images
303                Aread=sum(double(Aread),3);% take the sum of color components
[442]304            end
[676]305            Ak(:,:,nbaver_ima-step+iburst)=Aread;% fill the last burst of the current image series by the new image
306        end
307        Asort=sort(Ak,3);%sort the new current image series by luminosity
308        B=Asort(:,:,rank);%current background image
309        %substract the background for the current burst
310        for iburst=1:step
311            Acor=double(Ak(:,:,step*halfnbaver+iburst))-double(B); %the current image has been already read ans stored as index step*halfnbaver+iburst in the current series
312            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
313            ifile=indselect(ifield+iburst);
314            if ~isempty(j1_series{1})
315                j1=j1_series{1}(ifile);
316            end
317            newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
318            %write result file
319            if Param.ActionInput.CheckLevelTransform
320                C=levels(Acor);
321                imwrite(C,newname,'BitDepth',8); % save the new image
322            else
323                if isequal(FileInfo{1}.BitDepth,16)
324                    C=uint16(Acor);
325                    imwrite(C,newname,'BitDepth',16); % save the new image
326                else
327                    C=uint8(Acor);
[616]328                    imwrite(C,newname,'BitDepth',8); % save the new image
[214]329                end
[24]330            end
[676]331            display([newname ' written'])       
332        end
[24]333    end
[616]334end
335
336%% substract the background from the last images
337display('last background image will be substracted')
[676]338for  ifield=nbfield_i-step*halfnbaver+1:nbfield_i
339    Acor=double(Ak(:,:,ifield-nbfield_i+step*(2*halfnbaver+1)))-double(B);
[616]340    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
341    ifile=indselect(ifield);
342    if ~isempty(j1_series{1})
343        j1=j1_series{1}(ifile);
344    end
[676]345    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1); 
[616]346    %write result file
347    if Param.ActionInput.CheckLevelTransform
348        C=levels(Acor);
349        imwrite(C,newname,'BitDepth',8); % save the new image
350    else
351        if isequal(FileInfo{1}.BitDepth,16)
352            C=uint16(Acor);
353            imwrite(C,newname,'BitDepth',16); % save the new image
354        else
355            C=uint8(Acor);
[394]356            imwrite(C,newname,'BitDepth',8); % save the new image
357        end
358    end
[616]359    display([newname ' written'])
[24]360end
361
[214]362
[616]363
[214]364function C=levels(A)
365%whos A;
366B=double(A(:,:,1));
367windowsize=round(min(size(B,1),size(B,2))/20);
368windowsize=floor(windowsize/2)*2+1;
[239]369ix=1/2-windowsize/2:-1/2+windowsize/2;%
[214]370%del=np/3;
371%fct=exp(-(ix/del).^2);
372fct2=cos(ix/(windowsize-1)/2*pi/2);
373%Mfiltre=(ones(5,5)/5^2);
374%Mfiltre=fct2';
375Mfiltre=fct2'*fct2;
376Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
377
378C=filter2(Mfiltre,B);
379C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
380C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
381C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
382C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
383C=tanh(B./(2*C));
384[n,c]=hist(reshape(C,1,[]),100);
385% figure;plot(c,n);
386
387[m,i]=max(n);
388c_max=c(i);
389[dummy,index]=sort(abs(c-c(i)));
390n=n(index);
391c=c(index);
392i_select = find(cumsum(n)<0.95*sum(n));
393if isempty(i_select)
394    i_select = 1:length(c);
395end
396c_select=c(i_select);
397n_select=n(i_select);
398cmin=min(c_select);
399cmax=max(c_select);
400C=(C-cmin)/(cmax-cmin)*256;
401C=uint8(C);
Note: See TracBrowser for help on using the repository browser.