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 commentaires

Jorge Ortiz
Jorge Ortiz le 16 Mar 2019
Modifié(e) : Jorge Ortiz le 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);
Jorge Ortiz
Jorge Ortiz le 22 Mar 2019
Priyamvada Shankar
Priyamvada Shankar le 22 Mar 2019
Thank you very much... I got it where I went wrong
Xenium Adil
Xenium Adil le 30 Avr 2019
hey guys i have done almost the whole course but i am stuck at that sparse2matrix assignment plz somebody help me out........
Jorge Ortiz
Jorge Ortiz le 30 Avr 2019
What's the question?
Oyedamola ASIYANBOLA
Oyedamola ASIYANBOLA le 23 Juil 2019
Modifié(e) : Oyedamola ASIYANBOLA le 23 Juil 2019
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
Fahim MUMAND
Fahim MUMAND le 15 Oct 2019
If anyone has solved this problem, please share the hints or solution.
Image Analyst
Image Analyst le 15 Oct 2019
I solved it in my Answer in two different ways. Scroll down to see my Answer.
Raghav Gupta
Raghav Gupta le 1 Déc 2020
Is it possible to solve this problem using a single for loop?
Image Analyst
Image Analyst le 1 Déc 2020
Yes but it would be a lot harder, and no faster.
Sana Hafeez
Sana Hafeez le 2 Juin 2021
@Jorge Ortiz please guide me. by using that code i cannot solved my assignment
Image Analyst
Image Analyst le 2 Juin 2021
@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.
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Please send me a correct code.
Walter Roberson
Walter Roberson le 2 Juin 2021
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
Sana Hafeez
Sana Hafeez le 4 Juin 2021
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!
Walter Roberson
Walter Roberson le 4 Juin 2021
uint8() not unit8()
Image Analyst
Image Analyst le 4 Juin 2021
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.
Sana Hafeez
Sana Hafeez le 5 Juin 2021
Thank you so much

Connectez-vous pour commenter.

Réponses (13)

Dipesh Poudel
Dipesh Poudel le 9 Avr 2020

6 votes

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 commentaires

Mohammed Shahin P
Mohammed Shahin P le 4 Mai 2020
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);
Sourabh Bhange
Sourabh Bhange le 10 Fév 2021
Modifié(e) : Sourabh Bhange le 10 Fév 2021
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??
Image Analyst
Image Analyst le 10 Fév 2021
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 le 10 Fév 2021
Modifié(e) : DGM le 28 Fév 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
Image Analyst le 11 Fév 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)

Connectez-vous pour commenter.

Yaksha SJ
Yaksha SJ le 10 Mai 2020

2 votes

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 commentaires

hint:
r1 = max(1, ii-w);
Kartik agarwal
Kartik agarwal le 14 Mai 2020
Modifié(e) : Kartik agarwal le 14 Mai 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

Connectez-vous pour commenter.

KSSV
KSSV le 16 Mar 2019
Modifié(e) : KSSV le 16 Mar 2019

0 votes

I = imread('peppers.png') ;
for i = 1:3
I(:,:,i) = uint8(conv2(I(:,:,i),ones(20)/20^2,'same'));
end
imshow(I) ;

4 commentaires

Image Analyst
Image Analyst le 16 Mar 2019
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 le 16 Mar 2019
Modifié(e) : Image Analyst le 4 Mai 2020
Already done!! Above in the question is the solution I chose.
Thank you very much anyway.
Gloria Paul
Gloria Paul le 22 Juin 2020
Hello Jorge, I really need help figuring this code out
Image Analyst
Image Analyst le 23 Juin 2020
What code? Jorge's or KSSV's? Or one of the other multitude of places where code appears on this page?

Connectez-vous pour commenter.

Image Analyst
Image Analyst le 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 commentaires

