I am doing some coding on image processing. There is a thing I can’t figure out for long time after tons of googling.

I have came across of k-NN algorithm, freemans coding etc., but they doesn’t fit my needs, at least from what I know, it could be I’m wrong.

I am trying to get the neighbors pixels of a point, be it a 4-connectivity or 8-connectivity neighbor.

Say given a point (x,y) on a coordinate plane, and I want to get the 8 neighbors pixels (1 to 8 of figure above) of that (x,y) point.

My question is: Is there any fast and efficient way of calculating and getting these neighbors of a point?

I have tried the hard coded method, for example (x-1, y-1) for 1st pixel, (x, y-1) for 2nd pixel and so on…

This method is ok but if I want to extend it by input a depth value, for example if depth is 2 and then my first pixel would be (x-2, y-2) and so on, the hard coded way might not work.

Hope anyone who know this can help me out!