복붙노트

[PYTHON] 파이썬을 사용하여 2 차원 어레이 (이미지)의 픽셀 이웃

PYTHON

파이썬을 사용하여 2 차원 어레이 (이미지)의 픽셀 이웃

나는 이런 식으로 배열을 가지고있다.

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

함수를 만들어야 다음과 같은 입력 매개 변수를 사용하여 "이웃"이라고 부릅니다.

출력으로 주어진 거리 d로 셀 i, j의 이웃을 얻고 싶습니다. 그래서 내가 달리면

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

나는 다음의 값들의 색인을 얻어야한다 : [1,2,3,4,6,7,8,9]. 나는 그것을 분명히하기를 희망한다. 이것을 다루는 scipy와 같은 도서관이 있습니까?

나는 일하는 것을 해봤지만 근본적인 해결책이다.

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

어떻게 개선 할 수 있습니까?

해결법

  1. ==============================

    1.편집 : 아, 젠장, 내 대답은 그냥 [i-d : i + d + 1, j-d : j + d + 1] .flatten () 작성하지만 이해할 수없는 방식으로 작성 :)

    편집 : 아, 젠장, 내 대답은 그냥 [i-d : i + d + 1, j-d : j + d + 1] .flatten () 작성하지만 이해할 수없는 방식으로 작성 :)

    좋은 오래된 슬라이딩 윈도우 트릭이 여기에 도움이 될 수 있습니다 :

    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)
    

    여기에 어떤 타이밍도 없었지만,이 버전은 합리적인 성능을 가지고있을 가능성이 있습니다.

    더 자세한 정보는 "rolling window numpy"또는 "sliding window numpy"라는 문구로 그물을 검색하십시오.

  2. ==============================

    2.scipy.ndimage.generic_filter를 살펴보십시오.

    scipy.ndimage.generic_filter를 살펴보십시오.

    예로서:

    import numpy as np
    import scipy.ndimage as ndimage
    
    def test_func(values):
        print values
        return values.sum()
    
    
    x = np.array([[1,2,3],[4,5,6],[7,8,9]])
    
    footprint = np.array([[1,1,1],
                          [1,0,1],
                          [1,1,1]])
    
    results = ndimage.generic_filter(x, test_func, footprint=footprint)
    

    기본적으로 경계의 값을 "반영"합니다. mode 키워드 인수를 사용하여이를 제어 할 수 있습니다.

    그러나 이와 같은 일을하고 싶다면 어떤 종류의 회선으로 문제를 표현할 수있는 좋은 기회가 있습니다. 그렇다면 길쌈 단계로 나누고보다 최적화 된 기능 (예 : 대부분의 scipy.ndimage)을 사용하는 것이 훨씬 빠릅니다.

  3. ==============================

    3.이것에 대한 라이브러리 함수는 모르지만 numpy의 훌륭한 슬라이싱 기능을 사용하면 다음과 같이 쉽게 작성할 수 있습니다.

    이것에 대한 라이브러리 함수는 모르지만 numpy의 훌륭한 슬라이싱 기능을 사용하면 다음과 같이 쉽게 작성할 수 있습니다.

    import numpy as np
    def neighbors(im, i, j, d=1):
        n = im[i-d:i+d+1, j-d:j+d+1].flatten()
        # remove the element (i,j)
        n = np.hstack((b[:len(b)//2],b[len(b)//2+1:] ))
        return n
    

    물론 범위를 벗어나는 것을 막기 위해 범위 검사를 수행해야합니다.

  4. ==============================

    4.Joe Kingtons의 답변에 동의합니다. 발자국을 추가하는 것입니다.

    Joe Kingtons의 답변에 동의합니다. 발자국을 추가하는 것입니다.

    import numpy as np
    from scipy.ndimage import generate_binary_structure
    from scipy.ndimage import iterate_structure
    foot = np.array(generate_binary_structure(2, 1),dtype=int)
    

    또는 더 큰 발자국이나 다른 발자국의 경우.

    np.array(iterate_structure(foot , 2),dtype=int)
    
  5. ==============================

    5.아마도 SciPy에서 KDTree를 사용할 수 있습니까?

    아마도 SciPy에서 KDTree를 사용할 수 있습니까?

  6. from https://stackoverflow.com/questions/10996769/pixel-neighbors-in-2d-array-image-using-python by cc-by-sa and MIT license