# How can blur an image

348 views (last 30 days)

Show older comments

Write a function called blur that blurs the input image. The function is to be called like this:

output = blur(img,w);

where img, the input image is a two-dimensional matrix of grayscale pixel values between 0 and 255. Blurring is to be carried out by averaging the pixel values in the vicinity of every pixel. Specifically, the output pixel value is the mean of the pixels in a square submatrix of size 2w+1 where the given pixel sits in the center. For example, if w is 1, then we use a 3x3 matrix, that is, we average all the neighboring pixels of the given pixel and itself. Only use valid pixels when portions of the blurring matrix fall outside the image. For example, the blurred value corresponding to w = 1 at index (1,1) would be the mean of of elements (1,1), (1, 2), (2,1) and (2, 2). Both input img and output output are of type uint8.

##### 23 Comments

Image Analyst
on 4 Jun 2021

### Answers (13)

Dipesh Poudel
on 9 Apr 2020

function [output] = blur(A,w)

[row col] = size(A);

A=uint8(A);

B=nan(size(A) + (2*w));

B(w+1:end-w,w+1:end-w)=A;

output = 0*A;

for i=w+1:row+w

for j=w+1:col+w

tmp=B(i-w:i+w,j-w:j+w);

output(i-w,j-w)=mean(tmp(~isnan(tmp)));

end

end

output=uint8(output);

##### 6 Comments

Sourabh Bhange
on 10 Feb 2021

Edited: DGM
on 28 Feb 2022

Hello, Thank you for the reply.

Using the function you suggested:

function output = blur(grayImage, w)

% Get the dimensions of the image.

% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.

[rows, columns, numberOfColorChannels] = size(grayImage);

% Make sure it's a gray scale image, not a color image.

if numberOfColorChannels > 1

% It's not really gray scale like we expected - it's color.

% Use weighted sum of ALL channels to create a gray scale image.

grayImage = rgb2gray(grayImage);

% ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,

% which in a typical snapshot will be the least noisy channel.

% grayImage = grayImage(:, :, 2); % Take green channel.

end

B = nan(size(grayImage) + (2*w)); % Make B larger, padding with NaNs.

B(w+1:end-w, w+1:end-w) = grayImage; % Make central part of B match A.

output = double(grayImage); % Initialize a double array for the output with the size and values of the input.

% Scan the window over the image making the output the average of the input at each pixel location.

for row = w+1:rows+w

for col = w+1:columns+w

% Extract the part of the image under the window at the window's current location.

tmp = B(row-w:row+w, col-w:col+w);

% Replace the output's value there with the mean of the input.

output(row-w, col-w) = mean(tmp(:), 'omitnan');

end

end

% Cast output image to be the same class (uint8, uint16, single, or double) as the input image.

output = cast(output, 'like', grayImage);

When I used in my code I am able to convert rgb2gray and gray2blur.

How I can modify this function if I want to conver rgb2blur?

Image Analyst
on 11 Feb 2021

Your MyBlur() function, which takes an RGB image needs to call imsplit() and call your blur(), which deals with monochrome images:

function blurredRGBImage = MyBlur(rgbImage, windowWidth)

% Split into separate color channels.

[redChannel, greenChannel, blueChannel] = imsplit(rgbImage);

% Blur each color channel independently.

blurredR = blur(redChannel, windowWidth);

blurredG = blur(greenChannel, windowWidth);

blurredB = blur(blueChannel, windowWidth);

% Recombine into a single RGB image.

blurredRGBImage = cat(3, blurredR, blurredG, blurredB);

Then call it:

rgbImage = imread('peppers.png');

blurredRGBImage = uint8(MyBlur(rgbImage, 9));

imshow(blurredRGBImage)

Yaksha SJ
on 10 May 2020

function out = blur(img,w)

% convert to double for doing calculations

imgD = double(img);

[row, col] = size(img);

out = zeros(row, col);

for ii = 1:row

for jj = 1:col

% Get the indices for a submatrix

