Isnan use inappropiate?

Hi, in the code below I want to blur an image by inserting values to cells by progressively averaging the squares of 3*3 surrounding it. The cell specified sits in the middle.
The problem appears at the edges. for example at (1,1) the cell is at the top left corner if I want to make (1,1) sit at the middle of a 3x3 square; non-existent cell appears,..... (0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2). if you draw in a copy you can see that (1,1) is in the middle. My question is, for the edges, How can I take the valid values only and ignore the non-existent one??
clc;clear all;
A=imread('vandy.png'); % A random image
w=1; %the square will be of dimension 2w+1
M=double(A);
C=zeros(size(A));
for i=1:size(A,1)
for j=1:size(A,2)
C(i,j)=mean(M([i-w:i+w],[j-w:j+w]),'all'); % This is done to make the cell sit in the middle
if i-w<=0 || j-w<=0
C(i,j)=NaN; % I know its a wrong approach.. If you get my idea... let me know what changes i can make here
end
end
end
F=uint8(C);
imshow(F)

Answers (1)

If you do the blurring this way you can (or should, perhaps even "have to") slightly modify your indexing, this can be conventiently done with the power of matlab's cunning indexing. It could look something like this:
A = imread('vandy.png'); % A random image
w = 1; %the square will be of dimension 2w+1
M = double(A);
szIm = size(M)
C = zeros(size(A));
for i1 = 1:size(A,1)
for i2 = 1:size(A,2)
C(i1,i2) = mean(M(max(1,i1-w):min(szIm(1),i1+w),max(1,i2-w):min(szIm(2),i2+w)),'all');
% This should reduce the region along the edges avoiding trying to average over pixels
% outside the image
end
end
F=uint8(C);
imshow(F)
If you have access to the image processing toolbox you could use the imfilter function that has additional options for edge-handling, such as 'replicate', 'symmetric' - sometimes such options are preferable to simply shrinking the filter-kernel. (If it wasn't for edges image processing would be so much easier, so much easier...)
HTH

Categories

Find more on Images in Help Center and File Exchange

Tags

Asked:

on 1 Oct 2020

Commented:

on 1 Oct 2020

Community Treasure Hunt

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

Start Hunting!