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

Last change on this file since 295 was 240, checked in by sommeria, 13 years ago

cleaning

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