r1 = ii-w;

r2 = ii+w;

c1 = jj-w;

c2 = jj+w;

% Test that indices are valid

% If not, set to min/max that is valid

if r1 < 1

r1 = 1;

end

if r2 > row

r2 = row;

end

if c1 < 1

c1 = 1;

end

if c2 > col

c2 = col;

end

% Get the submatrix and assign the mean to the output pixel

m = imgD(r1:r2, c1:c2);

out(ii,jj) = mean(m(:));

end

end

% convert back to uint8

out = uint8(out);

end

##### 2 Comments

Kartik agarwal
on 14 May 2020

Edited: Kartik agarwal
on 14 May 2020

Hey, if I produce this change in the last segment of your code, I am getting errors :

Original code :

% Get the submatrix and assign the mean to the output pixel

m = imgD(r1:r2, c1:c2);

out(ii,jj) = mean(m(:));

end

end

% convert back to uint8

out = uint8(out);

end

Changed code :

% Get the submatrix and assign the mean to the output pixel

m = imgD(r1:r2, c1:c2);

out(ii,jj) = uint8(mean(m(:))); % uint8 conversion done here itself%

end

end

end

The error says that Variable output must be of data type uint8. It is currently of type double.

I am new to Matlab. I can't understand the error in doing conversion the way I did in changed code. Please help

KSSV
on 16 Mar 2019

Edited: KSSV
on 16 Mar 2019

I = imread('peppers.png') ;

for i = 1:3

I(:,:,i) = uint8(conv2(I(:,:,i),ones(20)/20^2,'same'));

end

imshow(I) ;

##### 4 Comments

Image Analyst
on 23 Jun 2020

Image Analyst
on 16 Mar 2019

Can your function call the built-in functions conv2() or imfilter()?

If not, see, and adapt, my attached manual convolution program.

##### 2 Comments

Image Analyst
on 22 Mar 2019

Edited: Image Analyst
on 4 May 2020

Well the solution you chose is not very robust, but it will work in some cases, not all cases.

Jaimin Motavar
on 4 Jul 2019

can someone help me to figure out what is wrong in this code?

function output = blur(img,w)

B=double(img);

[m,n] = size(B);

k=2*w+1;

for i = 1:m

for j = 1:n

p=i-fix(k/2);

q=i+fix(k/2);

r=j-fix(k/2);

s=j+fix(k/2);

if p<1

p=1;

end

if q>m

q=m;

end

if r<1

r=1;

end

if s>n

s=n;

end

A=B([p:q],[r:s]);

B(i,j)=mean(A(:));

end

end

output=uint8(B);

end

##### 5 Comments

Namarta Kapil
on 21 Jul 2019

Can somebody please tell me what is wrong with this code? it gives the following error:

- Assessment result: incorrectSimple testVariable output has an incorrect value. Tested with a 5x5 uint8 matrix with all 255-s in the first and last rows and columns and zeros everywhere else and w = 1
- Assessment result: incorrectUsing image fileVariable output has an incorrect value. Tested with the vandy.png file and w = 1

Walter Roberson
on 23 Jul 2019

Brandon McLaughlin
on 22 Jul 2019

Help! I'm almost done with this course but for some reason I can't get this function to work. I have my code all set, but it keeps saying I'm doing it wrong. What am I doing wrong?

function output=blur(img,w)

img=double(img);

d=w*2+1

s=size(img)

output=[]

for r=1:d:s(1)

row=[];

for c=1:d:s(2)

if r+w<=s(1) && c+w<=s(2) && r-w>=1 && c-w>=1

tot=sum(sum(img((r-w):(r+w),(c-w):(c+w))));

val=tot/(d*d);

nxt=ones(d,d);

nxt(1:end,1:end)=val;

row=[row nxt];

elseif c+w<=s(2) && r-w>=1 && c-w>=1

tot=sum(sum(img((r-w):end,(c-w):(c+w))));

val=tot/(d*(s(1)-r+w));

