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

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

fct improved by reducing the input file check when selected.

File size: 18.9 KB
[457]1%'sub_background': substract a sliding background to an image series
[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)
[457]15% function GUI_config=sub_background(Param)
[451]17%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
[596]20% ParamOut: sets options in the GUI series.fig needed for the function
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
[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
[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)
[459]53function ParamOut=sub_background (Param)
[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
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
[592]90    %% check the validity of  input file types
91    ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
[716]92    FileType=get_file_type(FirstFileName);
[592]93    CheckImage=~isempty(find(strcmp(FileType,ImageTypeOptions), 1));% =1 for images
94    if ~CheckImage
[642]95        msgbox_uvmat('ERROR',['invalid file type input: ' FileType ' not an image'])
[451]96        return
[592]97    end
[676]99    %% numbers of fields
100    NbSlice=1;%default
101    if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
102        NbSlice=Param.IndexRange.NbSlice;
[592]103    end
[676]104    %nbview=numel(i1_series);%number of input file series (lines in InputTable)
[716]105    nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)%A CORRIGER !!!!!!!
[676]106    nbfield_i=size(i1_series{1},2); %nb of fields for the i index
107    nbfield=nbfield_j*nbfield_i; %total number of fields
108    nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[676]110    %% setting of  parameters specific to sub_background
111    nbaver_init=23; %default number of images used for the sliding background: to be adjusted later to include an integer number of bursts 
[592]112    if nbfield_i~=1
113        nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
114        if isequal(floor(nbaver/2),nbaver)
115            nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
116        end
117        nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
118    end
[676]120    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
121        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
122    dlg_title = 'get (slice by slice) a sliding background and substract to each image';
123    num_lines= 3;
124    def     = { 'No';num2str(nbaver_init);'0.1'};
125    answer = inputdlg(prompt,dlg_title,num_lines,def);
127    %check input consistency
128    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
129        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
130        if ~strcmp(check,'Yes')
131            return
[592]132        end
133    end
[676]134    if strcmp(answer{1},'Yes')
135        step=1;
136    else
137        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
138    end
139    nbaver_ima=str2num(answer{2});%number of images for the sliding background
140    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
141    if isequal(floor(nbaver/2),nbaver)
142        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
143    end
144    nbaver_ima=nbaver*step;% correct the nbre of images corresponding to nbaver
[599]145    ParamOut.ActionInput.CheckVolume=strcmp(answer{1},'Yes');
146    ParamOut.ActionInput.SlidingSequenceLength=nbaver_ima;
147    ParamOut.ActionInput.BrightnessRankThreshold=str2num(answer{3});
149    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
150    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
[599]151    ParamOut.ActionInput.CheckLevelTransform=strcmp(answer,'Yes');
[592]152    return
[676]154%%%%%%%%%%%%%%%%%    STOP HERE FOR PAMETER INPUT MODE   %%%%%%%%%%%%%%%%%
[592]156%% read input parameters from an xml file if input is a file name (batch mode)
[457]158if ischar(Param)
[592]159    Param=xml2struct(Param);% read Param as input file (batch case)
160    checkrun=0;
163RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
164WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
166%% input preparation
169if ~isequal(NbSlice,1)
170    display(['multi-level splitting into ' num2str(NbSlice) ' slices']);
179    % The cell array filecell is the list of input file names, while
180    % filecell{iview,fileindex}:
181    %        iview: line in the table corresponding to a given file series
182    %        fileindex: file index within  the file series,
183    % 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
184    % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
187    if ~isempty(j1_series{1})
188        frame_index{1}=j1_series{1};
189    else
190        frame_index{1}=i1_series{1};
191    end
[454]192nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
193nbfield_i=size(i1_series{1},2); %nb of fields for the i index
194nbfield=nbfield_j*nbfield_i; %total number of fields
[592]195nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[454]196nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
[676]198%% output
[592]199FileExtOut='.png'; % write result as .png images for image inputs
200if strcmp(lower(NomType{1}(end)),'a')
201    NomTypeOut=NomType{1};%case of letter appendix
202elseif isempty(j1_series)
203    NomTypeOut='_1';
[592]205    NomTypeOut='_1_1';% caseof purely numerical indexing
[592]208OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[599]210if isequal(Param.ActionInput.CheckVolume,1)
[592]211    step=1;
213    step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
[599]215nbaver_ima=Param.ActionInput.SlidingSequenceLength;%number of images for the sliding background
[592]216nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
217if isequal(floor(nbaver/2),nbaver)
218    nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
221if nbaver_ima > nbfield
222    display('number of images in a slice smaller than the proposed number of images for the sliding average')
223    return
226% calculate absolute brightness rank
[24]228if rank==0
229    rank=1;%rank selected in the sorted image series
[239]232%% prealocate memory for the sliding background
[454]234    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
[700]235    [npy,npx,nbcolor]=size(Afirst);% the argument nbcolor is important to get npx right for color images
[454]236    if strcmp(class(Afirst),'uint8') % case of 8bit images
237        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
238        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
239    else
240        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
241        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
242    end
[239]243catch ME
[592]244    msgbox_uvmat('ERROR',['sub_background/read_image/' ME.message])
[239]245    return
[676]248%% summary of the parameters:
249% nbfield : total number of images treated (in case of multislices the function sub_background is repeated for each slice)
250% step: shift at each step of the sliding background (corresponding to the nbre of images in a burst)
251% nbaver_ima: length of the sequence used for the sliding background
[676]253% nbaver=nbaver_ima/step: nbaver_ima has been adjusted so that nbaver is an odd integer
254halfnbaver=floor(nbaver/2); % half width (in unit of bursts) of the sliding background
256%% select the series of image indices to process
[616]257indselect=1:step:nbfield;% select file indices of the slice
258for ifield=1:step-1
259    indselect=[indselect;indselect(end,:)+1];
262%% read the first series of nbaver_ima images and sort by luminosity at each pixel
263for ifield = 1:nbaver_ima
264    ifile=indselect(ifield);
265    filename=filecell{1,ifile};
266    Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
267    if ndims(Aread)==3;%color images
268        Aread=sum(double(Aread),3);% take the sum of color components
[394]269    end
[616]270    Ak(:,:,ifield)=Aread;
272Asort=sort(Ak,3);%sort the luminosity of images at each point
273B=Asort(:,:,rank);%background image
275%% substract the first background image to the first images
[616]276display( 'first background image will be substracted')
[676]277for ifield=1:step*(halfnbaver+1);% nbre of images treated by the first background image
[616]278    Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
279    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
280    ifile=indselect(ifield);
281    if ~isempty(j1_series{1})
282        j1=j1_series{1}(ifile);
283    end
284    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[616]286    %write result file
287    if Param.ActionInput.CheckLevelTransform
288        C=levels(Acor);
289        imwrite(C,newname,'BitDepth',8); % save the new image
290    else
291        if isequal(FileInfo{1}.BitDepth,16)
292            C=uint16(Acor);
293            imwrite(C,newname,'BitDepth',16); % save the new image
294        else
295            C=uint8(Acor);
296            imwrite(C,newname,'BitDepth',8); % save the new image
[454]297        end
[24]298    end
[616]299    display([newname ' written'])
302%% repeat the operation on a sliding series of images
303display('sliding background image will be substracted')
304if nbfield_i > nbaver_ima
[676]305    for ifield = step*(halfnbaver+1):step:nbfield_i-step*(halfnbaver+1)% ifield +iburst=index of the current processed image
306        update_waitbar(WaitbarHandle,ifield/nbfield_i)
307        if ~isempty(RUNHandle) &&ishandle(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
308            disp('program stopped by user')
309            return
310        end
311        Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
312        %incorporate next burst in the current image series
313        for iburst=1:step
314            ifile=indselect(ifield+iburst+step*halfnbaver);
315            filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1_series{1}(ifile));
316            Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
317            if ndims(Aread)==3;%color images
318                Aread=sum(double(Aread),3);% take the sum of color components
[442]319            end
[676]320            Ak(:,:,nbaver_ima-step+iburst)=Aread;% fill the last burst of the current image series by the new image
321        end
322        Asort=sort(Ak,3);%sort the new current image series by luminosity
323        B=Asort(:,:,rank);%current background image
324        %substract the background for the current burst
325        for iburst=1:step
326            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
327            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
328            ifile=indselect(ifield+iburst);
329            if ~isempty(j1_series{1})
330                j1=j1_series{1}(ifile);
331            end
332            newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
333            %write result file
334            if Param.ActionInput.CheckLevelTransform
335                C=levels(Acor);
336                imwrite(C,newname,'BitDepth',8); % save the new image
337            else
338                if isequal(FileInfo{1}.BitDepth,16)
339                    C=uint16(Acor);
340                    imwrite(C,newname,'BitDepth',16); % save the new image
341                else
342                    C=uint8(Acor);
[616]343                    imwrite(C,newname,'BitDepth',8); % save the new image
[214]344                end
[24]345            end
[676]346            display([newname ' written'])       
347        end
[24]348    end
351%% substract the background from the last images
352display('last background image will be substracted')
[676]353for  ifield=nbfield_i-step*halfnbaver+1:nbfield_i
354    Acor=double(Ak(:,:,ifield-nbfield_i+step*(2*halfnbaver+1)))-double(B);
[616]355    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
356    ifile=indselect(ifield);
357    if ~isempty(j1_series{1})
358        j1=j1_series{1}(ifile);
359    end
[676]360    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1); 
[616]361    %write result file
362    if Param.ActionInput.CheckLevelTransform
363        C=levels(Acor);
364        imwrite(C,newname,'BitDepth',8); % save the new image
365    else
366        if isequal(FileInfo{1}.BitDepth,16)
367            C=uint16(Acor);
368            imwrite(C,newname,'BitDepth',16); % save the new image
369        else
370            C=uint8(Acor);
[394]371            imwrite(C,newname,'BitDepth',8); % save the new image
372        end
373    end
[616]374    display([newname ' written'])
[214]379function C=levels(A)
380%whos A;
400% figure;plot(c,n);
407i_select = find(cumsum(n)<0.95*sum(n));
408if isempty(i_select)
409    i_select = 1:length(c);
Note: See TracBrowser for help on using the repository browser.