Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8087787
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T18:53:29+00:00 2026-06-05T18:53:29+00:00

I have a numpy array like this: x = np.array([[1,2,3],[4,5,6],[7,8,9]]) I need to create

  • 0

I have a numpy array like this:

x = np.array([[1,2,3],[4,5,6],[7,8,9]])

I need to create a function let’s call it “neighbors” with the following input parameter:

  • x: a numpy 2d array
  • (i,j): the index of an element in a 2d array
  • d: neighborhood radius

As output I want to get the neighbors of the cell i,j with a given distance d.
So if I run

neighbors(im, i, j, d=1) with i = 1 and j = 1 (element value = 5) 

I should get the indices of the following values: [1,2,3,4,6,7,8,9]. I hope I make it clear.
Is there any library like scipy which deal with this?

I’ve done something working but it’s a rough solution.

def pixel_neighbours(self, p):

    rows, cols = self.im.shape

    i, j = p[0], p[1]

    rmin = i - 1 if i - 1 >= 0 else 0
    rmax = i + 1 if i + 1 < rows else i

    cmin = j - 1 if j - 1 >= 0 else 0
    cmax = j + 1 if j + 1 < cols else j

    neighbours = []

    for x in xrange(rmin, rmax + 1):
        for y in xrange(cmin, cmax + 1):
            neighbours.append([x, y])
    neighbours.remove([p[0], p[1]])

    return neighbours

How can I improve this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T18:53:30+00:00Added an answer on June 5, 2026 at 6:53 pm

    EDIT: ah crap, my answer is just writing im[i-d:i+d+1, j-d:j+d+1].flatten() but written in a incomprehensible way 🙂


    The good old sliding window trick may help here:

    import numpy as np
    from numpy.lib.stride_tricks import as_strided
    
    def sliding_window(arr, window_size):
        """ Construct a sliding window view of the array"""
        arr = np.asarray(arr)
        window_size = int(window_size)
        if arr.ndim != 2:
            raise ValueError("need 2-D input")
        if not (window_size > 0):
            raise ValueError("need a positive window size")
        shape = (arr.shape[0] - window_size + 1,
                 arr.shape[1] - window_size + 1,
                 window_size, window_size)
        if shape[0] <= 0:
            shape = (1, shape[1], arr.shape[0], shape[3])
        if shape[1] <= 0:
            shape = (shape[0], 1, shape[2], arr.shape[1])
        strides = (arr.shape[1]*arr.itemsize, arr.itemsize,
                   arr.shape[1]*arr.itemsize, arr.itemsize)
        return as_strided(arr, shape=shape, strides=strides)
    
    def cell_neighbors(arr, i, j, d):
        """Return d-th neighbors of cell (i, j)"""
        w = sliding_window(arr, 2*d+1)
    
        ix = np.clip(i - d, 0, w.shape[0]-1)
        jx = np.clip(j - d, 0, w.shape[1]-1)
    
        i0 = max(0, i - d - ix)
        j0 = max(0, j - d - jx)
        i1 = w.shape[2] - max(0, d - i + ix)
        j1 = w.shape[3] - max(0, d - j + jx)
    
        return w[ix, jx][i0:i1,j0:j1].ravel()
    
    x = np.arange(8*8).reshape(8, 8)
    print x
    
    for d in [1, 2]:
        for p in [(0,0), (0,1), (6,6), (8,8)]:
            print "-- d=%d, %r" % (d, p)
            print cell_neighbors(x, p[0], p[1], d=d)
    

    Didn’t do any timings here, but it’s possible this version has reasonable performance.

    For more info, search the net with phrases “rolling window numpy” or “sliding window numpy”.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a numpy array like this a = np.array(1) Now if I want
I have a 2-dimensional numpy array that looks like this: [[a b c] [d
i have a numpy array like the following [[ 1 2 3 4 ]
I have a NumPy array a like the following: >>> str(a) '[ nan nan
I have a 2d numpy array Something like this: [[ 1 2 3 4],
I have an array like this numpy array dd =[[0.567 2 0.611] [0.469 1
I have an array like this numpy array dd= [[foo 0.567 0.611] [bar 0.469
I have a numpy.ndarray like this: array([[ 11.18033989, 0. ], [ 8.24621125, 3. ],
I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like
I have a Numpy 3 axis array whose elements are 3 dimensional. I'd like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.