nxt=ones((s(1)-r+w),d);

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r+w<=s(1) && r-w>=1 && c-w>=1

tot=sum(sum(img((r-w):(r+w),(c-w):end)));

val=tot/(d*(s(2)-c+w));

nxt=ones(d,(s(2)-c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r+w<=s(1) && c+w<=s(2) && r-w>=1

tot=sum(sum(img((r-w):(r+w),1:(c+w))));

val=tot/(d*(c+w));

nxt=ones(d,(c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r+w<=s(1) && c+w<=s(2) && c-w>=1

tot=sum(sum(img(1:(r+w),(c-w):(c+w))));

val=tot/(d*(r+w));

nxt=ones((r+w),d);

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r+w<=s(1) && c+w<=s(2)

tot=sum(sum(img(1:(r+w),1:(c+w))));

val=tot/((r+w)*(c+w));

nxt=ones((c+w),(r+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r-w>=1 && c-w>=1

tot=sum(sum(img((r-w):end,(c-w):end)));

val=tot/((s(1)-r+w)*(s(2)-c+w));

nxt=ones((s(1)-r+w),(s(2)-c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif r+w<=s(1) && c-w>=1

tot=sum(sum(img(1:(r+w),(c-w):end)));

val=tot/((r+w)*(s(2)-c+w));

nxt=ones((r+w),(s(2)-c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif c+w<=s(2) && r-w>=1

tot=sum(sum(img((r-w):end,1:(c+w))));

val=tot/((s(1)-r+w)*(c+w));

nxt=ones((s(1)-r+w),(c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

end

end

output=[output;row];

end

row=[]

s2=size(output)

if s2(1)<s(1)

for c=1:d:s(2)

if c+w<=s(2) && c-w>=1

tot=sum(sum(img((s2(1)+1):s(1),(c-w):(c+w))));

val=tot/((s(1)-s2(1))*d);

nxt=ones((s(1)-s2(1)),d);

nxt(1:end,1:end)=val;

row=[row nxt];

elseif c+w<=s(2)

tot=sum(sum(img((s2(1)+1):s(1),1:(c+w))));

val=tot/((s(1)-s2(1))*(c+w));

nxt=ones((s(1)-s2(1)),(c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

elseif c-w>=1

tot=sum(sum(img((s2(1)+1):s(1),(c-w):end)));

val=tot/((s(1)-s2(1))*(s2(2)-c+w));

nxt=ones((s(1)-s2(1)),(s2(2)-c+w));

nxt(1:end,1:end)=val;

row=[row nxt];

end

end

output=[output;row];

end

row=[]

col=[]

s3=size(output)

if s3(2)<s(2)

for r=1:d:s(1)

if r+w<=s(1) && r-w>=1

tot=sum(sum(img((r-w):(r+w),(s3(2)+1):s(2))));

val=tot/(d*(s(2)-s3(2)));

nxt=ones(d,(s(2)-s3(2)));

nxt(1:end,1:end)=val;

col=[col;nxt];

elseif r+w<=s(1)

tot=sum(sum(img(1:(r+w),(s3(2)+1):s(2))));

val=tot/((r+w)*(s(2)-s3(2)));

nxt=ones((r+w),(s(2)-s3(2)));

nxt(1:end,1:end)=val;

col=[col;nxt];

elseif r-w>=1

tot=sum(sum(img((r-w):(r+w),(s3(2)+1):s(2))));

val=tot/((s3(1)-r+w)*(s(2)-s3(2)));

nxt=ones((s3(1)-r+w),(s(2)-s3(2)));

nxt(1:end,1:end)=val;

col=[col;nxt];

end

end

s4=size(col)

if s4(1)<s3(1) || s4(1)<s(1)

tot=sum(sum(img((s2(1)+1):s(1),(s3(2)+1):s(2))));

val=tot/((s(1)-s2(1))*(s(2)-s3(2)));

nxt=ones((s(1)-s2(1)),(s(2)-s3(2)));

nxt(1:end,1:end)=val;

col=[col;nxt];

end

output=[output col];

end

output=uint8(output);

##### 3 Comments

shreyansh pitroda
on 29 Apr 2020

%% can some one find what is error in this code

function [output] = blur(img,w)

img = uint8(img);

[a,b] = size(img);

output = zeros(a,b);

h = 2*w+1;

for i = 1:a-h

for j = 1:b-h

value = img(i:(h+i-1),j:(h+j-1));

output(i,j) = mean(value(:));

end

end

output = uint8(output);

end

##### 6 Comments

Image Analyst
on 4 Jun 2021

@Sana Hafeez, post your code, because I just copied and pasted my code above and it works great. You must have defined blur() differently. Is it in the same file as your script, or a separate m-file. What does this show:

>> which -all blur

Again, here is my code that works perfectly fine.

grayImage = imread('cameraman.tif');

hFig = figure;

subplot(1, 2, 1);

imshow(grayImage);

title('Original', 'FontSize', 20);

hFig.WindowState = 'maximized';

windowHalfWidth = 9;

output = blur(grayImage, windowHalfWidth);

subplot(1, 2, 2);

imshow(output);

title('Blurred', 'FontSize', 20);

% can some one find what is error in this code

function output = blur(img, w)

img = uint8(img);

[rows, columns] = size(img);

output = img; % Initialize output to be the same size as the input image.

h = 2 * w + 1;

fprintf('Filter is %d rows by %d columns.\n', h, h);

for col = h : columns-h

for row = h : rows-h

value = img(row : (h+row-1), col : (h+col-1));

output(row, col) = mean(value(:));

end

end

output = uint8(output);

end

David Gonzalez
on 25 May 2020

function output = blur(img,w)

mirror = -1*ones(size(img) + 2*w);

mirror(w+1:end-w,w+1:end-w) = img;

output = zeros(size(img));

for ii = w+1:size(mirror,1)-w

for jj = w+1:size(mirror,2)-w

submatrix = mirror(ii-w:ii+w,jj-w:jj+w);

sum_values = sum(submatrix(submatrix>=0));

valid = sum(submatrix(:)>=0);

output(ii-w,jj-w) = sum_values/valid;

end

end

output = uint8(output);

##### 0 Comments

Divya Ratna
on 25 May 2020

i figured it out by myself...

i know its too lengthy..

function out = blur (img, w)

temp = img;

s = size(img);

if s(1) > w && s(2) > w

%1

for i = 1 : w

for j = 1 : w

temp (i,j) = sum(sum(img(1:i+w , 1:j+w))') / ((i+w)*(j+w));

end

end

%2

for i = 1 : w

for j = w+1 : s(2)-w

temp (i,j) = sum(sum(img(1:i+w , j-w:j+w))') / ((i+w)*(w+w+1));

end

end

%3

for i = 1 : w

for j = s(2)-w+1 : s(2)

temp (i,j) = sum(sum(img(1:i+w , j-w:s(2)))') / ((i+w)*(s(2)-j+1+w));

end

end

%4

for i = w+1 : s(1)-w

for j = 1 : w

temp (i,j) = sum(sum(img(i-w:i+w , 1:j+w))') / ((w+w+1)*(j+w));

end

end

%5

for i = w+1 : s(1)-w

for j = w+1 : s(2)-w

temp (i,j) = sum(sum(img(i-w:i+w , j-w:j+w))') / ((w+w+1)*(w+w+1));

end

end

%6

for i = w+1 : s(1)-w

for j = s(2)-w+1 : s(2)

temp (i,j) = sum(sum(img(i-w:i+w , j-w:s(2)))') / ((w+w+1)*(s(2)-j+1+w));

end

end

%7

for i = s(1)-w+1 : s(1)

for j = 1 : w

temp (i,j) = sum(sum(img(i-w:s(1) , 1:j+w))') / ((s(1)-i+1+w)*(j+w));

end

end

%8

for i = s(1)-w+1 : s(1)

for j = w+1 : s(2)-w

temp (i,j) = sum(sum(img(i-w:s(1) , j-w:j+w))') / ((s(1)-i+1+w)*(w+w+1));

end

end

%9

for i = s(1)-w+1 : s(1)

for j = s(2)-w : s(2)

temp (i,j) = sum(sum(img(i-w:s(1) , j-w:s(2)))') / ((s(1)-i+1+w)*(s(2)-j+1+w));

end

end

end

out = temp;

end

Chandrashekhar Dhangar
on 16 Jul 2020

%can someone pls help with this?

%Error=Variable output has an incorrect value.

%Tested with a 5x5 uint8 matrix with all 255-s in the first and last rows and columns and zeros everywhere else and w = 1

function output=blur(img,w)

[m, n]=size(img);

im=double(img);

S=zeros(2*w+1,2*w+1);

out=zeros(m,n);

for i=1:m

for j=1:n

for u=1:2*w+1

for v=1:2*w+1

if i-w>0 && j-w>0 && i-w+u-1<=m && j-w+v-1<=n

S(u,v)=im(i-w+u-1,j-w+v-1);

else

S(u,v)=0;

end

end

end

out(i,j)=sum(S(:))/(2*w+1)^2;

end

end

output=uint8(out);

end

##### 9 Comments

aniket GIRI
on 18 Jul 2020

Edited: DGM
on 28 Feb 2022

function out = blur(img,w)

% convert to double for doing calculations

imgD = double(img);

[row, col] = size(img);

out = zeros(row, col);

for ii = 1:row

for jj = 1:col

% Get the indices for a submatrix

r1 = ii-w;

r2 = ii+w;

c1 = jj-w;

c2 = jj+w;

% Test that indices are valid % If not, set to min/max that is valid

if 1 < 1

r1 = 1;

end

if r2 > row

r2 = row;

end

if c1 < 1

c1 = 1;

end

if c2 > col

c2 = col;

end

% Get the submatrix and assign the mean to the output pixel

m = imgD(r1:r2, c1:c2);

out(ii,jj) = mean(m(:));

end

end

% convert back to uint8

out = uint8(out);

end

##### 4 Comments

Deepthi Thomas
on 23 Jul 2020

I changed the mean variable to another name 'mean1'. I checked with the debugger and the loop is running till row=1 and col=3.

But it then stops with another error message:

Index in position 1 is invalid. Array indices must be positive integers or logical values.

Error in blur (line 22)

sub_matrix= img1(row-w:row+w,col-w:col+w);

The sub_matrix remains a 3X4 double and the mean1 is a 1X1 double, 255, since I changed mean1= mean(sub_matrix(:)). But the debugger goes to the else statement and shows this error message.

Image Analyst
on 23 Jul 2020

Josh Yaksich
on 13 Jun 2021

Edited: Josh Yaksich
on 13 Jun 2021

This is what I did and it worked. Please don't copy it directly, as you will only be hurting yourself. Hopefully it helps when deciding what approach to take:

function output = blur(img,w)

%save dimensions of img

y = size(img,1);

x = size(img,2);

%make a duplicate img for modification

imgdup = img;

%create a larger matrix of all -1's that's the same size as image plus a border

bsquare = ones(y + 2 * w,x + 2 * w) * -1;

%copy img inside of larger matrix

bsquare((w + 1):end - w, w + 1:end - w) = img;

for i = 1:y

for j = 1:x

%make a small matrix for an individual pixel plus its surrounding pixels

pixelraw = bsquare([i:2 * w + i],[j:2 * w + j]);

%calculate the average value in the small matrix while ignoring -1

pixelavg = mean(pixelraw(pixelraw ~= -1));

%copy the average value to an individual pixel in the duplicate image

imgdup(i,j) = pixelavg;

end

end

%convert duplicate image to unint8 and assign to output

output = uint8(imgdup);

##### 0 Comments

### See Also

### Categories

### Products

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!