How can blur an image

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.
You can download the test image here to use in MATLAB.

23 Comments

Jorge Ortiz
Jorge Ortiz on 16 Mar 2019
Edited: Jorge Ortiz on 16 Mar 2019
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);
Thank you very much... I got it where I went wrong
hey guys i have done almost the whole course but i am stuck at that sparse2matrix assignment plz somebody help me out........
What's the question?
Sparse Matrix was quite tricky, as you have to make your code robust to handle alot of input
function matrix = sparse2matrix(cellvec)
r= cellvec{1}(1); c= cellvec{1}(2);
matrix = zeros(r, c) + cellvec{2};
i =3;
while i <= size(cellvec, 2)
j=1;
matrix(cellvec{i}(j),cellvec{i}(j+1)) = cellvec{i}(j+2);
i = i+1;
end
end
If anyone has solved this problem, please share the hints or solution.
I solved it in my Answer in two different ways. Scroll down to see my Answer.
Is it possible to solve this problem using a single for loop?
Yes but it would be a lot harder, and no faster.
@Jorge Ortiz please guide me. by using that code i cannot solved my assignment
@Sana Hafeez, post your code and image in a new thread if you can't solve it using any of the code in the answers below.
Please send me a correct code.
Delete the end on line 12. Add an end statement after the assignment statement.
Image Analyst and I have better things to do with our time then to type in code from an image of code just to exchange two lines.
By the way: you have not defined unit8
Please guide what method that used to defined unit 8
still I am stucked
I am tired now
anyone please help me.......
Thanks in Advance!
uint8() not unit8()
You know, there is a little double page icon in the upper left of the code blocks so that you can copy the code. The code blocks I see here all have uint8(), not unit8(). If you had copied, you would not have had that problem.
Thank you so much

Sign in to comment.

Answers (13)

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

output(i-w,j-w)=mean(tmp(~isnan(tmp)))
can anyone explain this statement of the code
It takes the mean of the small tmp window but only for valid values, not NaN values (which should normally not be any). There is a new flag for mean, 'omitnan', so the newest way of doing that would be
output(i - w, j - w) = mean(tmp(:), 'omitnan');
It then assigns the mean of the window to the output at the cirrent location of the center of the window.
I've corrected a number of errors in that code, and made it more robust. The corrected code is shown below. Though you'd probably be better off using the code in my Answer instead.
% grayImage is the input image. It may be of any type (uint8, uint16, single, double).
% w is the window width of the scanning filter.
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);
clc;
A = imread('xyz.bmp');
B = rgb2gray(A);
A2 = MyBlur(A,2);
B2 = MyBlur(B,2);
subplot(2, 2, 1), imshow(A), title('A');
subplot(2, 2, 2), imshow(B), title('B');
subplot(2, 2, 3), imshow(A2), title('A2');
subplot(2, 2, 4), imshow(B2), title('B2');
How can I modify MyBlur function so it will blur the images without converting to rgb2gray??
Do it one channel at a time
% Split into separate color channels.
[redChannel, greenChannel, blueChannel] = imsplit(A);
% Blur each color channel independently.
blurredR = MyBlur(redChannel, 2);
blurredG = MyBlur(greenChannel, 2);
blurredB = MyBlur(blueChannel, 2);
% Recombine into a single RGB image.
blurredRGBImage = cat(3, blurredR, blurredG, blurredB);
Sourabh Bhange
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?
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)

Sign in to comment.

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

hint:
r1 = max(1, ii-w);
Kartik agarwal
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

Sign in to comment.

KSSV
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

I think you mean
conv2(double(I(:,:,i)),ones(2*w+1)/(2*w+1)^2,'same') % Need to cast from uint8 to double in order to use conv2()
Jorge Ortiz
Jorge Ortiz on 16 Mar 2019
Edited: Image Analyst on 4 May 2020
Already done!! Above in the question is the solution I chose.
Thank you very much anyway.
Hello Jorge, I really need help figuring this code out
What code? Jorge's or KSSV's? Or one of the other multitude of places where code appears on this page?

Sign in to comment.

Image Analyst
Image Analyst on 16 Mar 2019

0 votes

