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

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

functions updated in series for the new file configuration

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)
45        %'VelTypeMenu';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
46        %'FieldMenu';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
47        %'VelTypeMenu_1';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
48        %'FieldMenu_1';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
49        %'CoordType';...%can use a transform function
50        %'GetObject';...;%can use projection object
51        %'GetMask';...;%can use mask option 
[214]52        %'PARAMETER';'NbSliding';...
53        %'PARAMETER';'VolumeScan';...
54        %'PARAMETER';'RankBrightness';...
[24]55               ''};
56    return %exit the function
57end
58
[374]59%% input parameters
60% read the xml file for batch case
61if ischar(Param) && ~isempty(find(regexp('Param','.xml$')))
62    Param=xml2struct(Param);
[442]63    checkrun=0;
[374]64else %  RUN case: parameters introduced as the input structure Param
65    hseries=guidata(Param.hseries);%handles of the GUI series
66    WaitbarPos=get(hseries.waitbar_frame,'Position');
[442]67    checkrun=1;
[374]68end
[442]69filebase=fullfile(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3});
[394]70dir_images=Param.InputTable{1,1};
71NomType=Param.InputTable{1,4};
72FileExt=Param.InputTable{1,5};
[442]73[filecell,i1_series,tild,j1_series]=get_file_series(Param);%generates the set
74of input file names
[374]75if size(filecell,1)>1
[394]76    msgbox_uvmat('WARNING','This function uses only the first input image series')
[54]77    return
[24]78end
[394]79
[214]80%% determine input image type
[54]81FileType=[];%default
82MovieObject=[];
[394]83%FileExt=Series.FileExt;
[89]84
[54]85if isequal(lower(FileExt),'.avi')
86    hhh=which('mmreader');
87    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
[442]88        MovieObject=mmreader(fullfile(RootPath,SubDir,[RootFile FileExt]));
[54]89        FileType='movie';
90    else
91        FileType='avi';
92    end
93elseif isequal(lower(FileExt),'.vol')
94    FileType='vol';
[394]95else
96    form=imformats(FileExt(2:end));
97    if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
98        if isequal(NomType,'*');
99            FileType='multimage';
100        else
101            FileType='image';
102        end
103    end
[54]104end
105if isempty(FileType)
106    msgbox_uvmat('ERROR',['invalid file extension ' FileExt ': this function only accepts image or movie input'])
107    return
108end
109
[394]110nbslice_i=Param.NbSlice; %number of slices
111siz=size(i1_series{1});
[24]112nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
[394]113j1=[];%default
[24]114
[214]115%% apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
116answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
117test_level=isequal(answer,'Yes');
118
119%% adjust the proposed number of images in the sliding average to include an integer number of bursts
[24]120if siz(2)~=1
[394]121    nbaver=floor(nbaver_init/siz(1)); % number of bursts used for the sliding background,
[24]122    if isequal(floor(nbaver/2),nbaver)
123        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
124    end
125    nbaver_init=nbaver*siz(1);%propose by default an integer number of bursts
126end
127
[214]128%% create dir of the new images
129if test_level
[442]130    term='.sbk.lev';
[214]131else
[442]132    term='.sbk';
[214]133end
[442]134SubdirResult=[Param.InputTable{1,2} term];
[214]135try
[442]136    mkdir(fullfile(Param.InputTable{1,1},SubdirResult));
[239]137catch ME
[442]138    msgbox_uvmat('ERROR',['error in creating result directory: ' ME.message]);
[394]139    return
[214]140end
[442]141[xx,msg2] = fileattrib(fullfile(Param.InputTable{1,1},SubdirResult),'+w','g'); %yield writing access (+w) to user group (g)
[128]142if ~strcmp(msg2,'')
[442]143    msgbox_uvmat('ERROR',['pb of permission for ' fullfile(Param.InputTable{1,1},SubdirResult) ': ' msg2])%error message for directory creation
[128]144    return
145end
[24]146
[214]147%% set processing parameters
[239]148prompt = {'Number of images for the sliding background (MUST FIT IN COMPUETER MEMORY)';'The number of positions (laser slices)';'volume scan mode (Yes/No)';...
[394]149    'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
[442]150dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' SubdirResult];
[24]151num_lines= 3;
152def     = { num2str(nbaver_init);num2str(nbslice_i);'No';'0.1'};
153answer = inputdlg(prompt,dlg_title,num_lines,def);
154set(hseries.ParamVal,'String',answer([1 [3:4]]))
155set(hseries.ParamVal,'Visible','on')
156
157nbaver_ima=str2num(answer{1});%number of images for the sliding background
[214]158nbaver=ceil(nbaver_ima/siz(1));%number of bursts for the sliding background
[24]159if isequal(floor(nbaver/2),nbaver)
[394]160    nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
[24]161end
[394]162step=siz(1);%case of bursts: the sliding background is shifted by one burst
[24]163vol_test=answer{3};
164if isequal(vol_test,'Yes')
165    nbfield2=1;%case of volume: no consecutive series at a given level
[394]166    nbslice_i=siz(1);%number of slices
[24]167else
168    nbfield2=siz(1); %nb of consecutive images at each level(burst)
169    if siz(2)>1
[394]170        % nbslice_i=str2num(answer{2})/(num_i1(1,2)-num_i1(1,1));% number of slices
171        nbslice_i=str2num(answer{2})/(i1_series{1}(1,2)-i1_series{1}(1,1));% number of slices
[24]172    else
173        nbslice_i=1;
174    end
175    if ~isequal(floor(nbslice_i),nbslice_i)
[38]176        msgbox_uvmat('ERROR','the number of slices must be a multiple of the i increment')
[24]177        return
178    end
179end
180rank=floor(str2num(answer{4})*nbaver_ima);
181if rank==0
182    rank=1;%rank selected in the sorted image series
183end
184lengthtot=siz(1)*siz(2);
185nbfield=floor(lengthtot/(nbfield2*nbslice_i));%total number of i indexes (adjusted to an integer number of slices)
186nbfield_slice=nbfield*nbfield2;% number of fields per slice
187if nbaver_ima > nbfield*nbfield2
[239]188    msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
[24]189    return
190end
191nbfirst=(ceil(nbaver/2))*step;
192if nbfirst>nbaver_ima
[214]193    nbfirst=ceil(nbaver_ima/2);
[24]194    step=1;
195    nbaver=nbaver_ima;
196end
197
[239]198%% prealocate memory for the sliding background
[394]199% first_image=name_generator(filebase,num_i1(1),num_j1(1),FileExt,NomType);
200% Afirst=read_image(first_image,FileType,num_i1(1),MovieObject);
201Afirst=read_image(filecell{1,1},FileType,i1_series{1}(1),MovieObject);
[239]202[npy,npx]=size(Afirst);
[394]203try
204    Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
205    Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
[239]206catch ME
207    msgbox_uvmat('ERROR',ME.message)
208    return
209end
210
[442]211%% update the xml file
212SubDirBase=regexprep(Param.InputTable{1,2},'\..*','');%take the root part of SubDir, before the first dot '.'
213filexml=fulfille(Param.InputTable{1,1},[SubDirBase '.xml']);
214if ~exist(filexml,'file') && exist([filebase '.xml'],'file')% xml inside the image directory
215    copyfile([filebase '.xml'],filexml);% copy the .xml file
216end
217if exist(filexml,'file')
218    t=xmltree([filexml '.xml']); 
[24]219    %update information on the first image name in the series
220    uid_Heading=find(t,'ImaDoc/Heading');
221    if isempty(uid_Heading)
222        [t,uid_Heading]=add(t,1,'element','Heading');
[394]223    end
[24]224    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
[394]225    if ~isempty(j1_series{1})
226        j1=j1_series{1}(1);
227    end
228    ImageName=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(1),[],j1);
229    %     ImageName=name_generator(filebase_b,num_i1(1),num_j1(1),'.png',NomType);
[24]230    [pth,ImageName]=fileparts(ImageName);
[239]231    ImageName=[ImageName '.png'];
[24]232    if isempty(uid_ImageName)
[394]233        [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
[24]234    end
235    uid_value=children(t,uid_ImageName);
236    if isempty(uid_value)
[239]237        t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
[24]238    else
[239]239        t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
[394]240    end
241   
[24]242    %add information about image transform
243    [t,new_uid]=add(t,1,'element','ImageTransform');
244    [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
[394]245    [t]=add(t,NameFunction_uid,'chardata','sub_background');
[217]246    if test_level
[394]247        [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
248        [t]=add(t,NameFunction_uid,'chardata','levels');
[214]249    end
[24]250    [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
251    [t]=add(t,new_uid,'chardata',num2str(nbslice_i));
252    [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
253    [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
254    [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
[394]255    [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
[442]256    save(t,filexml)
[24]257end
258%copy the mask
[442]259% if exist([filebase '_1mask_1'],'file')
260%     copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
261% end
[24]262
263%MAIN LOOP ON SLICES
264for islice=1:nbslice_i
[214]265    %% select the series of image indices at the level islice
[24]266    for ifield=1:nbfield
267        for iburst=1:nbfield2
268            indselect(iburst,ifield)=((ifield-1)*nbslice_i+(islice-1))*nbfield2+iburst;
269        end
[394]270    end
[214]271   
272    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
[24]273    for ifield = 1:nbaver_ima
[54]274        ifile=indselect(ifield);
[394]275        filename=filecell{1,ifile};
276        % filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
277        Aread=read_image(filename,FileType,i1_series{1}(ifile),MovieObject);
278        Ak(:,:,ifield)=Aread;
[24]279    end
280    Asort=sort(Ak,3);%sort the luminosity of images at each point
281    B=Asort(:,:,rank);%background image
[394]282    display( 'first background image will be substracted')
[24]283    for ifield=1:nbfirst
[394]284        Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
285        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
286        C=uint16(Acor);% set to integer 16 bits
287        ifile=indselect(ifield);
288        %             newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType)% makes the new file name
289        if ~isempty(j1_series{1})
290            j1=j1_series{1}(ifile);
291        end
[442]292        newname=fullfile_uvmat(Param.InputTable{1,1},SubdirResult,Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
[394]293        %newname=name_generator(filebase_b,i1_series{1}(ifile),j1_series{1}(ifile),'.png',NomType);% makes the new file name
294        if test_level
295            C=levels(C);
296            imwrite(C,newname,'BitDepth',8); % save the new image
297        else
298            imwrite(C,newname,'BitDepth',16); % save the new image
299        end
[24]300    end
[214]301   
302    %% repeat the operation on a sliding series of nbaver*nbfield2 images
303    display('sliding background image will be substracted')
[24]304    if nbfield_slice > nbaver_ima
305        for ifield = step*ceil(nbaver/2)+1:step:nbfield_slice-step*floor(nbaver/2)
[442]306            if checkrun
307                stopstate=get(hseries.RUN,'BusyAction');
[24]308                update_waitbar(hseries.waitbar,WaitbarPos,(ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i))
[240]309                display((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);
[442]318                    filename=fullfile_uvmat(Param.InputTable{1,1},Subdir,Param.InputTable{1,3},FileExt,NomType,num_i1(ifile),[],num_j1(ifile));
319                    %filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
[89]320                    Aread=read_image(filename,FileType,num_i1(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.