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

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

aver_stat modified in the new rationalized form.
OTHER series FCTS NOT OPERATIONAL

File size: 18.2 KB
RevLine 
[169]1%'sub_background': substract background to an image series, used with series.fig
2%------------------------------------------------------------------------
[374]3% function GUI_input=sub_background(Param)
[169]4%
5%OUTPUT
6% GUI_input=list of options in the GUI series.fig needed for the function
7%
8%INPUT:
9%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
10%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
11%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
12%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
13%Series: Matlab structure containing information set by the series interface
14%       .RootPath: path to the image series
15%       .RootFile: root file name
16%       .FileExt: image file extension
17%       .NomType: nomenclature type for file indexing
18%       .NbSlice: %number of slices defined on the interface
[24]19%----------------------------------------------------------------------
20% Method:
21    %calculate the background image by sorting the luminosity of each point
22    % over a sliding sub-sequence of 'nbaver_ima' images.
23    % The luminosity value of rank 'rank' is selected as the
24    % 'background'. rank=nbimages/2 gives the median value.  Smaller values are appropriate
25    % for a dense set of particles. The extrem value rank=1 gives the true minimum
26    % luminosity, but it can be polluted by noise.
27% Organization of image indices:
28    % The program is working on a series of images, labelled by two indices i and j, given
29    % by the input matlab vectors num_i1 and num_j1 respectively. In the list, j is the fastest increasing index.
30    % The processing can be done in slices (number nbslice), with bursts of
31    % nbfield2 successive images for a given slice (mode 'multilevel')
[169]32    % In the mode 'volume', nbfield2=1 (1 image at each level)
33%
[374]34function GUI_input=sub_background (Param)
[24]35
36%------------------------------------------------------------------------
37%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
[374]38if ~exist('Param','var')
[24]39    GUI_input={'RootPath';'on';...
40        'SubDir';'off';... % subdirectory of derived files (PIV fields), ('on' by default)
41        'RootFile';'on';... %root input file name ('on' by default)
42        'FileExt';'on';... %inputf file extension ('on' by default)
43        'NomType';'on';...%type of file indexing ('on' by default)
44        'NbSlice';'on'; ...%nbre of slices ('off' by default)
[447]45        'OutputDirExt';'.sbk';...
[24]46        %'VelTypeMenu';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
47        %'FieldMenu';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
48        %'VelTypeMenu_1';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
49        %'FieldMenu_1';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
50        %'CoordType';...%can use a transform function
51        %'GetObject';...;%can use projection object
52        %'GetMask';...;%can use mask option 
[214]53        %'PARAMETER';'NbSliding';...
54        %'PARAMETER';'VolumeScan';...
55        %'PARAMETER';'RankBrightness';...
[24]56               ''};
57    return %exit the function
58end
59
[374]60%% input parameters
61% read the xml file for batch case
62if ischar(Param) && ~isempty(find(regexp('Param','.xml$')))
63    Param=xml2struct(Param);
[442]64    checkrun=0;
[374]65else %  RUN case: parameters introduced as the input structure Param
66    hseries=guidata(Param.hseries);%handles of the GUI series
67    WaitbarPos=get(hseries.waitbar_frame,'Position');
[442]68    checkrun=1;
[374]69end
[442]70filebase=fullfile(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3});
[394]71dir_images=Param.InputTable{1,1};
72NomType=Param.InputTable{1,4};
[447]73SubDir=Param.InputTable{1,2};
[394]74FileExt=Param.InputTable{1,5};
[447]75[filecell,i1_series,tild,j1_series]=get_file_series(Param);%generates the set of input file names
[374]76if size(filecell,1)>1
[394]77    msgbox_uvmat('WARNING','This function uses only the first input image series')
[54]78    return
[24]79end
[394]80
[214]81%% determine input image type
[54]82FileType=[];%default
83MovieObject=[];
[394]84%FileExt=Series.FileExt;
[89]85
[54]86if isequal(lower(FileExt),'.avi')
87    hhh=which('mmreader');
88    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
[442]89        MovieObject=mmreader(fullfile(RootPath,SubDir,[RootFile FileExt]));
[54]90        FileType='movie';
91    else
92        FileType='avi';
93    end
94elseif isequal(lower(FileExt),'.vol')
95    FileType='vol';
[394]96else
97    form=imformats(FileExt(2:end));
98    if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
99        if isequal(NomType,'*');
100            FileType='multimage';
101        else
102            FileType='image';
103        end
104    end
[54]105end
106if isempty(FileType)
107    msgbox_uvmat('ERROR',['invalid file extension ' FileExt ': this function only accepts image or movie input'])
108    return
109end
110
[394]111nbslice_i=Param.NbSlice; %number of slices
112siz=size(i1_series{1});
[24]113nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
[394]114j1=[];%default
[24]115
[214]116%% apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
117answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
118test_level=isequal(answer,'Yes');
119
120%% adjust the proposed number of images in the sliding average to include an integer number of bursts
[24]121if siz(2)~=1
[394]122    nbaver=floor(nbaver_init/siz(1)); % number of bursts used for the sliding background,
[24]123    if isequal(floor(nbaver/2),nbaver)
124        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
125    end
126    nbaver_init=nbaver*siz(1);%propose by default an integer number of bursts
127end
128
[214]129%% create dir of the new images
130if test_level
[442]131    term='.sbk.lev';
[214]132else
[442]133    term='.sbk';
[214]134end
[442]135SubdirResult=[Param.InputTable{1,2} term];
[214]136try
[442]137    mkdir(fullfile(Param.InputTable{1,1},SubdirResult));
[239]138catch ME
[442]139    msgbox_uvmat('ERROR',['error in creating result directory: ' ME.message]);
[394]140    return
[214]141end
[442]142[xx,msg2] = fileattrib(fullfile(Param.InputTable{1,1},SubdirResult),'+w','g'); %yield writing access (+w) to user group (g)
[128]143if ~strcmp(msg2,'')
[442]144    msgbox_uvmat('ERROR',['pb of permission for ' fullfile(Param.InputTable{1,1},SubdirResult) ': ' msg2])%error message for directory creation
[128]145    return
146end
[24]147
[214]148%% set processing parameters
[239]149prompt = {'Number of images for the sliding background (MUST FIT IN COMPUETER MEMORY)';'The number of positions (laser slices)';'volume scan mode (Yes/No)';...
[394]150    'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
[442]151dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' SubdirResult];
[24]152num_lines= 3;
153def     = { num2str(nbaver_init);num2str(nbslice_i);'No';'0.1'};
154answer = inputdlg(prompt,dlg_title,num_lines,def);
155set(hseries.ParamVal,'String',answer([1 [3:4]]))
156set(hseries.ParamVal,'Visible','on')
157
158nbaver_ima=str2num(answer{1});%number of images for the sliding background
[214]159nbaver=ceil(nbaver_ima/siz(1));%number of bursts for the sliding background
[24]160if isequal(floor(nbaver/2),nbaver)
[394]161    nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
[24]162end
[394]163step=siz(1);%case of bursts: the sliding background is shifted by one burst
[24]164vol_test=answer{3};
165if isequal(vol_test,'Yes')
166    nbfield2=1;%case of volume: no consecutive series at a given level
[394]167    nbslice_i=siz(1);%number of slices
[24]168else
169    nbfield2=siz(1); %nb of consecutive images at each level(burst)
170    if siz(2)>1
[394]171        % nbslice_i=str2num(answer{2})/(num_i1(1,2)-num_i1(1,1));% number of slices
172        nbslice_i=str2num(answer{2})/(i1_series{1}(1,2)-i1_series{1}(1,1));% number of slices
[24]173    else
174        nbslice_i=1;
175    end
176    if ~isequal(floor(nbslice_i),nbslice_i)
[38]177        msgbox_uvmat('ERROR','the number of slices must be a multiple of the i increment')
[24]178        return
179    end
180end
181rank=floor(str2num(answer{4})*nbaver_ima);
182if rank==0
183    rank=1;%rank selected in the sorted image series
184end
185lengthtot=siz(1)*siz(2);
186nbfield=floor(lengthtot/(nbfield2*nbslice_i));%total number of i indexes (adjusted to an integer number of slices)
187nbfield_slice=nbfield*nbfield2;% number of fields per slice
188if nbaver_ima > nbfield*nbfield2
[239]189    msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
[24]190    return
191end
192nbfirst=(ceil(nbaver/2))*step;
193if nbfirst>nbaver_ima
[214]194    nbfirst=ceil(nbaver_ima/2);
[24]195    step=1;
196    nbaver=nbaver_ima;
197end
198
[239]199%% prealocate memory for the sliding background
[394]200% first_image=name_generator(filebase,num_i1(1),num_j1(1),FileExt,NomType);
201% Afirst=read_image(first_image,FileType,num_i1(1),MovieObject);
202Afirst=read_image(filecell{1,1},FileType,i1_series{1}(1),MovieObject);
[239]203[npy,npx]=size(Afirst);
[394]204try
205    Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
206    Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
[239]207catch ME
208    msgbox_uvmat('ERROR',ME.message)
209    return
210end
211
[442]212%% update the xml file
213SubDirBase=regexprep(Param.InputTable{1,2},'\..*','');%take the root part of SubDir, before the first dot '.'
[447]214filexml=fullfile(Param.InputTable{1,1},[SubDirBase '.xml']);
[442]215if ~exist(filexml,'file') && exist([filebase '.xml'],'file')% xml inside the image directory
216    copyfile([filebase '.xml'],filexml);% copy the .xml file
217end
218if exist(filexml,'file')
[447]219    t=xmltree(filexml); 
[24]220    %update information on the first image name in the series
221    uid_Heading=find(t,'ImaDoc/Heading');
222    if isempty(uid_Heading)
223        [t,uid_Heading]=add(t,1,'element','Heading');
[394]224    end
[24]225    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
[394]226    if ~isempty(j1_series{1})
227        j1=j1_series{1}(1);
228    end
229    ImageName=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(1),[],j1);
230    %     ImageName=name_generator(filebase_b,num_i1(1),num_j1(1),'.png',NomType);
[24]231    [pth,ImageName]=fileparts(ImageName);
[239]232    ImageName=[ImageName '.png'];
[24]233    if isempty(uid_ImageName)
[394]234        [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
[24]235    end
236    uid_value=children(t,uid_ImageName);
237    if isempty(uid_value)
[239]238        t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
[24]239    else
[239]240        t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
[394]241    end
242   
[24]243    %add information about image transform
244    [t,new_uid]=add(t,1,'element','ImageTransform');
245    [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
[394]246    [t]=add(t,NameFunction_uid,'chardata','sub_background');
[217]247    if test_level
[394]248        [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
249        [t]=add(t,NameFunction_uid,'chardata','levels');
[214]250    end
[24]251    [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
252    [t]=add(t,new_uid,'chardata',num2str(nbslice_i));
253    [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
254    [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
255    [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
[394]256    [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
[442]257    save(t,filexml)
[24]258end
259%copy the mask
[442]260% if exist([filebase '_1mask_1'],'file')
261%     copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
262% end
[24]263
264%MAIN LOOP ON SLICES
265for islice=1:nbslice_i
[214]266    %% select the series of image indices at the level islice
[24]267    for ifield=1:nbfield
268        for iburst=1:nbfield2
269            indselect(iburst,ifield)=((ifield-1)*nbslice_i+(islice-1))*nbfield2+iburst;
270        end
[394]271    end
[214]272   
273    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
[24]274    for ifield = 1:nbaver_ima
[54]275        ifile=indselect(ifield);
[394]276        filename=filecell{1,ifile};
277        % filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
278        Aread=read_image(filename,FileType,i1_series{1}(ifile),MovieObject);
279        Ak(:,:,ifield)=Aread;
[24]280    end
281    Asort=sort(Ak,3);%sort the luminosity of images at each point
282    B=Asort(:,:,rank);%background image
[394]283    display( 'first background image will be substracted')
[24]284    for ifield=1:nbfirst
[394]285        Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
286        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
287        C=uint16(Acor);% set to integer 16 bits
288        ifile=indselect(ifield);
289        %             newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType)% makes the new file name
290        if ~isempty(j1_series{1})
291            j1=j1_series{1}(ifile);
292        end
[442]293        newname=fullfile_uvmat(Param.InputTable{1,1},SubdirResult,Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
[394]294        %newname=name_generator(filebase_b,i1_series{1}(ifile),j1_series{1}(ifile),'.png',NomType);% makes the new file name
295        if test_level
296            C=levels(C);
297            imwrite(C,newname,'BitDepth',8); % save the new image
298        else
299            imwrite(C,newname,'BitDepth',16); % save the new image
300        end
[24]301    end
[214]302   
303    %% repeat the operation on a sliding series of nbaver*nbfield2 images
304    display('sliding background image will be substracted')
[24]305    if nbfield_slice > nbaver_ima
306        for ifield = step*ceil(nbaver/2)+1:step:nbfield_slice-step*floor(nbaver/2)
[442]307            if checkrun
308                stopstate=get(hseries.RUN,'BusyAction');
[447]309                update_waitbar(hseries.waitbar_frame,WaitbarPos,(ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i))
[442]310            else
311                stopstate='queue';
312            end
313            if isequal(stopstate,'queue')% enable STOP command
[240]314                Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
[24]315                %incorporate next burst in the current image series
316                for iburst=1:step
317                    ifile=indselect(ifield+step*floor(nbaver/2)+iburst-1);
[447]318                    filename=fullfile_uvmat(Param.InputTable{1,1},SubDir,Param.InputTable{1,3},FileExt,NomType,i1_series{1}(ifile),[],j1_series{1}(ifile));
[442]319                    %filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
[447]320                    Aread=read_image(filename,FileType,i1_series{1}(ifile),MovieObject);
[24]321                    Ak(:,:,nbaver_ima-step+iburst)=Aread;
322                end
323                Asort=sort(Ak,3);%sort the new current image series by luminosity
324                B=Asort(:,:,rank);%current background image
325                for iburst=1:step
326                    index=step*floor(nbaver/2)+iburst;
327                    Acor=double(Ak(:,:,index))-double(B);
328                    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
329                    C=uint16(Acor);
330                    ifile=indselect(ifield+iburst-1);
[394]331                    if ~isempty(j1_series{1})
332                        j1=j1_series{1}(ifile);
333                    end
[442]334                    newname=fullfile_uvmat(Param.InputTable{1,1},SubdirResult,Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
[394]335                    %[newname]=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType) % makes the new file name
[214]336                    if test_level
337                        C=levels(C);
338                        imwrite(C,newname,'BitDepth',8); % save the new image
339                    else
340                        imwrite(C,newname,'BitDepth',16); % save the new image
341                    end
342                end
[24]343            else
344                return
345            end
346        end
347    end
[394]348   
349    %% substract the background from the last images
[214]350    display('last background image will be substracted')
[394]351    ifield=nbfield_slice-(step*ceil(nbaver/2))+1:nbfield_slice;
352    for ifield=nbfield_slice-(step*floor(nbaver/2))+1:nbfield_slice
353        index=ifield-nbfield_slice+step*(2*floor(nbaver/2)+1);
354        Acor=double(Ak(:,:,index))-double(B);
355        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
356        C=uint16(Acor);
357        ifile=indselect(ifield);
358        if ~isempty(j1_series{1})
359            j1=j1_series{1}(ifile);
360        end
[442]361        newname=fullfile_uvmat(Param.InputTable{1,1},SubdirResult,Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
[394]362        if test_level
363            C=levels(C);
364            imwrite(C,newname,'BitDepth',8); % save the new image
365        else
366            imwrite(C,newname,'BitDepth',16); % save the new image
367        end
368    end
[24]369end
370
371%finish the waitbar
[442]372if checkrun
373    update_waitbar(hseries.waitbar,WaitbarPos,1)
374end
[24]375
[54]376%------------------------------------------------------------------------
377%--read images and convert them to the uint16 format used for PIV
[89]378function A=read_image(filename,type_ima,num,MovieObject)
[54]379%------------------------------------------------------------------------
380%num is the view number needed for an avi movie
381switch type_ima
382    case 'movie'
[89]383        A=read(MovieObject,num);
[54]384    case 'avi'
385        mov=aviread(filename,num);
386        A=frame2im(mov(1));
387    case 'multimage'
388        A=imread(filename,num);
389    case 'image'   
390        A=imread(filename);
391end
392siz=size(A);
393if length(siz)==3;%color images
394    A=sum(double(A),3);
395end
[24]396   
[214]397
398function C=levels(A)
399%whos A;
400B=double(A(:,:,1));
401windowsize=round(min(size(B,1),size(B,2))/20);
402windowsize=floor(windowsize/2)*2+1;
[239]403ix=1/2-windowsize/2:-1/2+windowsize/2;%
[214]404%del=np/3;
405%fct=exp(-(ix/del).^2);
406fct2=cos(ix/(windowsize-1)/2*pi/2);
407%Mfiltre=(ones(5,5)/5^2);
408%Mfiltre=fct2';
409Mfiltre=fct2'*fct2;
410Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
411
412C=filter2(Mfiltre,B);
413C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
414C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
415C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
416C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
417C=tanh(B./(2*C));
418[n,c]=hist(reshape(C,1,[]),100);
419% figure;plot(c,n);
420
421[m,i]=max(n);
422c_max=c(i);
423[dummy,index]=sort(abs(c-c(i)));
424n=n(index);
425c=c(index);
426i_select = find(cumsum(n)<0.95*sum(n));
427if isempty(i_select)
428    i_select = 1:length(c);
429end
430c_select=c(i_select);
431n_select=n(i_select);
432cmin=min(c_select);
433cmax=max(c_select);
434C=(C-cmin)/(cmax-cmin)*256;
435C=uint8(C);
Note: See TracBrowser for help on using the repository browser.