Can your function call the built-in functions conv2() or imfilter()?
If not, see, and adapt, my attached manual convolution program.

2 Comments

Jorge Ortiz
Jorge Ortiz on 16 Mar 2019
Edited: Image Analyst on 4 May 2020
Already done!! Above in the question is the solution I chose.
Thank you very much anyway.
Image Analyst
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.

Sign in to comment.

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

KSSV
KSSV on 4 Jul 2019
It works fine...what problem you have?
it is not giving proper answer.
Attach your images (input and blurred output) and say WHY it's not giving the proper answer.
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
You are overwriting your input data in B as you do the calculation, so your calculation is being based upon the already-smoothed pixels above and to the left instead of on the original pixels above and to the left.

Sign in to comment.

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);
Image Analyst
Image Analyst on 23 Jul 2019

0 votes

See my manual convolution routine, attached.
%% 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

Try this:
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
still getting the same error
What error are you getting, on what inputs?
Note that your blur function will only work for grayscale images, not for RGB images.
@Image Analyst by using that code still i getting an error
Please Help
Undefined function 'blur' for input arguments of type 'uint8'.
@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
Thanks a lot!!

Sign in to comment.

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);
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
%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

This ran without error for me:
img = zeros(5, 5, 'uint8');
img([1, end],:) = 255;
img(:, [1, end]) = 255
w = 1;
output=blur(img,w)
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
Thanks for the response. Its working in Matlab software but showing the above error on website..
Huh? What website? As you can see, the code does run without error but probably doesn't do what you expect.
I'm agree with you. But the code is doing what we expect here. It was an assignment on Coursera.com
Look at the result:
img =
5×5 uint8 matrix
255 255 255 255 255
255 0 0 0 255
255 0 0 0 255
255 0 0 0 255
255 255 255 255 255
output =
5×5 uint8 matrix
0 0 0 0 0
0 142 85 142 113
0 85 0 85 85
0 142 85 142 113
0 113 85 113 85
You're going from row/col 2 to the very end. How are you supposed to handle edge effects? Were you supposed to replace the 255's on the top row with the average of the first two rows? Or were you supposed to leave it as 255? Were you supposed to compute the averages all the way to the end, or were you supposed to quit a line before the last row or column?
ohh sorry. Got it. Thanks a lot.
@Image Analyst that code does not ran. Please help me I am tired to solve image blur problem...

Sign in to comment.

aniket GIRI
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

This is the same image blur question that I'm trying
Here is my code
but I'm getting an error saying this:
Index exceeds the number of array elements (1).
Error in blur (line 11)
mean=mean(sub_matrix)
Can anyone tell me what's wrong with my code?
I have seen the solution above but Im still trying to modify my code since I dont want to copy paste the solution. So pls help if its possible to improve my code to get to the solution.
here is my code:
function output = blur(img,w)
mean=0;
img1=double(img);
[r,c]=size(img1);
for row=1:r
for col=1:c
if row-w <=0 && col-w<=0
sub_matrix= img1(1:row+w, 1:col+w);
mean=mean(sub_matrix);
elseif row+w>= r && col+w>=c
sub_matrix= img1(row-w:r,col-w:c);
mean=mean(sub_matrix);
elseif row-w<0 && col+w>=c
sub_matrix=img1(1:row+w,col-w:c);
mean=mean(sub_matrix);
elseif row+w>=r && col-w<0
sub_matrix=img1(row-w:r, col:col+w);
mean=mean(sub_matrix);
else
sub_matrix= img1(row-w:row+w,col-w:col+w);
mean=mean(sub_matrix);
end
end
output=uint8(mean);
end
mean=mean(sub_matrix);
That replaces the function named mean() with a variable named mean . After you do that you can no longer use mean() as a function.
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.
If row is 1, then row-w is zero or negative. You can't start at row 1 unless you check for the case where the window would be off the image, in which case you'd have to truncate the window. See my attached manual convolution.

Sign in to comment.

Josh Yaksich
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);

Categories

Find more on Convert Image Type in Help Center and File Exchange

Asked:

on 16 Mar 2019

Edited:

DGM
on 28 Feb 2022

Community Treasure Hunt

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

Start Hunting!