Forums

Re: For Loop Execution

Started by Joe Sababa December 9, 2001
--- bakoguz <> wrote:
> I have a problem of for loops.
> I saw the messages about them but it did not help
> me.
> I want to filter my matrix(actually an image) by a
> filter
> and I want to convolve(2D) my filter with my image.
> If I use
> for loops, I need two of them, but the execution is
> too slow.
>
> Can you suggest something about it ?
>
> Thank you...
>
> burak > Example Problem :
>
> % 3x3 mean filter
> mask = [ 1/9 1/9 1/9 ; 1/9 1/9 1/9 ; 1/9 1/9 1/9] ;
>
> [row_mask, col_mask] = size(mask) ;
>
> [row_im , col_im , rgb_ ] = size(image) ;
>
> image = im2double(image,'indexed');
>
> result_image = image ;
>
> for k = 1 : (row_im + 1 - row_mask),
> for m = 1 : (col_im + 1 - col_mask),
>
> part_of_im=image(k:row_mask+k-1,m:col_mask+m-1);
> temp_matrix = times(part_of_im , mask) ;
> sum_temp = round( sum(sum(temp_matrix)) ) ;
> temp_index_row = k-1 +(row_mask+1)/2 ;
> temp_index_col = m-1 +(col_mask+1)/2 ;
> result_image(temp_index_row ,
> temp_index_col) = sum_temp ;
>
> end;
> end; > Hi,
If I followed correctly your example you just want to
put the average of 9 surrounding pixels at each pixel.
The following transformation matrix does it for square
samples:
B=diag(ones(N-1),1); % N is the height (and width)
T=eye(N)+B+B'; % Transformation matrix
Then apply it:
Result=T*A*T/9; % A is the original matrix
*End*
You can try to generalize it to non-square matrices or
to divide your matrix to square blocks.

Joe
BSTEX - Equation viewer for Matlab
http://www.geocities.com/bstex2001

>
>


__________________________________________________