Index in position 2 exceeds array bounds (must not exceed 320).

1 view (last 30 days)
How do I fix this error? The error is occuring in line 24 ( the line below case "Inside" ). I am confused because the values of i and j should shouldn't ever exceed the array size because they are derived from the array. Can somebody please explain the issue. One of the errors that I thought could be occuring is that the local function in my code is not correctly identifing the positions of those indicies, but I check my function over with my friend and his works just fine.
myImage_color = imread("sunflower.jpg");
myImage_grayscale = rgb2gray(myImage_color);
% finds size of image
[row, col] = size(myImage_grayscale);
myImage_blur = zeros(row,col);
for i = 1 : row
for j = 1 : col
% calculates position of image
position = IndexLocation(i,j, row, col);
% blurs each pixel depending on position
switch position
case "INSIDE"
myImage_blur(i,j) = ( myImage_grayscale(i,j+1) ...
+ myImage_grayscale(i,j-1) + myImage_grayscale(i,j) ...
+ myImage_grayscale(i-1,j-1) + myImage_grayscale(i-1,j) ...
+ myImage_grayscale(i-1,j+1) + myImage_grayscale(i+1,j-1) ...
+ myImage_grayscale(i+1,j) + myImage_grayscale(i+1,j+1) ) * (1/9)
case "NE"
myImage_blur(i,j) = ( myImage_grayscale(i+1,j) ...
+ 3 * myImage_grayscale(i,j) + myImage_grayscale(i,j-1) ...
+ myImage_grayscale(i+1,j-1) ) * (1/6) ;
case "RIGHT"
myImage_blur(i,j) = ( myImage_grayscale(i+1,j) ...
+ myImage_grayscale(i-1,j) + myImage_grayscale(i,j-1) ...
+ 2 * myImage_grayscale(i,j) + myImage_grayscale(i+1,j-1) ...
+ myImage_grayscale(i-1,j-1) ) * (1/7) ;
otherwise
myImage_blur = otherNodes(myImage_grayscale, i, j, position);
end
end
end
% displays grayscale and blurred image
imshow(myImage_grayscale)
imshow(myImage_blur)
% calculates position of pixel based on indicies
function [position] = IndexLocation(i,j, row, col)
if i == 1 & j ~= 1 & j ~= col
position = "LEFT";
elseif i == row & j ~= 1 & j ~= col
position = "RIGHT";
elseif j == 1 & i ~= 1 & i ~= row
position = "TOP";
elseif j == col & i ~= 1 & i ~= row
position = "BOTTOM";
elseif i == 1 & j == 1
position = "NW";
elseif i == 1 & j == row
position = "NE";
elseif i == row & j == 1
position = "SW";
elseif i == row & j == col
position = "SE";
else
position = "INSIDE";
end
end

Accepted Answer

Bhargavi Maganuru
Bhargavi Maganuru on 30 Mar 2020
myImage_grayscale(i+1, j+1) %causes error when i=row or j=col.
myImage_grayscale(i-1, j-1) %causes error when i=1 or j=1.
You could make changes accordingly.

More Answers (1)

Image Analyst
Image Analyst on 30 Mar 2020
Change the lines to not go within half a window width of the edge. Your filter window is 3-by-3 so half the width is 1 and you should start at pixel 2, not pixel 1:
myImage_blur = myImage_grayscale; % Not zeros.
for i = 2 : row-1
for j = 2 : col-1

Products

Community Treasure Hunt

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

Start Hunting!