Jorge Ortiz
Jorge Ortiz le 16 Mar 2019
Modifié(e) : Image Analyst le 4 Mai 2020
Already done!! Above in the question is the solution I chose.
Thank you very much anyway.
Image Analyst
Image Analyst le 22 Mar 2019
Modifié(e) : Image Analyst le 4 Mai 2020
Well the solution you chose is not very robust, but it will work in some cases, not all cases.

Connectez-vous pour commenter.

Jaimin Motavar
Jaimin Motavar le 4 Juil 2019

0 votes

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 commentaires

KSSV
KSSV le 4 Juil 2019
It works fine...what problem you have?
Jaimin Motavar
Jaimin Motavar le 4 Juil 2019
it is not giving proper answer.
Image Analyst
Image Analyst le 4 Juil 2019
Attach your images (input and blurred output) and say WHY it's not giving the proper answer.
Namarta Kapil
Namarta Kapil le 21 Juil 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
Walter Roberson le 23 Juil 2019
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.

Connectez-vous pour commenter.

Brandon McLaughlin
Brandon McLaughlin le 22 Juil 2019

0 votes

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 le 23 Juil 2019

0 votes

See my manual convolution routine, attached.
shreyansh pitroda
shreyansh pitroda le 29 Avr 2020

0 votes

%% 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 commentaires

Image Analyst
Image Analyst le 29 Avr 2020
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
shreyansh pitroda
shreyansh pitroda le 30 Avr 2020
still getting the same error
Walter Roberson
Walter Roberson le 30 Avr 2020
What error are you getting, on what inputs?
Note that your blur function will only work for grayscale images, not for RGB images.
Sana Hafeez
Sana Hafeez le 4 Juin 2021
@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
Sana Hafeez
Sana Hafeez le 5 Juin 2021
Thanks a lot!!

Connectez-vous pour commenter.

David Gonzalez
David Gonzalez le 25 Mai 2020

0 votes

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);
Divya Ratna
Divya Ratna le 25 Mai 2020

0 votes

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
Chandrashekhar Dhangar le 16 Juil 2020

0 votes

%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 commentaires

Image Analyst
Image Analyst le 16 Juil 2020
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
Chandrashekhar Dhangar
Chandrashekhar Dhangar le 16 Juil 2020
Thanks for the response. Its working in Matlab software but showing the above error on website..
Image Analyst
Image Analyst le 16 Juil 2020
Huh? What website? As you can see, the code does run without error but probably doesn't do what you expect.
Chandrashekhar Dhangar
Chandrashekhar Dhangar le 16 Juil 2020
Modifié(e) : Chandrashekhar Dhangar le 16 Juil 2020
I'm agree with you. But the code is doing what we expect here. It was an assignment on Coursera.com
Image Analyst
Image Analyst le 16 Juil 2020
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?
Chandrashekhar Dhangar
Chandrashekhar Dhangar le 16 Juil 2020
ohh sorry. Got it. Thanks a lot.
Sana Hafeez
Sana Hafeez le 2 Juin 2021
@Image Analyst that code does not ran. Please help me I am tired to solve image blur problem...
Sana Hafeez
Sana Hafeez le 2 Juin 2021
Sana Hafeez
Sana Hafeez le 2 Juin 2021

Connectez-vous pour commenter.

aniket GIRI
aniket GIRI le 18 Juil 2020
Modifié(e) : DGM le 28 Fév 2022

0 votes

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 commentaires

Deepthi Thomas
Deepthi Thomas le 22 Juil 2020
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.
Deepthi Thomas
Deepthi Thomas le 23 Juil 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
Image Analyst le 23 Juil 2020
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.

Connectez-vous pour commenter.

Josh Yaksich
Josh Yaksich le 13 Juin 2021
Modifié(e) : Josh Yaksich le 13 Juin 2021

0 votes

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

Catégories

En savoir plus sur Convert Image Type dans Centre d'aide et File Exchange

Modifié(e) :

DGM
le 28 Fév 2022

Community Treasure Hunt

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

Start Hunting!

Translated by