asendjasni
asendjasni

Reputation: 1074

Given a pixel coordinates, how can I extract all his neighbors?

I want to build a 3x3 block for a given matrix point with that point in the center of the block. This is my code :

function frmBlock = fetchNeighbors(frame, row, column)
%Create a 3x3 matrix contains the neighbors of the point(x, y)
%[n, m] = size(frame);
frmBlock = zeros(3, 3);
x = floor(row);
y = floor(column);
    frmBlock(1) = frame(x-1, y-1);
    frmBlock(2) = frame(x, y-1);
    frmBlock(3) = frame(x+1, y+1);
    frmBlock(4) = frame(x-1, y);
    frmBlock(5) = frame(x, y);
    frmBlock(6) = frame(x+1, y);
    frmBlock(7) = frame(x-1, y+1);
    frmBlock(8) = frame(x, y+1);
    frmBlock(9) = frame(x+1, y-1);
end

As you can see, I create a 3x3 matrix initialized by 0. What I want to do is to fill that matrix with all the neighbors of the coordinate in input(row, column). If I can't get the neighbors for some reason I do nothing (i.e let that position in the 3x3 block as 0).

When I run this code I got an error saying:

Error using fetchNeighbors (line 12) Index exceeds matrix dimensions.

Can someone help ?

Upvotes: 0

Views: 783

Answers (1)

Lior
Lior

Reputation: 2019

I'm guessing that the error is due to the fact that you are taking row and column to be on the boundaries of the matrix frame, and then when you try to access the element just right or left or below or above (depends on which boundary you are on), you are out of bounds and this raises the error. For example, if row equals 1, this means that at some point you are trying to access frame(0,column), which is illegal.

You can fix this by adding a check (using an if statement) before any access to the matrix, to make sure you are in bounds. I add here an alternative approach:

function frmBlock = fetchNeighbors(frame, row, column)
% Create a 3x3 matrix that contains the neighbors of the point (row,column)
    [n,m] = size(frame);
    neighbors_x = max(row-1,1):min(row+1,n);
    neighbors_y = max(column-1,1):min(column+1,m);
    frmBlock = zeros(3,3);
    frmBlock(neighbors_x-row+2,neighbors_y-column+2) = frame(neighbors_x,neighbors_y);
end

Upvotes: 4

Related Questions