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

Last change on this file since 802 was 802, checked in by sommeria, 10 years ago

sub_background corrected

File size: 19.6 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
[716]69    % check the existence of the first file in the series
70        first_j=[];
71    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
72    last_j=[];
73    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
74    PairString='';
75    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
76    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
77    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
78        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
79    if ~exist(FirstFileName,'file')
80        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
81    else
82        [i1,i2,j1,j2] = get_file_index(Param.IndexRange.last_i,last_j,PairString);
83        LastFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
84        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
85        if ~exist(FirstFileName,'file')
86             msgbox_uvmat('WARNING',['the last input file ' LastFileName ' does not exist'])
87        end
[605]88    end
[716]89
[592]90    %% check the validity of  input file types
91    ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
[784]92    FileInfo=get_file_info(FirstFileName);
[783]93    FileType=FileInfo.FileType;
[592]94    CheckImage=~isempty(find(strcmp(FileType,ImageTypeOptions), 1));% =1 for images
95    if ~CheckImage
[642]96        msgbox_uvmat('ERROR',['invalid file type input: ' FileType ' not an image'])
[451]97        return
[592]98    end
99   
[676]100    %% numbers of fields
101    NbSlice=1;%default
102    if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
103        NbSlice=Param.IndexRange.NbSlice;
[592]104    end
[774]105    incr_j=1;%default
106    if isfield(Param.IndexRange,'incr_j')&&~isempty(Param.IndexRange.incr_j)
107        incr_j=Param.IndexRange.incr_j;
108    end
109    if isempty(first_j)||isempty(last_j)
110        nbfield_j=1;
111    else
112        nbfield_j=numel(first_j:incr_j:last_j);%nb of fields for the j index (bursts or volume slices)
113    end
114    incr_i=1;%default
115    first_i=1;last_i=1;incr_i;%default
116    if isfield(Param.IndexRange,'first_i'); last_i=Param.IndexRange.first_i; end   
[802]117    if isfield(Param.IndexRange,'last_i'); last_i=Param.IndexRange.last_i; end
[774]118    if isfield(Param.IndexRange,'incr_i')&&~isempty(Param.IndexRange.incr_i)
119        incr_i=Param.IndexRange.incr_i;
120    end
121    nbfield_i=numel(first_i:incr_i:last_i);%nb of fields for the i index (bursts or volume slices)
[676]122    nbfield=nbfield_j*nbfield_i; %total number of fields
123    nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[592]124   
[676]125    %% setting of  parameters specific to sub_background
126    nbaver_init=23; %default number of images used for the sliding background: to be adjusted later to include an integer number of bursts 
[592]127    if nbfield_i~=1
128        nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
129        if isequal(floor(nbaver/2),nbaver)
130            nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
131        end
132        nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
133    end
134   
[676]135    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
136        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
137    dlg_title = 'get (slice by slice) a sliding background and substract to each image';
138    num_lines= 3;
139    def     = { 'No';num2str(nbaver_init);'0.1'};
140    answer = inputdlg(prompt,dlg_title,num_lines,def);
141   
142    %check input consistency
143    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
144        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
145        if ~strcmp(check,'Yes')
146            return
[592]147        end
148    end
[676]149    if strcmp(answer{1},'Yes')
150        step=1;
151    else
152        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
153    end
154    nbaver_ima=str2num(answer{2});%number of images for the sliding background
155    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
156    if isequal(floor(nbaver/2),nbaver)
157        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
158    end
159    nbaver_ima=nbaver*step;% correct the nbre of images corresponding to nbaver
[599]160    ParamOut.ActionInput.CheckVolume=strcmp(answer{1},'Yes');
161    ParamOut.ActionInput.SlidingSequenceLength=nbaver_ima;
162    ParamOut.ActionInput.BrightnessRankThreshold=str2num(answer{3});
[592]163   
164    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
165    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
[599]166    ParamOut.ActionInput.CheckLevelTransform=strcmp(answer,'Yes');
[592]167    return
[24]168end
[676]169%%%%%%%%%%%%%%%%%    STOP HERE FOR PAMETER INPUT MODE   %%%%%%%%%%%%%%%%%
[24]170
[592]171%% read input parameters from an xml file if input is a file name (batch mode)
172checkrun=1;
[457]173if ischar(Param)
[592]174    Param=xml2struct(Param);% read Param as input file (batch case)
175    checkrun=0;
[374]176end
[624]177hseries=findobj(allchild(0),'Tag','series');
178RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
179WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
[676]180
181%% input preparation
[599]182nbaver_ima=Param.ActionInput.SlidingSequenceLength;
[592]183NbSlice=Param.IndexRange.NbSlice;
184if ~isequal(NbSlice,1)
185    display(['multi-level splitting into ' num2str(NbSlice) ' slices']);
186end
[457]187RootPath=Param.InputTable(:,1);
188RootFile=Param.InputTable(:,3);
189SubDir=Param.InputTable(:,2);
190NomType=Param.InputTable(:,4);
191FileExt=Param.InputTable(:,5);
[774]192hdisp=disp_uvmat('WAITING...','checking the file series',checkrun);
[451]193[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
[774]194if ~isempty(hdisp),delete(hdisp),end;
[676]195%%%%%%%%%%%%
196    % The cell array filecell is the list of input file names, while
197    % filecell{iview,fileindex}:
198    %        iview: line in the table corresponding to a given file series
199    %        fileindex: file index within  the file series,
200    % 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
201    % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
202%%%%%%%%%%%%
[784]203[FileInfo{1},MovieObject{1}]=get_file_info(filecell{1,1});
[783]204FileType{1}=FileInfo{1}.FileType;
[592]205    if ~isempty(j1_series{1})
206        frame_index{1}=j1_series{1};
207    else
208        frame_index{1}=i1_series{1};
209    end
[454]210nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
211nbfield_i=size(i1_series{1},2); %nb of fields for the i index
212nbfield=nbfield_j*nbfield_i; %total number of fields
[592]213nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[454]214nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
[451]215
[676]216%% output
[592]217FileExtOut='.png'; % write result as .png images for image inputs
218if strcmp(lower(NomType{1}(end)),'a')
219    NomTypeOut=NomType{1};%case of letter appendix
[802]220elseif isempty(j1_series{1})
[592]221    NomTypeOut='_1';
[454]222else
[592]223    NomTypeOut='_1_1';% caseof purely numerical indexing
[454]224end
[451]225
[592]226OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[451]227
[599]228if isequal(Param.ActionInput.CheckVolume,1)
[592]229    step=1;
230else
231    step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
[54]232end
[599]233nbaver_ima=Param.ActionInput.SlidingSequenceLength;%number of images for the sliding background
[592]234nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
235if isequal(floor(nbaver/2),nbaver)
236    nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
[24]237end
[592]238nbaver_ima=nbaver*step;
239if nbaver_ima > nbfield
240    display('number of images in a slice smaller than the proposed number of images for the sliding average')
241    return
[24]242end
[454]243
244% calculate absolute brightness rank
[599]245rank=floor(Param.ActionInput.BrightnessRankThreshold*nbaver_ima);
[24]246if rank==0
247    rank=1;%rank selected in the sorted image series
248end
249
[239]250%% prealocate memory for the sliding background
[394]251try
[454]252    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
[700]253    [npy,npx,nbcolor]=size(Afirst);% the argument nbcolor is important to get npx right for color images
[454]254    if strcmp(class(Afirst),'uint8') % case of 8bit images
255        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
256        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
257    else
258        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
259        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
260    end
[239]261catch ME
[592]262    msgbox_uvmat('ERROR',['sub_background/read_image/' ME.message])
[239]263    return
264end
265
[676]266%% summary of the parameters:
267% nbfield : total number of images treated (in case of multislices the function sub_background is repeated for each slice)
268% step: shift at each step of the sliding background (corresponding to the nbre of images in a burst)
269% nbaver_ima: length of the sequence used for the sliding background
[24]270
[676]271% nbaver=nbaver_ima/step: nbaver_ima has been adjusted so that nbaver is an odd integer
272halfnbaver=floor(nbaver/2); % half width (in unit of bursts) of the sliding background
273
274%% select the series of image indices to process
[616]275indselect=1:step:nbfield;% select file indices of the slice
276for ifield=1:step-1
277    indselect=[indselect;indselect(end,:)+1];
278end
279
280%% read the first series of nbaver_ima images and sort by luminosity at each pixel
281for ifield = 1:nbaver_ima
282    ifile=indselect(ifield);
283    filename=filecell{1,ifile};
284    Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
285    if ndims(Aread)==3;%color images
286        Aread=sum(double(Aread),3);% take the sum of color components
[394]287    end
[616]288    Ak(:,:,ifield)=Aread;
289end
290Asort=sort(Ak,3);%sort the luminosity of images at each point
291B=Asort(:,:,rank);%background image
[676]292
293%% substract the first background image to the first images
[616]294display( 'first background image will be substracted')
[676]295for ifield=1:step*(halfnbaver+1);% nbre of images treated by the first background image
[616]296    Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
297    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
298    ifile=indselect(ifield);
[802]299    j1=1;
[616]300    if ~isempty(j1_series{1})
301        j1=j1_series{1}(ifile);
302    end
303    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[214]304   
[616]305    %write result file
306    if Param.ActionInput.CheckLevelTransform
307        C=levels(Acor);
308        imwrite(C,newname,'BitDepth',8); % save the new image
309    else
310        if isequal(FileInfo{1}.BitDepth,16)
311            C=uint16(Acor);
312            imwrite(C,newname,'BitDepth',16); % save the new image
313        else
314            C=uint8(Acor);
315            imwrite(C,newname,'BitDepth',8); % save the new image
[454]316        end
[24]317    end
[616]318    display([newname ' written'])
319end
320
321%% repeat the operation on a sliding series of images
322display('sliding background image will be substracted')
323if nbfield_i > nbaver_ima
[676]324    for ifield = step*(halfnbaver+1):step:nbfield_i-step*(halfnbaver+1)% ifield +iburst=index of the current processed image
325        update_waitbar(WaitbarHandle,ifield/nbfield_i)
326        if ~isempty(RUNHandle) &&ishandle(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
327            disp('program stopped by user')
328            return
329        end
330        Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
331        %incorporate next burst in the current image series
332        for iburst=1:step
333            ifile=indselect(ifield+iburst+step*halfnbaver);
[802]334            j1=1;
335    if ~isempty(j1_series{1})
336        j1=j1_series{1}(ifile);
337    end
338            filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1);
[676]339            Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
340            if ndims(Aread)==3;%color images
341                Aread=sum(double(Aread),3);% take the sum of color components
[442]342            end
[676]343            Ak(:,:,nbaver_ima-step+iburst)=Aread;% fill the last burst of the current image series by the new image
344        end
345        Asort=sort(Ak,3);%sort the new current image series by luminosity
346        B=Asort(:,:,rank);%current background image
347        %substract the background for the current burst
348        for iburst=1:step
349            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
350            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
351            ifile=indselect(ifield+iburst);
352            if ~isempty(j1_series{1})
353                j1=j1_series{1}(ifile);
354            end
355            newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
356            %write result file
357            if Param.ActionInput.CheckLevelTransform
358                C=levels(Acor);
359                imwrite(C,newname,'BitDepth',8); % save the new image
360            else
361                if isequal(FileInfo{1}.BitDepth,16)
362                    C=uint16(Acor);
363                    imwrite(C,newname,'BitDepth',16); % save the new image
364                else
365                    C=uint8(Acor);
[616]366                    imwrite(C,newname,'BitDepth',8); % save the new image
[214]367                end
[24]368            end
[676]369            display([newname ' written'])       
370        end
[24]371    end
[616]372end
373
374%% substract the background from the last images
375display('last background image will be substracted')
[676]376for  ifield=nbfield_i-step*halfnbaver+1:nbfield_i
377    Acor=double(Ak(:,:,ifield-nbfield_i+step*(2*halfnbaver+1)))-double(B);
[616]378    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
379    ifile=indselect(ifield);
380    if ~isempty(j1_series{1})
381        j1=j1_series{1}(ifile);
382    end
[676]383    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1); 
[616]384    %write result file
385    if Param.ActionInput.CheckLevelTransform
386        C=levels(Acor);
387        imwrite(C,newname,'BitDepth',8); % save the new image
388    else
389        if isequal(FileInfo{1}.BitDepth,16)
390            C=uint16(Acor);
391            imwrite(C,newname,'BitDepth',16); % save the new image
392        else
393            C=uint8(Acor);
[394]394            imwrite(C,newname,'BitDepth',8); % save the new image
395        end
396    end
[616]397    display([newname ' written'])
[24]398end
399
[214]400
[616]401
[214]402function C=levels(A)
403%whos A;
404B=double(A(:,:,1));
405windowsize=round(min(size(B,1),size(B,2))/20);
406windowsize=floor(windowsize/2)*2+1;
[239]407ix=1/2-windowsize/2:-1/2+windowsize/2;%
[214]408%del=np/3;
409%fct=exp(-(ix/del).^2);
410fct2=cos(ix/(windowsize-1)/2*pi/2);
411%Mfiltre=(ones(5,5)/5^2);
412%Mfiltre=fct2';
413Mfiltre=fct2'*fct2;
414Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
415
416C=filter2(Mfiltre,B);
417C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
418C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
419C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
420C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
421C=tanh(B./(2*C));
422[n,c]=hist(reshape(C,1,[]),100);
423% figure;plot(c,n);
424
425[m,i]=max(n);
426c_max=c(i);
427[dummy,index]=sort(abs(c-c(i)));
428n=n(index);
429c=c(index);
430i_select = find(cumsum(n)<0.95*sum(n));
431if isempty(i_select)
432    i_select = 1:length(c);
433end
434c_select=c(i_select);
435n_select=n(i_select);
436cmin=min(c_select);
437cmax=max(c_select);
438C=(C-cmin)/(cmax-cmin)*256;
439C=uint8(C);
Note: See TracBrowser for help on using the repository browser.