Pixel Neighborhood
Implement a function to extract the neighborhood of pixels around a given position in an image. This task is essential in image processing as it involves analyzing local regions of an image.
In computer vision, many operations rely on considering local neighborhoods, such as filtering, where the value of a pixel is determined by its neighboring pixels. The neighborhood of the pixel at position in an image can be represented as a square region of size centered at that pixel. To handle boundary conditions, zero-padding is used, where pixels outside the image boundaries are assumed to have a value of .
The neighborhood is defined by:
- The half-size , which sets how far the window reaches from the center in each direction.
- The window covers every row from to and every column from to , both ends inclusive.
- A window position inside the image takes the image's value there; a position outside the image takes .
Return the neighborhood as an list of lists (one inner list per row, top to bottom), with the center pixel in the middle.
This technique is widely used in image filtering applications.
Example
get_neighborhood([[1,2,3],[4,5,6],[7,8,9]], 1, 1, 3)
[[1,2,3],[4,5,6],[7,8,9]]
- Inputs:
imageis a grid of intensities – (row at the top),row,colpick the centre pixel (value ), andsizeis the window's side length. - Bounds: the half-size is , so the window covers rows through and columns through , inclusive: positions each way.
- Padding: valid indices here are –, so all window positions are inside the image. Nothing is zero-padded; each entry is the image value there.
- Output: a list of lists,
[[1,2,3],[4,5,6],[7,8,9]], with in the middle. Here it equals the whole image. - Notice the edge: centred at the window spans indices to . The positions with a index lie outside and become , giving
[[0, 0, 0], [0, 1, 2], [0, 4, 5]]. The window stays wherever it sits.
Constraints
- Image is a 2D array
- Position (row, col) may be near edges
- Neighborhood size n is odd (1, 3, 5, etc.)
- Use zero-padding for out-of-bounds pixels